@segosolutions/auto-task 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +41 -40
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,63 +1,64 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "module";
|
|
3
3
|
const require = createRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`).replace(/^/gm," ".repeat(l))}let
|
|
6
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,a=40){let l=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",h=new RegExp(`[\\n][${l}]+`);if(e.match(h))return e;let p=t-i;if(p<a)return e;let g=e.slice(0,i),
|
|
4
|
+
var Pg=Object.create;var yc=Object.defineProperty;var Ig=Object.getOwnPropertyDescriptor;var Mg=Object.getOwnPropertyNames;var xg=Object.getPrototypeOf,Ng=Object.prototype.hasOwnProperty;var q=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var $=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Lg=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Mg(e))!Ng.call(s,a)&&a!==t&&yc(s,a,{get:()=>e[a],enumerable:!(i=Ig(e,a))||i.enumerable});return s};var br=(s,e,t)=>(t=s!=null?Pg(xg(s)):{},Lg(e||!s||!s.__esModule?yc(t,"default",{value:s,enumerable:!0}):t,s));var ls=$(wr=>{var Vs=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},vr=class extends Vs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};wr.CommanderError=Vs;wr.InvalidArgumentError=vr});var zs=$(Er=>{var{InvalidArgumentError:jg}=ls(),Cr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new jg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Dg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}Er.Argument=Cr;Er.humanReadableArgName=Dg});var Or=$(_c=>{var{humanReadableArgName:Ug}=zs(),kr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(a=>!a._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((a,l)=>a.name().localeCompare(l.name())),t}compareOptions(e,t){let i=a=>a.short?a.short.replace(/^-/,""):a.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(a=>!a.hidden),i=e._getHelpOption();if(i&&!i.hidden){let a=i.short&&e._findOption(i.short),l=i.long&&e._findOption(i.long);!a&&!l?t.push(i):i.long&&!l?t.push(e.createOption(i.long,i.description)):i.short&&!a&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let a=i.options.filter(l=>!l.hidden);t.push(...a)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>Ug(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,a)=>Math.max(i,t.subcommandTerm(a).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,a)=>Math.max(i,t.optionTerm(a).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,a)=>Math.max(i,t.optionTerm(a).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,a)=>Math.max(i,t.argumentTerm(a).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let a=e.parent;a;a=a.parent)i=a.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),a=t.helpWidth||80,l=2,h=2;function p(A,E){if(E){let O=`${A.padEnd(i+h)}${E}`;return t.wrap(O,a-l,i+h)}return A}function g(A){return A.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(l))}let m=[`Usage: ${t.commandUsage(e)}`,""],v=t.commandDescription(e);v.length>0&&(m=m.concat([t.wrap(v,a,0),""]));let C=t.visibleArguments(e).map(A=>p(t.argumentTerm(A),t.argumentDescription(A)));C.length>0&&(m=m.concat(["Arguments:",g(C),""]));let k=t.visibleOptions(e).map(A=>p(t.optionTerm(A),t.optionDescription(A)));if(k.length>0&&(m=m.concat(["Options:",g(k),""])),this.showGlobalOptions){let A=t.visibleGlobalOptions(e).map(E=>p(t.optionTerm(E),t.optionDescription(E)));A.length>0&&(m=m.concat(["Global Options:",g(A),""]))}let S=t.visibleCommands(e).map(A=>p(t.subcommandTerm(A),t.subcommandDescription(A)));return S.length>0&&(m=m.concat(["Commands:",g(S),""])),m.join(`
|
|
6
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,a=40){let l=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",h=new RegExp(`[\\n][${l}]+`);if(e.match(h))return e;let p=t-i;if(p<a)return e;let g=e.slice(0,i),m=e.slice(i).replace(`\r
|
|
7
7
|
`,`
|
|
8
|
-
`),
|
|
9
|
-
|.{1,${p-1}}([${
|
|
10
|
-
`?"":(
|
|
11
|
-
`)}};_c.Help=
|
|
8
|
+
`),v=" ".repeat(i),k="\\s\u200B",S=new RegExp(`
|
|
9
|
+
|.{1,${p-1}}([${k}]|$)|[^${k}]+?([${k}]|$)`,"g"),A=m.match(S)||[];return g+A.map((E,O)=>E===`
|
|
10
|
+
`?"":(O>0?v:"")+E.trimEnd()).join(`
|
|
11
|
+
`)}};_c.Help=kr});var Rr=$(Ar=>{var{InvalidArgumentError:qg}=ls(),Sr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=$g(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new qg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Bg(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Tr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let a=this.negativeOptions.get(i).presetArg,l=a!==void 0?a:!1;return t.negate===(l===e)}};function Bg(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function $g(s){let e,t,i=s.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Ar.Option=Sr;Ar.DualOptions=Tr});var vc=$(bc=>{function Hg(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let i=0;i<=s.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let a=1;a<=s.length;a++){let l=1;s[a-1]===e[i-1]?l=0:l=1,t[a][i]=Math.min(t[a-1][i]+1,t[a][i-1]+1,t[a-1][i-1]+l),a>1&&i>1&&s[a-1]===e[i-2]&&s[a-2]===e[i-1]&&(t[a][i]=Math.min(t[a][i],t[a-2][i-2]+1))}return t[s.length][e.length]}function Gg(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(h=>h.slice(2)));let i=[],a=3,l=.4;return e.forEach(h=>{if(h.length<=1)return;let p=Hg(s,h),g=Math.max(s.length,h.length);(g-p)/g>l&&(p<a?(a=p,i=[h]):p===a&&i.push(h))}),i.sort((h,p)=>h.localeCompare(p)),t&&(i=i.map(h=>`--${h}`)),i.length>1?`
|
|
12
12
|
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
13
|
-
(Did you mean ${i[0]}?)`:""}bc.suggestSimilar=
|
|
14
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
+
(Did you mean ${i[0]}?)`:""}bc.suggestSimilar=Gg});var Oc=$(kc=>{var Fg=q("node:events").EventEmitter,Pr=q("node:child_process"),Ke=q("node:path"),Ir=q("node:fs"),oe=q("node:process"),{Argument:Wg,humanReadableArgName:Vg}=zs(),{CommanderError:Mr}=ls(),{Help:zg}=Or(),{Option:wc,DualOptions:Kg}=Rr(),{suggestSimilar:Cc}=vc(),xr=class s extends Fg{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>oe.stdout.write(t),writeErr:t=>oe.stderr.write(t),getOutHelpWidth:()=>oe.stdout.isTTY?oe.stdout.columns:void 0,getErrHelpWidth:()=>oe.stderr.isTTY?oe.stderr.columns:void 0,outputError:(t,i)=>i(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let a=t,l=i;typeof a=="object"&&a!==null&&(l=a,a=null),l=l||{};let[,h,p]=e.match(/([^ ]+) *(.*)/),g=this.createCommand(h);return a&&(g.description(a),g._executableHandler=!0),l.isDefault&&(this._defaultCommandName=g._name),g._hidden=!!(l.noHelp||l.hidden),g._executableFile=l.executableFile||null,p&&g.arguments(p),this._registerCommand(g),g.parent=this,g.copyInheritedSettings(this),a?this:g}createCommand(e){return new s(e)}createHelp(){return Object.assign(new zg,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Wg(e,t)}argument(e,t,i,a){let l=this.createArgument(e,t);return typeof i=="function"?l.default(a).argParser(i):l.default(i),this.addArgument(l),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,a]=e.match(/([^ ]+) *(.*)/),l=t??"display help for command",h=this.createCommand(i);return h.helpOption(!1),a&&h.arguments(a),l&&h.description(l),this._addImplicitHelpCommand=!0,this._helpCommand=h,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
15
15
|
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new Mr(e,t,i)),oe.exit(e)}action(e){let t=i=>{let a=this.registeredArguments.length,l=i.slice(0,a);return this._storeOptionsAsProperties?l[a]=this:l[a]=this.opts(),l.push(this),e.apply(this,l)};return this._actionHandler=t,this}createOption(e,t){return new wc(e,t)}_callParseArg(e,t,i,a){try{return e.parseArg(t,i)}catch(l){if(l.code==="commander.invalidArgument"){let h=`${a} ${l.message}`;this.error(h,{exitCode:l.exitCode,code:l.code})}throw l}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
16
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=a=>[a.name()].concat(a.aliases()),i=t(e).find(a=>this._findCommand(a));if(i){let a=t(this._findCommand(i)).join("|"),l=t(e).join("|");throw new Error(`cannot add command '${l}' as already have command '${a}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let l=e.long.replace(/^--no-/,"--");this._findOption(l)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let a=(l,h,p)=>{l==null&&e.presetArg!==void 0&&(l=e.presetArg);let g=this.getOptionValue(i);l!==null&&e.parseArg?l=this._callParseArg(e,l,g,h):l!==null&&e.variadic&&(l=e._concatValue(l,g)),l==null&&(e.negate?l=!1:e.isBoolean()||e.optional?l=!0:l=""),this.setOptionValueWithSource(i,l,p)};return this.on("option:"+t,l=>{let h=`error: option '${e.flags}' argument '${l}' is invalid.`;a(l,h,"cli")}),e.envVar&&this.on("optionEnv:"+t,l=>{let h=`error: option '${e.flags}' value '${l}' from env '${e.envVar}' is invalid.`;a(l,h,"env")}),this}_optionEx(e,t,i,a,l){if(typeof t=="object"&&t instanceof wc)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let h=this.createOption(t,i);if(h.makeOptionMandatory(!!e.mandatory),typeof a=="function")h.default(l).argParser(a);else if(a instanceof RegExp){let p=a;a=(g,
|
|
16
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=a=>[a.name()].concat(a.aliases()),i=t(e).find(a=>this._findCommand(a));if(i){let a=t(this._findCommand(i)).join("|"),l=t(e).join("|");throw new Error(`cannot add command '${l}' as already have command '${a}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let l=e.long.replace(/^--no-/,"--");this._findOption(l)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let a=(l,h,p)=>{l==null&&e.presetArg!==void 0&&(l=e.presetArg);let g=this.getOptionValue(i);l!==null&&e.parseArg?l=this._callParseArg(e,l,g,h):l!==null&&e.variadic&&(l=e._concatValue(l,g)),l==null&&(e.negate?l=!1:e.isBoolean()||e.optional?l=!0:l=""),this.setOptionValueWithSource(i,l,p)};return this.on("option:"+t,l=>{let h=`error: option '${e.flags}' argument '${l}' is invalid.`;a(l,h,"cli")}),e.envVar&&this.on("optionEnv:"+t,l=>{let h=`error: option '${e.flags}' value '${l}' from env '${e.envVar}' is invalid.`;a(l,h,"env")}),this}_optionEx(e,t,i,a,l){if(typeof t=="object"&&t instanceof wc)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let h=this.createOption(t,i);if(h.makeOptionMandatory(!!e.mandatory),typeof a=="function")h.default(l).argParser(a);else if(a instanceof RegExp){let p=a;a=(g,m)=>{let v=p.exec(g);return v?v[0]:m},h.default(l).argParser(a)}else h.default(a);return this.addOption(h)}option(e,t,i,a){return this._optionEx({},e,t,i,a)}requiredOption(e,t,i,a){return this._optionEx({mandatory:!0},e,t,i,a)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){oe.versions?.electron&&(t.from="electron");let a=oe.execArgv??[];(a.includes("-e")||a.includes("--eval")||a.includes("-p")||a.includes("--print"))&&(t.from="eval")}e===void 0&&(e=oe.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":oe.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,a=[".js",".ts",".tsx",".mjs",".cjs"];function l(v,C){let k=Ke.resolve(v,C);if(Ir.existsSync(k))return k;if(a.includes(Ke.extname(C)))return;let S=a.find(A=>Ir.existsSync(`${k}${A}`));if(S)return`${k}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let h=e._executableFile||`${this._name}-${e._name}`,p=this._executableDir||"";if(this._scriptPath){let v;try{v=Ir.realpathSync(this._scriptPath)}catch{v=this._scriptPath}p=Ke.resolve(Ke.dirname(v),p)}if(p){let v=l(p,h);if(!v&&!e._executableFile&&this._scriptPath){let C=Ke.basename(this._scriptPath,Ke.extname(this._scriptPath));C!==this._name&&(v=l(p,`${C}-${e._name}`))}h=v||h}i=a.includes(Ke.extname(h));let g;oe.platform!=="win32"?i?(t.unshift(h),t=Ec(oe.execArgv).concat(t),g=Pr.spawn(oe.argv[0],t,{stdio:"inherit"})):g=Pr.spawn(h,t,{stdio:"inherit"}):(t.unshift(h),t=Ec(oe.execArgv).concat(t),g=Pr.spawn(oe.execPath,t,{stdio:"inherit"})),g.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(C=>{oe.on(C,()=>{g.killed===!1&&g.exitCode===null&&g.kill(C)})});let m=this._exitCallback;g.on("close",v=>{v=v??1,m?m(new Mr(v,"commander.executeSubCommandAsync","(close)")):oe.exit(v)}),g.on("error",v=>{if(v.code==="ENOENT"){let C=p?`searched for local subcommand relative to directory '${p}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",k=`'${h}' does not exist
|
|
17
17
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
18
18
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
19
|
-
- ${
|
|
19
|
+
- ${C}`;throw new Error(k)}else if(v.code==="EACCES")throw new Error(`'${h}' not executable`);if(!m)oe.exit(1);else{let C=new Mr(1,"commander.executeSubCommandAsync","(error)");C.nestedError=v,m(C)}}),this.runningCommand=g}_dispatchSubcommand(e,t,i){let a=this._findCommand(e);a||this.help({error:!0});let l;return l=this._chainOrCallSubCommandHook(l,a,"preSubcommand"),l=this._chainOrCall(l,()=>{if(a._executableHandler)this._executeSubCommand(a,t.concat(i));else return a._parseCommand(t,i)}),l}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(i,a,l)=>{let h=a;if(a!==null&&i.parseArg){let p=`error: command-argument value '${a}' is invalid for argument '${i.name()}'.`;h=this._callParseArg(i,a,l,p)}return h};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,a)=>{let l=i.defaultValue;i.variadic?a<this.args.length?(l=this.args.slice(a),i.parseArg&&(l=l.reduce((h,p)=>e(i,p,h),i.defaultValue))):l===void 0&&(l=[]):a<this.args.length&&(l=this.args[a],i.parseArg&&(l=e(i,l,i.defaultValue))),t[a]=l}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,a=[];return this._getCommandAndAncestors().reverse().filter(l=>l._lifeCycleHooks[t]!==void 0).forEach(l=>{l._lifeCycleHooks[t].forEach(h=>{a.push({hookedCommand:l,callback:h})})}),t==="postAction"&&a.reverse(),a.forEach(l=>{i=this._chainOrCall(i,()=>l.callback(l.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let a=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(l=>{a=this._chainOrCall(a,()=>l(this,t))}),a}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},l=`command:${this.name()}`;if(this._actionHandler){a(),this._processArguments();let h;return h=this._chainOrCallHooks(h,"preAction"),h=this._chainOrCall(h,()=>this._actionHandler(this.processedArgs)),this.parent&&(h=this._chainOrCall(h,()=>{this.parent.emit(l,e,t)})),h=this._chainOrCallHooks(h,"postAction"),h}if(this.parent&&this.parent.listenerCount(l))a(),this._processArguments(),this.parent.emit(l,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(a(),this._processArguments())}else this.commands.length?(a(),this.help({error:!0})):(a(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let a=i.attributeName();return this.getOptionValue(a)===void 0?!1:this.getOptionValueSource(a)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let a=e.find(l=>i.conflictsWith.includes(l.attributeName()));a&&this._conflictingOption(i,a)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],a=t,l=e.slice();function h(g){return g.length>1&&g[0]==="-"}let p=null;for(;l.length;){let g=l.shift();if(g==="--"){a===i&&a.push(g),a.push(...l);break}if(p&&!h(g)){this.emit(`option:${p.name()}`,g);continue}if(p=null,h(g)){let m=this._findOption(g);if(m){if(m.required){let v=l.shift();v===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,v)}else if(m.optional){let v=null;l.length>0&&!h(l[0])&&(v=l.shift()),this.emit(`option:${m.name()}`,v)}else this.emit(`option:${m.name()}`);p=m.variadic?m:null;continue}}if(g.length>2&&g[0]==="-"&&g[1]!=="-"){let m=this._findOption(`-${g[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,g.slice(2)):(this.emit(`option:${m.name()}`),l.unshift(`-${g.slice(2)}`));continue}}if(/^--[^=]+=/.test(g)){let m=g.indexOf("="),v=this._findOption(g.slice(0,m));if(v&&(v.required||v.optional)){this.emit(`option:${v.name()}`,g.slice(m+1));continue}}if(h(g)&&(a=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(g)){t.push(g),l.length>0&&i.push(...l);break}else if(this._getHelpCommand()&&g===this._getHelpCommand().name()){t.push(g),l.length>0&&t.push(...l);break}else if(this._defaultCommandName){i.push(g),l.length>0&&i.push(...l);break}}if(this._passThroughOptions){a.push(g),l.length>0&&a.push(...l);break}a.push(g)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let a=this.options[i].attributeName();e[a]=a===this._versionOptionName?this._version:this[a]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
20
20
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
21
21
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
22
|
-
`),this.outputHelp({error:!0}));let i=t||{},a=i.exitCode||1,l=i.code||"commander.error";this._exit(a,l,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in oe.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,oe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
23
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let a=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${a}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>
|
|
22
|
+
`),this.outputHelp({error:!0}));let i=t||{},a=i.exitCode||1,l=i.code||"commander.error";this._exit(a,l,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in oe.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,oe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Kg(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(a=>!t(a)).forEach(a=>{this.setOptionValueWithSource(a,i.implied[a],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=h=>{let p=h.attributeName(),g=this.getOptionValue(p),m=this.options.find(C=>C.negate&&p===C.attributeName()),v=this.options.find(C=>!C.negate&&p===C.attributeName());return m&&(m.presetArg===void 0&&g===!1||m.presetArg!==void 0&&g===m.presetArg)?m:v||h},a=h=>{let p=i(h),g=p.attributeName();return this.getOptionValueSource(g)==="env"?`environment variable '${p.envVar}'`:`option '${p.flags}'`},l=`error: ${a(e)} cannot be used with ${a(t)}`;this.error(l,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let a=[],l=this;do{let h=l.createHelp().visibleOptions(l).filter(p=>p.long).map(p=>p.long);a=a.concat(h),l=l.parent}while(l&&!l._enablePositionalOptions);t=Cc(e,a)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",l=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(l,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let a=[];this.createHelp().visibleCommands(this).forEach(l=>{a.push(l.name()),l.alias()&&a.push(l.alias())}),t=Cc(e,a)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let a=this.createOption(t,i);return this._versionOptionName=a.attributeName(),this._registerOption(a),this.on("option:"+a.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
23
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let a=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${a}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>Vg(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Ke.basename(e,Ke.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=a=>this._outputConfiguration.writeErr(a):i=a=>this._outputConfiguration.writeOut(a),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(l=>l.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let a=this.helpInformation(i);if(t&&(a=t(a),typeof a!="string"&&!Buffer.isBuffer(a)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(a),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(l=>l.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=oe.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
24
24
|
Expecting one of '${i.join("', '")}'`);let a=`${e}Help`;return this.on(a,l=>{let h;typeof t=="function"?h=t({error:l.error,command:l.command}):h=t,h&&l.write(`${h}
|
|
25
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ec(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",a="9229",l;return(l=e.match(/^(--inspect(-brk)?)$/))!==null?t=l[1]:(l=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=l[1],/^\d+$/.test(l[3])?a=l[3]:i=l[3]):(l=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=l[1],i=l[3],a=l[4]),t&&a!=="0"?`${t}=${i}:${parseInt(a)+1}`:e})}
|
|
26
|
-
`);let i;for(;(i=
|
|
27
|
-
`),l=l.replace(/\\r/g,"\r")),e[a]=l}return e}function im(s){s=s||{};let e=jc(s);s.path=e;let t=le.configDotenv(s);if(!t.parsed){let h=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw h.code="MISSING_DATA",h}let i=Lc(s).split(","),a=i.length,l;for(let h=0;h<a;h++)try{let p=i[h].trim(),g=am(t,p);l=le.decrypt(g.ciphertext,g.key);break}catch(p){if(h+1>=a)throw p}return le.parse(l)}function om(s){console.error(`[dotenv@${jr}][WARN] ${s}`)}function hs(s){console.log(`[dotenv@${jr}][DEBUG] ${s}`)}function Nc(s){console.log(`[dotenv@${jr}] ${s}`)}function Lc(s){return s&&s.DOTENV_KEY&&s.DOTENV_KEY.length>0?s.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function am(s,e){let t;try{t=new URL(e)}catch(p){if(p.code==="ERR_INVALID_URL"){let g=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw g.code="INVALID_DOTENV_KEY",g}throw p}let i=t.password;if(!i){let p=new Error("INVALID_DOTENV_KEY: Missing key part");throw p.code="INVALID_DOTENV_KEY",p}let a=t.searchParams.get("environment");if(!a){let p=new Error("INVALID_DOTENV_KEY: Missing environment part");throw p.code="INVALID_DOTENV_KEY",p}let l=`DOTENV_VAULT_${a.toUpperCase()}`,h=s.parsed[l];if(!h){let p=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${l} in your .env.vault file.`);throw p.code="NOT_FOUND_DOTENV_ENVIRONMENT",p}return{ciphertext:h,key:i}}function jc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Lr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Ks.resolve(process.cwd(),".env.vault");return Lr.existsSync(e)?e:null}function xc(s){return s[0]==="~"?Ks.join(Qg.homedir(),s.slice(1)):s}function cm(s){let e=xt(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=xt(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Nc("Loading env from encrypted .env.vault");let i=le._parseVault(s),a=process.env;return s&&s.processEnv!=null&&(a=s.processEnv),le.populate(a,i,s),{parsed:i}}function lm(s){let e=Ks.resolve(process.cwd(),".env"),t="utf8",i=process.env;s&&s.processEnv!=null&&(i=s.processEnv);let a=xt(i.DOTENV_CONFIG_DEBUG||s&&s.debug),l=xt(i.DOTENV_CONFIG_QUIET||s&&s.quiet);s&&s.encoding?t=s.encoding:a&&hs("No encoding is specified. UTF-8 is used by default");let h=[e];if(s&&s.path)if(!Array.isArray(s.path))h=[xc(s.path)];else{h=[];for(let C of s.path)h.push(xc(C))}let p,g={};for(let C of h)try{let v=le.parse(Lr.readFileSync(C,{encoding:t}));le.populate(g,v,s)}catch(v){a&&hs(`Failed to load ${C} ${v.message}`),p=v}let y=le.populate(i,g,s);if(a=xt(i.DOTENV_CONFIG_DEBUG||a),l=xt(i.DOTENV_CONFIG_QUIET||l),a||!l){let C=Object.keys(y).length,v=[];for(let O of h)try{let k=Ks.relative(process.cwd(),O);v.push(k)}catch(k){a&&hs(`Failed to load ${O} ${k.message}`),p=k}Nc(`injecting env (${C}) from ${v.join(",")} ${sm(`-- tip: ${em()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function um(s){if(Lc(s).length===0)return le.configDotenv(s);let e=jc(s);return e?le._configVault(s):(om(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),le.configDotenv(s))}function hm(s,e){let t=Buffer.from(e.slice(-64),"hex"),i=Buffer.from(s,"base64"),a=i.subarray(0,12),l=i.subarray(-16);i=i.subarray(12,-16);try{let h=Xg.createDecipheriv("aes-256-gcm",t,a);return h.setAuthTag(l),`${h.update(i)}${h.final()}`}catch(h){let p=h instanceof RangeError,g=h.message==="Invalid key length",y=h.message==="Unsupported state or unable to authenticate data";if(p||g){let C=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw C.code="INVALID_DOTENV_KEY",C}else if(y){let C=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw C.code="DECRYPTION_FAILED",C}else throw h}}function dm(s,e,t={}){let i=!!(t&&t.debug),a=!!(t&&t.override),l={};if(typeof e!="object"){let h=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw h.code="OBJECT_REQUIRED",h}for(let h of Object.keys(e))Object.prototype.hasOwnProperty.call(s,h)?(a===!0&&(s[h]=e[h],l[h]=e[h]),i&&hs(a===!0?`"${h}" is already defined and WAS overwritten`:`"${h}" is already defined and was NOT overwritten`)):(s[h]=e[h],l[h]=e[h]);return l}var le={configDotenv:lm,_configVault:cm,_parseVault:im,config:um,decrypt:hm,parse:rm,populate:dm};Je.exports.configDotenv=le.configDotenv;Je.exports._configVault=le._configVault;Je.exports._parseVault=le._parseVault;Je.exports.config=le.config;Je.exports.decrypt=le.decrypt;Je.exports.parse=le.parse;Je.exports.populate=le.populate;Je.exports=le});var Ye=$((Vw,tl)=>{"use strict";var Zc=["nodebuffer","arraybuffer","fragments"],el=typeof Blob<"u";el&&Zc.push("blob");tl.exports={BINARY_TYPES:Zc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:el,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ds=$((zw,Xs)=>{"use strict";var{EMPTY_BUFFER:km}=Ye(),Br=Buffer[Symbol.species];function Sm(s,e){if(s.length===0)return km;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),i=0;for(let a=0;a<s.length;a++){let l=s[a];t.set(l,i),i+=l.length}return i<e?new Br(t.buffer,t.byteOffset,i):t}function sl(s,e,t,i,a){for(let l=0;l<a;l++)t[i+l]=s[l]^e[l&3]}function nl(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function Tm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function $r(s){if($r.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Br(s):ArrayBuffer.isView(s)?e=new Br(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),$r.readOnly=!1),e}Xs.exports={concat:Sm,mask:sl,toArrayBuffer:Tm,toBuffer:$r,unmask:nl};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=D("bufferutil");Xs.exports.mask=function(e,t,i,a,l){l<48?sl(e,t,i,a,l):s.mask(e,t,i,a,l)},Xs.exports.unmask=function(e,t){e.length<32?nl(e,t):s.unmask(e,t)}}catch{}});var ol=$((Kw,il)=>{"use strict";var rl=Symbol("kDone"),Hr=Symbol("kRun"),Gr=class{constructor(e){this[rl]=()=>{this.pending--,this[Hr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hr]()}[Hr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[rl])}}};il.exports=Gr});var ps=$((Jw,ul)=>{"use strict";var fs=D("zlib"),al=ds(),Am=ol(),{kStatusCode:cl}=Ye(),Rm=Buffer[Symbol.species],Pm=Buffer.from([0,0,255,255]),en=Symbol("permessage-deflate"),Qe=Symbol("total-length"),Nt=Symbol("callback"),lt=Symbol("buffers"),Lt=Symbol("error"),Zs,Fr=class{constructor(e,t,i){if(this._maxPayload=i|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Zs){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zs=new Am(a)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Nt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,i=e.find(a=>!(t.serverNoContextTakeover===!1&&a.server_no_context_takeover||a.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>a.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!a.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(i=>{let a=t[i];if(a.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(a=a[0],i==="client_max_window_bits"){if(a!==!0){let l=+a;if(!Number.isInteger(l)||l<8||l>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=l}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else if(i==="server_max_window_bits"){let l=+a;if(!Number.isInteger(l)||l<8||l>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=l}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(a!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=a})}),e}decompress(e,t,i){Zs.add(a=>{this._decompress(e,t,(l,h)=>{a(),i(l,h)})})}compress(e,t,i){Zs.add(a=>{this._compress(e,t,(l,h)=>{a(),i(l,h)})})}_decompress(e,t,i){let a=this._isServer?"client":"server";if(!this._inflate){let l=`${a}_max_window_bits`,h=typeof this.params[l]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[l];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:h}),this._inflate[en]=this,this._inflate[Qe]=0,this._inflate[lt]=[],this._inflate.on("error",Mm),this._inflate.on("data",ll)}this._inflate[Nt]=i,this._inflate.write(e),t&&this._inflate.write(Pm),this._inflate.flush(()=>{let l=this._inflate[Lt];if(l){this._inflate.close(),this._inflate=null,i(l);return}let h=al.concat(this._inflate[lt],this._inflate[Qe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qe]=0,this._inflate[lt]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,h)})}_compress(e,t,i){let a=this._isServer?"server":"client";if(!this._deflate){let l=`${a}_max_window_bits`,h=typeof this.params[l]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[l];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:h}),this._deflate[Qe]=0,this._deflate[lt]=[],this._deflate.on("data",Im)}this._deflate[Nt]=i,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let l=al.concat(this._deflate[lt],this._deflate[Qe]);t&&(l=new Rm(l.buffer,l.byteOffset,l.length-4)),this._deflate[Nt]=null,this._deflate[Qe]=0,this._deflate[lt]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,l)})}};ul.exports=Fr;function Im(s){this[lt].push(s),this[Qe]+=s.length}function ll(s){if(this[Qe]+=s.length,this[en]._maxPayload<1||this[Qe]<=this[en]._maxPayload){this[lt].push(s);return}this[Lt]=new RangeError("Max payload size exceeded"),this[Lt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Lt][cl]=1009,this.removeListener("data",ll),this.reset()}function Mm(s){if(this[en]._inflate=null,this[Lt]){this[Nt](this[Lt]);return}s[cl]=1007,this[Nt](s)}});var jt=$((Yw,tn)=>{"use strict";var{isUtf8:hl}=D("buffer"),{hasBlob:xm}=Ye(),Nm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Lm(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Wr(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}function jm(s){return xm&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}tn.exports={isBlob:jm,isValidStatusCode:Lm,isValidUTF8:Wr,tokenChars:Nm};if(hl)tn.exports.isValidUTF8=function(s){return s.length<24?Wr(s):hl(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=D("utf-8-validate");tn.exports.isValidUTF8=function(e){return e.length<32?Wr(e):s(e)}}catch{}});var Yr=$((Qw,_l)=>{"use strict";var{Writable:qm}=D("stream"),dl=ps(),{BINARY_TYPES:Um,EMPTY_BUFFER:fl,kStatusCode:Dm,kWebSocket:Bm}=Ye(),{concat:Vr,toArrayBuffer:$m,unmask:Hm}=ds(),{isValidStatusCode:Gm,isValidUTF8:pl}=jt(),sn=Buffer[Symbol.species],Pe=0,gl=1,ml=2,yl=3,zr=4,Kr=5,nn=6,Jr=class extends qm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Um[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Bm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Pe}_write(e,t,i){if(this._opcode===8&&this._state==Pe)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new sn(i.buffer,i.byteOffset+e,i.length-e),new sn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],a=t.length-e;e>=i.length?t.set(this._buffers.shift(),a):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),a),this._buffers[0]=new sn(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Pe:this.getInfo(e);break;case gl:this.getPayloadLength16(e);break;case ml:this.getPayloadLength64(e);break;case yl:this.getMask();break;case zr:this.getData(e);break;case Kr:case nn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let a=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(a);return}let i=(t[0]&64)===64;if(i&&!this._extensions[dl.extensionName]){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(!this._fragmented){let a=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let a=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(a);return}if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let a=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(a);return}}else{let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let a=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(a);return}}else if(this._masked){let a=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(a);return}this._payloadLength===126?this._state=gl:this._payloadLength===127?this._state=ml:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let a=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(a);return}this._payloadLength=i*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=yl:this._state=zr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zr}getData(e){let t=fl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Hm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Kr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[dl.extensionName].decompress(e,this._fin,(a,l)=>{if(a)return t(a);if(l.length){if(this._messageLength+=l.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let h=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(h);return}this._fragments.push(l)}this.dataMessage(t),this._state===Pe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Pe;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let a;this._binaryType==="nodebuffer"?a=Vr(i,t):this._binaryType==="arraybuffer"?a=$m(Vr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=Pe):(this._state=nn,setImmediate(()=>{this.emit("message",a,!0),this._state=Pe,this.startLoop(e)}))}else{let a=Vr(i,t);if(!this._skipUTF8Validation&&!pl(a)){let l=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(l);return}this._state===Kr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=Pe):(this._state=nn,setImmediate(()=>{this.emit("message",a,!1),this._state=Pe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fl),this.end();else{let i=e.readUInt16BE(0);if(!Gm(i)){let l=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(l);return}let a=new sn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!pl(a)){let l=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(l);return}this._loop=!1,this.emit("conclude",i,a),this.end()}this._state=Pe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Pe):(this._state=nn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Pe,this.startLoop(t)}))}createError(e,t,i,a,l){this._loop=!1,this._errored=!0;let h=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(h,this.createError),h.code=l,h[Dm]=a,h}};_l.exports=Jr});var Zr=$((Zw,wl)=>{"use strict";var{Duplex:Xw}=D("stream"),{randomFillSync:Fm}=D("crypto"),bl=ps(),{EMPTY_BUFFER:Wm,kWebSocket:Vm,NOOP:zm}=Ye(),{isBlob:qt,isValidStatusCode:Km}=jt(),{mask:vl,toBuffer:_t}=ds(),Ie=Symbol("kByteLength"),Jm=Buffer.alloc(4),rn=8*1024,bt,Ut=rn,De=0,Ym=1,Qm=2,Qr=class s{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=De,this.onerror=zm,this[Vm]=void 0}static frame(e,t){let i,a=!1,l=2,h=!1;t.mask&&(i=t.maskBuffer||Jm,t.generateMask?t.generateMask(i):(Ut===rn&&(bt===void 0&&(bt=Buffer.alloc(rn)),Fm(bt,0,rn),Ut=0),i[0]=bt[Ut++],i[1]=bt[Ut++],i[2]=bt[Ut++],i[3]=bt[Ut++]),h=(i[0]|i[1]|i[2]|i[3])===0,l=6);let p;typeof e=="string"?(!t.mask||h)&&t[Ie]!==void 0?p=t[Ie]:(e=Buffer.from(e),p=e.length):(p=e.length,a=t.mask&&t.readOnly&&!h);let g=p;p>=65536?(l+=8,g=127):p>125&&(l+=2,g=126);let y=Buffer.allocUnsafe(a?p+l:l);return y[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(y[0]|=64),y[1]=g,g===126?y.writeUInt16BE(p,2):g===127&&(y[2]=y[3]=0,y.writeUIntBE(p,4,6)),t.mask?(y[1]|=128,y[l-4]=i[0],y[l-3]=i[1],y[l-2]=i[2],y[l-1]=i[3],h?[y,e]:a?(vl(e,i,y,l,p),[y]):(vl(e,i,e,0,p),[y,e])):[y,e]}close(e,t,i,a){let l;if(e===void 0)l=Wm;else{if(typeof e!="number"||!Km(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)l=Buffer.allocUnsafe(2),l.writeUInt16BE(e,0);else{let p=Buffer.byteLength(t);if(p>123)throw new RangeError("The message must not be greater than 123 bytes");l=Buffer.allocUnsafe(2+p),l.writeUInt16BE(e,0),typeof t=="string"?l.write(t,2):l.set(t,2)}}let h={[Ie]:l.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==De?this.enqueue([this.dispatch,l,!1,h,a]):this.sendFrame(s.frame(l,h),a)}ping(e,t,i){let a,l;if(typeof e=="string"?(a=Buffer.byteLength(e),l=!1):qt(e)?(a=e.size,l=!1):(e=_t(e),a=e.length,l=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Ie]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:l,rsv1:!1};qt(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==De?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}pong(e,t,i){let a,l;if(typeof e=="string"?(a=Buffer.byteLength(e),l=!1):qt(e)?(a=e.size,l=!1):(e=_t(e),a=e.length,l=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Ie]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:l,rsv1:!1};qt(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==De?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}send(e,t,i){let a=this._extensions[bl.extensionName],l=t.binary?2:1,h=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):qt(e)?(p=e.size,g=!1):(e=_t(e),p=e.length,g=_t.readOnly),this._firstFragment?(this._firstFragment=!1,h&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(h=p>=a._threshold),this._compress=h):(h=!1,l=0),t.fin&&(this._firstFragment=!0);let y={[Ie]:p,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:l,readOnly:g,rsv1:h};qt(e)?this._state!==De?this.enqueue([this.getBlobData,e,this._compress,y,i]):this.getBlobData(e,this._compress,y,i):this._state!==De?this.enqueue([this.dispatch,e,this._compress,y,i]):this.dispatch(e,this._compress,y,i)}getBlobData(e,t,i,a){this._bufferedBytes+=i[Ie],this._state=Qm,e.arrayBuffer().then(l=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(Xr,this,p,a);return}this._bufferedBytes-=i[Ie];let h=_t(l);t?this.dispatch(h,t,i,a):(this._state=De,this.sendFrame(s.frame(h,i),a),this.dequeue())}).catch(l=>{process.nextTick(Xm,this,l,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let l=this._extensions[bl.extensionName];this._bufferedBytes+=i[Ie],this._state=Ym,l.compress(e,i.fin,(h,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");Xr(this,g,a);return}this._bufferedBytes-=i[Ie],this._state=De,i.readOnly=!1,this.sendFrame(s.frame(p,i),a),this.dequeue()})}dequeue(){for(;this._state===De&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};wl.exports=Qr;function Xr(s,e,t){typeof t=="function"&&t(e);for(let i=0;i<s._queue.length;i++){let a=s._queue[i],l=a[a.length-1];typeof l=="function"&&l(e)}}function Xm(s,e,t){Xr(s,e,t),s.onerror(e)}});var Pl=$((eC,Rl)=>{"use strict";var{kForOnEventAttribute:gs,kListener:ei}=Ye(),Cl=Symbol("kCode"),El=Symbol("kData"),Ol=Symbol("kError"),kl=Symbol("kMessage"),Sl=Symbol("kReason"),Dt=Symbol("kTarget"),Tl=Symbol("kType"),Al=Symbol("kWasClean"),Xe=class{constructor(e){this[Dt]=null,this[Tl]=e}get target(){return this[Dt]}get type(){return this[Tl]}};Object.defineProperty(Xe.prototype,"target",{enumerable:!0});Object.defineProperty(Xe.prototype,"type",{enumerable:!0});var vt=class extends Xe{constructor(e,t={}){super(e),this[Cl]=t.code===void 0?0:t.code,this[Sl]=t.reason===void 0?"":t.reason,this[Al]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Cl]}get reason(){return this[Sl]}get wasClean(){return this[Al]}};Object.defineProperty(vt.prototype,"code",{enumerable:!0});Object.defineProperty(vt.prototype,"reason",{enumerable:!0});Object.defineProperty(vt.prototype,"wasClean",{enumerable:!0});var Bt=class extends Xe{constructor(e,t={}){super(e),this[Ol]=t.error===void 0?null:t.error,this[kl]=t.message===void 0?"":t.message}get error(){return this[Ol]}get message(){return this[kl]}};Object.defineProperty(Bt.prototype,"error",{enumerable:!0});Object.defineProperty(Bt.prototype,"message",{enumerable:!0});var ms=class extends Xe{constructor(e,t={}){super(e),this[El]=t.data===void 0?null:t.data}get data(){return this[El]}};Object.defineProperty(ms.prototype,"data",{enumerable:!0});var Zm={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[gs]&&a[ei]===e&&!a[gs])return;let i;if(s==="message")i=function(l,h){let p=new ms("message",{data:h?l:l.toString()});p[Dt]=this,on(e,this,p)};else if(s==="close")i=function(l,h){let p=new vt("close",{code:l,reason:h.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[Dt]=this,on(e,this,p)};else if(s==="error")i=function(l){let h=new Bt("error",{error:l,message:l.message});h[Dt]=this,on(e,this,h)};else if(s==="open")i=function(){let l=new Xe("open");l[Dt]=this,on(e,this,l)};else return;i[gs]=!!t[gs],i[ei]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[ei]===e&&!t[gs]){this.removeListener(s,t);break}}};Rl.exports={CloseEvent:vt,ErrorEvent:Bt,Event:Xe,EventTarget:Zm,MessageEvent:ms};function on(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var ti=$((tC,Il)=>{"use strict";var{tokenChars:ys}=jt();function He(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function ey(s){let e=Object.create(null),t=Object.create(null),i=!1,a=!1,l=!1,h,p,g=-1,y=-1,C=-1,v=0;for(;v<s.length;v++)if(y=s.charCodeAt(v),h===void 0)if(C===-1&&ys[y]===1)g===-1&&(g=v);else if(v!==0&&(y===32||y===9))C===-1&&g!==-1&&(C=v);else if(y===59||y===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${v}`);C===-1&&(C=v);let k=s.slice(g,C);y===44?(He(e,k,t),t=Object.create(null)):h=k,g=C=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);else if(p===void 0)if(C===-1&&ys[y]===1)g===-1&&(g=v);else if(y===32||y===9)C===-1&&g!==-1&&(C=v);else if(y===59||y===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${v}`);C===-1&&(C=v),He(t,s.slice(g,C),!0),y===44&&(He(e,h,t),t=Object.create(null),h=void 0),g=C=-1}else if(y===61&&g!==-1&&C===-1)p=s.slice(g,v),g=C=-1;else throw new SyntaxError(`Unexpected character at index ${v}`);else if(a){if(ys[y]!==1)throw new SyntaxError(`Unexpected character at index ${v}`);g===-1?g=v:i||(i=!0),a=!1}else if(l)if(ys[y]===1)g===-1&&(g=v);else if(y===34&&g!==-1)l=!1,C=v;else if(y===92)a=!0;else throw new SyntaxError(`Unexpected character at index ${v}`);else if(y===34&&s.charCodeAt(v-1)===61)l=!0;else if(C===-1&&ys[y]===1)g===-1&&(g=v);else if(g!==-1&&(y===32||y===9))C===-1&&(C=v);else if(y===59||y===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${v}`);C===-1&&(C=v);let k=s.slice(g,C);i&&(k=k.replace(/\\/g,""),i=!1),He(t,p,k),y===44&&(He(e,h,t),t=Object.create(null),h=void 0),p=void 0,g=C=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);if(g===-1||l||y===32||y===9)throw new SyntaxError("Unexpected end of input");C===-1&&(C=v);let O=s.slice(g,C);return h===void 0?He(e,O,t):(p===void 0?He(t,O,!0):i?He(t,p,O.replace(/\\/g,"")):He(t,p,O),He(e,h,t)),e}function ty(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(a=>{let l=i[a];return Array.isArray(l)||(l=[l]),l.map(h=>h===!0?a:`${a}=${h}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Il.exports={format:ty,parse:ey}});var un=$((rC,Gl)=>{"use strict";var sy=D("events"),ny=D("https"),ry=D("http"),Nl=D("net"),iy=D("tls"),{randomBytes:oy,createHash:ay}=D("crypto"),{Duplex:sC,Readable:nC}=D("stream"),{URL:si}=D("url"),ut=ps(),cy=Yr(),ly=Zr(),{isBlob:uy}=jt(),{BINARY_TYPES:Ml,CLOSE_TIMEOUT:hy,EMPTY_BUFFER:an,GUID:dy,kForOnEventAttribute:ni,kListener:fy,kStatusCode:py,kWebSocket:de,NOOP:Ll}=Ye(),{EventTarget:{addEventListener:gy,removeEventListener:my}}=Pl(),{format:yy,parse:_y}=ti(),{toBuffer:by}=ds(),jl=Symbol("kAborted"),ri=[8,13],Ze=["CONNECTING","OPEN","CLOSING","CLOSED"],vy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class s extends sy{constructor(e,t,i){super(),this._binaryType=Ml[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=an,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(i=t,t=[]):t=[t]),ql(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ml.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,i){let a=new cy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),l=new ly(e,this._extensions,i.generateMask);this._receiver=a,this._sender=l,this._socket=e,a[de]=this,l[de]=this,e[de]=this,a.on("conclude",Ey),a.on("drain",Oy),a.on("error",ky),a.on("message",Sy),a.on("ping",Ty),a.on("pong",Ay),l.onerror=Ry,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Bl),e.on("data",ln),e.on("end",$l),e.on("error",Hl),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ut.extensionName]&&this._extensions[ut.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Dl(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||an,t,i)}pong(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||an,t,i)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ii(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ut.extensionName]||(a.compress=!1),this._sender.send(e||an,a,i)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(re.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(re.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[ni])return e[fy];return null},set(e){for(let t of this.listeners(s))if(t[ni]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[ni]:!0})}})});re.prototype.addEventListener=gy;re.prototype.removeEventListener=my;Gl.exports=re;function ql(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:hy,protocolVersion:ri[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=a.autoPong,s._closeTimeout=a.closeTimeout,!ri.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${ri.join(", ")})`);let l;if(e instanceof si)l=e;else try{l=new si(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}l.protocol==="http:"?l.protocol="ws:":l.protocol==="https:"&&(l.protocol="wss:"),s._url=l.href;let h=l.protocol==="wss:",p=l.protocol==="ws+unix:",g;if(l.protocol!=="ws:"&&!h&&!p?g=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?g="The URL's pathname is empty":l.hash&&(g="The URL contains a fragment identifier"),g){let E=new SyntaxError(g);if(s._redirects===0)throw E;cn(s,E);return}let y=h?443:80,C=oy(16).toString("base64"),v=h?ny.request:ry.request,O=new Set,k;if(a.createConnection=a.createConnection||(h?Cy:wy),a.defaultPort=a.defaultPort||y,a.port=l.port||y,a.host=l.hostname.startsWith("[")?l.hostname.slice(1,-1):l.hostname,a.headers={...a.headers,"Sec-WebSocket-Version":a.protocolVersion,"Sec-WebSocket-Key":C,Connection:"Upgrade",Upgrade:"websocket"},a.path=l.pathname+l.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(k=new ut(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=yy({[ut.extensionName]:k.offer()})),t.length){for(let E of t){if(typeof E!="string"||!vy.test(E)||O.has(E))throw new SyntaxError("An invalid or duplicated subprotocol was specified");O.add(E)}a.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(a.origin&&(a.protocolVersion<13?a.headers["Sec-WebSocket-Origin"]=a.origin:a.headers.Origin=a.origin),(l.username||l.password)&&(a.auth=`${l.username}:${l.password}`),p){let E=a.path.split(":");a.socketPath=E[0],a.path=E[1]}let T;if(a.followRedirects){if(s._redirects===0){s._originalIpc=p,s._originalSecure=h,s._originalHostOrSocketPath=p?a.socketPath:l.host;let E=i&&i.headers;if(i={...i,headers:{}},E)for(let[S,N]of Object.entries(E))i.headers[S.toLowerCase()]=N}else if(s.listenerCount("redirect")===0){let E=p?s._originalIpc?a.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:l.host===s._originalHostOrSocketPath;(!E||s._originalSecure&&!h)&&(delete a.headers.authorization,delete a.headers.cookie,E||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),T=s._req=v(a),s._redirects&&s.emit("redirect",s.url,T)}else T=s._req=v(a);a.timeout&&T.on("timeout",()=>{Se(s,T,"Opening handshake has timed out")}),T.on("error",E=>{T===null||T[jl]||(T=s._req=null,cn(s,E))}),T.on("response",E=>{let S=E.headers.location,N=E.statusCode;if(S&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Se(s,T,"Maximum redirects exceeded");return}T.abort();let W;try{W=new si(S,e)}catch{let se=new SyntaxError(`Invalid URL: ${S}`);cn(s,se);return}ql(s,W,t,i)}else s.emit("unexpected-response",T,E)||Se(s,T,`Unexpected server response: ${E.statusCode}`)}),T.on("upgrade",(E,S,N)=>{if(s.emit("upgrade",E),s.readyState!==re.CONNECTING)return;T=s._req=null;let W=E.headers.upgrade;if(W===void 0||W.toLowerCase()!=="websocket"){Se(s,S,"Invalid Upgrade header");return}let Y=ay("sha1").update(C+dy).digest("base64");if(E.headers["sec-websocket-accept"]!==Y){Se(s,S,"Invalid Sec-WebSocket-Accept header");return}let se=E.headers["sec-websocket-protocol"],Z;if(se!==void 0?O.size?O.has(se)||(Z="Server sent an invalid subprotocol"):Z="Server sent a subprotocol but none was requested":O.size&&(Z="Server sent no subprotocol"),Z){Se(s,S,Z);return}se&&(s._protocol=se);let Te=E.headers["sec-websocket-extensions"];if(Te!==void 0){if(!k){Se(s,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Le;try{Le=_y(Te)}catch{Se(s,S,"Invalid Sec-WebSocket-Extensions header");return}let ot=Object.keys(Le);if(ot.length!==1||ot[0]!==ut.extensionName){Se(s,S,"Server indicated an extension that was not requested");return}try{k.accept(Le[ut.extensionName])}catch{Se(s,S,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ut.extensionName]=k}s.setSocket(S,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(T,s):T.end()}function cn(s,e){s._readyState=re.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function wy(s){return s.path=s.socketPath,Nl.connect(s)}function Cy(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Nl.isIP(s.host)?"":s.host),iy.connect(s)}function Se(s,e,t){s._readyState=re.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Se),e.setHeader?(e[jl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(cn,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ii(s,e,t){if(e){let i=uy(e)?e.size:by(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${Ze[s.readyState]})`);process.nextTick(t,i)}}function Ey(s,e){let t=this[de];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[de]!==void 0&&(t._socket.removeListener("data",ln),process.nextTick(Ul,t._socket),s===1005?t.close():t.close(s,e))}function Oy(){let s=this[de];s.isPaused||s._socket.resume()}function ky(s){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",ln),process.nextTick(Ul,e._socket),e.close(s[py])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function xl(){this[de].emitClose()}function Sy(s,e){this[de].emit("message",s,e)}function Ty(s){let e=this[de];e._autoPong&&e.pong(s,!this._isServer,Ll),e.emit("ping",s)}function Ay(s){this[de].emit("pong",s)}function Ul(s){s.resume()}function Ry(s){let e=this[de];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Dl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Dl(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function Bl(){let s=this[de];if(this.removeListener("close",Bl),this.removeListener("data",ln),this.removeListener("end",$l),s._readyState=re.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[de]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",xl),s._receiver.on("finish",xl))}function ln(s){this[de]._receiver.write(s)||this.pause()}function $l(){let s=this[de];s._readyState=re.CLOSING,s._receiver.end(),this.end()}function Hl(){let s=this[de];this.removeListener("error",Hl),this.on("error",Ll),s&&(s._readyState=re.CLOSING,this.destroy())}});var zl=$((oC,Vl)=>{"use strict";var iC=un(),{Duplex:Py}=D("stream");function Fl(s){s.emit("close")}function Iy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Wl(s){this.removeListener("error",Wl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function My(s,e){let t=!0,i=new Py({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(l,h){let p=!h&&i._readableState.objectMode?l.toString():l;i.push(p)||s.pause()}),s.once("error",function(l){i.destroyed||(t=!1,i.destroy(l))}),s.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(a,l){if(s.readyState===s.CLOSED){l(a),process.nextTick(Fl,i);return}let h=!1;s.once("error",function(g){h=!0,l(g)}),s.once("close",function(){h||l(a),process.nextTick(Fl,i)}),t&&s.terminate()},i._final=function(a){if(s.readyState===s.CONNECTING){s.once("open",function(){i._final(a)});return}s._socket!==null&&(s._socket._writableState.finished?(a(),i._readableState.endEmitted&&i.destroy()):(s._socket.once("finish",function(){a()}),s.close()))},i._read=function(){s.isPaused&&s.resume()},i._write=function(a,l,h){if(s.readyState===s.CONNECTING){s.once("open",function(){i._write(a,l,h)});return}s.send(a,h)},i.on("end",Iy),i.on("error",Wl),i}Vl.exports=My});var Jl=$((aC,Kl)=>{"use strict";var{tokenChars:xy}=jt();function Ny(s){let e=new Set,t=-1,i=-1,a=0;for(a;a<s.length;a++){let h=s.charCodeAt(a);if(i===-1&&xy[h]===1)t===-1&&(t=a);else if(a!==0&&(h===32||h===9))i===-1&&t!==-1&&(i=a);else if(h===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let p=s.slice(t,i);if(e.has(p))throw new SyntaxError(`The "${p}" subprotocol is duplicated`);e.add(p),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${a}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let l=s.slice(t,a);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);return e.add(l),e}Kl.exports={parse:Ny}});var su=$((lC,tu)=>{"use strict";var Ly=D("events"),hn=D("http"),{Duplex:cC}=D("stream"),{createHash:jy}=D("crypto"),Yl=ti(),wt=ps(),qy=Jl(),Uy=un(),{CLOSE_TIMEOUT:Dy,GUID:By,kWebSocket:$y}=Ye(),Hy=/^[+/0-9A-Za-z]{22}==$/,Ql=0,Xl=1,eu=2,oi=class extends Ly{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Dy,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Uy,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=hn.createServer((i,a)=>{let l=hn.STATUS_CODES[426];a.writeHead(426,{"Content-Length":l.length,"Content-Type":"text/plain"}),a.end(l)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=Gy(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,l,h)=>{this.handleUpgrade(a,l,h,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ql}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===eu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(_s,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(_s,this):process.nextTick(_s,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{_s(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,i,a){t.on("error",Zl);let l=e.headers["sec-websocket-key"],h=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ct(this,e,t,405,"Invalid HTTP method");return}if(h===void 0||h.toLowerCase()!=="websocket"){Ct(this,e,t,400,"Invalid Upgrade header");return}if(l===void 0||!Hy.test(l)){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(p!==13&&p!==8){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){bs(t,400);return}let g=e.headers["sec-websocket-protocol"],y=new Set;if(g!==void 0)try{y=qy.parse(g)}catch{Ct(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let C=e.headers["sec-websocket-extensions"],v={};if(this.options.perMessageDeflate&&C!==void 0){let O=new wt(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let k=Yl.parse(C);k[wt.extensionName]&&(O.accept(k[wt.extensionName]),v[wt.extensionName]=O)}catch{Ct(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let O={origin:e.headers[`${p===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(O,(k,T,E,S)=>{if(!k)return bs(t,T||401,E,S);this.completeUpgrade(v,l,y,e,t,i,a)});return}if(!this.options.verifyClient(O))return bs(t,401)}this.completeUpgrade(v,l,y,e,t,i,a)}completeUpgrade(e,t,i,a,l,h,p){if(!l.readable||!l.writable)return l.destroy();if(l[$y])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ql)return bs(l,503);let y=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${jy("sha1").update(t+By).digest("base64")}`],C=new this.options.WebSocket(null,void 0,this.options);if(i.size){let v=this.options.handleProtocols?this.options.handleProtocols(i,a):i.values().next().value;v&&(y.push(`Sec-WebSocket-Protocol: ${v}`),C._protocol=v)}if(e[wt.extensionName]){let v=e[wt.extensionName].params,O=Yl.format({[wt.extensionName]:[v]});y.push(`Sec-WebSocket-Extensions: ${O}`),C._extensions=e}this.emit("headers",y,a),l.write(y.concat(`\r
|
|
25
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(a=>t.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ec(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",a="9229",l;return(l=e.match(/^(--inspect(-brk)?)$/))!==null?t=l[1]:(l=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=l[1],/^\d+$/.test(l[3])?a=l[3]:i=l[3]):(l=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=l[1],i=l[3],a=l[4]),t&&a!=="0"?`${t}=${i}:${parseInt(a)+1}`:e})}kc.Command=xr});var Rc=$(Re=>{var{Argument:Sc}=zs(),{Command:Nr}=Oc(),{CommanderError:Jg,InvalidArgumentError:Tc}=ls(),{Help:Yg}=Or(),{Option:Ac}=Rr();Re.program=new Nr;Re.createCommand=s=>new Nr(s);Re.createOption=(s,e)=>new Ac(s,e);Re.createArgument=(s,e)=>new Sc(s,e);Re.Command=Nr;Re.Option=Ac;Re.Argument=Sc;Re.Help=Yg;Re.CommanderError=Jg;Re.InvalidArgumentError=Tc;Re.InvalidOptionArgumentError=Tc});var Ic=$((qw,Qg)=>{Qg.exports={name:"dotenv",version:"17.2.3",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var Dc=$((Bw,Je)=>{var Lr=q("fs"),Ks=q("path"),Xg=q("os"),Zg=q("crypto"),em=Ic(),jr=em.version,Mc=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F4E1} add observability to secrets: https://dotenvx.com/ops","\u{1F465} sync secrets across teammates & machines: https://dotenvx.com/ops","\u{1F5C2}\uFE0F backup and recover secrets: https://dotenvx.com/ops","\u2705 audit secrets and track compliance: https://dotenvx.com/ops","\u{1F504} add secrets lifecycle management: https://dotenvx.com/ops","\u{1F511} add access controls to secrets: https://dotenvx.com/ops","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function tm(){return Mc[Math.floor(Math.random()*Mc.length)]}function xt(s){return typeof s=="string"?!["false","0","no","off",""].includes(s.toLowerCase()):!!s}function sm(){return process.stdout.isTTY}function nm(s){return sm()?`\x1B[2m${s}\x1B[0m`:s}var rm=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function im(s){let e={},t=s.toString();t=t.replace(/\r\n?/mg,`
|
|
26
|
+
`);let i;for(;(i=rm.exec(t))!=null;){let a=i[1],l=i[2]||"";l=l.trim();let h=l[0];l=l.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),h==='"'&&(l=l.replace(/\\n/g,`
|
|
27
|
+
`),l=l.replace(/\\r/g,"\r")),e[a]=l}return e}function om(s){s=s||{};let e=jc(s);s.path=e;let t=le.configDotenv(s);if(!t.parsed){let h=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw h.code="MISSING_DATA",h}let i=Lc(s).split(","),a=i.length,l;for(let h=0;h<a;h++)try{let p=i[h].trim(),g=cm(t,p);l=le.decrypt(g.ciphertext,g.key);break}catch(p){if(h+1>=a)throw p}return le.parse(l)}function am(s){console.error(`[dotenv@${jr}][WARN] ${s}`)}function hs(s){console.log(`[dotenv@${jr}][DEBUG] ${s}`)}function Nc(s){console.log(`[dotenv@${jr}] ${s}`)}function Lc(s){return s&&s.DOTENV_KEY&&s.DOTENV_KEY.length>0?s.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function cm(s,e){let t;try{t=new URL(e)}catch(p){if(p.code==="ERR_INVALID_URL"){let g=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw g.code="INVALID_DOTENV_KEY",g}throw p}let i=t.password;if(!i){let p=new Error("INVALID_DOTENV_KEY: Missing key part");throw p.code="INVALID_DOTENV_KEY",p}let a=t.searchParams.get("environment");if(!a){let p=new Error("INVALID_DOTENV_KEY: Missing environment part");throw p.code="INVALID_DOTENV_KEY",p}let l=`DOTENV_VAULT_${a.toUpperCase()}`,h=s.parsed[l];if(!h){let p=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${l} in your .env.vault file.`);throw p.code="NOT_FOUND_DOTENV_ENVIRONMENT",p}return{ciphertext:h,key:i}}function jc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Lr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Ks.resolve(process.cwd(),".env.vault");return Lr.existsSync(e)?e:null}function xc(s){return s[0]==="~"?Ks.join(Xg.homedir(),s.slice(1)):s}function lm(s){let e=xt(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=xt(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Nc("Loading env from encrypted .env.vault");let i=le._parseVault(s),a=process.env;return s&&s.processEnv!=null&&(a=s.processEnv),le.populate(a,i,s),{parsed:i}}function um(s){let e=Ks.resolve(process.cwd(),".env"),t="utf8",i=process.env;s&&s.processEnv!=null&&(i=s.processEnv);let a=xt(i.DOTENV_CONFIG_DEBUG||s&&s.debug),l=xt(i.DOTENV_CONFIG_QUIET||s&&s.quiet);s&&s.encoding?t=s.encoding:a&&hs("No encoding is specified. UTF-8 is used by default");let h=[e];if(s&&s.path)if(!Array.isArray(s.path))h=[xc(s.path)];else{h=[];for(let v of s.path)h.push(xc(v))}let p,g={};for(let v of h)try{let C=le.parse(Lr.readFileSync(v,{encoding:t}));le.populate(g,C,s)}catch(C){a&&hs(`Failed to load ${v} ${C.message}`),p=C}let m=le.populate(i,g,s);if(a=xt(i.DOTENV_CONFIG_DEBUG||a),l=xt(i.DOTENV_CONFIG_QUIET||l),a||!l){let v=Object.keys(m).length,C=[];for(let k of h)try{let S=Ks.relative(process.cwd(),k);C.push(S)}catch(S){a&&hs(`Failed to load ${k} ${S.message}`),p=S}Nc(`injecting env (${v}) from ${C.join(",")} ${nm(`-- tip: ${tm()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function hm(s){if(Lc(s).length===0)return le.configDotenv(s);let e=jc(s);return e?le._configVault(s):(am(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),le.configDotenv(s))}function dm(s,e){let t=Buffer.from(e.slice(-64),"hex"),i=Buffer.from(s,"base64"),a=i.subarray(0,12),l=i.subarray(-16);i=i.subarray(12,-16);try{let h=Zg.createDecipheriv("aes-256-gcm",t,a);return h.setAuthTag(l),`${h.update(i)}${h.final()}`}catch(h){let p=h instanceof RangeError,g=h.message==="Invalid key length",m=h.message==="Unsupported state or unable to authenticate data";if(p||g){let v=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw v.code="INVALID_DOTENV_KEY",v}else if(m){let v=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw v.code="DECRYPTION_FAILED",v}else throw h}}function fm(s,e,t={}){let i=!!(t&&t.debug),a=!!(t&&t.override),l={};if(typeof e!="object"){let h=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw h.code="OBJECT_REQUIRED",h}for(let h of Object.keys(e))Object.prototype.hasOwnProperty.call(s,h)?(a===!0&&(s[h]=e[h],l[h]=e[h]),i&&hs(a===!0?`"${h}" is already defined and WAS overwritten`:`"${h}" is already defined and was NOT overwritten`)):(s[h]=e[h],l[h]=e[h]);return l}var le={configDotenv:um,_configVault:lm,_parseVault:om,config:hm,decrypt:dm,parse:im,populate:fm};Je.exports.configDotenv=le.configDotenv;Je.exports._configVault=le._configVault;Je.exports._parseVault=le._parseVault;Je.exports.config=le.config;Je.exports.decrypt=le.decrypt;Je.exports.parse=le.parse;Je.exports.populate=le.populate;Je.exports=le});var Ye=$((Qw,sl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");sl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ds=$((Xw,Xs)=>{"use strict";var{EMPTY_BUFFER:Pm}=Ye(),Br=Buffer[Symbol.species];function Im(s,e){if(s.length===0)return Pm;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),i=0;for(let a=0;a<s.length;a++){let l=s[a];t.set(l,i),i+=l.length}return i<e?new Br(t.buffer,t.byteOffset,i):t}function nl(s,e,t,i,a){for(let l=0;l<a;l++)t[i+l]=s[l]^e[l&3]}function rl(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function Mm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function $r(s){if($r.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Br(s):ArrayBuffer.isView(s)?e=new Br(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),$r.readOnly=!1),e}Xs.exports={concat:Im,mask:nl,toArrayBuffer:Mm,toBuffer:$r,unmask:rl};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=q("bufferutil");Xs.exports.mask=function(e,t,i,a,l){l<48?nl(e,t,i,a,l):s.mask(e,t,i,a,l)},Xs.exports.unmask=function(e,t){e.length<32?rl(e,t):s.unmask(e,t)}}catch{}});var al=$((Zw,ol)=>{"use strict";var il=Symbol("kDone"),Hr=Symbol("kRun"),Gr=class{constructor(e){this[il]=()=>{this.pending--,this[Hr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hr]()}[Hr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[il])}}};ol.exports=Gr});var ps=$((eC,hl)=>{"use strict";var fs=q("zlib"),cl=ds(),xm=al(),{kStatusCode:ll}=Ye(),Nm=Buffer[Symbol.species],Lm=Buffer.from([0,0,255,255]),en=Symbol("permessage-deflate"),Qe=Symbol("total-length"),Nt=Symbol("callback"),lt=Symbol("buffers"),Lt=Symbol("error"),Zs,Fr=class{constructor(e,t,i){if(this._maxPayload=i|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Zs){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zs=new xm(a)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Nt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,i=e.find(a=>!(t.serverNoContextTakeover===!1&&a.server_no_context_takeover||a.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>a.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!a.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(i=>{let a=t[i];if(a.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(a=a[0],i==="client_max_window_bits"){if(a!==!0){let l=+a;if(!Number.isInteger(l)||l<8||l>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=l}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else if(i==="server_max_window_bits"){let l=+a;if(!Number.isInteger(l)||l<8||l>15)throw new TypeError(`Invalid value for parameter "${i}": ${a}`);a=l}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(a!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${a}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=a})}),e}decompress(e,t,i){Zs.add(a=>{this._decompress(e,t,(l,h)=>{a(),i(l,h)})})}compress(e,t,i){Zs.add(a=>{this._compress(e,t,(l,h)=>{a(),i(l,h)})})}_decompress(e,t,i){let a=this._isServer?"client":"server";if(!this._inflate){let l=`${a}_max_window_bits`,h=typeof this.params[l]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[l];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:h}),this._inflate[en]=this,this._inflate[Qe]=0,this._inflate[lt]=[],this._inflate.on("error",Dm),this._inflate.on("data",ul)}this._inflate[Nt]=i,this._inflate.write(e),t&&this._inflate.write(Lm),this._inflate.flush(()=>{let l=this._inflate[Lt];if(l){this._inflate.close(),this._inflate=null,i(l);return}let h=cl.concat(this._inflate[lt],this._inflate[Qe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qe]=0,this._inflate[lt]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,h)})}_compress(e,t,i){let a=this._isServer?"server":"client";if(!this._deflate){let l=`${a}_max_window_bits`,h=typeof this.params[l]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[l];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:h}),this._deflate[Qe]=0,this._deflate[lt]=[],this._deflate.on("data",jm)}this._deflate[Nt]=i,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let l=cl.concat(this._deflate[lt],this._deflate[Qe]);t&&(l=new Nm(l.buffer,l.byteOffset,l.length-4)),this._deflate[Nt]=null,this._deflate[Qe]=0,this._deflate[lt]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,l)})}};hl.exports=Fr;function jm(s){this[lt].push(s),this[Qe]+=s.length}function ul(s){if(this[Qe]+=s.length,this[en]._maxPayload<1||this[Qe]<=this[en]._maxPayload){this[lt].push(s);return}this[Lt]=new RangeError("Max payload size exceeded"),this[Lt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Lt][ll]=1009,this.removeListener("data",ul),this.reset()}function Dm(s){if(this[en]._inflate=null,this[Lt]){this[Nt](this[Lt]);return}s[ll]=1007,this[Nt](s)}});var jt=$((tC,tn)=>{"use strict";var{isUtf8:dl}=q("buffer"),{hasBlob:Um}=Ye(),qm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Bm(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Wr(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}function $m(s){return Um&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}tn.exports={isBlob:$m,isValidStatusCode:Bm,isValidUTF8:Wr,tokenChars:qm};if(dl)tn.exports.isValidUTF8=function(s){return s.length<24?Wr(s):dl(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=q("utf-8-validate");tn.exports.isValidUTF8=function(e){return e.length<32?Wr(e):s(e)}}catch{}});var Yr=$((sC,bl)=>{"use strict";var{Writable:Hm}=q("stream"),fl=ps(),{BINARY_TYPES:Gm,EMPTY_BUFFER:pl,kStatusCode:Fm,kWebSocket:Wm}=Ye(),{concat:Vr,toArrayBuffer:Vm,unmask:zm}=ds(),{isValidStatusCode:Km,isValidUTF8:gl}=jt(),sn=Buffer[Symbol.species],Pe=0,ml=1,yl=2,_l=3,zr=4,Kr=5,nn=6,Jr=class extends Hm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Gm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Wm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Pe}_write(e,t,i){if(this._opcode===8&&this._state==Pe)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new sn(i.buffer,i.byteOffset+e,i.length-e),new sn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],a=t.length-e;e>=i.length?t.set(this._buffers.shift(),a):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),a),this._buffers[0]=new sn(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Pe:this.getInfo(e);break;case ml:this.getPayloadLength16(e);break;case yl:this.getPayloadLength64(e);break;case _l:this.getMask();break;case zr:this.getData(e);break;case Kr:case nn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let a=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(a);return}let i=(t[0]&64)===64;if(i&&!this._extensions[fl.extensionName]){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(!this._fragmented){let a=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let a=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(a);return}if(i){let a=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(a);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let a=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(a);return}}else{let a=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(a);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let a=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(a);return}}else if(this._masked){let a=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(a);return}this._payloadLength===126?this._state=ml:this._payloadLength===127?this._state=yl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let a=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(a);return}this._payloadLength=i*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=_l:this._state=zr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zr}getData(e){let t=pl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&zm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Kr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.extensionName].decompress(e,this._fin,(a,l)=>{if(a)return t(a);if(l.length){if(this._messageLength+=l.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let h=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(h);return}this._fragments.push(l)}this.dataMessage(t),this._state===Pe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Pe;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let a;this._binaryType==="nodebuffer"?a=Vr(i,t):this._binaryType==="arraybuffer"?a=Vm(Vr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=Pe):(this._state=nn,setImmediate(()=>{this.emit("message",a,!0),this._state=Pe,this.startLoop(e)}))}else{let a=Vr(i,t);if(!this._skipUTF8Validation&&!gl(a)){let l=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(l);return}this._state===Kr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=Pe):(this._state=nn,setImmediate(()=>{this.emit("message",a,!1),this._state=Pe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pl),this.end();else{let i=e.readUInt16BE(0);if(!Km(i)){let l=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(l);return}let a=new sn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!gl(a)){let l=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(l);return}this._loop=!1,this.emit("conclude",i,a),this.end()}this._state=Pe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Pe):(this._state=nn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Pe,this.startLoop(t)}))}createError(e,t,i,a,l){this._loop=!1,this._errored=!0;let h=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(h,this.createError),h.code=l,h[Fm]=a,h}};bl.exports=Jr});var Zr=$((rC,Cl)=>{"use strict";var{Duplex:nC}=q("stream"),{randomFillSync:Jm}=q("crypto"),vl=ps(),{EMPTY_BUFFER:Ym,kWebSocket:Qm,NOOP:Xm}=Ye(),{isBlob:Dt,isValidStatusCode:Zm}=jt(),{mask:wl,toBuffer:_t}=ds(),Ie=Symbol("kByteLength"),ey=Buffer.alloc(4),rn=8*1024,bt,Ut=rn,qe=0,ty=1,sy=2,Qr=class s{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=qe,this.onerror=Xm,this[Qm]=void 0}static frame(e,t){let i,a=!1,l=2,h=!1;t.mask&&(i=t.maskBuffer||ey,t.generateMask?t.generateMask(i):(Ut===rn&&(bt===void 0&&(bt=Buffer.alloc(rn)),Jm(bt,0,rn),Ut=0),i[0]=bt[Ut++],i[1]=bt[Ut++],i[2]=bt[Ut++],i[3]=bt[Ut++]),h=(i[0]|i[1]|i[2]|i[3])===0,l=6);let p;typeof e=="string"?(!t.mask||h)&&t[Ie]!==void 0?p=t[Ie]:(e=Buffer.from(e),p=e.length):(p=e.length,a=t.mask&&t.readOnly&&!h);let g=p;p>=65536?(l+=8,g=127):p>125&&(l+=2,g=126);let m=Buffer.allocUnsafe(a?p+l:l);return m[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(m[0]|=64),m[1]=g,g===126?m.writeUInt16BE(p,2):g===127&&(m[2]=m[3]=0,m.writeUIntBE(p,4,6)),t.mask?(m[1]|=128,m[l-4]=i[0],m[l-3]=i[1],m[l-2]=i[2],m[l-1]=i[3],h?[m,e]:a?(wl(e,i,m,l,p),[m]):(wl(e,i,e,0,p),[m,e])):[m,e]}close(e,t,i,a){let l;if(e===void 0)l=Ym;else{if(typeof e!="number"||!Zm(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)l=Buffer.allocUnsafe(2),l.writeUInt16BE(e,0);else{let p=Buffer.byteLength(t);if(p>123)throw new RangeError("The message must not be greater than 123 bytes");l=Buffer.allocUnsafe(2+p),l.writeUInt16BE(e,0),typeof t=="string"?l.write(t,2):l.set(t,2)}}let h={[Ie]:l.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==qe?this.enqueue([this.dispatch,l,!1,h,a]):this.sendFrame(s.frame(l,h),a)}ping(e,t,i){let a,l;if(typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Dt(e)?(a=e.size,l=!1):(e=_t(e),a=e.length,l=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Ie]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:l,rsv1:!1};Dt(e)?this._state!==qe?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==qe?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}pong(e,t,i){let a,l;if(typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Dt(e)?(a=e.size,l=!1):(e=_t(e),a=e.length,l=_t.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Ie]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:l,rsv1:!1};Dt(e)?this._state!==qe?this.enqueue([this.getBlobData,e,!1,h,i]):this.getBlobData(e,!1,h,i):this._state!==qe?this.enqueue([this.dispatch,e,!1,h,i]):this.sendFrame(s.frame(e,h),i)}send(e,t,i){let a=this._extensions[vl.extensionName],l=t.binary?2:1,h=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):Dt(e)?(p=e.size,g=!1):(e=_t(e),p=e.length,g=_t.readOnly),this._firstFragment?(this._firstFragment=!1,h&&a&&a.params[a._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(h=p>=a._threshold),this._compress=h):(h=!1,l=0),t.fin&&(this._firstFragment=!0);let m={[Ie]:p,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:l,readOnly:g,rsv1:h};Dt(e)?this._state!==qe?this.enqueue([this.getBlobData,e,this._compress,m,i]):this.getBlobData(e,this._compress,m,i):this._state!==qe?this.enqueue([this.dispatch,e,this._compress,m,i]):this.dispatch(e,this._compress,m,i)}getBlobData(e,t,i,a){this._bufferedBytes+=i[Ie],this._state=sy,e.arrayBuffer().then(l=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(Xr,this,p,a);return}this._bufferedBytes-=i[Ie];let h=_t(l);t?this.dispatch(h,t,i,a):(this._state=qe,this.sendFrame(s.frame(h,i),a),this.dequeue())}).catch(l=>{process.nextTick(ny,this,l,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let l=this._extensions[vl.extensionName];this._bufferedBytes+=i[Ie],this._state=ty,l.compress(e,i.fin,(h,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");Xr(this,g,a);return}this._bufferedBytes-=i[Ie],this._state=qe,i.readOnly=!1,this.sendFrame(s.frame(p,i),a),this.dequeue()})}dequeue(){for(;this._state===qe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Cl.exports=Qr;function Xr(s,e,t){typeof t=="function"&&t(e);for(let i=0;i<s._queue.length;i++){let a=s._queue[i],l=a[a.length-1];typeof l=="function"&&l(e)}}function ny(s,e,t){Xr(s,e,t),s.onerror(e)}});var Il=$((iC,Pl)=>{"use strict";var{kForOnEventAttribute:gs,kListener:ei}=Ye(),El=Symbol("kCode"),kl=Symbol("kData"),Ol=Symbol("kError"),Sl=Symbol("kMessage"),Tl=Symbol("kReason"),qt=Symbol("kTarget"),Al=Symbol("kType"),Rl=Symbol("kWasClean"),Xe=class{constructor(e){this[qt]=null,this[Al]=e}get target(){return this[qt]}get type(){return this[Al]}};Object.defineProperty(Xe.prototype,"target",{enumerable:!0});Object.defineProperty(Xe.prototype,"type",{enumerable:!0});var vt=class extends Xe{constructor(e,t={}){super(e),this[El]=t.code===void 0?0:t.code,this[Tl]=t.reason===void 0?"":t.reason,this[Rl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[El]}get reason(){return this[Tl]}get wasClean(){return this[Rl]}};Object.defineProperty(vt.prototype,"code",{enumerable:!0});Object.defineProperty(vt.prototype,"reason",{enumerable:!0});Object.defineProperty(vt.prototype,"wasClean",{enumerable:!0});var Bt=class extends Xe{constructor(e,t={}){super(e),this[Ol]=t.error===void 0?null:t.error,this[Sl]=t.message===void 0?"":t.message}get error(){return this[Ol]}get message(){return this[Sl]}};Object.defineProperty(Bt.prototype,"error",{enumerable:!0});Object.defineProperty(Bt.prototype,"message",{enumerable:!0});var ms=class extends Xe{constructor(e,t={}){super(e),this[kl]=t.data===void 0?null:t.data}get data(){return this[kl]}};Object.defineProperty(ms.prototype,"data",{enumerable:!0});var ry={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[gs]&&a[ei]===e&&!a[gs])return;let i;if(s==="message")i=function(l,h){let p=new ms("message",{data:h?l:l.toString()});p[qt]=this,on(e,this,p)};else if(s==="close")i=function(l,h){let p=new vt("close",{code:l,reason:h.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[qt]=this,on(e,this,p)};else if(s==="error")i=function(l){let h=new Bt("error",{error:l,message:l.message});h[qt]=this,on(e,this,h)};else if(s==="open")i=function(){let l=new Xe("open");l[qt]=this,on(e,this,l)};else return;i[gs]=!!t[gs],i[ei]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[ei]===e&&!t[gs]){this.removeListener(s,t);break}}};Pl.exports={CloseEvent:vt,ErrorEvent:Bt,Event:Xe,EventTarget:ry,MessageEvent:ms};function on(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var ti=$((oC,Ml)=>{"use strict";var{tokenChars:ys}=jt();function He(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function iy(s){let e=Object.create(null),t=Object.create(null),i=!1,a=!1,l=!1,h,p,g=-1,m=-1,v=-1,C=0;for(;C<s.length;C++)if(m=s.charCodeAt(C),h===void 0)if(v===-1&&ys[m]===1)g===-1&&(g=C);else if(C!==0&&(m===32||m===9))v===-1&&g!==-1&&(v=C);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${C}`);v===-1&&(v=C);let S=s.slice(g,v);m===44?(He(e,S,t),t=Object.create(null)):h=S,g=v=-1}else throw new SyntaxError(`Unexpected character at index ${C}`);else if(p===void 0)if(v===-1&&ys[m]===1)g===-1&&(g=C);else if(m===32||m===9)v===-1&&g!==-1&&(v=C);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${C}`);v===-1&&(v=C),He(t,s.slice(g,v),!0),m===44&&(He(e,h,t),t=Object.create(null),h=void 0),g=v=-1}else if(m===61&&g!==-1&&v===-1)p=s.slice(g,C),g=v=-1;else throw new SyntaxError(`Unexpected character at index ${C}`);else if(a){if(ys[m]!==1)throw new SyntaxError(`Unexpected character at index ${C}`);g===-1?g=C:i||(i=!0),a=!1}else if(l)if(ys[m]===1)g===-1&&(g=C);else if(m===34&&g!==-1)l=!1,v=C;else if(m===92)a=!0;else throw new SyntaxError(`Unexpected character at index ${C}`);else if(m===34&&s.charCodeAt(C-1)===61)l=!0;else if(v===-1&&ys[m]===1)g===-1&&(g=C);else if(g!==-1&&(m===32||m===9))v===-1&&(v=C);else if(m===59||m===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${C}`);v===-1&&(v=C);let S=s.slice(g,v);i&&(S=S.replace(/\\/g,""),i=!1),He(t,p,S),m===44&&(He(e,h,t),t=Object.create(null),h=void 0),p=void 0,g=v=-1}else throw new SyntaxError(`Unexpected character at index ${C}`);if(g===-1||l||m===32||m===9)throw new SyntaxError("Unexpected end of input");v===-1&&(v=C);let k=s.slice(g,v);return h===void 0?He(e,k,t):(p===void 0?He(t,k,!0):i?He(t,p,k.replace(/\\/g,"")):He(t,p,k),He(e,h,t)),e}function oy(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(a=>{let l=i[a];return Array.isArray(l)||(l=[l]),l.map(h=>h===!0?a:`${a}=${h}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ml.exports={format:oy,parse:iy}});var un=$((lC,Fl)=>{"use strict";var ay=q("events"),cy=q("https"),ly=q("http"),Ll=q("net"),uy=q("tls"),{randomBytes:hy,createHash:dy}=q("crypto"),{Duplex:aC,Readable:cC}=q("stream"),{URL:si}=q("url"),ut=ps(),fy=Yr(),py=Zr(),{isBlob:gy}=jt(),{BINARY_TYPES:xl,CLOSE_TIMEOUT:my,EMPTY_BUFFER:an,GUID:yy,kForOnEventAttribute:ni,kListener:_y,kStatusCode:by,kWebSocket:de,NOOP:jl}=Ye(),{EventTarget:{addEventListener:vy,removeEventListener:wy}}=Il(),{format:Cy,parse:Ey}=ti(),{toBuffer:ky}=ds(),Dl=Symbol("kAborted"),ri=[8,13],Ze=["CONNECTING","OPEN","CLOSING","CLOSED"],Oy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class s extends ay{constructor(e,t,i){super(),this._binaryType=xl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=an,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(i=t,t=[]):t=[t]),Ul(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,i){let a=new fy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),l=new py(e,this._extensions,i.generateMask);this._receiver=a,this._sender=l,this._socket=e,a[de]=this,l[de]=this,e[de]=this,a.on("conclude",Ay),a.on("drain",Ry),a.on("error",Py),a.on("message",Iy),a.on("ping",My),a.on("pong",xy),l.onerror=Ny,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",$l),e.on("data",ln),e.on("end",Hl),e.on("error",Gl),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ut.extensionName]&&this._extensions[ut.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Bl(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||an,t,i)}pong(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ii(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||an,t,i)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ii(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ut.extensionName]||(a.compress=!1),this._sender.send(e||an,a,i)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Ze.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Ze.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Ze.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(re.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(re.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[ni])return e[_y];return null},set(e){for(let t of this.listeners(s))if(t[ni]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[ni]:!0})}})});re.prototype.addEventListener=vy;re.prototype.removeEventListener=wy;Fl.exports=re;function Ul(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:my,protocolVersion:ri[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=a.autoPong,s._closeTimeout=a.closeTimeout,!ri.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${ri.join(", ")})`);let l;if(e instanceof si)l=e;else try{l=new si(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}l.protocol==="http:"?l.protocol="ws:":l.protocol==="https:"&&(l.protocol="wss:"),s._url=l.href;let h=l.protocol==="wss:",p=l.protocol==="ws+unix:",g;if(l.protocol!=="ws:"&&!h&&!p?g=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?g="The URL's pathname is empty":l.hash&&(g="The URL contains a fragment identifier"),g){let E=new SyntaxError(g);if(s._redirects===0)throw E;cn(s,E);return}let m=h?443:80,v=hy(16).toString("base64"),C=h?cy.request:ly.request,k=new Set,S;if(a.createConnection=a.createConnection||(h?Ty:Sy),a.defaultPort=a.defaultPort||m,a.port=l.port||m,a.host=l.hostname.startsWith("[")?l.hostname.slice(1,-1):l.hostname,a.headers={...a.headers,"Sec-WebSocket-Version":a.protocolVersion,"Sec-WebSocket-Key":v,Connection:"Upgrade",Upgrade:"websocket"},a.path=l.pathname+l.search,a.timeout=a.handshakeTimeout,a.perMessageDeflate&&(S=new ut(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=Cy({[ut.extensionName]:S.offer()})),t.length){for(let E of t){if(typeof E!="string"||!Oy.test(E)||k.has(E))throw new SyntaxError("An invalid or duplicated subprotocol was specified");k.add(E)}a.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(a.origin&&(a.protocolVersion<13?a.headers["Sec-WebSocket-Origin"]=a.origin:a.headers.Origin=a.origin),(l.username||l.password)&&(a.auth=`${l.username}:${l.password}`),p){let E=a.path.split(":");a.socketPath=E[0],a.path=E[1]}let A;if(a.followRedirects){if(s._redirects===0){s._originalIpc=p,s._originalSecure=h,s._originalHostOrSocketPath=p?a.socketPath:l.host;let E=i&&i.headers;if(i={...i,headers:{}},E)for(let[O,N]of Object.entries(E))i.headers[O.toLowerCase()]=N}else if(s.listenerCount("redirect")===0){let E=p?s._originalIpc?a.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:l.host===s._originalHostOrSocketPath;(!E||s._originalSecure&&!h)&&(delete a.headers.authorization,delete a.headers.cookie,E||delete a.headers.host,a.auth=void 0)}a.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(a.auth).toString("base64")),A=s._req=C(a),s._redirects&&s.emit("redirect",s.url,A)}else A=s._req=C(a);a.timeout&&A.on("timeout",()=>{Se(s,A,"Opening handshake has timed out")}),A.on("error",E=>{A===null||A[Dl]||(A=s._req=null,cn(s,E))}),A.on("response",E=>{let O=E.headers.location,N=E.statusCode;if(O&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Se(s,A,"Maximum redirects exceeded");return}A.abort();let H;try{H=new si(O,e)}catch{let se=new SyntaxError(`Invalid URL: ${O}`);cn(s,se);return}Ul(s,H,t,i)}else s.emit("unexpected-response",A,E)||Se(s,A,`Unexpected server response: ${E.statusCode}`)}),A.on("upgrade",(E,O,N)=>{if(s.emit("upgrade",E),s.readyState!==re.CONNECTING)return;A=s._req=null;let H=E.headers.upgrade;if(H===void 0||H.toLowerCase()!=="websocket"){Se(s,O,"Invalid Upgrade header");return}let K=dy("sha1").update(v+yy).digest("base64");if(E.headers["sec-websocket-accept"]!==K){Se(s,O,"Invalid Sec-WebSocket-Accept header");return}let se=E.headers["sec-websocket-protocol"],Z;if(se!==void 0?k.size?k.has(se)||(Z="Server sent an invalid subprotocol"):Z="Server sent a subprotocol but none was requested":k.size&&(Z="Server sent no subprotocol"),Z){Se(s,O,Z);return}se&&(s._protocol=se);let Te=E.headers["sec-websocket-extensions"];if(Te!==void 0){if(!S){Se(s,O,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Le;try{Le=Ey(Te)}catch{Se(s,O,"Invalid Sec-WebSocket-Extensions header");return}let ot=Object.keys(Le);if(ot.length!==1||ot[0]!==ut.extensionName){Se(s,O,"Server indicated an extension that was not requested");return}try{S.accept(Le[ut.extensionName])}catch{Se(s,O,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ut.extensionName]=S}s.setSocket(O,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(A,s):A.end()}function cn(s,e){s._readyState=re.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function Sy(s){return s.path=s.socketPath,Ll.connect(s)}function Ty(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Ll.isIP(s.host)?"":s.host),uy.connect(s)}function Se(s,e,t){s._readyState=re.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Se),e.setHeader?(e[Dl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(cn,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ii(s,e,t){if(e){let i=gy(e)?e.size:ky(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${Ze[s.readyState]})`);process.nextTick(t,i)}}function Ay(s,e){let t=this[de];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[de]!==void 0&&(t._socket.removeListener("data",ln),process.nextTick(ql,t._socket),s===1005?t.close():t.close(s,e))}function Ry(){let s=this[de];s.isPaused||s._socket.resume()}function Py(s){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",ln),process.nextTick(ql,e._socket),e.close(s[by])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function Nl(){this[de].emitClose()}function Iy(s,e){this[de].emit("message",s,e)}function My(s){let e=this[de];e._autoPong&&e.pong(s,!this._isServer,jl),e.emit("ping",s)}function xy(s){this[de].emit("pong",s)}function ql(s){s.resume()}function Ny(s){let e=this[de];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Bl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Bl(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function $l(){let s=this[de];if(this.removeListener("close",$l),this.removeListener("data",ln),this.removeListener("end",Hl),s._readyState=re.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[de]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Nl),s._receiver.on("finish",Nl))}function ln(s){this[de]._receiver.write(s)||this.pause()}function Hl(){let s=this[de];s._readyState=re.CLOSING,s._receiver.end(),this.end()}function Gl(){let s=this[de];this.removeListener("error",Gl),this.on("error",jl),s&&(s._readyState=re.CLOSING,this.destroy())}});var Kl=$((hC,zl)=>{"use strict";var uC=un(),{Duplex:Ly}=q("stream");function Wl(s){s.emit("close")}function jy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(s){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function Dy(s,e){let t=!0,i=new Ly({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",function(l,h){let p=!h&&i._readableState.objectMode?l.toString():l;i.push(p)||s.pause()}),s.once("error",function(l){i.destroyed||(t=!1,i.destroy(l))}),s.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(a,l){if(s.readyState===s.CLOSED){l(a),process.nextTick(Wl,i);return}let h=!1;s.once("error",function(g){h=!0,l(g)}),s.once("close",function(){h||l(a),process.nextTick(Wl,i)}),t&&s.terminate()},i._final=function(a){if(s.readyState===s.CONNECTING){s.once("open",function(){i._final(a)});return}s._socket!==null&&(s._socket._writableState.finished?(a(),i._readableState.endEmitted&&i.destroy()):(s._socket.once("finish",function(){a()}),s.close()))},i._read=function(){s.isPaused&&s.resume()},i._write=function(a,l,h){if(s.readyState===s.CONNECTING){s.once("open",function(){i._write(a,l,h)});return}s.send(a,h)},i.on("end",jy),i.on("error",Vl),i}zl.exports=Dy});var Yl=$((dC,Jl)=>{"use strict";var{tokenChars:Uy}=jt();function qy(s){let e=new Set,t=-1,i=-1,a=0;for(a;a<s.length;a++){let h=s.charCodeAt(a);if(i===-1&&Uy[h]===1)t===-1&&(t=a);else if(a!==0&&(h===32||h===9))i===-1&&t!==-1&&(i=a);else if(h===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let p=s.slice(t,i);if(e.has(p))throw new SyntaxError(`The "${p}" subprotocol is duplicated`);e.add(p),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${a}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let l=s.slice(t,a);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);return e.add(l),e}Jl.exports={parse:qy}});var nu=$((pC,su)=>{"use strict";var By=q("events"),hn=q("http"),{Duplex:fC}=q("stream"),{createHash:$y}=q("crypto"),Ql=ti(),wt=ps(),Hy=Yl(),Gy=un(),{CLOSE_TIMEOUT:Fy,GUID:Wy,kWebSocket:Vy}=Ye(),zy=/^[+/0-9A-Za-z]{22}==$/,Xl=0,Zl=1,tu=2,oi=class extends By{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Fy,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Gy,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=hn.createServer((i,a)=>{let l=hn.STATUS_CODES[426];a.writeHead(426,{"Content-Length":l.length,"Content-Type":"text/plain"}),a.end(l)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=Ky(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(a,l,h)=>{this.handleUpgrade(a,l,h,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Xl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===tu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(_s,this);return}if(e&&this.once("close",e),this._state!==Zl)if(this._state=Zl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(_s,this):process.nextTick(_s,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{_s(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,i,a){t.on("error",eu);let l=e.headers["sec-websocket-key"],h=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ct(this,e,t,405,"Invalid HTTP method");return}if(h===void 0||h.toLowerCase()!=="websocket"){Ct(this,e,t,400,"Invalid Upgrade header");return}if(l===void 0||!zy.test(l)){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(p!==13&&p!==8){Ct(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){bs(t,400);return}let g=e.headers["sec-websocket-protocol"],m=new Set;if(g!==void 0)try{m=Hy.parse(g)}catch{Ct(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let v=e.headers["sec-websocket-extensions"],C={};if(this.options.perMessageDeflate&&v!==void 0){let k=new wt(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let S=Ql.parse(v);S[wt.extensionName]&&(k.accept(S[wt.extensionName]),C[wt.extensionName]=k)}catch{Ct(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let k={origin:e.headers[`${p===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(k,(S,A,E,O)=>{if(!S)return bs(t,A||401,E,O);this.completeUpgrade(C,l,m,e,t,i,a)});return}if(!this.options.verifyClient(k))return bs(t,401)}this.completeUpgrade(C,l,m,e,t,i,a)}completeUpgrade(e,t,i,a,l,h,p){if(!l.readable||!l.writable)return l.destroy();if(l[Vy])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xl)return bs(l,503);let m=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$y("sha1").update(t+Wy).digest("base64")}`],v=new this.options.WebSocket(null,void 0,this.options);if(i.size){let C=this.options.handleProtocols?this.options.handleProtocols(i,a):i.values().next().value;C&&(m.push(`Sec-WebSocket-Protocol: ${C}`),v._protocol=C)}if(e[wt.extensionName]){let C=e[wt.extensionName].params,k=Ql.format({[wt.extensionName]:[C]});m.push(`Sec-WebSocket-Extensions: ${k}`),v._extensions=e}this.emit("headers",m,a),l.write(m.concat(`\r
|
|
28
28
|
`).join(`\r
|
|
29
|
-
`)),l.removeListener("error",
|
|
29
|
+
`)),l.removeListener("error",eu),v.setSocket(l,h,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(v),v.on("close",()=>{this.clients.delete(v),this._shouldEmitClose&&!this.clients.size&&process.nextTick(_s,this)})),p(v,a)}};su.exports=oi;function Ky(s,e){for(let t of Object.keys(e))s.on(t,e[t]);return function(){for(let i of Object.keys(e))s.removeListener(i,e[i])}}function _s(s){s._state=tu,s.emit("close")}function eu(){this.destroy()}function bs(s,e,t,i){t=t||hn.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...i},s.once("finish",s.destroy),s.end(`HTTP/1.1 ${e} ${hn.STATUS_CODES[e]}\r
|
|
30
30
|
`+Object.keys(i).map(a=>`${a}: ${i[a]}`).join(`\r
|
|
31
31
|
`)+`\r
|
|
32
32
|
\r
|
|
33
|
-
`+t)}function Ct(s,e,t,i,a,l){if(s.listenerCount("wsClientError")){let h=new Error(a);Error.captureStackTrace(h,Ct),s.emit("wsClientError",h,t,e)}else bs(t,i,a,l)}});var dn=$((uC,nu)=>{"use strict";var et=un();et.createWebSocketStream=zl();et.Server=su();et.Receiver=Yr();et.Sender=Zr();et.WebSocket=et;et.WebSocketServer=et.Server;nu.exports=et});var st=$((tt,fn)=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});var ru=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Fy(s){return ru.includes(s)}var Wy=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Blob","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","FormData","URLSearchParams","HTMLElement",...ru];function Vy(s){return Wy.includes(s)}var zy=["null","undefined","string","number","bigint","boolean","symbol"];function Ky(s){return zy.includes(s)}function $t(s){return e=>typeof e===s}var{toString:iu}=Object.prototype,vs=s=>{let e=iu.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&b.domElement(s))return"HTMLElement";if(Vy(e))return e},te=s=>e=>vs(e)===s;function b(s){if(s===null)return"null";switch(typeof s){case"undefined":return"undefined";case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"function":return"Function";case"bigint":return"bigint";case"symbol":return"symbol";default:}if(b.observable(s))return"Observable";if(b.array(s))return"Array";if(b.buffer(s))return"Buffer";let e=vs(s);if(e)return e;if(s instanceof String||s instanceof Boolean||s instanceof Number)throw new TypeError("Please don't use object wrappers for primitive types");return"Object"}b.undefined=$t("undefined");b.string=$t("string");var Jy=$t("number");b.number=s=>Jy(s)&&!b.nan(s);b.bigint=$t("bigint");b.function_=$t("function");b.null_=s=>s===null;b.class_=s=>b.function_(s)&&s.toString().startsWith("class ");b.boolean=s=>s===!0||s===!1;b.symbol=$t("symbol");b.numericString=s=>b.string(s)&&!b.emptyStringOrWhitespace(s)&&!Number.isNaN(Number(s));b.array=(s,e)=>Array.isArray(s)?b.function_(e)?s.every(e):!0:!1;b.buffer=s=>{var e,t,i,a;return(a=(i=(t=(e=s)===null||e===void 0?void 0:e.constructor)===null||t===void 0?void 0:t.isBuffer)===null||i===void 0?void 0:i.call(t,s))!==null&&a!==void 0?a:!1};b.blob=s=>te("Blob")(s);b.nullOrUndefined=s=>b.null_(s)||b.undefined(s);b.object=s=>!b.null_(s)&&(typeof s=="object"||b.function_(s));b.iterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.iterator])};b.asyncIterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.asyncIterator])};b.generator=s=>{var e,t;return b.iterable(s)&&b.function_((e=s)===null||e===void 0?void 0:e.next)&&b.function_((t=s)===null||t===void 0?void 0:t.throw)};b.asyncGenerator=s=>b.asyncIterable(s)&&b.function_(s.next)&&b.function_(s.throw);b.nativePromise=s=>te("Promise")(s);var Yy=s=>{var e,t;return b.function_((e=s)===null||e===void 0?void 0:e.then)&&b.function_((t=s)===null||t===void 0?void 0:t.catch)};b.promise=s=>b.nativePromise(s)||Yy(s);b.generatorFunction=te("GeneratorFunction");b.asyncGeneratorFunction=s=>vs(s)==="AsyncGeneratorFunction";b.asyncFunction=s=>vs(s)==="AsyncFunction";b.boundFunction=s=>b.function_(s)&&!s.hasOwnProperty("prototype");b.regExp=te("RegExp");b.date=te("Date");b.error=te("Error");b.map=s=>te("Map")(s);b.set=s=>te("Set")(s);b.weakMap=s=>te("WeakMap")(s);b.weakSet=s=>te("WeakSet")(s);b.int8Array=te("Int8Array");b.uint8Array=te("Uint8Array");b.uint8ClampedArray=te("Uint8ClampedArray");b.int16Array=te("Int16Array");b.uint16Array=te("Uint16Array");b.int32Array=te("Int32Array");b.uint32Array=te("Uint32Array");b.float32Array=te("Float32Array");b.float64Array=te("Float64Array");b.bigInt64Array=te("BigInt64Array");b.bigUint64Array=te("BigUint64Array");b.arrayBuffer=te("ArrayBuffer");b.sharedArrayBuffer=te("SharedArrayBuffer");b.dataView=te("DataView");b.enumCase=(s,e)=>Object.values(e).includes(s);b.directInstanceOf=(s,e)=>Object.getPrototypeOf(s)===e.prototype;b.urlInstance=s=>te("URL")(s);b.urlString=s=>{if(!b.string(s))return!1;try{return new URL(s),!0}catch{return!1}};b.truthy=s=>!!s;b.falsy=s=>!s;b.nan=s=>Number.isNaN(s);b.primitive=s=>b.null_(s)||Ky(typeof s);b.integer=s=>Number.isInteger(s);b.safeInteger=s=>Number.isSafeInteger(s);b.plainObject=s=>{if(iu.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};b.typedArray=s=>Fy(vs(s));var Qy=s=>b.safeInteger(s)&&s>=0;b.arrayLike=s=>!b.nullOrUndefined(s)&&!b.function_(s)&&Qy(s.length);b.inRange=(s,e)=>{if(b.number(e))return s>=Math.min(0,e)&&s<=Math.max(e,0);if(b.array(e)&&e.length===2)return s>=Math.min(...e)&&s<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var Xy=1,Zy=["innerHTML","ownerDocument","style","attributes","nodeValue"];b.domElement=s=>b.object(s)&&s.nodeType===Xy&&b.string(s.nodeName)&&!b.plainObject(s)&&Zy.every(e=>e in s);b.observable=s=>{var e,t,i,a;return s?s===((t=(e=s)[Symbol.observable])===null||t===void 0?void 0:t.call(e))||s===((a=(i=s)["@@observable"])===null||a===void 0?void 0:a.call(i)):!1};b.nodeStream=s=>b.object(s)&&b.function_(s.pipe)&&!b.observable(s);b.infinite=s=>s===1/0||s===-1/0;var ou=s=>e=>b.integer(e)&&Math.abs(e%2)===s;b.evenInteger=ou(0);b.oddInteger=ou(1);b.emptyArray=s=>b.array(s)&&s.length===0;b.nonEmptyArray=s=>b.array(s)&&s.length>0;b.emptyString=s=>b.string(s)&&s.length===0;var e_=s=>b.string(s)&&!/\S/.test(s);b.emptyStringOrWhitespace=s=>b.emptyString(s)||e_(s);b.nonEmptyString=s=>b.string(s)&&s.length>0;b.nonEmptyStringAndNotWhitespace=s=>b.string(s)&&!b.emptyStringOrWhitespace(s);b.emptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length===0;b.nonEmptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length>0;b.emptySet=s=>b.set(s)&&s.size===0;b.nonEmptySet=s=>b.set(s)&&s.size>0;b.emptyMap=s=>b.map(s)&&s.size===0;b.nonEmptyMap=s=>b.map(s)&&s.size>0;b.propertyKey=s=>b.any([b.string,b.number,b.symbol],s);b.formData=s=>te("FormData")(s);b.urlSearchParams=s=>te("URLSearchParams")(s);var au=(s,e,t)=>{if(!b.function_(e))throw new TypeError(`Invalid predicate: ${JSON.stringify(e)}`);if(t.length===0)throw new TypeError("Invalid number of values");return s.call(t,e)};b.any=(s,...e)=>(b.array(s)?s:[s]).some(i=>au(Array.prototype.some,i,e));b.all=(s,...e)=>au(Array.prototype.every,s,e);var B=(s,e,t,i={})=>{if(!s){let{multipleValues:a}=i,l=a?`received values of types ${[...new Set(t.map(h=>`\`${b(h)}\``))].join(", ")}`:`received value of type \`${b(t)}\``;throw new TypeError(`Expected value which is \`${e}\`, ${l}.`)}};tt.assert={undefined:s=>B(b.undefined(s),"undefined",s),string:s=>B(b.string(s),"string",s),number:s=>B(b.number(s),"number",s),bigint:s=>B(b.bigint(s),"bigint",s),function_:s=>B(b.function_(s),"Function",s),null_:s=>B(b.null_(s),"null",s),class_:s=>B(b.class_(s),"Class",s),boolean:s=>B(b.boolean(s),"boolean",s),symbol:s=>B(b.symbol(s),"symbol",s),numericString:s=>B(b.numericString(s),"string with a number",s),array:(s,e)=>{B(b.array(s),"Array",s),e&&s.forEach(e)},buffer:s=>B(b.buffer(s),"Buffer",s),blob:s=>B(b.blob(s),"Blob",s),nullOrUndefined:s=>B(b.nullOrUndefined(s),"null or undefined",s),object:s=>B(b.object(s),"Object",s),iterable:s=>B(b.iterable(s),"Iterable",s),asyncIterable:s=>B(b.asyncIterable(s),"AsyncIterable",s),generator:s=>B(b.generator(s),"Generator",s),asyncGenerator:s=>B(b.asyncGenerator(s),"AsyncGenerator",s),nativePromise:s=>B(b.nativePromise(s),"native Promise",s),promise:s=>B(b.promise(s),"Promise",s),generatorFunction:s=>B(b.generatorFunction(s),"GeneratorFunction",s),asyncGeneratorFunction:s=>B(b.asyncGeneratorFunction(s),"AsyncGeneratorFunction",s),asyncFunction:s=>B(b.asyncFunction(s),"AsyncFunction",s),boundFunction:s=>B(b.boundFunction(s),"Function",s),regExp:s=>B(b.regExp(s),"RegExp",s),date:s=>B(b.date(s),"Date",s),error:s=>B(b.error(s),"Error",s),map:s=>B(b.map(s),"Map",s),set:s=>B(b.set(s),"Set",s),weakMap:s=>B(b.weakMap(s),"WeakMap",s),weakSet:s=>B(b.weakSet(s),"WeakSet",s),int8Array:s=>B(b.int8Array(s),"Int8Array",s),uint8Array:s=>B(b.uint8Array(s),"Uint8Array",s),uint8ClampedArray:s=>B(b.uint8ClampedArray(s),"Uint8ClampedArray",s),int16Array:s=>B(b.int16Array(s),"Int16Array",s),uint16Array:s=>B(b.uint16Array(s),"Uint16Array",s),int32Array:s=>B(b.int32Array(s),"Int32Array",s),uint32Array:s=>B(b.uint32Array(s),"Uint32Array",s),float32Array:s=>B(b.float32Array(s),"Float32Array",s),float64Array:s=>B(b.float64Array(s),"Float64Array",s),bigInt64Array:s=>B(b.bigInt64Array(s),"BigInt64Array",s),bigUint64Array:s=>B(b.bigUint64Array(s),"BigUint64Array",s),arrayBuffer:s=>B(b.arrayBuffer(s),"ArrayBuffer",s),sharedArrayBuffer:s=>B(b.sharedArrayBuffer(s),"SharedArrayBuffer",s),dataView:s=>B(b.dataView(s),"DataView",s),enumCase:(s,e)=>B(b.enumCase(s,e),"EnumCase",s),urlInstance:s=>B(b.urlInstance(s),"URL",s),urlString:s=>B(b.urlString(s),"string with a URL",s),truthy:s=>B(b.truthy(s),"truthy",s),falsy:s=>B(b.falsy(s),"falsy",s),nan:s=>B(b.nan(s),"NaN",s),primitive:s=>B(b.primitive(s),"primitive",s),integer:s=>B(b.integer(s),"integer",s),safeInteger:s=>B(b.safeInteger(s),"integer",s),plainObject:s=>B(b.plainObject(s),"plain object",s),typedArray:s=>B(b.typedArray(s),"TypedArray",s),arrayLike:s=>B(b.arrayLike(s),"array-like",s),domElement:s=>B(b.domElement(s),"HTMLElement",s),observable:s=>B(b.observable(s),"Observable",s),nodeStream:s=>B(b.nodeStream(s),"Node.js Stream",s),infinite:s=>B(b.infinite(s),"infinite number",s),emptyArray:s=>B(b.emptyArray(s),"empty array",s),nonEmptyArray:s=>B(b.nonEmptyArray(s),"non-empty array",s),emptyString:s=>B(b.emptyString(s),"empty string",s),emptyStringOrWhitespace:s=>B(b.emptyStringOrWhitespace(s),"empty string or whitespace",s),nonEmptyString:s=>B(b.nonEmptyString(s),"non-empty string",s),nonEmptyStringAndNotWhitespace:s=>B(b.nonEmptyStringAndNotWhitespace(s),"non-empty string and not whitespace",s),emptyObject:s=>B(b.emptyObject(s),"empty object",s),nonEmptyObject:s=>B(b.nonEmptyObject(s),"non-empty object",s),emptySet:s=>B(b.emptySet(s),"empty set",s),nonEmptySet:s=>B(b.nonEmptySet(s),"non-empty set",s),emptyMap:s=>B(b.emptyMap(s),"empty map",s),nonEmptyMap:s=>B(b.nonEmptyMap(s),"non-empty map",s),propertyKey:s=>B(b.propertyKey(s),"PropertyKey",s),formData:s=>B(b.formData(s),"FormData",s),urlSearchParams:s=>B(b.urlSearchParams(s),"URLSearchParams",s),evenInteger:s=>B(b.evenInteger(s),"even integer",s),oddInteger:s=>B(b.oddInteger(s),"odd integer",s),directInstanceOf:(s,e)=>B(b.directInstanceOf(s,e),"T",s),inRange:(s,e)=>B(b.inRange(s,e),"in range",s),any:(s,...e)=>B(b.any(s,...e),"predicate returns truthy for any value",e,{multipleValues:!0}),all:(s,...e)=>B(b.all(s,...e),"predicate returns truthy for all values",e,{multipleValues:!0})};Object.defineProperties(b,{class:{value:b.class_},function:{value:b.function_},null:{value:b.null_}});Object.defineProperties(tt.assert,{class:{value:tt.assert.class_},function:{value:tt.assert.function_},null:{value:tt.assert.null_}});tt.default=b;fn.exports=b;fn.exports.default=b;fn.exports.assert=tt.assert});var cu=$((hC,ai)=>{"use strict";var pn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},gn=class s{static fn(e){return(...t)=>new s((i,a,l)=>{t.push(l),e(...t).then(i,a)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((t,i)=>{this._reject=i;let a=p=>{(!this._isCanceled||!h.shouldReject)&&(this._isPending=!1,t(p))},l=p=>{this._isPending=!1,i(p)},h=p=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(p)};return Object.defineProperties(h,{shouldReject:{get:()=>this._rejectOnCancel,set:p=>{this._rejectOnCancel=p}}}),e(a,l,h)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let t of this._cancelHandlers)t()}catch(t){this._reject(t);return}this._rejectOnCancel&&this._reject(new pn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(gn.prototype,Promise.prototype);ai.exports=gn;ai.exports.CancelError=pn});var lu=$((li,ui)=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});function t_(s){return s.encrypted}var ci=(s,e)=>{let t;typeof e=="function"?t={connect:e}:t=e;let i=typeof t.connect=="function",a=typeof t.secureConnect=="function",l=typeof t.close=="function",h=()=>{i&&t.connect(),t_(s)&&a&&(s.authorized?t.secureConnect():s.authorizationError||s.once("secureConnect",t.secureConnect)),l&&s.once("close",t.close)};s.writable&&!s.connecting?h():s.connecting?s.once("connect",h):s.destroyed&&l&&t.close(s._hadError)};li.default=ci;ui.exports=ci;ui.exports.default=ci});var uu=$((di,fi)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var s_=lu(),n_=D("util"),r_=Number(process.versions.node.split(".")[0]),hi=s=>{if(s.timings)return s.timings;let e={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};s.timings=e;let t=p=>{let g=p.emit.bind(p);p.emit=(y,...C)=>(y==="error"&&(e.error=Date.now(),e.phases.total=e.error-e.start,p.emit=g),g(y,...C))};t(s);let i=()=>{e.abort=Date.now(),(!e.response||r_>=13)&&(e.phases.total=Date.now()-e.start)};s.prependOnceListener("abort",i);let a=p=>{if(e.socket=Date.now(),e.phases.wait=e.socket-e.start,n_.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),s_.default(p,{connect:()=>{e.connect=Date.now(),e.lookup===void 0&&(p.removeListener("lookup",g),e.lookup=e.connect,e.phases.dns=e.lookup-e.socket),e.phases.tcp=e.connect-e.lookup},secureConnect:()=>{e.secureConnect=Date.now(),e.phases.tls=e.secureConnect-e.connect}})};s.socket?a(s.socket):s.prependOnceListener("socket",a);let l=()=>{var p;e.upload=Date.now(),e.phases.request=e.upload-((p=e.secureConnect)!==null&&p!==void 0?p:e.connect)};return(typeof s.writableFinished=="boolean"?s.writableFinished:s.finished&&s.outputSize===0&&(!s.socket||s.socket.writableLength===0))?l():s.prependOnceListener("finish",l),s.prependOnceListener("response",p=>{e.response=Date.now(),e.phases.firstByte=e.response-e.upload,p.timings=e,t(p),p.prependOnceListener("end",()=>{e.end=Date.now(),e.phases.download=e.end-e.response,e.phases.total=e.end-e.start}),p.prependOnceListener("aborted",i)}),e};di.default=hi;fi.exports=hi;fi.exports.default=hi});var yu=$((dC,mi)=>{"use strict";var{V4MAPPED:i_,ADDRCONFIG:o_,ALL:mu,promises:{Resolver:hu},lookup:a_}=D("dns"),{promisify:pi}=D("util"),c_=D("os"),Ht=Symbol("cacheableLookupCreateConnection"),gi=Symbol("cacheableLookupInstance"),du=Symbol("expires"),l_=typeof mu=="number",fu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},u_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},pu=()=>{let s=!1,e=!1;for(let t of Object.values(c_.networkInterfaces()))for(let i of t)if(!i.internal&&(i.family==="IPv6"?e=!0:s=!0,s&&e))return{has4:s,has6:e};return{has4:s,has6:e}},h_=s=>Symbol.iterator in s,gu={ttl:!0},d_={all:!0},mn=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:l=new hu,lookup:h=a_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=l,this._dnsLookup=pi(h),this._resolver instanceof hu?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=pi(this._resolver.resolve4.bind(this._resolver)),this._resolve6=pi(this._resolver.resolve6.bind(this._resolver))),this._iface=pu(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,i<1)this._fallback=!1;else{this._fallback=!0;let p=setInterval(()=>{this._hostnamesToFallback.clear()},i*1e3);p.unref&&p.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,t,i){if(typeof t=="function"?(i=t,t={}):typeof t=="number"&&(t={family:t}),!i)throw new Error("Callback must be a function.");this.lookupAsync(e,t).then(a=>{t.all?i(null,a):i(null,a.address,a.family,a.expires,a.ttl)},i)}async lookupAsync(e,t={}){typeof t=="number"&&(t={family:t});let i=await this.query(e);if(t.family===6){let a=i.filter(l=>l.family===6);t.hints&i_&&(l_&&t.hints&mu||a.length===0)?u_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&o_){let{_iface:a}=this;i=i.filter(l=>l.family===6?a.has6:a.has4)}if(i.length===0){let a=new Error(`cacheableLookup ENOTFOUND ${e}`);throw a.code="ENOTFOUND",a.hostname=e,a}return t.all?i:i[0]}async query(e){let t=await this._cache.get(e);if(!t){let i=this._pending[e];if(i)t=await i;else{let a=this.queryAndCache(e);this._pending[e]=a;try{t=await a}finally{delete this._pending[e]}}}return t=t.map(i=>({...i})),t}async _resolve(e){let t=async y=>{try{return await y}catch(C){if(C.code==="ENODATA"||C.code==="ENOTFOUND")return[];throw C}},[i,a]=await Promise.all([this._resolve4(e,gu),this._resolve6(e,gu)].map(y=>t(y))),l=0,h=0,p=0,g=Date.now();for(let y of i)y.family=4,y.expires=g+y.ttl*1e3,l=Math.max(l,y.ttl);for(let y of a)y.family=6,y.expires=g+y.ttl*1e3,h=Math.max(h,y.ttl);return i.length>0?a.length>0?p=Math.min(l,h):p=l:p=h,{entries:[...i,...a],cacheTtl:p}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,t,i){if(this.maxTtl>0&&i>0){i=Math.min(i,this.maxTtl)*1e3,t[du]=Date.now()+i;try{await this._cache.set(e,t,i)}catch(a){this.lookupAsync=async()=>{let l=new Error("Cache Error. Please recreate the CacheableLookup instance.");throw l.cause=a,l}}h_(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,d_);let t=await this._resolve(e);t.entries.length===0&&this._fallback&&(t=await this._lookup(e),t.entries.length!==0&&this._hostnamesToFallback.add(e));let i=t.entries.length===0?this.errorTtl:t.cacheTtl;return await this._set(e,t.entries,i),t.entries}_tick(e){let t=this._nextRemovalTime;(!t||e<t)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let i=1/0,a=Date.now();for(let[l,h]of this._cache){let p=h[du];a>=p?this._cache.delete(l):p<i&&(i=p)}i!==1/0&&this._tick(i-a)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(fu(e),Ht in e)throw new Error("CacheableLookup has been already installed");e[Ht]=e.createConnection,e[gi]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Ht](t,i))}uninstall(e){if(fu(e),e[Ht]){if(e[gi]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Ht],delete e[Ht],delete e[gi]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=pu(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){if(e){this._cache.delete(e);return}this._cache.clear()}};mi.exports=mn;mi.exports.default=mn});var vu=$((fC,bu)=>{"use strict";var f_="text/plain",p_="us-ascii",_u=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),g_=(s,{stripHash:e})=>{let t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(s);if(!t)throw new Error(`Invalid URL: ${s}`);let{type:i,data:a,hash:l}=t.groups,h=i.split(";");l=e?"":l;let p=!1;h[h.length-1]==="base64"&&(h.pop(),p=!0);let g=(h.shift()||"").toLowerCase(),C=[...h.map(v=>{let[O,k=""]=v.split("=").map(T=>T.trim());return O==="charset"&&(k=k.toLowerCase(),k===p_)?"":`${O}${k?`=${k}`:""}`}).filter(Boolean)];return p&&C.push("base64"),(C.length!==0||g&&g!==f_)&&C.unshift(g),`data:${C.join(";")},${p?a.trim():a}${l?`#${l}`:""}`},m_=(s,e)=>{if(e={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},s=s.trim(),/^data:/i.test(s))return g_(s,e);if(/^view-source:/i.test(s))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let t=s.startsWith("//");!t&&/^\.*\//.test(s)||(s=s.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));let a=new URL(s);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&a.protocol==="https:"&&(a.protocol="http:"),e.forceHttps&&a.protocol==="http:"&&(a.protocol="https:"),e.stripAuthentication&&(a.username="",a.password=""),e.stripHash?a.hash="":e.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,"")),a.pathname&&(a.pathname=a.pathname.replace(/(?<!\b(?:[a-z][a-z\d+\-.]{1,50}:))\/{2,}/g,"/")),a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let h=a.pathname.split("/"),p=h[h.length-1];_u(p,e.removeDirectoryIndex)&&(h=h.slice(0,h.length-1),a.pathname=h.slice(1).join("/")+"/")}if(a.hostname&&(a.hostname=a.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(let h of[...a.searchParams.keys()])_u(h,e.removeQueryParameters)&&a.searchParams.delete(h);e.removeQueryParameters===!0&&(a.search=""),e.sortQueryParameters&&a.searchParams.sort(),e.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\/$/,""));let l=s;return s=a.toString(),!e.removeSingleSlash&&a.pathname==="/"&&!l.endsWith("/")&&a.hash===""&&(s=s.replace(/\/$/,"")),(e.removeTrailingSlash||a.pathname==="/")&&a.hash===""&&e.removeSingleSlash&&(s=s.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(s=s.replace(/^http:\/\//,"//")),e.stripProtocol&&(s=s.replace(/^(?:https?:)?\/\//,"")),s};bu.exports=m_});var Eu=$((pC,Cu)=>{Cu.exports=wu;function wu(s,e){if(s&&e)return wu(s)(e);if(typeof s!="function")throw new TypeError("need wrapper function");return Object.keys(s).forEach(function(i){t[i]=s[i]}),t;function t(){for(var i=new Array(arguments.length),a=0;a<i.length;a++)i[a]=arguments[a];var l=s.apply(this,i),h=i[i.length-1];return typeof l=="function"&&l!==h&&Object.keys(h).forEach(function(p){l[p]=h[p]}),l}}});var _i=$((gC,yi)=>{var Ou=Eu();yi.exports=Ou(yn);yi.exports.strict=Ou(ku);yn.proto=yn(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return yn(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return ku(this)},configurable:!0})});function yn(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function ku(s){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=s.apply(this,arguments)},t=s.name||"Function wrapped with `once`";return e.onceError=t+" shouldn't be called more than once",e.called=!1,e}});var Au=$((mC,Tu)=>{var y_=_i(),__=function(){},b_=global.Bare?queueMicrotask:process.nextTick.bind(process),v_=function(s){return s.setHeader&&typeof s.abort=="function"},w_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Su=function(s,e,t){if(typeof e=="function")return Su(s,null,e);e||(e={}),t=y_(t||__);var i=s._writableState,a=s._readableState,l=e.readable||e.readable!==!1&&s.readable,h=e.writable||e.writable!==!1&&s.writable,p=!1,g=function(){s.writable||y()},y=function(){h=!1,l||t.call(s)},C=function(){l=!1,h||t.call(s)},v=function(S){t.call(s,S?new Error("exited with error code: "+S):null)},O=function(S){t.call(s,S)},k=function(){b_(T)},T=function(){if(!p){if(l&&!(a&&a.ended&&!a.destroyed))return t.call(s,new Error("premature close"));if(h&&!(i&&i.ended&&!i.destroyed))return t.call(s,new Error("premature close"))}},E=function(){s.req.on("finish",y)};return v_(s)?(s.on("complete",y),s.on("abort",k),s.req?E():s.on("request",E)):h&&!i&&(s.on("end",g),s.on("close",g)),w_(s)&&s.on("exit",v),s.on("end",C),s.on("finish",y),e.error!==!1&&s.on("error",O),s.on("close",k),function(){p=!0,s.removeListener("complete",y),s.removeListener("abort",k),s.removeListener("request",E),s.req&&s.req.removeListener("finish",y),s.removeListener("end",g),s.removeListener("close",g),s.removeListener("finish",y),s.removeListener("exit",v),s.removeListener("end",C),s.removeListener("error",O),s.removeListener("close",k)}};Tu.exports=Su});var Iu=$((yC,Pu)=>{var C_=_i(),E_=Au(),_n;try{_n=D("fs")}catch{}var ws=function(){},O_=typeof process>"u"?!1:/^v?\.0/.test(process.version),bn=function(s){return typeof s=="function"},k_=function(s){return!O_||!_n?!1:(s instanceof(_n.ReadStream||ws)||s instanceof(_n.WriteStream||ws))&&bn(s.close)},S_=function(s){return s.setHeader&&bn(s.abort)},T_=function(s,e,t,i){i=C_(i);var a=!1;s.on("close",function(){a=!0}),E_(s,{readable:e,writable:t},function(h){if(h)return i(h);a=!0,i()});var l=!1;return function(h){if(!a&&!l){if(l=!0,k_(s))return s.close(ws);if(S_(s))return s.abort();if(bn(s.destroy))return s.destroy();i(h||new Error("stream was destroyed"))}}},Ru=function(s){s()},A_=function(s,e){return s.pipe(e)},R_=function(){var s=Array.prototype.slice.call(arguments),e=bn(s[s.length-1]||ws)&&s.pop()||ws;if(Array.isArray(s[0])&&(s=s[0]),s.length<2)throw new Error("pump requires two streams per minimum");var t,i=s.map(function(a,l){var h=l<s.length-1,p=l>0;return T_(a,h,p,function(g){t||(t=g),g&&i.forEach(Ru),!h&&(i.forEach(Ru),e(t))})});return s.reduce(A_)};Pu.exports=R_});var xu=$((_C,Mu)=>{"use strict";var{PassThrough:P_}=D("stream");Mu.exports=s=>{s={...s};let{array:e}=s,{encoding:t}=s,i=t==="buffer",a=!1;e?a=!(t||i):t=t||"utf8",i&&(t=null);let l=new P_({objectMode:a});t&&l.setEncoding(t);let h=0,p=[];return l.on("data",g=>{p.push(g),a?h=p.length:h+=g.length}),l.getBufferedValue=()=>e?p:i?Buffer.concat(p,h):p.join(""),l.getBufferedLength=()=>h,l}});var Nu=$((bC,Gt)=>{"use strict";var{constants:I_}=D("buffer"),M_=Iu(),x_=xu(),vn=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function wn(s,e){if(!s)return Promise.reject(new Error("Expected a stream"));e={maxBuffer:1/0,...e};let{maxBuffer:t}=e,i;return await new Promise((a,l)=>{let h=p=>{p&&i.getBufferedLength()<=I_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),l(p)};i=M_(s,x_(e),p=>{if(p){h(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&h(new vn)})}),i.getBufferedValue()}Gt.exports=wn;Gt.exports.default=wn;Gt.exports.buffer=(s,e)=>wn(s,{...e,encoding:"buffer"});Gt.exports.array=(s,e)=>wn(s,{...e,array:!0});Gt.exports.MaxBufferError=vn});var ju=$((wC,Lu)=>{"use strict";var N_=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),L_=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),j_=new Set([500,502,503,504]),q_={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},U_={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function nt(s){let e=parseInt(s,10);return isFinite(e)?e:0}function D_(s){return s?j_.has(s.status):!0}function bi(s){let e={};if(!s)return e;let t=s.trim().split(/,/);for(let i of t){let[a,l]=i.split(/=/,2);e[a.trim()]=l===void 0?!0:l.trim().replace(/^"|"$/g,"")}return e}function B_(s){let e=[];for(let t in s){let i=s[t];e.push(i===!0?t:t+"="+i)}if(e.length)return e.join(", ")}Lu.exports=class{constructor(e,t,{shared:i,cacheHeuristic:a,immutableMinTimeToLive:l,ignoreCargoCult:h,_fromObject:p}={}){if(p){this._fromObject(p);return}if(!t||!t.headers)throw Error("Response headers missing");this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=i!==!1,this._ignoreCargoCult=!!h,this._cacheHeuristic=a!==void 0?a:.1,this._immutableMinTtl=l!==void 0?l:24*3600*1e3,this._status="status"in t?t.status:200,this._resHeaders=t.headers,this._rescc=bi(t.headers["cache-control"]),this._method="method"in e?e.method:"GET",this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=t.headers.vary?e.headers:null,this._reqcc=bi(e.headers["cache-control"]),this._ignoreCargoCult&&"pre-check"in this._rescc&&"post-check"in this._rescc&&(delete this._rescc["pre-check"],delete this._rescc["post-check"],delete this._rescc["no-cache"],delete this._rescc["no-store"],delete this._rescc["must-revalidate"],this._resHeaders=Object.assign({},this._resHeaders,{"cache-control":B_(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),t.headers["cache-control"]==null&&/no-cache/.test(t.headers.pragma)&&(this._rescc["no-cache"]=!0)}now(){return Date.now()}storable(){return!!(!this._reqcc["no-store"]&&(this._method==="GET"||this._method==="HEAD"||this._method==="POST"&&this._hasExplicitExpiration())&&L_.has(this._status)&&!this._rescc["no-store"]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc["max-age"]||this._isShared&&this._rescc["s-maxage"]||this._rescc.public||N_.has(this._status)))}_hasExplicitExpiration(){return!!(this._isShared&&this._rescc["s-maxage"]||this._rescc["max-age"]||this._resHeaders.expires)}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error("Request headers missing")}satisfiesWithoutRevalidation(e){return!this.evaluateRequest(e).revalidation}_evaluateRequestHitResult(e){return{response:{headers:this.responseHeaders()},revalidation:e}}_evaluateRequestRevalidation(e,t){return{synchronous:t,headers:this.revalidationHeaders(e)}}_evaluateRequestMissResult(e){return{response:void 0,revalidation:this._evaluateRequestRevalidation(e,!0)}}evaluateRequest(e){if(this._assertRequestHasHeaders(e),this._rescc["must-revalidate"])return this._evaluateRequestMissResult(e);if(!this._requestMatches(e,!1))return this._evaluateRequestMissResult(e);let t=bi(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>nt(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<nt(t["min-fresh"])?this._evaluateRequestMissResult(e):this.stale()?"max-stale"in t&&(t["max-stale"]===!0||t["max-stale"]>this.age()-this.maxAge())?this._evaluateRequestHitResult(void 0):this.useStaleWhileRevalidate()?this._evaluateRequestHitResult(this._evaluateRequestRevalidation(e,!1)):this._evaluateRequestMissResult(e):this._evaluateRequestHitResult(void 0)}_requestMatches(e,t){return!!((!this._url||this._url===e.url)&&this._host===e.headers.host&&(!e.method||this._method===e.method||t&&e.method==="HEAD")&&this._varyMatches(e))}_allowsStoringAuthenticated(){return!!(this._rescc["must-revalidate"]||this._rescc.public||this._rescc["s-maxage"])}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary==="*")return!1;let t=this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);for(let i of t)if(e.headers[i]!==this._reqHeaders[i])return!1;return!0}_copyWithoutHopByHopHeaders(e){let t={};for(let i in e)q_[i]||(t[i]=e[i]);if(e.connection){let i=e.connection.trim().split(/\s*,\s*/);for(let a of i)delete t[a]}if(t.warning){let i=t.warning.split(/,/).filter(a=>!/^\s*1[0-9][0-9]/.test(a));i.length?t.warning=i.join(",").trim():delete t.warning}return t}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),t=this.age();return t>3600*24&&!this._hasExplicitExpiration()&&this.maxAge()>3600*24&&(e.warning=(e.warning?`${e.warning}, `:"")+'113 - "rfc7234 5.5.4"'),e.age=`${Math.round(t)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){let e=this._ageValue(),t=(this.now()-this._responseTime)/1e3;return e+t}_ageValue(){return nt(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc["no-cache"]||this._isShared&&this._resHeaders["set-cookie"]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary==="*")return 0;if(this._isShared){if(this._rescc["proxy-revalidate"])return 0;if(this._rescc["s-maxage"])return nt(this._rescc["s-maxage"])}if(this._rescc["max-age"])return nt(this._rescc["max-age"]);let e=this._rescc.immutable?this._immutableMinTtl:0,t=this.date();if(this._resHeaders.expires){let i=Date.parse(this._resHeaders.expires);return Number.isNaN(i)||i<t?0:Math.max(e,(i-t)/1e3)}if(this._resHeaders["last-modified"]){let i=Date.parse(this._resHeaders["last-modified"]);if(isFinite(i)&&t>i)return Math.max(e,(t-i)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),t=e+nt(this._rescc["stale-if-error"]),i=e+nt(this._rescc["stale-while-revalidate"]);return Math.round(Math.max(0,e,t,i)*1e3)}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+nt(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=nt(this._rescc["stale-while-revalidate"]);return e>0&&this.maxAge()+e>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error("Reinitialized");if(!e||e.v!==1)throw Error("Invalid serialization");this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm!==void 0?e.imm:24*3600*1e3,this._ignoreCargoCult=!!e.icc,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,icc:this._ignoreCargoCult,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let t=this._copyWithoutHopByHopHeaders(e.headers);if(delete t["if-range"],!this._requestMatches(e,!0)||!this.storable())return delete t["if-none-match"],delete t["if-modified-since"],t;if(this._resHeaders.etag&&(t["if-none-match"]=t["if-none-match"]?`${t["if-none-match"]}, ${this._resHeaders.etag}`:this._resHeaders.etag),t["accept-ranges"]||t["if-match"]||t["if-unmodified-since"]||this._method&&this._method!="GET"){if(delete t["if-modified-since"],t["if-none-match"]){let a=t["if-none-match"].split(/,/).filter(l=>!/^\s*W\//.test(l));a.length?t["if-none-match"]=a.join(",").trim():delete t["if-none-match"]}}else this._resHeaders["last-modified"]&&!t["if-modified-since"]&&(t["if-modified-since"]=this._resHeaders["last-modified"]);return t}revalidatedPolicy(e,t){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&D_(t))return{policy:this,modified:!1,matches:!0};if(!t||!t.headers)throw Error("Response headers missing");let i=!1;t.status!==void 0&&t.status!=304?i=!1:t.headers.etag&&!/^\s*W\//.test(t.headers.etag)?i=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag:this._resHeaders.etag&&t.headers.etag?i=this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag.replace(/^\s*W\//,""):this._resHeaders["last-modified"]?i=this._resHeaders["last-modified"]===t.headers["last-modified"]:!this._resHeaders.etag&&!this._resHeaders["last-modified"]&&!t.headers.etag&&!t.headers["last-modified"]&&(i=!0);let a={shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl,ignoreCargoCult:this._ignoreCargoCult};if(!i)return{policy:new this.constructor(e,t,a),modified:t.status!=304,matches:!1};let l={};for(let p in this._resHeaders)l[p]=p in t.headers&&!U_[p]?t.headers[p]:this._resHeaders[p];let h=Object.assign({},t,{status:this._status,method:this._method,headers:l});return{policy:new this.constructor(e,h,a),modified:!1,matches:!0}}}});var Cn=$((CC,qu)=>{"use strict";qu.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Du=$((EC,Uu)=>{"use strict";var $_=D("stream").Readable,H_=Cn(),vi=class extends $_{constructor(e,t,i,a){if(typeof e!="number")throw new TypeError("Argument `statusCode` should be a number");if(typeof t!="object")throw new TypeError("Argument `headers` should be an object");if(!(i instanceof Buffer))throw new TypeError("Argument `body` should be a buffer");if(typeof a!="string")throw new TypeError("Argument `url` should be a string");super(),this.statusCode=e,this.headers=H_(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};Uu.exports=vi});var $u=$((OC,Bu)=>{"use strict";var G_=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];Bu.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(G_));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Gu=$((kC,Hu)=>{"use strict";var F_=D("stream").PassThrough,W_=$u(),V_=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new F_;return W_(s,e),s.pipe(e)};Hu.exports=V_});var Fu=$(wi=>{wi.stringify=function s(e){if(typeof e>"u")return e;if(e&&Buffer.isBuffer(e))return JSON.stringify(":base64:"+e.toString("base64"));if(e&&e.toJSON&&(e=e.toJSON()),e&&typeof e=="object"){var t="",i=Array.isArray(e);t=i?"[":"{";var a=!0;for(var l in e){var h=typeof e[l]=="function"||!i&&typeof e[l]>"u";Object.hasOwnProperty.call(e,l)&&!h&&(a||(t+=","),a=!1,i?e[l]==null?t+="null":t+=s(e[l]):e[l]!==void 0&&(t+=s(l)+":"+s(e[l])))}return t+=i?"]":"}",t}else return typeof e=="string"?JSON.stringify(/^:/.test(e)?":"+e:e):typeof e>"u"?"null":JSON.stringify(e)};wi.parse=function(s){return JSON.parse(s,function(e,t){return typeof t=="string"?/^:base64:/.test(t)?Buffer.from(t.substring(8),"base64"):/^:/.test(t)?t.substring(1):t:t})}});var Ku=$((TC,zu)=>{"use strict";var z_=D("events"),Wu=Fu(),K_=s=>{let e={redis:"@keyv/redis",rediss:"@keyv/redis",mongodb:"@keyv/mongo",mongo:"@keyv/mongo",sqlite:"@keyv/sqlite",postgresql:"@keyv/postgres",postgres:"@keyv/postgres",mysql:"@keyv/mysql",etcd:"@keyv/etcd",offline:"@keyv/offline",tiered:"@keyv/tiered"};if(s.adapter||s.uri){let t=s.adapter||/^[^:+]*/.exec(s.uri)[0];return new(D(e[t]))(s)}return new Map},Vu=["sqlite","postgres","mysql","mongo","redis","tiered"],Ci=class extends z_{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:Wu.stringify,deserialize:Wu.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let l={...this.opts};this.opts.store=K_(l)}if(this.opts.compression){let l=this.opts.compression;this.opts.serialize=l.serialize.bind(l),this.opts.deserialize=l.deserialize.bind(l)}typeof this.opts.store.on=="function"&&t&&this.opts.store.on("error",l=>this.emit("error",l)),this.opts.store.namespace=this.opts.namespace;let a=l=>async function*(){for await(let[h,p]of typeof l=="function"?l(this.opts.store.namespace):l){let g=await this.opts.deserialize(p);if(!(this.opts.store.namespace&&!h.includes(this.opts.store.namespace))){if(typeof g.expires=="number"&&Date.now()>g.expires){this.delete(h);continue}yield[this._getKeyUnprefix(h),g.value]}}};typeof this.opts.store[Symbol.iterator]=="function"&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator=="function"&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return Vu.includes(this.opts.store.opts.dialect)||Vu.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(t=>`${this.opts.namespace}:${t}`)}_getKeyUnprefix(e){return e.split(":").splice(1).join(":")}get(e,t){let{store:i}=this.opts,a=Array.isArray(e),l=a?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(a&&i.getMany===void 0){let h=[];for(let p of l)h.push(Promise.resolve().then(()=>i.get(p)).then(g=>typeof g=="string"?this.opts.deserialize(g):this.opts.compression?this.opts.deserialize(g):g).then(g=>{if(g!=null)return typeof g.expires=="number"&&Date.now()>g.expires?this.delete(p).then(()=>{}):t&&t.raw?g:g.value}));return Promise.allSettled(h).then(p=>{let g=[];for(let y of p)g.push(y.value);return g})}return Promise.resolve().then(()=>a?i.getMany(l):i.get(l)).then(h=>typeof h=="string"?this.opts.deserialize(h):this.opts.compression?this.opts.deserialize(h):h).then(h=>{if(h!=null)return a?h.map((p,g)=>{if(typeof p=="string"&&(p=this.opts.deserialize(p)),p!=null){if(typeof p.expires=="number"&&Date.now()>p.expires){this.delete(e[g]).then(()=>{});return}return t&&t.raw?p:p.value}}):typeof h.expires=="number"&&Date.now()>h.expires?this.delete(e).then(()=>{}):t&&t.raw?h:h.value})}set(e,t,i){let a=this._getKeyPrefix(e);typeof i>"u"&&(i=this.opts.ttl),i===0&&(i=void 0);let{store:l}=this.opts;return Promise.resolve().then(()=>{let h=typeof i=="number"?Date.now()+i:null;return typeof t=="symbol"&&this.emit("error","symbol cannot be serialized"),t={value:t,expires:h},this.opts.serialize(t)}).then(h=>l.set(a,h,i)).then(()=>!0)}delete(e){let{store:t}=this.opts;if(Array.isArray(e)){let a=this._getKeyPrefixArray(e);if(t.deleteMany===void 0){let l=[];for(let h of a)l.push(t.delete(h));return Promise.allSettled(l).then(h=>h.every(p=>p.value===!0))}return Promise.resolve().then(()=>t.deleteMany(a))}let i=this._getKeyPrefix(e);return Promise.resolve().then(()=>t.delete(i))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let t=this._getKeyPrefix(e),{store:i}=this.opts;return Promise.resolve().then(async()=>typeof i.has=="function"?i.has(t):await i.get(t)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect=="function")return e.disconnect()}};zu.exports=Ci});var Qu=$((RC,Yu)=>{"use strict";var J_=D("events"),En=D("url"),Y_=vu(),Q_=Nu(),Ei=ju(),Ju=Du(),X_=Cn(),Z_=Gu(),eb=Ku(),Cs=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new eb({uri:typeof t=="string"&&t,store:typeof t!="string"&&t,namespace:"cacheable-request"}),this.createCacheableRequest(e)}createCacheableRequest(e){return(t,i)=>{let a;if(typeof t=="string")a=Oi(En.parse(t)),t={};else if(t instanceof En.URL)a=Oi(En.parse(t.toString())),t={};else{let[v,...O]=(t.path||"").split("?"),k=O.length>0?`?${O.join("?")}`:"";a=Oi({...t,pathname:v,search:k})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...tb(a)},t.headers=X_(t.headers);let l=new J_,h=Y_(En.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${h}`,g=!1,y=!1,C=v=>{y=!0;let O=!1,k,T=new Promise(S=>{k=()=>{O||(O=!0,S())}}),E=S=>{if(g&&!v.forceRefresh){S.status=S.statusCode;let W=Ei.fromObject(g.cachePolicy).revalidatedPolicy(v,S);if(!W.modified){let Y=W.policy.responseHeaders();S=new Ju(g.statusCode,Y,g.body,g.url),S.cachePolicy=W.policy,S.fromCache=!0}}S.fromCache||(S.cachePolicy=new Ei(v,S,v),S.fromCache=!1);let N;v.cache&&S.cachePolicy.storable()?(N=Z_(S),(async()=>{try{let W=Q_.buffer(S);if(await Promise.race([T,new Promise(Te=>S.once("end",Te))]),O)return;let Y=await W,se={cachePolicy:S.cachePolicy.toObject(),url:S.url,statusCode:S.fromCache?g.statusCode:S.statusCode,body:Y},Z=v.strictTtl?S.cachePolicy.timeToLive():void 0;v.maxTtl&&(Z=Z?Math.min(Z,v.maxTtl):v.maxTtl),await this.cache.set(p,se,Z)}catch(W){l.emit("error",new s.CacheError(W))}})()):v.cache&&g&&(async()=>{try{await this.cache.delete(p)}catch(W){l.emit("error",new s.CacheError(W))}})(),l.emit("response",N||S),typeof i=="function"&&i(N||S)};try{let S=e(v,E);S.once("error",k),S.once("abort",k),l.emit("request",S)}catch(S){l.emit("error",new s.RequestError(S))}};return(async()=>{let v=async k=>{await Promise.resolve();let T=k.cache?await this.cache.get(p):void 0;if(typeof T>"u")return C(k);let E=Ei.fromObject(T.cachePolicy);if(E.satisfiesWithoutRevalidation(k)&&!k.forceRefresh){let S=E.responseHeaders(),N=new Ju(T.statusCode,S,T.body,T.url);N.cachePolicy=E,N.fromCache=!0,l.emit("response",N),typeof i=="function"&&i(N)}else g=T,k.headers=E.revalidationHeaders(k),C(k)},O=k=>l.emit("error",new s.CacheError(k));this.cache.once("error",O),l.on("response",()=>this.cache.removeListener("error",O));try{await v(t)}catch(k){t.automaticFailover&&!y&&C(t),l.emit("error",new s.CacheError(k))}})(),l}}};function tb(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function Oi(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}Cs.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};Cs.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};Yu.exports=Cs});var Zu=$((MC,Xu)=>{"use strict";var sb=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];Xu.exports=(s,e)=>{if(e._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");let t=new Set(Object.keys(s).concat(sb)),i={};for(let a of t)a in e||(i[a]={get(){let l=s[a];return typeof l=="function"?l.bind(s):l},set(l){s[a]=l},enumerable:!0,configurable:!1});return Object.defineProperties(e,i),s.once("aborted",()=>{e.destroy(),e.emit("aborted")}),s.once("close",()=>{s.complete&&e.readable?e.once("end",()=>{e.emit("close")}):e.emit("close")}),e}});var th=$((xC,eh)=>{"use strict";var{Transform:nb,PassThrough:rb}=D("stream"),ki=D("zlib"),ib=Zu();eh.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof ki.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new nb({transform(p,g,y){i=!1,y(null,p)},flush(p){p()}}),l=new rb({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),h=t?ki.createBrotliDecompress():ki.createUnzip();return h.once("error",p=>{if(i&&!s.readable){l.end();return}l.destroy(p)}),ib(s,l),s.pipe(a).pipe(h).pipe(l),l}});var Ti=$((NC,sh)=>{"use strict";var Si=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction=="function")for(let[i,a]of this.oldCache.entries())this.onEviction(i,a);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};sh.exports=Si});var Ri=$((LC,oh)=>{"use strict";var ob=D("events"),ab=D("tls"),cb=D("http2"),lb=Ti(),be=Symbol("currentStreamsCount"),nh=Symbol("request"),Me=Symbol("cachedOriginSet"),Ft=Symbol("gracefullyClosing"),ub=["maxDeflateDynamicTableSize","maxSessionMemory","maxHeaderListPairs","maxOutstandingPings","maxReservedRemoteStreams","maxSendHeaderBlockLength","paddingStrategy","localAddress","path","rejectUnauthorized","minDHSize","ca","cert","clientCertEngine","ciphers","key","pfx","servername","minVersion","maxVersion","secureProtocol","crl","honorCipherOrder","ecdhCurve","dhparam","secureOptions","sessionIdContext"],hb=(s,e,t)=>{let i=0,a=s.length;for(;i<a;){let l=i+a>>>1;t(s[l],e)?i=l+1:a=l}return i},db=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Ai=(s,e)=>{for(let t of s)t[Me].length<e[Me].length&&t[Me].every(i=>e[Me].includes(i))&&t[be]+e[be]<=e.remoteSettings.maxConcurrentStreams&&ih(t)},fb=(s,e)=>{for(let t of s)e[Me].length<t[Me].length&&e[Me].every(i=>t[Me].includes(i))&&e[be]+t[be]<=t.remoteSettings.maxConcurrentStreams&&ih(e)},rh=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let l=s.sessions[i].filter(h=>{let p=h[Et.kCurrentStreamsCount]<h.remoteSettings.maxConcurrentStreams;return e?p:!p});l.length!==0&&(t[i]=l)}return t},ih=s=>{s[Ft]=!0,s[be]===0&&s.close()},Et=class s extends ob{constructor({timeout:e=6e4,maxSessions:t=1/0,maxFreeSessions:i=10,maxCachedTlsSessions:a=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=t,this.maxFreeSessions=i,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new lb({maxSize:a})}static normalizeOrigin(e,t){return typeof e=="string"&&(e=new URL(e)),t&&e.hostname!==t&&(e.hostname=t),e.origin}normalizeOptions(e){let t="";if(e)for(let i of ub)e[i]&&(t+=`:${e[i]}`);return t}_tryToCreateNewSession(e,t){if(!(e in this.queue)||!(t in this.queue[e]))return;let i=this.queue[e][t];this._sessionsCount<this.maxSessions&&!i.completed&&(i.completed=!0,i())}getSession(e,t,i){return new Promise((a,l)=>{Array.isArray(i)?(i=[...i],a()):i=[{resolve:a,reject:l}];let h=this.normalizeOptions(t),p=s.normalizeOrigin(e,t&&t.servername);if(p===void 0){for(let{reject:C}of i)C(new TypeError("The `origin` argument needs to be a string or an URL object"));return}if(h in this.sessions){let C=this.sessions[h],v=-1,O=-1,k;for(let T of C){let E=T.remoteSettings.maxConcurrentStreams;if(E<v)break;if(T[Me].includes(p)){let S=T[be];if(S>=E||T[Ft]||T.destroyed)continue;k||(v=E),S>O&&(k=T,O=S)}}if(k){if(i.length!==1){for(let{reject:T}of i){let E=new Error(`Expected the length of listeners to be 1, got ${i.length}.
|
|
34
|
-
Please report this to https://github.com/szmarczak/http2-wrapper/`);T(E)}return}i[0].resolve(k);return}}if(h in this.queue){if(p in this.queue[h]){this.queue[h][p].listeners.push(...i),this._tryToCreateNewSession(h,p);return}}else this.queue[h]={};let g=()=>{h in this.queue&&this.queue[h][p]===y&&(delete this.queue[h][p],Object.keys(this.queue[h]).length===0&&delete this.queue[h])},y=()=>{let C=`${p}:${h}`,v=!1;try{let O=cb.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(C),...t});O[be]=0,O[Ft]=!1;let k=()=>O[be]<O.remoteSettings.maxConcurrentStreams,T=!0;O.socket.once("session",S=>{this.tlsSessionCache.set(C,S)}),O.once("error",S=>{for(let{reject:N}of i)N(S);this.tlsSessionCache.delete(C)}),O.setTimeout(this.timeout,()=>{O.destroy()}),O.once("close",()=>{if(v){T&&this._freeSessionsCount--,this._sessionsCount--;let S=this.sessions[h];S.splice(S.indexOf(O),1),S.length===0&&delete this.sessions[h]}else{let S=new Error("Session closed without receiving a SETTINGS frame");S.code="HTTP2WRAPPER_NOSETTINGS";for(let{reject:N}of i)N(S);g()}this._tryToCreateNewSession(h,p)});let E=()=>{if(!(!(h in this.queue)||!k())){for(let S of O[Me])if(S in this.queue[h]){let{listeners:N}=this.queue[h][S];for(;N.length!==0&&k();)N.shift().resolve(O);let W=this.queue[h];if(W[S].listeners.length===0&&(delete W[S],Object.keys(W).length===0)){delete this.queue[h];break}if(!k())break}}};O.on("origin",()=>{O[Me]=O.originSet,k()&&(E(),Ai(this.sessions[h],O))}),O.once("remoteSettings",()=>{if(O.ref(),O.unref(),this._sessionsCount++,y.destroyed){let S=new Error("Agent has been destroyed");for(let N of i)N.reject(S);O.destroy();return}O[Me]=O.originSet;{let S=this.sessions;if(h in S){let N=S[h];N.splice(hb(N,O,db),0,O)}else S[h]=[O]}this._freeSessionsCount+=1,v=!0,this.emit("session",O),E(),g(),O[be]===0&&this._freeSessionsCount>this.maxFreeSessions&&O.close(),i.length!==0&&(this.getSession(p,t,i),i.length=0),O.on("remoteSettings",()=>{E(),Ai(this.sessions[h],O)})}),O[nh]=O.request,O.request=(S,N)=>{if(O[Ft])throw new Error("The session is gracefully closing. No new streams are allowed.");let W=O[nh](S,N);return O.ref(),++O[be],O[be]===O.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,W.once("close",()=>{if(T=k(),--O[be],!O.destroyed&&!O.closed&&(fb(this.sessions[h],O),k()&&!O.closed)){T||(this._freeSessionsCount++,T=!0);let Y=O[be]===0;Y&&O.unref(),Y&&(this._freeSessionsCount>this.maxFreeSessions||O[Ft])?O.close():(Ai(this.sessions[h],O),E())}}),W}}catch(O){for(let k of i)k.reject(O);g()}};y.listeners=i,y.completed=!1,y.destroyed=!1,this.queue[h][p]=y,this._tryToCreateNewSession(h,p)})}request(e,t,i,a){return new Promise((l,h)=>{this.getSession(e,t,[{reject:h,resolve:p=>{try{l(p.request(i,a))}catch(g){h(g)}}}])})}createConnection(e,t){return s.connect(e,t)}static connect(e,t){t.ALPNProtocols=["h2"];let i=e.port||443,a=e.hostname||e.host;return typeof t.servername>"u"&&(t.servername=a),ab.connect(i,a,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[be]===0&&t.close()}destroy(e){for(let t of Object.values(this.sessions))for(let i of t)i.destroy(e);for(let t of Object.values(this.queue))for(let i of Object.values(t))i.destroyed=!0;this.queue={}}get freeSessions(){return rh({agent:this,isFree:!0})}get busySessions(){return rh({agent:this,isFree:!1})}};Et.kCurrentStreamsCount=be;Et.kGracefullyClosing=Ft;oh.exports={Agent:Et,globalAgent:new Et}});var Ii=$((jC,ah)=>{"use strict";var{Readable:pb}=D("stream"),Pi=class extends pb{constructor(e,t){super({highWaterMark:t,autoDestroy:!1}),this.statusCode=null,this.statusMessage="",this.httpVersion="2.0",this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,t){return this.req.setTimeout(e,t),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners("data"),this.resume())}_read(){this.req&&this.req._request.resume()}};ah.exports=Pi});var Mi=$((qC,ch)=>{"use strict";ch.exports=s=>{let e={protocol:s.protocol,hostname:typeof s.hostname=="string"&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return typeof s.port=="string"&&s.port.length!==0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var uh=$((UC,lh)=>{"use strict";lh.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var dh=$((DC,hh)=>{"use strict";hh.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var ph=$(($C,fh)=>{"use strict";var Wt=(s,e,t)=>{fh.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};Wt(TypeError,"ERR_INVALID_ARG_TYPE",s=>{let e=s[0].includes(".")?"property":"argument",t=s[1],i=Array.isArray(t);return i&&(t=`${t.slice(0,-1).join(", ")} or ${t.slice(-1)}`),`The "${s[0]}" ${e} must be ${i?"one of":"of"} type ${t}. Received ${typeof s[2]}`});Wt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);Wt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);Wt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);Wt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);Wt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var qi=$((HC,wh)=>{"use strict";var gb=D("http2"),{Writable:mb}=D("stream"),{Agent:gh,globalAgent:yb}=Ri(),_b=Ii(),bb=Mi(),vb=uh(),wb=dh(),{ERR_INVALID_ARG_TYPE:xi,ERR_INVALID_PROTOCOL:Cb,ERR_HTTP_HEADERS_SENT:mh,ERR_INVALID_HTTP_TOKEN:Eb,ERR_HTTP_INVALID_HEADER_VALUE:Ob,ERR_INVALID_CHAR:kb}=ph(),{HTTP2_HEADER_STATUS:yh,HTTP2_HEADER_METHOD:_h,HTTP2_HEADER_PATH:bh,HTTP2_METHOD_CONNECT:Sb}=gb.constants,ye=Symbol("headers"),Ni=Symbol("origin"),Li=Symbol("session"),vh=Symbol("options"),On=Symbol("flushedHeaders"),Es=Symbol("jobs"),Tb=/^[\^`\-\w!#$%&*+.|~]+$/,Ab=/[^\t\u0020-\u007E\u0080-\u00FF]/,ji=class extends mb{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=bb(e instanceof URL?e:new URL(e))),typeof t=="function"||t===void 0?(i=t,t=a?e:{...e}):t={...e,...t},t.h2session)this[Li]=t.h2session;else if(t.agent===!1)this.agent=new gh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new gh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=yb;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new xi("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new Cb(t.protocol,"https:");let l=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,h=t.hostname||t.host||"localhost";delete t.hostname,delete t.host,delete t.port;let{timeout:p}=t;if(t.timeout=void 0,this[ye]=Object.create(null),this[Es]=[],this.socket=null,this.connection=null,this.method=t.method||"GET",this.path=t.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,t.headers)for(let[g,y]of Object.entries(t.headers))this.setHeader(g,y);t.auth&&!("authorization"in this[ye])&&(this[ye].authorization="Basic "+Buffer.from(t.auth).toString("base64")),t.session=t.tlsSession,t.path=t.socketPath,this[vh]=t,l===443?(this[Ni]=`https://${h}`,":authority"in this[ye]||(this[ye][":authority"]=h)):(this[Ni]=`https://${h}:${l}`,":authority"in this[ye]||(this[ye][":authority"]=`${h}:${l}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[On]=!1}get method(){return this[ye][_h]}set method(e){e&&(this[ye][_h]=e.toUpperCase())}get path(){return this[ye][bh]}set path(e){e&&(this[ye][bh]=e)}get _mustNotHaveABody(){return this.method==="GET"||this.method==="HEAD"||this.method==="DELETE"}_write(e,t,i){if(this._mustNotHaveABody){i(new Error("The GET, HEAD and DELETE methods must NOT have a body"));return}this.flushHeaders();let a=()=>this._request.write(e,t,i);this._request?a():this[Es].push(a)}_final(e){if(this.destroyed)return;this.flushHeaders();let t=()=>{if(this._mustNotHaveABody){e();return}this._request.end(e)};this._request?t():this[Es].push(t)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit("abort")),this.aborted=!0,this.destroy())}_destroy(e,t){this.res&&this.res._dump(),this._request&&this._request.destroy(),t(e)}async flushHeaders(){if(this[On]||this.destroyed)return;this[On]=!0;let e=this.method===Sb,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||vb(i,this,["timeout","continue","close","error"]);let a=h=>(...p)=>{!this.writable&&!this.destroyed?h(...p):this.once("finish",()=>{h(...p)})};i.once("response",a((h,p,g)=>{let y=new _b(this.socket,i.readableHighWaterMark);this.res=y,y.req=this,y.statusCode=h[yh],y.headers=h,y.rawHeaders=g,y.once("end",()=>{this.aborted?(y.aborted=!0,y.emit("aborted")):(y.complete=!0,y.socket=null,y.connection=null)}),e?(y.upgrade=!0,this.emit("connect",y,i,Buffer.alloc(0))?this.emit("close"):i.destroy()):(i.on("data",C=>{!y._dumped&&!y.push(C)&&i.pause()}),i.once("end",()=>{y.push(null)}),this.emit("response",y)||y._dump())})),i.once("headers",a(h=>this.emit("information",{statusCode:h[yh]}))),i.once("trailers",a((h,p,g)=>{let{res:y}=this;y.trailers=h,y.rawTrailers=g}));let{socket:l}=i.session;this.socket=l,this.connection=l;for(let h of this[Es])h();this.emit("socket",this.socket)};if(this[Li])try{t(this[Li].request(this[ye]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[Ni],this[vh],this[ye]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new xi("name","string",e);return this[ye][e.toLowerCase()]}get headersSent(){return this[On]}removeHeader(e){if(typeof e!="string")throw new xi("name","string",e);if(this.headersSent)throw new mh("remove");delete this[ye][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new mh("set");if(typeof e!="string"||!Tb.test(e)&&!wb(e))throw new Eb("Header name",e);if(typeof t>"u")throw new Ob(t,e);if(Ab.test(t))throw new kb("header content",e);this[ye][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let i=()=>this._request.setTimeout(e,t);return this._request?i():this[Es].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};wh.exports=ji});var Eh=$((GC,Ch)=>{"use strict";var Rb=D("tls");Ch.exports=(s={},e=Rb.connect)=>new Promise((t,i)=>{let a=!1,l,h=async()=>{await g,l.off("timeout",p),l.off("error",i),s.resolveSocket?(t({alpnProtocol:l.alpnProtocol,socket:l,timeout:a}),a&&(await Promise.resolve(),l.emit("timeout"))):(l.destroy(),t({alpnProtocol:l.alpnProtocol,timeout:a}))},p=async()=>{a=!0,h()},g=(async()=>{try{l=await e(s,h),l.on("error",i),l.once("timeout",p)}catch(y){i(y)}})()})});var kh=$((FC,Oh)=>{"use strict";var Pb=D("net");Oh.exports=s=>{let e=s.host,t=s.headers&&s.headers.host;return t&&(t.startsWith("[")?t.indexOf("]")===-1?e=t:e=t.slice(1,-1):e=t.split(":",1)[0]),Pb.isIP(e)?"":e}});var Ah=$((WC,Di)=>{"use strict";var Sh=D("http"),Ui=D("https"),Ib=Eh(),Mb=Ti(),xb=qi(),Nb=kh(),Lb=Mi(),kn=new Mb({maxSize:100}),Os=new Map,Th=(s,e,t)=>{e._httpMessage={shouldKeepAlive:!0};let i=()=>{s.emit("free",e,t)};e.on("free",i);let a=()=>{s.removeSocket(e,t)};e.on("close",a);let l=()=>{s.removeSocket(e,t),e.off("close",a),e.off("free",i),e.off("agentRemove",l)};e.on("agentRemove",l),s.emit("free",e,t)},jb=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!kn.has(e)){if(Os.has(e))return(await Os.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=Ib(s);Os.set(e,a);try{let{socket:l,alpnProtocol:h}=await a;if(kn.set(e,h),s.path=t,h==="h2")l.destroy();else{let{globalAgent:p}=Ui,g=Ui.Agent.prototype.createConnection;i?i.createConnection===g?Th(i,l,s):l.destroy():p.createConnection===g?Th(p,l,s):l.destroy()}return Os.delete(e),h}catch(l){throw Os.delete(e),l}}return kn.get(e)};Di.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=Lb(new URL(s))),typeof e=="function"&&(t=e,e=void 0),e={ALPNProtocols:["h2","http/1.1"],...s,...e,resolveSocket:!0},!Array.isArray(e.ALPNProtocols)||e.ALPNProtocols.length===0)throw new Error("The `ALPNProtocols` option must be an Array with at least one entry");e.protocol=e.protocol||"https:";let i=e.protocol==="https:";e.host=e.hostname||e.host||"localhost",e.session=e.tlsSession,e.servername=e.servername||Nb(e),e.port=e.port||(i?443:80),e._defaultAgent=i?Ui.globalAgent:Sh.globalAgent;let a=e.agent;if(a){if(a.addRequest)throw new Error("The `options.agent` object can contain only `http`, `https` or `http2` properties");e.agent=a[i?"https":"http"]}return i&&await jb(e)==="h2"?(a&&(e.agent=a.http2),new xb(e,t)):Sh.request(e,t)};Di.exports.protocolCache=kn});var Ph=$((VC,Rh)=>{"use strict";var qb=D("http2"),Ub=Ri(),Bi=qi(),Db=Ii(),Bb=Ah(),$b=(s,e,t)=>new Bi(s,e,t),Hb=(s,e,t)=>{let i=new Bi(s,e,t);return i.end(),i};Rh.exports={...qb,ClientRequest:Bi,IncomingMessage:Db,...Ub,request:$b,get:Hb,auto:Bb}});var Hi=$($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var Ih=st();$i.default=s=>Ih.default.nodeStream(s)&&Ih.default.function_(s.getBoundary)});var Lh=$(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});var xh=D("fs"),Nh=D("util"),Mh=st(),Gb=Hi(),Fb=Nh.promisify(xh.stat);Gi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(Mh.default.string(s))return Buffer.byteLength(s);if(Mh.default.buffer(s))return s.length;if(Gb.default(s))return Nh.promisify(s.getLength.bind(s))();if(s instanceof xh.ReadStream){let{size:t}=await Fb(s.path);return t===0?void 0:t}}});var Wi=$(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});function Wb(s,e,t){let i={};for(let a of t)i[a]=(...l)=>{e.emit(a,...l)},s.on(a,i[a]);return()=>{for(let a of t)s.off(a,i[a])}}Fi.default=Wb});var jh=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.default=()=>{let s=[];return{once(e,t,i){e.once(t,i),s.push({origin:e,event:t,fn:i})},unhandleAll(){for(let e of s){let{origin:t,event:i,fn:a}=e;t.removeListener(i,a)}s.length=0}}}});var Uh=$(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.TimeoutError=void 0;var Vb=D("net"),zb=jh(),qh=Symbol("reentry"),Kb=()=>{},Sn=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};ks.TimeoutError=Sn;ks.default=(s,e,t)=>{if(qh in s)return Kb;s[qh]=!0;let i=[],{once:a,unhandleAll:l}=zb.default(),h=(v,O,k)=>{var T;let E=setTimeout(O,v,v,k);(T=E.unref)===null||T===void 0||T.call(E);let S=()=>{clearTimeout(E)};return i.push(S),S},{host:p,hostname:g}=t,y=(v,O)=>{s.destroy(new Sn(v,O))},C=()=>{for(let v of i)v();l()};if(s.once("error",v=>{if(C(),s.listenerCount("error")===0)throw v}),s.once("close",C),a(s,"response",v=>{a(v,"end",C)}),typeof e.request<"u"&&h(e.request,y,"request"),typeof e.socket<"u"){let v=()=>{y(e.socket,"socket")};s.setTimeout(e.socket,v),i.push(()=>{s.removeListener("timeout",v)})}return a(s,"socket",v=>{var O;let{socketPath:k}=s;if(v.connecting){let T=!!(k??Vb.isIP((O=g??p)!==null&&O!==void 0?O:"")!==0);if(typeof e.lookup<"u"&&!T&&typeof v.address().address>"u"){let E=h(e.lookup,y,"lookup");a(v,"lookup",E)}if(typeof e.connect<"u"){let E=()=>h(e.connect,y,"connect");T?a(v,"connect",E()):a(v,"lookup",S=>{S===null&&a(v,"connect",E())})}typeof e.secureConnect<"u"&&t.protocol==="https:"&&a(v,"connect",()=>{let E=h(e.secureConnect,y,"secureConnect");a(v,"secureConnect",E)})}if(typeof e.send<"u"){let T=()=>h(e.send,y,"send");v.connecting?a(v,"connect",()=>{a(s,"upload-complete",T())}):a(s,"upload-complete",T())}}),typeof e.response<"u"&&a(s,"upload-complete",()=>{let v=h(e.response,y,"response");a(s,"response",v)}),C}});var Bh=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var Dh=st();zi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Dh.default.string(s.hostname)&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return Dh.default.string(s.port)&&s.port.length>0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var $h=$(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var Jb=D("url"),Yb=["protocol","host","hostname","port","pathname","search"];Ki.default=(s,e)=>{var t,i;if(e.path){if(e.pathname)throw new TypeError("Parameters `path` and `pathname` are mutually exclusive.");if(e.search)throw new TypeError("Parameters `path` and `search` are mutually exclusive.");if(e.searchParams)throw new TypeError("Parameters `path` and `searchParams` are mutually exclusive.")}if(e.search&&e.searchParams)throw new TypeError("Parameters `search` and `searchParams` are mutually exclusive.");if(!s){if(!e.protocol)throw new TypeError("No URL protocol specified");s=`${e.protocol}//${(i=(t=e.hostname)!==null&&t!==void 0?t:e.host)!==null&&i!==void 0?i:""}`}let a=new Jb.URL(s);if(e.path){let l=e.path.indexOf("?");l===-1?e.pathname=e.path:(e.pathname=e.path.slice(0,l),e.search=e.path.slice(l+1)),delete e.path}for(let l of Yb)e[l]&&(a[l]=e[l].toString());return a}});var Hh=$(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var Ji=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,t){typeof e=="object"?this.weakMap.set(e,t):this.map.set(e,t)}get(e){return typeof e=="object"?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e=="object"?this.weakMap.has(e):this.map.has(e)}};Yi.default=Ji});var Xi=$(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var Qb=async s=>{let e=[],t=0;for await(let i of s)e.push(i),t+=Buffer.byteLength(i);return Buffer.isBuffer(e[0])?Buffer.concat(e,t):Buffer.from(e.join(""))};Qi.default=Qb});var Fh=$(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.dnsLookupIpVersionToFamily=Ot.isDnsLookupIpVersion=void 0;var Gh={auto:0,ipv4:4,ipv6:6};Ot.isDnsLookupIpVersion=s=>s in Gh;Ot.dnsLookupIpVersionToFamily=s=>{if(Ot.isDnsLookupIpVersion(s))return Gh[s];throw new Error("Invalid DNS lookup IP version")}});var Zi=$(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.isResponseOk=void 0;Tn.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var Vh=$(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var Wh=new Set;eo.default=s=>{Wh.has(s)||(Wh.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var zh=$(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var ne=st(),Xb=(s,e)=>{if(ne.default.null_(s.encoding))throw new TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");ne.assert.any([ne.default.string,ne.default.undefined],s.encoding),ne.assert.any([ne.default.boolean,ne.default.undefined],s.resolveBodyOnly),ne.assert.any([ne.default.boolean,ne.default.undefined],s.methodRewriting),ne.assert.any([ne.default.boolean,ne.default.undefined],s.isStream),ne.assert.any([ne.default.string,ne.default.undefined],s.responseType),s.responseType===void 0&&(s.responseType="text");let{retry:t}=s;if(e?s.retry={...e.retry}:s.retry={calculateDelay:i=>i.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},ne.default.object(t)?(s.retry={...s.retry,...t},s.retry.methods=[...new Set(s.retry.methods.map(i=>i.toUpperCase()))],s.retry.statusCodes=[...new Set(s.retry.statusCodes)],s.retry.errorCodes=[...new Set(s.retry.errorCodes)]):ne.default.number(t)&&(s.retry.limit=t),ne.default.undefined(s.retry.maxRetryAfter)&&(s.retry.maxRetryAfter=Math.min(...[s.timeout.request,s.timeout.connect].filter(ne.default.number))),ne.default.object(s.pagination)){e&&(s.pagination={...e.pagination,...s.pagination});let{pagination:i}=s;if(!ne.default.function_(i.transform))throw new Error("`options.pagination.transform` must be implemented");if(!ne.default.function_(i.shouldContinue))throw new Error("`options.pagination.shouldContinue` must be implemented");if(!ne.default.function_(i.filter))throw new TypeError("`options.pagination.filter` must be implemented");if(!ne.default.function_(i.paginate))throw new Error("`options.pagination.paginate` must be implemented")}return s.responseType==="json"&&s.headers.accept===void 0&&(s.headers.accept="application/json"),s};to.default=Xb});var Kh=$(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.retryAfterStatusCodes=void 0;Ss.retryAfterStatusCodes=new Set([413,429,503]);var Zb=({attemptCount:s,retryOptions:e,error:t,retryAfter:i})=>{if(s>e.limit)return 0;let a=e.methods.includes(t.options.method),l=e.errorCodes.includes(t.code),h=t.response&&e.statusCodes.includes(t.response.statusCode);if(!a||!l&&!h)return 0;if(t.response){if(i)return e.maxRetryAfter===void 0||i>e.maxRetryAfter?0:i;if(t.response.statusCode===413)return 0}let p=Math.random()*100;return 2**(s-1)*1e3+p};Ss.default=Zb});var Rs=$(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.UnsupportedProtocolError=Q.ReadError=Q.TimeoutError=Q.UploadError=Q.CacheError=Q.HTTPError=Q.MaxRedirectsError=Q.RequestError=Q.setNonEnumerableProperties=Q.knownHookEvents=Q.withoutBody=Q.kIsNormalizedAlready=void 0;var Jh=D("util"),Yh=D("stream"),ev=D("fs"),ht=D("url"),Qh=D("http"),so=D("http"),tv=D("https"),sv=uu(),nv=yu(),Xh=Qu(),rv=th(),iv=Ph(),ov=Cn(),M=st(),av=Lh(),Zh=Hi(),cv=Wi(),ed=Uh(),lv=Bh(),td=$h(),uv=Hh(),hv=Xi(),sd=Fh(),dv=Zi(),dt=Vh(),fv=zh(),pv=Kh(),no,fe=Symbol("request"),Pn=Symbol("response"),Vt=Symbol("responseSize"),zt=Symbol("downloadedSize"),Kt=Symbol("bodySize"),Jt=Symbol("uploadedSize"),An=Symbol("serverResponsesPiped"),nd=Symbol("unproxyEvents"),rd=Symbol("isFromCache"),ro=Symbol("cancelTimeouts"),id=Symbol("startedReading"),Yt=Symbol("stopReading"),Rn=Symbol("triggerRead"),ft=Symbol("body"),Ts=Symbol("jobs"),od=Symbol("originalResponse"),ad=Symbol("retryTimeout");Q.kIsNormalizedAlready=Symbol("isNormalizedAlready");var gv=M.default.string(process.versions.brotli);Q.withoutBody=new Set(["GET","HEAD"]);Q.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function mv(s){for(let e in s){let t=s[e];if(!M.default.string(t)&&!M.default.number(t)&&!M.default.boolean(t)&&!M.default.null_(t)&&!M.default.undefined(t))throw new TypeError(`The \`searchParams\` value '${String(t)}' must be a string, number, boolean or null`)}}function yv(s){return M.default.object(s)&&!("statusCode"in s)}var io=new uv.default,_v=async s=>new Promise((e,t)=>{let i=a=>{t(a)};s.pending||e(),s.once("error",i),s.once("ready",()=>{s.off("error",i),e()})}),bv=new Set([300,301,302,303,304,307,308]),vv=["context","body","json","form"];Q.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of vv)a in i&&(t[a]={writable:!0,configurable:!0,enumerable:!1,value:i[a]});Object.defineProperties(e,t)};var ae=class extends Error{constructor(e,t,i){var a,l;if(super(e),Error.captureStackTrace(this,this.constructor),this.name="RequestError",this.code=(a=t.code)!==null&&a!==void 0?a:"ERR_GOT_REQUEST_ERROR",i instanceof qn?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[Pn]}),Object.defineProperty(this,"options",{enumerable:!1,value:i.options})):Object.defineProperty(this,"options",{enumerable:!1,value:i}),this.timings=(l=this.request)===null||l===void 0?void 0:l.timings,M.default.string(t.stack)&&M.default.string(this.stack)){let h=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(h).split(`
|
|
33
|
+
`+t)}function Ct(s,e,t,i,a,l){if(s.listenerCount("wsClientError")){let h=new Error(a);Error.captureStackTrace(h,Ct),s.emit("wsClientError",h,t,e)}else bs(t,i,a,l)}});var dn=$((gC,ru)=>{"use strict";var et=un();et.createWebSocketStream=Kl();et.Server=nu();et.Receiver=Yr();et.Sender=Zr();et.WebSocket=et;et.WebSocketServer=et.Server;ru.exports=et});var st=$((tt,fn)=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});var iu=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Jy(s){return iu.includes(s)}var Yy=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Blob","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","FormData","URLSearchParams","HTMLElement",...iu];function Qy(s){return Yy.includes(s)}var Xy=["null","undefined","string","number","bigint","boolean","symbol"];function Zy(s){return Xy.includes(s)}function $t(s){return e=>typeof e===s}var{toString:ou}=Object.prototype,vs=s=>{let e=ou.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&b.domElement(s))return"HTMLElement";if(Qy(e))return e},te=s=>e=>vs(e)===s;function b(s){if(s===null)return"null";switch(typeof s){case"undefined":return"undefined";case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"function":return"Function";case"bigint":return"bigint";case"symbol":return"symbol";default:}if(b.observable(s))return"Observable";if(b.array(s))return"Array";if(b.buffer(s))return"Buffer";let e=vs(s);if(e)return e;if(s instanceof String||s instanceof Boolean||s instanceof Number)throw new TypeError("Please don't use object wrappers for primitive types");return"Object"}b.undefined=$t("undefined");b.string=$t("string");var e_=$t("number");b.number=s=>e_(s)&&!b.nan(s);b.bigint=$t("bigint");b.function_=$t("function");b.null_=s=>s===null;b.class_=s=>b.function_(s)&&s.toString().startsWith("class ");b.boolean=s=>s===!0||s===!1;b.symbol=$t("symbol");b.numericString=s=>b.string(s)&&!b.emptyStringOrWhitespace(s)&&!Number.isNaN(Number(s));b.array=(s,e)=>Array.isArray(s)?b.function_(e)?s.every(e):!0:!1;b.buffer=s=>{var e,t,i,a;return(a=(i=(t=(e=s)===null||e===void 0?void 0:e.constructor)===null||t===void 0?void 0:t.isBuffer)===null||i===void 0?void 0:i.call(t,s))!==null&&a!==void 0?a:!1};b.blob=s=>te("Blob")(s);b.nullOrUndefined=s=>b.null_(s)||b.undefined(s);b.object=s=>!b.null_(s)&&(typeof s=="object"||b.function_(s));b.iterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.iterator])};b.asyncIterable=s=>{var e;return b.function_((e=s)===null||e===void 0?void 0:e[Symbol.asyncIterator])};b.generator=s=>{var e,t;return b.iterable(s)&&b.function_((e=s)===null||e===void 0?void 0:e.next)&&b.function_((t=s)===null||t===void 0?void 0:t.throw)};b.asyncGenerator=s=>b.asyncIterable(s)&&b.function_(s.next)&&b.function_(s.throw);b.nativePromise=s=>te("Promise")(s);var t_=s=>{var e,t;return b.function_((e=s)===null||e===void 0?void 0:e.then)&&b.function_((t=s)===null||t===void 0?void 0:t.catch)};b.promise=s=>b.nativePromise(s)||t_(s);b.generatorFunction=te("GeneratorFunction");b.asyncGeneratorFunction=s=>vs(s)==="AsyncGeneratorFunction";b.asyncFunction=s=>vs(s)==="AsyncFunction";b.boundFunction=s=>b.function_(s)&&!s.hasOwnProperty("prototype");b.regExp=te("RegExp");b.date=te("Date");b.error=te("Error");b.map=s=>te("Map")(s);b.set=s=>te("Set")(s);b.weakMap=s=>te("WeakMap")(s);b.weakSet=s=>te("WeakSet")(s);b.int8Array=te("Int8Array");b.uint8Array=te("Uint8Array");b.uint8ClampedArray=te("Uint8ClampedArray");b.int16Array=te("Int16Array");b.uint16Array=te("Uint16Array");b.int32Array=te("Int32Array");b.uint32Array=te("Uint32Array");b.float32Array=te("Float32Array");b.float64Array=te("Float64Array");b.bigInt64Array=te("BigInt64Array");b.bigUint64Array=te("BigUint64Array");b.arrayBuffer=te("ArrayBuffer");b.sharedArrayBuffer=te("SharedArrayBuffer");b.dataView=te("DataView");b.enumCase=(s,e)=>Object.values(e).includes(s);b.directInstanceOf=(s,e)=>Object.getPrototypeOf(s)===e.prototype;b.urlInstance=s=>te("URL")(s);b.urlString=s=>{if(!b.string(s))return!1;try{return new URL(s),!0}catch{return!1}};b.truthy=s=>!!s;b.falsy=s=>!s;b.nan=s=>Number.isNaN(s);b.primitive=s=>b.null_(s)||Zy(typeof s);b.integer=s=>Number.isInteger(s);b.safeInteger=s=>Number.isSafeInteger(s);b.plainObject=s=>{if(ou.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};b.typedArray=s=>Jy(vs(s));var s_=s=>b.safeInteger(s)&&s>=0;b.arrayLike=s=>!b.nullOrUndefined(s)&&!b.function_(s)&&s_(s.length);b.inRange=(s,e)=>{if(b.number(e))return s>=Math.min(0,e)&&s<=Math.max(e,0);if(b.array(e)&&e.length===2)return s>=Math.min(...e)&&s<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var n_=1,r_=["innerHTML","ownerDocument","style","attributes","nodeValue"];b.domElement=s=>b.object(s)&&s.nodeType===n_&&b.string(s.nodeName)&&!b.plainObject(s)&&r_.every(e=>e in s);b.observable=s=>{var e,t,i,a;return s?s===((t=(e=s)[Symbol.observable])===null||t===void 0?void 0:t.call(e))||s===((a=(i=s)["@@observable"])===null||a===void 0?void 0:a.call(i)):!1};b.nodeStream=s=>b.object(s)&&b.function_(s.pipe)&&!b.observable(s);b.infinite=s=>s===1/0||s===-1/0;var au=s=>e=>b.integer(e)&&Math.abs(e%2)===s;b.evenInteger=au(0);b.oddInteger=au(1);b.emptyArray=s=>b.array(s)&&s.length===0;b.nonEmptyArray=s=>b.array(s)&&s.length>0;b.emptyString=s=>b.string(s)&&s.length===0;var i_=s=>b.string(s)&&!/\S/.test(s);b.emptyStringOrWhitespace=s=>b.emptyString(s)||i_(s);b.nonEmptyString=s=>b.string(s)&&s.length>0;b.nonEmptyStringAndNotWhitespace=s=>b.string(s)&&!b.emptyStringOrWhitespace(s);b.emptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length===0;b.nonEmptyObject=s=>b.object(s)&&!b.map(s)&&!b.set(s)&&Object.keys(s).length>0;b.emptySet=s=>b.set(s)&&s.size===0;b.nonEmptySet=s=>b.set(s)&&s.size>0;b.emptyMap=s=>b.map(s)&&s.size===0;b.nonEmptyMap=s=>b.map(s)&&s.size>0;b.propertyKey=s=>b.any([b.string,b.number,b.symbol],s);b.formData=s=>te("FormData")(s);b.urlSearchParams=s=>te("URLSearchParams")(s);var cu=(s,e,t)=>{if(!b.function_(e))throw new TypeError(`Invalid predicate: ${JSON.stringify(e)}`);if(t.length===0)throw new TypeError("Invalid number of values");return s.call(t,e)};b.any=(s,...e)=>(b.array(s)?s:[s]).some(i=>cu(Array.prototype.some,i,e));b.all=(s,...e)=>cu(Array.prototype.every,s,e);var B=(s,e,t,i={})=>{if(!s){let{multipleValues:a}=i,l=a?`received values of types ${[...new Set(t.map(h=>`\`${b(h)}\``))].join(", ")}`:`received value of type \`${b(t)}\``;throw new TypeError(`Expected value which is \`${e}\`, ${l}.`)}};tt.assert={undefined:s=>B(b.undefined(s),"undefined",s),string:s=>B(b.string(s),"string",s),number:s=>B(b.number(s),"number",s),bigint:s=>B(b.bigint(s),"bigint",s),function_:s=>B(b.function_(s),"Function",s),null_:s=>B(b.null_(s),"null",s),class_:s=>B(b.class_(s),"Class",s),boolean:s=>B(b.boolean(s),"boolean",s),symbol:s=>B(b.symbol(s),"symbol",s),numericString:s=>B(b.numericString(s),"string with a number",s),array:(s,e)=>{B(b.array(s),"Array",s),e&&s.forEach(e)},buffer:s=>B(b.buffer(s),"Buffer",s),blob:s=>B(b.blob(s),"Blob",s),nullOrUndefined:s=>B(b.nullOrUndefined(s),"null or undefined",s),object:s=>B(b.object(s),"Object",s),iterable:s=>B(b.iterable(s),"Iterable",s),asyncIterable:s=>B(b.asyncIterable(s),"AsyncIterable",s),generator:s=>B(b.generator(s),"Generator",s),asyncGenerator:s=>B(b.asyncGenerator(s),"AsyncGenerator",s),nativePromise:s=>B(b.nativePromise(s),"native Promise",s),promise:s=>B(b.promise(s),"Promise",s),generatorFunction:s=>B(b.generatorFunction(s),"GeneratorFunction",s),asyncGeneratorFunction:s=>B(b.asyncGeneratorFunction(s),"AsyncGeneratorFunction",s),asyncFunction:s=>B(b.asyncFunction(s),"AsyncFunction",s),boundFunction:s=>B(b.boundFunction(s),"Function",s),regExp:s=>B(b.regExp(s),"RegExp",s),date:s=>B(b.date(s),"Date",s),error:s=>B(b.error(s),"Error",s),map:s=>B(b.map(s),"Map",s),set:s=>B(b.set(s),"Set",s),weakMap:s=>B(b.weakMap(s),"WeakMap",s),weakSet:s=>B(b.weakSet(s),"WeakSet",s),int8Array:s=>B(b.int8Array(s),"Int8Array",s),uint8Array:s=>B(b.uint8Array(s),"Uint8Array",s),uint8ClampedArray:s=>B(b.uint8ClampedArray(s),"Uint8ClampedArray",s),int16Array:s=>B(b.int16Array(s),"Int16Array",s),uint16Array:s=>B(b.uint16Array(s),"Uint16Array",s),int32Array:s=>B(b.int32Array(s),"Int32Array",s),uint32Array:s=>B(b.uint32Array(s),"Uint32Array",s),float32Array:s=>B(b.float32Array(s),"Float32Array",s),float64Array:s=>B(b.float64Array(s),"Float64Array",s),bigInt64Array:s=>B(b.bigInt64Array(s),"BigInt64Array",s),bigUint64Array:s=>B(b.bigUint64Array(s),"BigUint64Array",s),arrayBuffer:s=>B(b.arrayBuffer(s),"ArrayBuffer",s),sharedArrayBuffer:s=>B(b.sharedArrayBuffer(s),"SharedArrayBuffer",s),dataView:s=>B(b.dataView(s),"DataView",s),enumCase:(s,e)=>B(b.enumCase(s,e),"EnumCase",s),urlInstance:s=>B(b.urlInstance(s),"URL",s),urlString:s=>B(b.urlString(s),"string with a URL",s),truthy:s=>B(b.truthy(s),"truthy",s),falsy:s=>B(b.falsy(s),"falsy",s),nan:s=>B(b.nan(s),"NaN",s),primitive:s=>B(b.primitive(s),"primitive",s),integer:s=>B(b.integer(s),"integer",s),safeInteger:s=>B(b.safeInteger(s),"integer",s),plainObject:s=>B(b.plainObject(s),"plain object",s),typedArray:s=>B(b.typedArray(s),"TypedArray",s),arrayLike:s=>B(b.arrayLike(s),"array-like",s),domElement:s=>B(b.domElement(s),"HTMLElement",s),observable:s=>B(b.observable(s),"Observable",s),nodeStream:s=>B(b.nodeStream(s),"Node.js Stream",s),infinite:s=>B(b.infinite(s),"infinite number",s),emptyArray:s=>B(b.emptyArray(s),"empty array",s),nonEmptyArray:s=>B(b.nonEmptyArray(s),"non-empty array",s),emptyString:s=>B(b.emptyString(s),"empty string",s),emptyStringOrWhitespace:s=>B(b.emptyStringOrWhitespace(s),"empty string or whitespace",s),nonEmptyString:s=>B(b.nonEmptyString(s),"non-empty string",s),nonEmptyStringAndNotWhitespace:s=>B(b.nonEmptyStringAndNotWhitespace(s),"non-empty string and not whitespace",s),emptyObject:s=>B(b.emptyObject(s),"empty object",s),nonEmptyObject:s=>B(b.nonEmptyObject(s),"non-empty object",s),emptySet:s=>B(b.emptySet(s),"empty set",s),nonEmptySet:s=>B(b.nonEmptySet(s),"non-empty set",s),emptyMap:s=>B(b.emptyMap(s),"empty map",s),nonEmptyMap:s=>B(b.nonEmptyMap(s),"non-empty map",s),propertyKey:s=>B(b.propertyKey(s),"PropertyKey",s),formData:s=>B(b.formData(s),"FormData",s),urlSearchParams:s=>B(b.urlSearchParams(s),"URLSearchParams",s),evenInteger:s=>B(b.evenInteger(s),"even integer",s),oddInteger:s=>B(b.oddInteger(s),"odd integer",s),directInstanceOf:(s,e)=>B(b.directInstanceOf(s,e),"T",s),inRange:(s,e)=>B(b.inRange(s,e),"in range",s),any:(s,...e)=>B(b.any(s,...e),"predicate returns truthy for any value",e,{multipleValues:!0}),all:(s,...e)=>B(b.all(s,...e),"predicate returns truthy for all values",e,{multipleValues:!0})};Object.defineProperties(b,{class:{value:b.class_},function:{value:b.function_},null:{value:b.null_}});Object.defineProperties(tt.assert,{class:{value:tt.assert.class_},function:{value:tt.assert.function_},null:{value:tt.assert.null_}});tt.default=b;fn.exports=b;fn.exports.default=b;fn.exports.assert=tt.assert});var lu=$((mC,ai)=>{"use strict";var pn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},gn=class s{static fn(e){return(...t)=>new s((i,a,l)=>{t.push(l),e(...t).then(i,a)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((t,i)=>{this._reject=i;let a=p=>{(!this._isCanceled||!h.shouldReject)&&(this._isPending=!1,t(p))},l=p=>{this._isPending=!1,i(p)},h=p=>{if(!this._isPending)throw new Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(p)};return Object.defineProperties(h,{shouldReject:{get:()=>this._rejectOnCancel,set:p=>{this._rejectOnCancel=p}}}),e(a,l,h)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let t of this._cancelHandlers)t()}catch(t){this._reject(t);return}this._rejectOnCancel&&this._reject(new pn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(gn.prototype,Promise.prototype);ai.exports=gn;ai.exports.CancelError=pn});var uu=$((li,ui)=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});function o_(s){return s.encrypted}var ci=(s,e)=>{let t;typeof e=="function"?t={connect:e}:t=e;let i=typeof t.connect=="function",a=typeof t.secureConnect=="function",l=typeof t.close=="function",h=()=>{i&&t.connect(),o_(s)&&a&&(s.authorized?t.secureConnect():s.authorizationError||s.once("secureConnect",t.secureConnect)),l&&s.once("close",t.close)};s.writable&&!s.connecting?h():s.connecting?s.once("connect",h):s.destroyed&&l&&t.close(s._hadError)};li.default=ci;ui.exports=ci;ui.exports.default=ci});var hu=$((di,fi)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var a_=uu(),c_=q("util"),l_=Number(process.versions.node.split(".")[0]),hi=s=>{if(s.timings)return s.timings;let e={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};s.timings=e;let t=p=>{let g=p.emit.bind(p);p.emit=(m,...v)=>(m==="error"&&(e.error=Date.now(),e.phases.total=e.error-e.start,p.emit=g),g(m,...v))};t(s);let i=()=>{e.abort=Date.now(),(!e.response||l_>=13)&&(e.phases.total=Date.now()-e.start)};s.prependOnceListener("abort",i);let a=p=>{if(e.socket=Date.now(),e.phases.wait=e.socket-e.start,c_.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),a_.default(p,{connect:()=>{e.connect=Date.now(),e.lookup===void 0&&(p.removeListener("lookup",g),e.lookup=e.connect,e.phases.dns=e.lookup-e.socket),e.phases.tcp=e.connect-e.lookup},secureConnect:()=>{e.secureConnect=Date.now(),e.phases.tls=e.secureConnect-e.connect}})};s.socket?a(s.socket):s.prependOnceListener("socket",a);let l=()=>{var p;e.upload=Date.now(),e.phases.request=e.upload-((p=e.secureConnect)!==null&&p!==void 0?p:e.connect)};return(typeof s.writableFinished=="boolean"?s.writableFinished:s.finished&&s.outputSize===0&&(!s.socket||s.socket.writableLength===0))?l():s.prependOnceListener("finish",l),s.prependOnceListener("response",p=>{e.response=Date.now(),e.phases.firstByte=e.response-e.upload,p.timings=e,t(p),p.prependOnceListener("end",()=>{e.end=Date.now(),e.phases.download=e.end-e.response,e.phases.total=e.end-e.start}),p.prependOnceListener("aborted",i)}),e};di.default=hi;fi.exports=hi;fi.exports.default=hi});var _u=$((yC,mi)=>{"use strict";var{V4MAPPED:u_,ADDRCONFIG:h_,ALL:yu,promises:{Resolver:du},lookup:d_}=q("dns"),{promisify:pi}=q("util"),f_=q("os"),Ht=Symbol("cacheableLookupCreateConnection"),gi=Symbol("cacheableLookupInstance"),fu=Symbol("expires"),p_=typeof yu=="number",pu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},g_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},gu=()=>{let s=!1,e=!1;for(let t of Object.values(f_.networkInterfaces()))for(let i of t)if(!i.internal&&(i.family==="IPv6"?e=!0:s=!0,s&&e))return{has4:s,has6:e};return{has4:s,has6:e}},m_=s=>Symbol.iterator in s,mu={ttl:!0},y_={all:!0},mn=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:l=new du,lookup:h=d_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=l,this._dnsLookup=pi(h),this._resolver instanceof du?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=pi(this._resolver.resolve4.bind(this._resolver)),this._resolve6=pi(this._resolver.resolve6.bind(this._resolver))),this._iface=gu(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,i<1)this._fallback=!1;else{this._fallback=!0;let p=setInterval(()=>{this._hostnamesToFallback.clear()},i*1e3);p.unref&&p.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,t,i){if(typeof t=="function"?(i=t,t={}):typeof t=="number"&&(t={family:t}),!i)throw new Error("Callback must be a function.");this.lookupAsync(e,t).then(a=>{t.all?i(null,a):i(null,a.address,a.family,a.expires,a.ttl)},i)}async lookupAsync(e,t={}){typeof t=="number"&&(t={family:t});let i=await this.query(e);if(t.family===6){let a=i.filter(l=>l.family===6);t.hints&u_&&(p_&&t.hints&yu||a.length===0)?g_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&h_){let{_iface:a}=this;i=i.filter(l=>l.family===6?a.has6:a.has4)}if(i.length===0){let a=new Error(`cacheableLookup ENOTFOUND ${e}`);throw a.code="ENOTFOUND",a.hostname=e,a}return t.all?i:i[0]}async query(e){let t=await this._cache.get(e);if(!t){let i=this._pending[e];if(i)t=await i;else{let a=this.queryAndCache(e);this._pending[e]=a;try{t=await a}finally{delete this._pending[e]}}}return t=t.map(i=>({...i})),t}async _resolve(e){let t=async m=>{try{return await m}catch(v){if(v.code==="ENODATA"||v.code==="ENOTFOUND")return[];throw v}},[i,a]=await Promise.all([this._resolve4(e,mu),this._resolve6(e,mu)].map(m=>t(m))),l=0,h=0,p=0,g=Date.now();for(let m of i)m.family=4,m.expires=g+m.ttl*1e3,l=Math.max(l,m.ttl);for(let m of a)m.family=6,m.expires=g+m.ttl*1e3,h=Math.max(h,m.ttl);return i.length>0?a.length>0?p=Math.min(l,h):p=l:p=h,{entries:[...i,...a],cacheTtl:p}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,t,i){if(this.maxTtl>0&&i>0){i=Math.min(i,this.maxTtl)*1e3,t[fu]=Date.now()+i;try{await this._cache.set(e,t,i)}catch(a){this.lookupAsync=async()=>{let l=new Error("Cache Error. Please recreate the CacheableLookup instance.");throw l.cause=a,l}}m_(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,y_);let t=await this._resolve(e);t.entries.length===0&&this._fallback&&(t=await this._lookup(e),t.entries.length!==0&&this._hostnamesToFallback.add(e));let i=t.entries.length===0?this.errorTtl:t.cacheTtl;return await this._set(e,t.entries,i),t.entries}_tick(e){let t=this._nextRemovalTime;(!t||e<t)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let i=1/0,a=Date.now();for(let[l,h]of this._cache){let p=h[fu];a>=p?this._cache.delete(l):p<i&&(i=p)}i!==1/0&&this._tick(i-a)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(pu(e),Ht in e)throw new Error("CacheableLookup has been already installed");e[Ht]=e.createConnection,e[gi]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Ht](t,i))}uninstall(e){if(pu(e),e[Ht]){if(e[gi]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Ht],delete e[Ht],delete e[gi]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=gu(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){if(e){this._cache.delete(e);return}this._cache.clear()}};mi.exports=mn;mi.exports.default=mn});var wu=$((_C,vu)=>{"use strict";var __="text/plain",b_="us-ascii",bu=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),v_=(s,{stripHash:e})=>{let t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(s);if(!t)throw new Error(`Invalid URL: ${s}`);let{type:i,data:a,hash:l}=t.groups,h=i.split(";");l=e?"":l;let p=!1;h[h.length-1]==="base64"&&(h.pop(),p=!0);let g=(h.shift()||"").toLowerCase(),v=[...h.map(C=>{let[k,S=""]=C.split("=").map(A=>A.trim());return k==="charset"&&(S=S.toLowerCase(),S===b_)?"":`${k}${S?`=${S}`:""}`}).filter(Boolean)];return p&&v.push("base64"),(v.length!==0||g&&g!==__)&&v.unshift(g),`data:${v.join(";")},${p?a.trim():a}${l?`#${l}`:""}`},w_=(s,e)=>{if(e={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},s=s.trim(),/^data:/i.test(s))return v_(s,e);if(/^view-source:/i.test(s))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let t=s.startsWith("//");!t&&/^\.*\//.test(s)||(s=s.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));let a=new URL(s);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&a.protocol==="https:"&&(a.protocol="http:"),e.forceHttps&&a.protocol==="http:"&&(a.protocol="https:"),e.stripAuthentication&&(a.username="",a.password=""),e.stripHash?a.hash="":e.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,"")),a.pathname&&(a.pathname=a.pathname.replace(/(?<!\b(?:[a-z][a-z\d+\-.]{1,50}:))\/{2,}/g,"/")),a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let h=a.pathname.split("/"),p=h[h.length-1];bu(p,e.removeDirectoryIndex)&&(h=h.slice(0,h.length-1),a.pathname=h.slice(1).join("/")+"/")}if(a.hostname&&(a.hostname=a.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(let h of[...a.searchParams.keys()])bu(h,e.removeQueryParameters)&&a.searchParams.delete(h);e.removeQueryParameters===!0&&(a.search=""),e.sortQueryParameters&&a.searchParams.sort(),e.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\/$/,""));let l=s;return s=a.toString(),!e.removeSingleSlash&&a.pathname==="/"&&!l.endsWith("/")&&a.hash===""&&(s=s.replace(/\/$/,"")),(e.removeTrailingSlash||a.pathname==="/")&&a.hash===""&&e.removeSingleSlash&&(s=s.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(s=s.replace(/^http:\/\//,"//")),e.stripProtocol&&(s=s.replace(/^(?:https?:)?\/\//,"")),s};vu.exports=w_});var ku=$((bC,Eu)=>{Eu.exports=Cu;function Cu(s,e){if(s&&e)return Cu(s)(e);if(typeof s!="function")throw new TypeError("need wrapper function");return Object.keys(s).forEach(function(i){t[i]=s[i]}),t;function t(){for(var i=new Array(arguments.length),a=0;a<i.length;a++)i[a]=arguments[a];var l=s.apply(this,i),h=i[i.length-1];return typeof l=="function"&&l!==h&&Object.keys(h).forEach(function(p){l[p]=h[p]}),l}}});var _i=$((vC,yi)=>{var Ou=ku();yi.exports=Ou(yn);yi.exports.strict=Ou(Su);yn.proto=yn(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return yn(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return Su(this)},configurable:!0})});function yn(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function Su(s){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=s.apply(this,arguments)},t=s.name||"Function wrapped with `once`";return e.onceError=t+" shouldn't be called more than once",e.called=!1,e}});var Ru=$((wC,Au)=>{var C_=_i(),E_=function(){},k_=global.Bare?queueMicrotask:process.nextTick.bind(process),O_=function(s){return s.setHeader&&typeof s.abort=="function"},S_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Tu=function(s,e,t){if(typeof e=="function")return Tu(s,null,e);e||(e={}),t=C_(t||E_);var i=s._writableState,a=s._readableState,l=e.readable||e.readable!==!1&&s.readable,h=e.writable||e.writable!==!1&&s.writable,p=!1,g=function(){s.writable||m()},m=function(){h=!1,l||t.call(s)},v=function(){l=!1,h||t.call(s)},C=function(O){t.call(s,O?new Error("exited with error code: "+O):null)},k=function(O){t.call(s,O)},S=function(){k_(A)},A=function(){if(!p){if(l&&!(a&&a.ended&&!a.destroyed))return t.call(s,new Error("premature close"));if(h&&!(i&&i.ended&&!i.destroyed))return t.call(s,new Error("premature close"))}},E=function(){s.req.on("finish",m)};return O_(s)?(s.on("complete",m),s.on("abort",S),s.req?E():s.on("request",E)):h&&!i&&(s.on("end",g),s.on("close",g)),S_(s)&&s.on("exit",C),s.on("end",v),s.on("finish",m),e.error!==!1&&s.on("error",k),s.on("close",S),function(){p=!0,s.removeListener("complete",m),s.removeListener("abort",S),s.removeListener("request",E),s.req&&s.req.removeListener("finish",m),s.removeListener("end",g),s.removeListener("close",g),s.removeListener("finish",m),s.removeListener("exit",C),s.removeListener("end",v),s.removeListener("error",k),s.removeListener("close",S)}};Au.exports=Tu});var Mu=$((CC,Iu)=>{var T_=_i(),A_=Ru(),_n;try{_n=q("fs")}catch{}var ws=function(){},R_=typeof process>"u"?!1:/^v?\.0/.test(process.version),bn=function(s){return typeof s=="function"},P_=function(s){return!R_||!_n?!1:(s instanceof(_n.ReadStream||ws)||s instanceof(_n.WriteStream||ws))&&bn(s.close)},I_=function(s){return s.setHeader&&bn(s.abort)},M_=function(s,e,t,i){i=T_(i);var a=!1;s.on("close",function(){a=!0}),A_(s,{readable:e,writable:t},function(h){if(h)return i(h);a=!0,i()});var l=!1;return function(h){if(!a&&!l){if(l=!0,P_(s))return s.close(ws);if(I_(s))return s.abort();if(bn(s.destroy))return s.destroy();i(h||new Error("stream was destroyed"))}}},Pu=function(s){s()},x_=function(s,e){return s.pipe(e)},N_=function(){var s=Array.prototype.slice.call(arguments),e=bn(s[s.length-1]||ws)&&s.pop()||ws;if(Array.isArray(s[0])&&(s=s[0]),s.length<2)throw new Error("pump requires two streams per minimum");var t,i=s.map(function(a,l){var h=l<s.length-1,p=l>0;return M_(a,h,p,function(g){t||(t=g),g&&i.forEach(Pu),!h&&(i.forEach(Pu),e(t))})});return s.reduce(x_)};Iu.exports=N_});var Nu=$((EC,xu)=>{"use strict";var{PassThrough:L_}=q("stream");xu.exports=s=>{s={...s};let{array:e}=s,{encoding:t}=s,i=t==="buffer",a=!1;e?a=!(t||i):t=t||"utf8",i&&(t=null);let l=new L_({objectMode:a});t&&l.setEncoding(t);let h=0,p=[];return l.on("data",g=>{p.push(g),a?h=p.length:h+=g.length}),l.getBufferedValue=()=>e?p:i?Buffer.concat(p,h):p.join(""),l.getBufferedLength=()=>h,l}});var Lu=$((kC,Gt)=>{"use strict";var{constants:j_}=q("buffer"),D_=Mu(),U_=Nu(),vn=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function wn(s,e){if(!s)return Promise.reject(new Error("Expected a stream"));e={maxBuffer:1/0,...e};let{maxBuffer:t}=e,i;return await new Promise((a,l)=>{let h=p=>{p&&i.getBufferedLength()<=j_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),l(p)};i=D_(s,U_(e),p=>{if(p){h(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&h(new vn)})}),i.getBufferedValue()}Gt.exports=wn;Gt.exports.default=wn;Gt.exports.buffer=(s,e)=>wn(s,{...e,encoding:"buffer"});Gt.exports.array=(s,e)=>wn(s,{...e,array:!0});Gt.exports.MaxBufferError=vn});var Du=$((SC,ju)=>{"use strict";var q_=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),B_=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),$_=new Set([500,502,503,504]),H_={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},G_={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function nt(s){let e=parseInt(s,10);return isFinite(e)?e:0}function F_(s){return s?$_.has(s.status):!0}function bi(s){let e={};if(!s)return e;let t=s.trim().split(/,/);for(let i of t){let[a,l]=i.split(/=/,2);e[a.trim()]=l===void 0?!0:l.trim().replace(/^"|"$/g,"")}return e}function W_(s){let e=[];for(let t in s){let i=s[t];e.push(i===!0?t:t+"="+i)}if(e.length)return e.join(", ")}ju.exports=class{constructor(e,t,{shared:i,cacheHeuristic:a,immutableMinTimeToLive:l,ignoreCargoCult:h,_fromObject:p}={}){if(p){this._fromObject(p);return}if(!t||!t.headers)throw Error("Response headers missing");this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=i!==!1,this._ignoreCargoCult=!!h,this._cacheHeuristic=a!==void 0?a:.1,this._immutableMinTtl=l!==void 0?l:24*3600*1e3,this._status="status"in t?t.status:200,this._resHeaders=t.headers,this._rescc=bi(t.headers["cache-control"]),this._method="method"in e?e.method:"GET",this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=t.headers.vary?e.headers:null,this._reqcc=bi(e.headers["cache-control"]),this._ignoreCargoCult&&"pre-check"in this._rescc&&"post-check"in this._rescc&&(delete this._rescc["pre-check"],delete this._rescc["post-check"],delete this._rescc["no-cache"],delete this._rescc["no-store"],delete this._rescc["must-revalidate"],this._resHeaders=Object.assign({},this._resHeaders,{"cache-control":W_(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),t.headers["cache-control"]==null&&/no-cache/.test(t.headers.pragma)&&(this._rescc["no-cache"]=!0)}now(){return Date.now()}storable(){return!!(!this._reqcc["no-store"]&&(this._method==="GET"||this._method==="HEAD"||this._method==="POST"&&this._hasExplicitExpiration())&&B_.has(this._status)&&!this._rescc["no-store"]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc["max-age"]||this._isShared&&this._rescc["s-maxage"]||this._rescc.public||q_.has(this._status)))}_hasExplicitExpiration(){return!!(this._isShared&&this._rescc["s-maxage"]||this._rescc["max-age"]||this._resHeaders.expires)}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error("Request headers missing")}satisfiesWithoutRevalidation(e){return!this.evaluateRequest(e).revalidation}_evaluateRequestHitResult(e){return{response:{headers:this.responseHeaders()},revalidation:e}}_evaluateRequestRevalidation(e,t){return{synchronous:t,headers:this.revalidationHeaders(e)}}_evaluateRequestMissResult(e){return{response:void 0,revalidation:this._evaluateRequestRevalidation(e,!0)}}evaluateRequest(e){if(this._assertRequestHasHeaders(e),this._rescc["must-revalidate"])return this._evaluateRequestMissResult(e);if(!this._requestMatches(e,!1))return this._evaluateRequestMissResult(e);let t=bi(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>nt(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<nt(t["min-fresh"])?this._evaluateRequestMissResult(e):this.stale()?"max-stale"in t&&(t["max-stale"]===!0||t["max-stale"]>this.age()-this.maxAge())?this._evaluateRequestHitResult(void 0):this.useStaleWhileRevalidate()?this._evaluateRequestHitResult(this._evaluateRequestRevalidation(e,!1)):this._evaluateRequestMissResult(e):this._evaluateRequestHitResult(void 0)}_requestMatches(e,t){return!!((!this._url||this._url===e.url)&&this._host===e.headers.host&&(!e.method||this._method===e.method||t&&e.method==="HEAD")&&this._varyMatches(e))}_allowsStoringAuthenticated(){return!!(this._rescc["must-revalidate"]||this._rescc.public||this._rescc["s-maxage"])}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary==="*")return!1;let t=this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);for(let i of t)if(e.headers[i]!==this._reqHeaders[i])return!1;return!0}_copyWithoutHopByHopHeaders(e){let t={};for(let i in e)H_[i]||(t[i]=e[i]);if(e.connection){let i=e.connection.trim().split(/\s*,\s*/);for(let a of i)delete t[a]}if(t.warning){let i=t.warning.split(/,/).filter(a=>!/^\s*1[0-9][0-9]/.test(a));i.length?t.warning=i.join(",").trim():delete t.warning}return t}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),t=this.age();return t>3600*24&&!this._hasExplicitExpiration()&&this.maxAge()>3600*24&&(e.warning=(e.warning?`${e.warning}, `:"")+'113 - "rfc7234 5.5.4"'),e.age=`${Math.round(t)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){let e=this._ageValue(),t=(this.now()-this._responseTime)/1e3;return e+t}_ageValue(){return nt(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc["no-cache"]||this._isShared&&this._resHeaders["set-cookie"]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary==="*")return 0;if(this._isShared){if(this._rescc["proxy-revalidate"])return 0;if(this._rescc["s-maxage"])return nt(this._rescc["s-maxage"])}if(this._rescc["max-age"])return nt(this._rescc["max-age"]);let e=this._rescc.immutable?this._immutableMinTtl:0,t=this.date();if(this._resHeaders.expires){let i=Date.parse(this._resHeaders.expires);return Number.isNaN(i)||i<t?0:Math.max(e,(i-t)/1e3)}if(this._resHeaders["last-modified"]){let i=Date.parse(this._resHeaders["last-modified"]);if(isFinite(i)&&t>i)return Math.max(e,(t-i)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),t=e+nt(this._rescc["stale-if-error"]),i=e+nt(this._rescc["stale-while-revalidate"]);return Math.round(Math.max(0,e,t,i)*1e3)}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+nt(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=nt(this._rescc["stale-while-revalidate"]);return e>0&&this.maxAge()+e>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error("Reinitialized");if(!e||e.v!==1)throw Error("Invalid serialization");this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm!==void 0?e.imm:24*3600*1e3,this._ignoreCargoCult=!!e.icc,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,icc:this._ignoreCargoCult,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let t=this._copyWithoutHopByHopHeaders(e.headers);if(delete t["if-range"],!this._requestMatches(e,!0)||!this.storable())return delete t["if-none-match"],delete t["if-modified-since"],t;if(this._resHeaders.etag&&(t["if-none-match"]=t["if-none-match"]?`${t["if-none-match"]}, ${this._resHeaders.etag}`:this._resHeaders.etag),t["accept-ranges"]||t["if-match"]||t["if-unmodified-since"]||this._method&&this._method!="GET"){if(delete t["if-modified-since"],t["if-none-match"]){let a=t["if-none-match"].split(/,/).filter(l=>!/^\s*W\//.test(l));a.length?t["if-none-match"]=a.join(",").trim():delete t["if-none-match"]}}else this._resHeaders["last-modified"]&&!t["if-modified-since"]&&(t["if-modified-since"]=this._resHeaders["last-modified"]);return t}revalidatedPolicy(e,t){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&F_(t))return{policy:this,modified:!1,matches:!0};if(!t||!t.headers)throw Error("Response headers missing");let i=!1;t.status!==void 0&&t.status!=304?i=!1:t.headers.etag&&!/^\s*W\//.test(t.headers.etag)?i=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag:this._resHeaders.etag&&t.headers.etag?i=this._resHeaders.etag.replace(/^\s*W\//,"")===t.headers.etag.replace(/^\s*W\//,""):this._resHeaders["last-modified"]?i=this._resHeaders["last-modified"]===t.headers["last-modified"]:!this._resHeaders.etag&&!this._resHeaders["last-modified"]&&!t.headers.etag&&!t.headers["last-modified"]&&(i=!0);let a={shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl,ignoreCargoCult:this._ignoreCargoCult};if(!i)return{policy:new this.constructor(e,t,a),modified:t.status!=304,matches:!1};let l={};for(let p in this._resHeaders)l[p]=p in t.headers&&!G_[p]?t.headers[p]:this._resHeaders[p];let h=Object.assign({},t,{status:this._status,method:this._method,headers:l});return{policy:new this.constructor(e,h,a),modified:!1,matches:!0}}}});var Cn=$((TC,Uu)=>{"use strict";Uu.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Bu=$((AC,qu)=>{"use strict";var V_=q("stream").Readable,z_=Cn(),vi=class extends V_{constructor(e,t,i,a){if(typeof e!="number")throw new TypeError("Argument `statusCode` should be a number");if(typeof t!="object")throw new TypeError("Argument `headers` should be an object");if(!(i instanceof Buffer))throw new TypeError("Argument `body` should be a buffer");if(typeof a!="string")throw new TypeError("Argument `url` should be a string");super(),this.statusCode=e,this.headers=z_(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};qu.exports=vi});var Hu=$((RC,$u)=>{"use strict";var K_=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];$u.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(K_));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Fu=$((PC,Gu)=>{"use strict";var J_=q("stream").PassThrough,Y_=Hu(),Q_=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new J_;return Y_(s,e),s.pipe(e)};Gu.exports=Q_});var Wu=$(wi=>{wi.stringify=function s(e){if(typeof e>"u")return e;if(e&&Buffer.isBuffer(e))return JSON.stringify(":base64:"+e.toString("base64"));if(e&&e.toJSON&&(e=e.toJSON()),e&&typeof e=="object"){var t="",i=Array.isArray(e);t=i?"[":"{";var a=!0;for(var l in e){var h=typeof e[l]=="function"||!i&&typeof e[l]>"u";Object.hasOwnProperty.call(e,l)&&!h&&(a||(t+=","),a=!1,i?e[l]==null?t+="null":t+=s(e[l]):e[l]!==void 0&&(t+=s(l)+":"+s(e[l])))}return t+=i?"]":"}",t}else return typeof e=="string"?JSON.stringify(/^:/.test(e)?":"+e:e):typeof e>"u"?"null":JSON.stringify(e)};wi.parse=function(s){return JSON.parse(s,function(e,t){return typeof t=="string"?/^:base64:/.test(t)?Buffer.from(t.substring(8),"base64"):/^:/.test(t)?t.substring(1):t:t})}});var Ju=$((MC,Ku)=>{"use strict";var X_=q("events"),Vu=Wu(),Z_=s=>{let e={redis:"@keyv/redis",rediss:"@keyv/redis",mongodb:"@keyv/mongo",mongo:"@keyv/mongo",sqlite:"@keyv/sqlite",postgresql:"@keyv/postgres",postgres:"@keyv/postgres",mysql:"@keyv/mysql",etcd:"@keyv/etcd",offline:"@keyv/offline",tiered:"@keyv/tiered"};if(s.adapter||s.uri){let t=s.adapter||/^[^:+]*/.exec(s.uri)[0];return new(q(e[t]))(s)}return new Map},zu=["sqlite","postgres","mysql","mongo","redis","tiered"],Ci=class extends X_{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:Vu.stringify,deserialize:Vu.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let l={...this.opts};this.opts.store=Z_(l)}if(this.opts.compression){let l=this.opts.compression;this.opts.serialize=l.serialize.bind(l),this.opts.deserialize=l.deserialize.bind(l)}typeof this.opts.store.on=="function"&&t&&this.opts.store.on("error",l=>this.emit("error",l)),this.opts.store.namespace=this.opts.namespace;let a=l=>async function*(){for await(let[h,p]of typeof l=="function"?l(this.opts.store.namespace):l){let g=await this.opts.deserialize(p);if(!(this.opts.store.namespace&&!h.includes(this.opts.store.namespace))){if(typeof g.expires=="number"&&Date.now()>g.expires){this.delete(h);continue}yield[this._getKeyUnprefix(h),g.value]}}};typeof this.opts.store[Symbol.iterator]=="function"&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator=="function"&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return zu.includes(this.opts.store.opts.dialect)||zu.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(t=>`${this.opts.namespace}:${t}`)}_getKeyUnprefix(e){return e.split(":").splice(1).join(":")}get(e,t){let{store:i}=this.opts,a=Array.isArray(e),l=a?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(a&&i.getMany===void 0){let h=[];for(let p of l)h.push(Promise.resolve().then(()=>i.get(p)).then(g=>typeof g=="string"?this.opts.deserialize(g):this.opts.compression?this.opts.deserialize(g):g).then(g=>{if(g!=null)return typeof g.expires=="number"&&Date.now()>g.expires?this.delete(p).then(()=>{}):t&&t.raw?g:g.value}));return Promise.allSettled(h).then(p=>{let g=[];for(let m of p)g.push(m.value);return g})}return Promise.resolve().then(()=>a?i.getMany(l):i.get(l)).then(h=>typeof h=="string"?this.opts.deserialize(h):this.opts.compression?this.opts.deserialize(h):h).then(h=>{if(h!=null)return a?h.map((p,g)=>{if(typeof p=="string"&&(p=this.opts.deserialize(p)),p!=null){if(typeof p.expires=="number"&&Date.now()>p.expires){this.delete(e[g]).then(()=>{});return}return t&&t.raw?p:p.value}}):typeof h.expires=="number"&&Date.now()>h.expires?this.delete(e).then(()=>{}):t&&t.raw?h:h.value})}set(e,t,i){let a=this._getKeyPrefix(e);typeof i>"u"&&(i=this.opts.ttl),i===0&&(i=void 0);let{store:l}=this.opts;return Promise.resolve().then(()=>{let h=typeof i=="number"?Date.now()+i:null;return typeof t=="symbol"&&this.emit("error","symbol cannot be serialized"),t={value:t,expires:h},this.opts.serialize(t)}).then(h=>l.set(a,h,i)).then(()=>!0)}delete(e){let{store:t}=this.opts;if(Array.isArray(e)){let a=this._getKeyPrefixArray(e);if(t.deleteMany===void 0){let l=[];for(let h of a)l.push(t.delete(h));return Promise.allSettled(l).then(h=>h.every(p=>p.value===!0))}return Promise.resolve().then(()=>t.deleteMany(a))}let i=this._getKeyPrefix(e);return Promise.resolve().then(()=>t.delete(i))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let t=this._getKeyPrefix(e),{store:i}=this.opts;return Promise.resolve().then(async()=>typeof i.has=="function"?i.has(t):await i.get(t)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect=="function")return e.disconnect()}};Ku.exports=Ci});var Xu=$((NC,Qu)=>{"use strict";var eb=q("events"),En=q("url"),tb=wu(),sb=Lu(),Ei=Du(),Yu=Bu(),nb=Cn(),rb=Fu(),ib=Ju(),Cs=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new ib({uri:typeof t=="string"&&t,store:typeof t!="string"&&t,namespace:"cacheable-request"}),this.createCacheableRequest(e)}createCacheableRequest(e){return(t,i)=>{let a;if(typeof t=="string")a=ki(En.parse(t)),t={};else if(t instanceof En.URL)a=ki(En.parse(t.toString())),t={};else{let[C,...k]=(t.path||"").split("?"),S=k.length>0?`?${k.join("?")}`:"";a=ki({...t,pathname:C,search:S})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...ob(a)},t.headers=nb(t.headers);let l=new eb,h=tb(En.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${h}`,g=!1,m=!1,v=C=>{m=!0;let k=!1,S,A=new Promise(O=>{S=()=>{k||(k=!0,O())}}),E=O=>{if(g&&!C.forceRefresh){O.status=O.statusCode;let H=Ei.fromObject(g.cachePolicy).revalidatedPolicy(C,O);if(!H.modified){let K=H.policy.responseHeaders();O=new Yu(g.statusCode,K,g.body,g.url),O.cachePolicy=H.policy,O.fromCache=!0}}O.fromCache||(O.cachePolicy=new Ei(C,O,C),O.fromCache=!1);let N;C.cache&&O.cachePolicy.storable()?(N=rb(O),(async()=>{try{let H=sb.buffer(O);if(await Promise.race([A,new Promise(Te=>O.once("end",Te))]),k)return;let K=await H,se={cachePolicy:O.cachePolicy.toObject(),url:O.url,statusCode:O.fromCache?g.statusCode:O.statusCode,body:K},Z=C.strictTtl?O.cachePolicy.timeToLive():void 0;C.maxTtl&&(Z=Z?Math.min(Z,C.maxTtl):C.maxTtl),await this.cache.set(p,se,Z)}catch(H){l.emit("error",new s.CacheError(H))}})()):C.cache&&g&&(async()=>{try{await this.cache.delete(p)}catch(H){l.emit("error",new s.CacheError(H))}})(),l.emit("response",N||O),typeof i=="function"&&i(N||O)};try{let O=e(C,E);O.once("error",S),O.once("abort",S),l.emit("request",O)}catch(O){l.emit("error",new s.RequestError(O))}};return(async()=>{let C=async S=>{await Promise.resolve();let A=S.cache?await this.cache.get(p):void 0;if(typeof A>"u")return v(S);let E=Ei.fromObject(A.cachePolicy);if(E.satisfiesWithoutRevalidation(S)&&!S.forceRefresh){let O=E.responseHeaders(),N=new Yu(A.statusCode,O,A.body,A.url);N.cachePolicy=E,N.fromCache=!0,l.emit("response",N),typeof i=="function"&&i(N)}else g=A,S.headers=E.revalidationHeaders(S),v(S)},k=S=>l.emit("error",new s.CacheError(S));this.cache.once("error",k),l.on("response",()=>this.cache.removeListener("error",k));try{await C(t)}catch(S){t.automaticFailover&&!m&&v(t),l.emit("error",new s.CacheError(S))}})(),l}}};function ob(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function ki(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}Cs.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};Cs.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};Qu.exports=Cs});var eh=$((DC,Zu)=>{"use strict";var ab=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];Zu.exports=(s,e)=>{if(e._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");let t=new Set(Object.keys(s).concat(ab)),i={};for(let a of t)a in e||(i[a]={get(){let l=s[a];return typeof l=="function"?l.bind(s):l},set(l){s[a]=l},enumerable:!0,configurable:!1});return Object.defineProperties(e,i),s.once("aborted",()=>{e.destroy(),e.emit("aborted")}),s.once("close",()=>{s.complete&&e.readable?e.once("end",()=>{e.emit("close")}):e.emit("close")}),e}});var sh=$((UC,th)=>{"use strict";var{Transform:cb,PassThrough:lb}=q("stream"),Oi=q("zlib"),ub=eh();th.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof Oi.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new cb({transform(p,g,m){i=!1,m(null,p)},flush(p){p()}}),l=new lb({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),h=t?Oi.createBrotliDecompress():Oi.createUnzip();return h.once("error",p=>{if(i&&!s.readable){l.end();return}l.destroy(p)}),ub(s,l),s.pipe(a).pipe(h).pipe(l),l}});var Ti=$((qC,nh)=>{"use strict";var Si=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction=="function")for(let[i,a]of this.oldCache.entries())this.onEviction(i,a);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};nh.exports=Si});var Ri=$((BC,ah)=>{"use strict";var hb=q("events"),db=q("tls"),fb=q("http2"),pb=Ti(),be=Symbol("currentStreamsCount"),rh=Symbol("request"),Me=Symbol("cachedOriginSet"),Ft=Symbol("gracefullyClosing"),gb=["maxDeflateDynamicTableSize","maxSessionMemory","maxHeaderListPairs","maxOutstandingPings","maxReservedRemoteStreams","maxSendHeaderBlockLength","paddingStrategy","localAddress","path","rejectUnauthorized","minDHSize","ca","cert","clientCertEngine","ciphers","key","pfx","servername","minVersion","maxVersion","secureProtocol","crl","honorCipherOrder","ecdhCurve","dhparam","secureOptions","sessionIdContext"],mb=(s,e,t)=>{let i=0,a=s.length;for(;i<a;){let l=i+a>>>1;t(s[l],e)?i=l+1:a=l}return i},yb=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Ai=(s,e)=>{for(let t of s)t[Me].length<e[Me].length&&t[Me].every(i=>e[Me].includes(i))&&t[be]+e[be]<=e.remoteSettings.maxConcurrentStreams&&oh(t)},_b=(s,e)=>{for(let t of s)e[Me].length<t[Me].length&&e[Me].every(i=>t[Me].includes(i))&&e[be]+t[be]<=t.remoteSettings.maxConcurrentStreams&&oh(e)},ih=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let l=s.sessions[i].filter(h=>{let p=h[Et.kCurrentStreamsCount]<h.remoteSettings.maxConcurrentStreams;return e?p:!p});l.length!==0&&(t[i]=l)}return t},oh=s=>{s[Ft]=!0,s[be]===0&&s.close()},Et=class s extends hb{constructor({timeout:e=6e4,maxSessions:t=1/0,maxFreeSessions:i=10,maxCachedTlsSessions:a=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=t,this.maxFreeSessions=i,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new pb({maxSize:a})}static normalizeOrigin(e,t){return typeof e=="string"&&(e=new URL(e)),t&&e.hostname!==t&&(e.hostname=t),e.origin}normalizeOptions(e){let t="";if(e)for(let i of gb)e[i]&&(t+=`:${e[i]}`);return t}_tryToCreateNewSession(e,t){if(!(e in this.queue)||!(t in this.queue[e]))return;let i=this.queue[e][t];this._sessionsCount<this.maxSessions&&!i.completed&&(i.completed=!0,i())}getSession(e,t,i){return new Promise((a,l)=>{Array.isArray(i)?(i=[...i],a()):i=[{resolve:a,reject:l}];let h=this.normalizeOptions(t),p=s.normalizeOrigin(e,t&&t.servername);if(p===void 0){for(let{reject:v}of i)v(new TypeError("The `origin` argument needs to be a string or an URL object"));return}if(h in this.sessions){let v=this.sessions[h],C=-1,k=-1,S;for(let A of v){let E=A.remoteSettings.maxConcurrentStreams;if(E<C)break;if(A[Me].includes(p)){let O=A[be];if(O>=E||A[Ft]||A.destroyed)continue;S||(C=E),O>k&&(S=A,k=O)}}if(S){if(i.length!==1){for(let{reject:A}of i){let E=new Error(`Expected the length of listeners to be 1, got ${i.length}.
|
|
34
|
+
Please report this to https://github.com/szmarczak/http2-wrapper/`);A(E)}return}i[0].resolve(S);return}}if(h in this.queue){if(p in this.queue[h]){this.queue[h][p].listeners.push(...i),this._tryToCreateNewSession(h,p);return}}else this.queue[h]={};let g=()=>{h in this.queue&&this.queue[h][p]===m&&(delete this.queue[h][p],Object.keys(this.queue[h]).length===0&&delete this.queue[h])},m=()=>{let v=`${p}:${h}`,C=!1;try{let k=fb.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(v),...t});k[be]=0,k[Ft]=!1;let S=()=>k[be]<k.remoteSettings.maxConcurrentStreams,A=!0;k.socket.once("session",O=>{this.tlsSessionCache.set(v,O)}),k.once("error",O=>{for(let{reject:N}of i)N(O);this.tlsSessionCache.delete(v)}),k.setTimeout(this.timeout,()=>{k.destroy()}),k.once("close",()=>{if(C){A&&this._freeSessionsCount--,this._sessionsCount--;let O=this.sessions[h];O.splice(O.indexOf(k),1),O.length===0&&delete this.sessions[h]}else{let O=new Error("Session closed without receiving a SETTINGS frame");O.code="HTTP2WRAPPER_NOSETTINGS";for(let{reject:N}of i)N(O);g()}this._tryToCreateNewSession(h,p)});let E=()=>{if(!(!(h in this.queue)||!S())){for(let O of k[Me])if(O in this.queue[h]){let{listeners:N}=this.queue[h][O];for(;N.length!==0&&S();)N.shift().resolve(k);let H=this.queue[h];if(H[O].listeners.length===0&&(delete H[O],Object.keys(H).length===0)){delete this.queue[h];break}if(!S())break}}};k.on("origin",()=>{k[Me]=k.originSet,S()&&(E(),Ai(this.sessions[h],k))}),k.once("remoteSettings",()=>{if(k.ref(),k.unref(),this._sessionsCount++,m.destroyed){let O=new Error("Agent has been destroyed");for(let N of i)N.reject(O);k.destroy();return}k[Me]=k.originSet;{let O=this.sessions;if(h in O){let N=O[h];N.splice(mb(N,k,yb),0,k)}else O[h]=[k]}this._freeSessionsCount+=1,C=!0,this.emit("session",k),E(),g(),k[be]===0&&this._freeSessionsCount>this.maxFreeSessions&&k.close(),i.length!==0&&(this.getSession(p,t,i),i.length=0),k.on("remoteSettings",()=>{E(),Ai(this.sessions[h],k)})}),k[rh]=k.request,k.request=(O,N)=>{if(k[Ft])throw new Error("The session is gracefully closing. No new streams are allowed.");let H=k[rh](O,N);return k.ref(),++k[be],k[be]===k.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,H.once("close",()=>{if(A=S(),--k[be],!k.destroyed&&!k.closed&&(_b(this.sessions[h],k),S()&&!k.closed)){A||(this._freeSessionsCount++,A=!0);let K=k[be]===0;K&&k.unref(),K&&(this._freeSessionsCount>this.maxFreeSessions||k[Ft])?k.close():(Ai(this.sessions[h],k),E())}}),H}}catch(k){for(let S of i)S.reject(k);g()}};m.listeners=i,m.completed=!1,m.destroyed=!1,this.queue[h][p]=m,this._tryToCreateNewSession(h,p)})}request(e,t,i,a){return new Promise((l,h)=>{this.getSession(e,t,[{reject:h,resolve:p=>{try{l(p.request(i,a))}catch(g){h(g)}}}])})}createConnection(e,t){return s.connect(e,t)}static connect(e,t){t.ALPNProtocols=["h2"];let i=e.port||443,a=e.hostname||e.host;return typeof t.servername>"u"&&(t.servername=a),db.connect(i,a,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[be]===0&&t.close()}destroy(e){for(let t of Object.values(this.sessions))for(let i of t)i.destroy(e);for(let t of Object.values(this.queue))for(let i of Object.values(t))i.destroyed=!0;this.queue={}}get freeSessions(){return ih({agent:this,isFree:!0})}get busySessions(){return ih({agent:this,isFree:!1})}};Et.kCurrentStreamsCount=be;Et.kGracefullyClosing=Ft;ah.exports={Agent:Et,globalAgent:new Et}});var Ii=$(($C,ch)=>{"use strict";var{Readable:bb}=q("stream"),Pi=class extends bb{constructor(e,t){super({highWaterMark:t,autoDestroy:!1}),this.statusCode=null,this.statusMessage="",this.httpVersion="2.0",this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,t){return this.req.setTimeout(e,t),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners("data"),this.resume())}_read(){this.req&&this.req._request.resume()}};ch.exports=Pi});var Mi=$((HC,lh)=>{"use strict";lh.exports=s=>{let e={protocol:s.protocol,hostname:typeof s.hostname=="string"&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return typeof s.port=="string"&&s.port.length!==0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var hh=$((GC,uh)=>{"use strict";uh.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var fh=$((FC,dh)=>{"use strict";dh.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var gh=$((VC,ph)=>{"use strict";var Wt=(s,e,t)=>{ph.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};Wt(TypeError,"ERR_INVALID_ARG_TYPE",s=>{let e=s[0].includes(".")?"property":"argument",t=s[1],i=Array.isArray(t);return i&&(t=`${t.slice(0,-1).join(", ")} or ${t.slice(-1)}`),`The "${s[0]}" ${e} must be ${i?"one of":"of"} type ${t}. Received ${typeof s[2]}`});Wt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);Wt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);Wt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);Wt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);Wt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var Di=$((zC,Ch)=>{"use strict";var vb=q("http2"),{Writable:wb}=q("stream"),{Agent:mh,globalAgent:Cb}=Ri(),Eb=Ii(),kb=Mi(),Ob=hh(),Sb=fh(),{ERR_INVALID_ARG_TYPE:xi,ERR_INVALID_PROTOCOL:Tb,ERR_HTTP_HEADERS_SENT:yh,ERR_INVALID_HTTP_TOKEN:Ab,ERR_HTTP_INVALID_HEADER_VALUE:Rb,ERR_INVALID_CHAR:Pb}=gh(),{HTTP2_HEADER_STATUS:_h,HTTP2_HEADER_METHOD:bh,HTTP2_HEADER_PATH:vh,HTTP2_METHOD_CONNECT:Ib}=vb.constants,ye=Symbol("headers"),Ni=Symbol("origin"),Li=Symbol("session"),wh=Symbol("options"),kn=Symbol("flushedHeaders"),Es=Symbol("jobs"),Mb=/^[\^`\-\w!#$%&*+.|~]+$/,xb=/[^\t\u0020-\u007E\u0080-\u00FF]/,ji=class extends wb{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=kb(e instanceof URL?e:new URL(e))),typeof t=="function"||t===void 0?(i=t,t=a?e:{...e}):t={...e,...t},t.h2session)this[Li]=t.h2session;else if(t.agent===!1)this.agent=new mh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new mh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=Cb;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new xi("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new Tb(t.protocol,"https:");let l=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,h=t.hostname||t.host||"localhost";delete t.hostname,delete t.host,delete t.port;let{timeout:p}=t;if(t.timeout=void 0,this[ye]=Object.create(null),this[Es]=[],this.socket=null,this.connection=null,this.method=t.method||"GET",this.path=t.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,t.headers)for(let[g,m]of Object.entries(t.headers))this.setHeader(g,m);t.auth&&!("authorization"in this[ye])&&(this[ye].authorization="Basic "+Buffer.from(t.auth).toString("base64")),t.session=t.tlsSession,t.path=t.socketPath,this[wh]=t,l===443?(this[Ni]=`https://${h}`,":authority"in this[ye]||(this[ye][":authority"]=h)):(this[Ni]=`https://${h}:${l}`,":authority"in this[ye]||(this[ye][":authority"]=`${h}:${l}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[kn]=!1}get method(){return this[ye][bh]}set method(e){e&&(this[ye][bh]=e.toUpperCase())}get path(){return this[ye][vh]}set path(e){e&&(this[ye][vh]=e)}get _mustNotHaveABody(){return this.method==="GET"||this.method==="HEAD"||this.method==="DELETE"}_write(e,t,i){if(this._mustNotHaveABody){i(new Error("The GET, HEAD and DELETE methods must NOT have a body"));return}this.flushHeaders();let a=()=>this._request.write(e,t,i);this._request?a():this[Es].push(a)}_final(e){if(this.destroyed)return;this.flushHeaders();let t=()=>{if(this._mustNotHaveABody){e();return}this._request.end(e)};this._request?t():this[Es].push(t)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit("abort")),this.aborted=!0,this.destroy())}_destroy(e,t){this.res&&this.res._dump(),this._request&&this._request.destroy(),t(e)}async flushHeaders(){if(this[kn]||this.destroyed)return;this[kn]=!0;let e=this.method===Ib,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||Ob(i,this,["timeout","continue","close","error"]);let a=h=>(...p)=>{!this.writable&&!this.destroyed?h(...p):this.once("finish",()=>{h(...p)})};i.once("response",a((h,p,g)=>{let m=new Eb(this.socket,i.readableHighWaterMark);this.res=m,m.req=this,m.statusCode=h[_h],m.headers=h,m.rawHeaders=g,m.once("end",()=>{this.aborted?(m.aborted=!0,m.emit("aborted")):(m.complete=!0,m.socket=null,m.connection=null)}),e?(m.upgrade=!0,this.emit("connect",m,i,Buffer.alloc(0))?this.emit("close"):i.destroy()):(i.on("data",v=>{!m._dumped&&!m.push(v)&&i.pause()}),i.once("end",()=>{m.push(null)}),this.emit("response",m)||m._dump())})),i.once("headers",a(h=>this.emit("information",{statusCode:h[_h]}))),i.once("trailers",a((h,p,g)=>{let{res:m}=this;m.trailers=h,m.rawTrailers=g}));let{socket:l}=i.session;this.socket=l,this.connection=l;for(let h of this[Es])h();this.emit("socket",this.socket)};if(this[Li])try{t(this[Li].request(this[ye]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[Ni],this[wh],this[ye]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new xi("name","string",e);return this[ye][e.toLowerCase()]}get headersSent(){return this[kn]}removeHeader(e){if(typeof e!="string")throw new xi("name","string",e);if(this.headersSent)throw new yh("remove");delete this[ye][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new yh("set");if(typeof e!="string"||!Mb.test(e)&&!Sb(e))throw new Ab("Header name",e);if(typeof t>"u")throw new Rb(t,e);if(xb.test(t))throw new Pb("header content",e);this[ye][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let i=()=>this._request.setTimeout(e,t);return this._request?i():this[Es].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};Ch.exports=ji});var kh=$((KC,Eh)=>{"use strict";var Nb=q("tls");Eh.exports=(s={},e=Nb.connect)=>new Promise((t,i)=>{let a=!1,l,h=async()=>{await g,l.off("timeout",p),l.off("error",i),s.resolveSocket?(t({alpnProtocol:l.alpnProtocol,socket:l,timeout:a}),a&&(await Promise.resolve(),l.emit("timeout"))):(l.destroy(),t({alpnProtocol:l.alpnProtocol,timeout:a}))},p=async()=>{a=!0,h()},g=(async()=>{try{l=await e(s,h),l.on("error",i),l.once("timeout",p)}catch(m){i(m)}})()})});var Sh=$((JC,Oh)=>{"use strict";var Lb=q("net");Oh.exports=s=>{let e=s.host,t=s.headers&&s.headers.host;return t&&(t.startsWith("[")?t.indexOf("]")===-1?e=t:e=t.slice(1,-1):e=t.split(":",1)[0]),Lb.isIP(e)?"":e}});var Rh=$((YC,qi)=>{"use strict";var Th=q("http"),Ui=q("https"),jb=kh(),Db=Ti(),Ub=Di(),qb=Sh(),Bb=Mi(),On=new Db({maxSize:100}),ks=new Map,Ah=(s,e,t)=>{e._httpMessage={shouldKeepAlive:!0};let i=()=>{s.emit("free",e,t)};e.on("free",i);let a=()=>{s.removeSocket(e,t)};e.on("close",a);let l=()=>{s.removeSocket(e,t),e.off("close",a),e.off("free",i),e.off("agentRemove",l)};e.on("agentRemove",l),s.emit("free",e,t)},$b=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!On.has(e)){if(ks.has(e))return(await ks.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=jb(s);ks.set(e,a);try{let{socket:l,alpnProtocol:h}=await a;if(On.set(e,h),s.path=t,h==="h2")l.destroy();else{let{globalAgent:p}=Ui,g=Ui.Agent.prototype.createConnection;i?i.createConnection===g?Ah(i,l,s):l.destroy():p.createConnection===g?Ah(p,l,s):l.destroy()}return ks.delete(e),h}catch(l){throw ks.delete(e),l}}return On.get(e)};qi.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=Bb(new URL(s))),typeof e=="function"&&(t=e,e=void 0),e={ALPNProtocols:["h2","http/1.1"],...s,...e,resolveSocket:!0},!Array.isArray(e.ALPNProtocols)||e.ALPNProtocols.length===0)throw new Error("The `ALPNProtocols` option must be an Array with at least one entry");e.protocol=e.protocol||"https:";let i=e.protocol==="https:";e.host=e.hostname||e.host||"localhost",e.session=e.tlsSession,e.servername=e.servername||qb(e),e.port=e.port||(i?443:80),e._defaultAgent=i?Ui.globalAgent:Th.globalAgent;let a=e.agent;if(a){if(a.addRequest)throw new Error("The `options.agent` object can contain only `http`, `https` or `http2` properties");e.agent=a[i?"https":"http"]}return i&&await $b(e)==="h2"?(a&&(e.agent=a.http2),new Ub(e,t)):Th.request(e,t)};qi.exports.protocolCache=On});var Ih=$((QC,Ph)=>{"use strict";var Hb=q("http2"),Gb=Ri(),Bi=Di(),Fb=Ii(),Wb=Rh(),Vb=(s,e,t)=>new Bi(s,e,t),zb=(s,e,t)=>{let i=new Bi(s,e,t);return i.end(),i};Ph.exports={...Hb,ClientRequest:Bi,IncomingMessage:Fb,...Gb,request:Vb,get:zb,auto:Wb}});var Hi=$($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var Mh=st();$i.default=s=>Mh.default.nodeStream(s)&&Mh.default.function_(s.getBoundary)});var jh=$(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});var Nh=q("fs"),Lh=q("util"),xh=st(),Kb=Hi(),Jb=Lh.promisify(Nh.stat);Gi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(xh.default.string(s))return Buffer.byteLength(s);if(xh.default.buffer(s))return s.length;if(Kb.default(s))return Lh.promisify(s.getLength.bind(s))();if(s instanceof Nh.ReadStream){let{size:t}=await Jb(s.path);return t===0?void 0:t}}});var Wi=$(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});function Yb(s,e,t){let i={};for(let a of t)i[a]=(...l)=>{e.emit(a,...l)},s.on(a,i[a]);return()=>{for(let a of t)s.off(a,i[a])}}Fi.default=Yb});var Dh=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.default=()=>{let s=[];return{once(e,t,i){e.once(t,i),s.push({origin:e,event:t,fn:i})},unhandleAll(){for(let e of s){let{origin:t,event:i,fn:a}=e;t.removeListener(i,a)}s.length=0}}}});var qh=$(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.TimeoutError=void 0;var Qb=q("net"),Xb=Dh(),Uh=Symbol("reentry"),Zb=()=>{},Sn=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};Os.TimeoutError=Sn;Os.default=(s,e,t)=>{if(Uh in s)return Zb;s[Uh]=!0;let i=[],{once:a,unhandleAll:l}=Xb.default(),h=(C,k,S)=>{var A;let E=setTimeout(k,C,C,S);(A=E.unref)===null||A===void 0||A.call(E);let O=()=>{clearTimeout(E)};return i.push(O),O},{host:p,hostname:g}=t,m=(C,k)=>{s.destroy(new Sn(C,k))},v=()=>{for(let C of i)C();l()};if(s.once("error",C=>{if(v(),s.listenerCount("error")===0)throw C}),s.once("close",v),a(s,"response",C=>{a(C,"end",v)}),typeof e.request<"u"&&h(e.request,m,"request"),typeof e.socket<"u"){let C=()=>{m(e.socket,"socket")};s.setTimeout(e.socket,C),i.push(()=>{s.removeListener("timeout",C)})}return a(s,"socket",C=>{var k;let{socketPath:S}=s;if(C.connecting){let A=!!(S??Qb.isIP((k=g??p)!==null&&k!==void 0?k:"")!==0);if(typeof e.lookup<"u"&&!A&&typeof C.address().address>"u"){let E=h(e.lookup,m,"lookup");a(C,"lookup",E)}if(typeof e.connect<"u"){let E=()=>h(e.connect,m,"connect");A?a(C,"connect",E()):a(C,"lookup",O=>{O===null&&a(C,"connect",E())})}typeof e.secureConnect<"u"&&t.protocol==="https:"&&a(C,"connect",()=>{let E=h(e.secureConnect,m,"secureConnect");a(C,"secureConnect",E)})}if(typeof e.send<"u"){let A=()=>h(e.send,m,"send");C.connecting?a(C,"connect",()=>{a(s,"upload-complete",A())}):a(s,"upload-complete",A())}}),typeof e.response<"u"&&a(s,"upload-complete",()=>{let C=h(e.response,m,"response");a(s,"response",C)}),v}});var $h=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var Bh=st();zi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Bh.default.string(s.hostname)&&s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,host:s.host,hash:s.hash,search:s.search,pathname:s.pathname,href:s.href,path:`${s.pathname||""}${s.search||""}`};return Bh.default.string(s.port)&&s.port.length>0&&(e.port=Number(s.port)),(s.username||s.password)&&(e.auth=`${s.username||""}:${s.password||""}`),e}});var Hh=$(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var ev=q("url"),tv=["protocol","host","hostname","port","pathname","search"];Ki.default=(s,e)=>{var t,i;if(e.path){if(e.pathname)throw new TypeError("Parameters `path` and `pathname` are mutually exclusive.");if(e.search)throw new TypeError("Parameters `path` and `search` are mutually exclusive.");if(e.searchParams)throw new TypeError("Parameters `path` and `searchParams` are mutually exclusive.")}if(e.search&&e.searchParams)throw new TypeError("Parameters `search` and `searchParams` are mutually exclusive.");if(!s){if(!e.protocol)throw new TypeError("No URL protocol specified");s=`${e.protocol}//${(i=(t=e.hostname)!==null&&t!==void 0?t:e.host)!==null&&i!==void 0?i:""}`}let a=new ev.URL(s);if(e.path){let l=e.path.indexOf("?");l===-1?e.pathname=e.path:(e.pathname=e.path.slice(0,l),e.search=e.path.slice(l+1)),delete e.path}for(let l of tv)e[l]&&(a[l]=e[l].toString());return a}});var Gh=$(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});var Ji=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,t){typeof e=="object"?this.weakMap.set(e,t):this.map.set(e,t)}get(e){return typeof e=="object"?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e=="object"?this.weakMap.has(e):this.map.has(e)}};Yi.default=Ji});var Xi=$(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var sv=async s=>{let e=[],t=0;for await(let i of s)e.push(i),t+=Buffer.byteLength(i);return Buffer.isBuffer(e[0])?Buffer.concat(e,t):Buffer.from(e.join(""))};Qi.default=sv});var Wh=$(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.dnsLookupIpVersionToFamily=kt.isDnsLookupIpVersion=void 0;var Fh={auto:0,ipv4:4,ipv6:6};kt.isDnsLookupIpVersion=s=>s in Fh;kt.dnsLookupIpVersionToFamily=s=>{if(kt.isDnsLookupIpVersion(s))return Fh[s];throw new Error("Invalid DNS lookup IP version")}});var Zi=$(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.isResponseOk=void 0;Tn.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var zh=$(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});var Vh=new Set;eo.default=s=>{Vh.has(s)||(Vh.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var Kh=$(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var ne=st(),nv=(s,e)=>{if(ne.default.null_(s.encoding))throw new TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");ne.assert.any([ne.default.string,ne.default.undefined],s.encoding),ne.assert.any([ne.default.boolean,ne.default.undefined],s.resolveBodyOnly),ne.assert.any([ne.default.boolean,ne.default.undefined],s.methodRewriting),ne.assert.any([ne.default.boolean,ne.default.undefined],s.isStream),ne.assert.any([ne.default.string,ne.default.undefined],s.responseType),s.responseType===void 0&&(s.responseType="text");let{retry:t}=s;if(e?s.retry={...e.retry}:s.retry={calculateDelay:i=>i.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},ne.default.object(t)?(s.retry={...s.retry,...t},s.retry.methods=[...new Set(s.retry.methods.map(i=>i.toUpperCase()))],s.retry.statusCodes=[...new Set(s.retry.statusCodes)],s.retry.errorCodes=[...new Set(s.retry.errorCodes)]):ne.default.number(t)&&(s.retry.limit=t),ne.default.undefined(s.retry.maxRetryAfter)&&(s.retry.maxRetryAfter=Math.min(...[s.timeout.request,s.timeout.connect].filter(ne.default.number))),ne.default.object(s.pagination)){e&&(s.pagination={...e.pagination,...s.pagination});let{pagination:i}=s;if(!ne.default.function_(i.transform))throw new Error("`options.pagination.transform` must be implemented");if(!ne.default.function_(i.shouldContinue))throw new Error("`options.pagination.shouldContinue` must be implemented");if(!ne.default.function_(i.filter))throw new TypeError("`options.pagination.filter` must be implemented");if(!ne.default.function_(i.paginate))throw new Error("`options.pagination.paginate` must be implemented")}return s.responseType==="json"&&s.headers.accept===void 0&&(s.headers.accept="application/json"),s};to.default=nv});var Jh=$(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.retryAfterStatusCodes=void 0;Ss.retryAfterStatusCodes=new Set([413,429,503]);var rv=({attemptCount:s,retryOptions:e,error:t,retryAfter:i})=>{if(s>e.limit)return 0;let a=e.methods.includes(t.options.method),l=e.errorCodes.includes(t.code),h=t.response&&e.statusCodes.includes(t.response.statusCode);if(!a||!l&&!h)return 0;if(t.response){if(i)return e.maxRetryAfter===void 0||i>e.maxRetryAfter?0:i;if(t.response.statusCode===413)return 0}let p=Math.random()*100;return 2**(s-1)*1e3+p};Ss.default=rv});var Rs=$(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.UnsupportedProtocolError=Q.ReadError=Q.TimeoutError=Q.UploadError=Q.CacheError=Q.HTTPError=Q.MaxRedirectsError=Q.RequestError=Q.setNonEnumerableProperties=Q.knownHookEvents=Q.withoutBody=Q.kIsNormalizedAlready=void 0;var Yh=q("util"),Qh=q("stream"),iv=q("fs"),ht=q("url"),Xh=q("http"),so=q("http"),ov=q("https"),av=hu(),cv=_u(),Zh=Xu(),lv=sh(),uv=Ih(),hv=Cn(),M=st(),dv=jh(),ed=Hi(),fv=Wi(),td=qh(),pv=$h(),sd=Hh(),gv=Gh(),mv=Xi(),nd=Wh(),yv=Zi(),dt=zh(),_v=Kh(),bv=Jh(),no,fe=Symbol("request"),Pn=Symbol("response"),Vt=Symbol("responseSize"),zt=Symbol("downloadedSize"),Kt=Symbol("bodySize"),Jt=Symbol("uploadedSize"),An=Symbol("serverResponsesPiped"),rd=Symbol("unproxyEvents"),id=Symbol("isFromCache"),ro=Symbol("cancelTimeouts"),od=Symbol("startedReading"),Yt=Symbol("stopReading"),Rn=Symbol("triggerRead"),ft=Symbol("body"),Ts=Symbol("jobs"),ad=Symbol("originalResponse"),cd=Symbol("retryTimeout");Q.kIsNormalizedAlready=Symbol("isNormalizedAlready");var vv=M.default.string(process.versions.brotli);Q.withoutBody=new Set(["GET","HEAD"]);Q.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function wv(s){for(let e in s){let t=s[e];if(!M.default.string(t)&&!M.default.number(t)&&!M.default.boolean(t)&&!M.default.null_(t)&&!M.default.undefined(t))throw new TypeError(`The \`searchParams\` value '${String(t)}' must be a string, number, boolean or null`)}}function Cv(s){return M.default.object(s)&&!("statusCode"in s)}var io=new gv.default,Ev=async s=>new Promise((e,t)=>{let i=a=>{t(a)};s.pending||e(),s.once("error",i),s.once("ready",()=>{s.off("error",i),e()})}),kv=new Set([300,301,302,303,304,307,308]),Ov=["context","body","json","form"];Q.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of Ov)a in i&&(t[a]={writable:!0,configurable:!0,enumerable:!1,value:i[a]});Object.defineProperties(e,t)};var ae=class extends Error{constructor(e,t,i){var a,l;if(super(e),Error.captureStackTrace(this,this.constructor),this.name="RequestError",this.code=(a=t.code)!==null&&a!==void 0?a:"ERR_GOT_REQUEST_ERROR",i instanceof Dn?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[Pn]}),Object.defineProperty(this,"options",{enumerable:!1,value:i.options})):Object.defineProperty(this,"options",{enumerable:!1,value:i}),this.timings=(l=this.request)===null||l===void 0?void 0:l.timings,M.default.string(t.stack)&&M.default.string(this.stack)){let h=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(h).split(`
|
|
35
35
|
`).reverse(),g=t.stack.slice(t.stack.indexOf(t.message)+t.message.length).split(`
|
|
36
36
|
`).reverse();for(;g.length!==0&&g[0]===p[0];)p.shift();this.stack=`${this.stack.slice(0,h)}${p.reverse().join(`
|
|
37
37
|
`)}${g.reverse().join(`
|
|
38
|
-
`)}`}}};Q.RequestError=ae;var In=class extends ae{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name="MaxRedirectsError",this.code="ERR_TOO_MANY_REDIRECTS"}};Q.MaxRedirectsError=In;var Mn=class extends ae{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name="HTTPError",this.code="ERR_NON_2XX_3XX_RESPONSE"}};Q.HTTPError=Mn;var xn=class extends ae{constructor(e,t){super(e.message,e,t),this.name="CacheError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_CACHE_ACCESS":this.code}};Q.CacheError=xn;var Nn=class extends ae{constructor(e,t){super(e.message,e,t),this.name="UploadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_UPLOAD":this.code}};Q.UploadError=Nn;var Ln=class extends ae{constructor(e,t,i){super(e.message,e,i),this.name="TimeoutError",this.event=e.event,this.timings=t}};Q.TimeoutError=Ln;var As=class extends ae{constructor(e,t){super(e.message,e,t),this.name="ReadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_READING_RESPONSE_STREAM":this.code}};Q.ReadError=As;var jn=class extends ae{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name="UnsupportedProtocolError",this.code="ERR_UNSUPPORTED_PROTOCOL"}};Q.UnsupportedProtocolError=jn;var wv=["socket","connect","continue","information","upgrade","timeout"],qn=class extends Yh.Duplex{constructor(e,t={},i){super({autoDestroy:!1,highWaterMark:0}),this[zt]=0,this[Jt]=0,this.requestInitialized=!1,this[An]=new Set,this.redirects=[],this[Yt]=!1,this[Rn]=!1,this[Ts]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),l=()=>this._lockWrite();this.on("pipe",y=>{y.prependListener("data",a),y.on("data",l),y.prependListener("end",a),y.on("end",l)}),this.on("unpipe",y=>{y.off("data",a),y.off("data",l),y.off("end",a),y.off("end",l)}),this.on("pipe",y=>{y instanceof so.IncomingMessage&&(this.options.headers={...y.headers,...this.options.headers})});let{json:h,body:p,form:g}=t;if((h||p||g)&&this._lockWrite(),Q.kIsNormalizedAlready in t)this.options=t;else try{this.options=this.constructor.normalizeArguments(e,t,i)}catch(y){M.default.nodeStream(t.body)&&t.body.destroy(),this.destroy(y);return}(async()=>{var y;try{this.options.body instanceof ev.ReadStream&&await _v(this.options.body);let{url:C}=this.options;if(!C)throw new TypeError("Missing `url` property");if(this.requestUrl=C.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(y=this[fe])===null||y===void 0||y.destroy();return}for(let v of this[Ts])v();this[Ts].length=0,this.requestInitialized=!0}catch(C){if(C instanceof ae){this._beforeError(C);return}this.destroyed||this.destroy(C)}})()}static normalizeArguments(e,t,i){var a,l,h,p,g;let y=t;if(M.default.object(e)&&!M.default.urlInstance(e))t={...i,...e,...t};else{if(e&&t&&t.url!==void 0)throw new TypeError("The `url` option is mutually exclusive with the `input` argument");t={...i,...t},e!==void 0&&(t.url=e),M.default.urlInstance(t.url)&&(t.url=new ht.URL(t.url.toString()))}if(t.cache===!1&&(t.cache=void 0),t.dnsCache===!1&&(t.dnsCache=void 0),M.assert.any([M.default.string,M.default.undefined],t.method),M.assert.any([M.default.object,M.default.undefined],t.headers),M.assert.any([M.default.string,M.default.urlInstance,M.default.undefined],t.prefixUrl),M.assert.any([M.default.object,M.default.undefined],t.cookieJar),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.searchParams),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.cache),M.assert.any([M.default.object,M.default.number,M.default.undefined],t.timeout),M.assert.any([M.default.object,M.default.undefined],t.context),M.assert.any([M.default.object,M.default.undefined],t.hooks),M.assert.any([M.default.boolean,M.default.undefined],t.decompress),M.assert.any([M.default.boolean,M.default.undefined],t.ignoreInvalidCookies),M.assert.any([M.default.boolean,M.default.undefined],t.followRedirect),M.assert.any([M.default.number,M.default.undefined],t.maxRedirects),M.assert.any([M.default.boolean,M.default.undefined],t.throwHttpErrors),M.assert.any([M.default.boolean,M.default.undefined],t.http2),M.assert.any([M.default.boolean,M.default.undefined],t.allowGetBody),M.assert.any([M.default.string,M.default.undefined],t.localAddress),M.assert.any([sd.isDnsLookupIpVersion,M.default.undefined],t.dnsLookupIpVersion),M.assert.any([M.default.object,M.default.undefined],t.https),M.assert.any([M.default.boolean,M.default.undefined],t.rejectUnauthorized),t.https&&(M.assert.any([M.default.boolean,M.default.undefined],t.https.rejectUnauthorized),M.assert.any([M.default.function_,M.default.undefined],t.https.checkServerIdentity),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificateAuthority),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.key),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificate),M.assert.any([M.default.string,M.default.undefined],t.https.passphrase),M.assert.any([M.default.string,M.default.buffer,M.default.array,M.default.undefined],t.https.pfx)),M.assert.any([M.default.object,M.default.undefined],t.cacheOptions),M.default.string(t.method)?t.method=t.method.toUpperCase():t.method="GET",t.headers===i?.headers?t.headers={...t.headers}:t.headers=ov({...i?.headers,...t.headers}),"slashes"in t)throw new TypeError("The legacy `url.Url` has been deprecated. Use `URL` instead.");if("auth"in t)throw new TypeError("Parameter `auth` is deprecated. Use `username` / `password` instead.");if("searchParams"in t&&t.searchParams&&t.searchParams!==i?.searchParams){let k;if(M.default.string(t.searchParams)||t.searchParams instanceof ht.URLSearchParams)k=new ht.URLSearchParams(t.searchParams);else{mv(t.searchParams),k=new ht.URLSearchParams;for(let T in t.searchParams){let E=t.searchParams[T];E===null?k.append(T,""):E!==void 0&&k.append(T,E)}}(a=i?.searchParams)===null||a===void 0||a.forEach((T,E)=>{k.has(E)||k.append(E,T)}),t.searchParams=k}if(t.username=(l=t.username)!==null&&l!==void 0?l:"",t.password=(h=t.password)!==null&&h!==void 0?h:"",M.default.undefined(t.prefixUrl)?t.prefixUrl=(p=i?.prefixUrl)!==null&&p!==void 0?p:"":(t.prefixUrl=t.prefixUrl.toString(),t.prefixUrl!==""&&!t.prefixUrl.endsWith("/")&&(t.prefixUrl+="/")),M.default.string(t.url)){if(t.url.startsWith("/"))throw new Error("`input` must not start with a slash when using `prefixUrl`");t.url=td.default(t.prefixUrl+t.url,t)}else(M.default.undefined(t.url)&&t.prefixUrl!==""||t.protocol)&&(t.url=td.default(t.prefixUrl,t));if(t.url){"port"in t&&delete t.port;let{prefixUrl:k}=t;Object.defineProperty(t,"prefixUrl",{set:E=>{let S=t.url;if(!S.href.startsWith(E))throw new Error(`Cannot change \`prefixUrl\` from ${k} to ${E}: ${S.href}`);t.url=new ht.URL(E+S.href.slice(k.length)),k=E},get:()=>k});let{protocol:T}=t.url;if(T==="unix:"&&(T="http:",t.url=new ht.URL(`http://unix${t.url.pathname}${t.url.search}`)),t.searchParams&&(t.url.search=t.searchParams.toString()),T!=="http:"&&T!=="https:")throw new jn(t);t.username===""?t.username=t.url.username:t.url.username=t.username,t.password===""?t.password=t.url.password:t.url.password=t.password}let{cookieJar:C}=t;if(C){let{setCookie:k,getCookieString:T}=C;M.assert.function_(k),M.assert.function_(T),k.length===4&&T.length===0&&(k=Jh.promisify(k.bind(t.cookieJar)),T=Jh.promisify(T.bind(t.cookieJar)),t.cookieJar={setCookie:k,getCookieString:T})}let{cache:v}=t;if(v&&(io.has(v)||io.set(v,new Xh((k,T)=>{let E=k[fe](k,T);return M.default.promise(E)&&(E.once=(S,N)=>{if(S==="error")E.catch(N);else if(S==="abort")(async()=>{try{(await E).once("abort",N)}catch{}})();else throw new Error(`Unknown HTTP2 promise event: ${S}`);return E}),E},v))),t.cacheOptions={...t.cacheOptions},t.dnsCache===!0)no||(no=new nv.default),t.dnsCache=no;else if(!M.default.undefined(t.dnsCache)&&!t.dnsCache.lookup)throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${M.default(t.dnsCache)}`);M.default.number(t.timeout)?t.timeout={request:t.timeout}:i&&t.timeout!==i.timeout?t.timeout={...i.timeout,...t.timeout}:t.timeout={...t.timeout},t.context||(t.context={});let O=t.hooks===i?.hooks;t.hooks={...t.hooks};for(let k of Q.knownHookEvents)if(k in t.hooks)if(M.default.array(t.hooks[k]))t.hooks[k]=[...t.hooks[k]];else throw new TypeError(`Parameter \`${k}\` must be an Array, got ${M.default(t.hooks[k])}`);else t.hooks[k]=[];if(i&&!O)for(let k of Q.knownHookEvents)i.hooks[k].length>0&&(t.hooks[k]=[...i.hooks[k],...t.hooks[k]]);if("family"in t&&dt.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'),i?.https&&(t.https={...i.https,...t.https}),"rejectUnauthorized"in t&&dt.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'),"checkServerIdentity"in t&&dt.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'),"ca"in t&&dt.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'),"key"in t&&dt.default('"options.key" was never documented, please use "options.https.key"'),"cert"in t&&dt.default('"options.cert" was never documented, please use "options.https.certificate"'),"passphrase"in t&&dt.default('"options.passphrase" was never documented, please use "options.https.passphrase"'),"pfx"in t&&dt.default('"options.pfx" was never documented, please use "options.https.pfx"'),"followRedirects"in t)throw new TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");if(t.agent){for(let k in t.agent)if(k!=="http"&&k!=="https"&&k!=="http2")throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${k}\``)}return t.maxRedirects=(g=t.maxRedirects)!==null&&g!==void 0?g:0,Q.setNonEnumerableProperties([i,y],t),fv.default(t,i)}_lockWrite(){let e=()=>{throw new TypeError("The payload has been already provided")};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:e}=this,{headers:t}=e,i=!M.default.undefined(e.form),a=!M.default.undefined(e.json),l=!M.default.undefined(e.body),h=i||a||l,p=Q.withoutBody.has(e.method)&&!(e.method==="GET"&&e.allowGetBody);if(this._cannotHaveBody=p,h){if(p)throw new TypeError(`The \`${e.method}\` method cannot be used with a body`);if([l,i,a].filter(g=>g).length>1)throw new TypeError("The `body`, `json` and `form` options are mutually exclusive");if(l&&!(e.body instanceof Yh.Readable)&&!M.default.string(e.body)&&!M.default.buffer(e.body)&&!Zh.default(e.body))throw new TypeError("The `body` option must be a stream.Readable, string or Buffer");if(i&&!M.default.object(e.form))throw new TypeError("The `form` option must be an Object");{let g=!M.default.string(t["content-type"]);l?(Zh.default(e.body)&&g&&(t["content-type"]=`multipart/form-data; boundary=${e.body.getBoundary()}`),this[ft]=e.body):i?(g&&(t["content-type"]="application/x-www-form-urlencoded"),this[ft]=new ht.URLSearchParams(e.form).toString()):(g&&(t["content-type"]="application/json"),this[ft]=e.stringifyJson(e.json));let y=await av.default(this[ft],e.headers);M.default.undefined(t["content-length"])&&M.default.undefined(t["transfer-encoding"])&&!p&&!M.default.undefined(y)&&(t["content-length"]=String(y))}}else p?this._lockWrite():this._unlockWrite();this[Kt]=Number(t["content-length"])||void 0}async _onResponseBase(e){let{options:t}=this,{url:i}=t;this[od]=e,t.decompress&&(e=rv(e));let a=e.statusCode,l=e;l.statusMessage=l.statusMessage?l.statusMessage:Qh.STATUS_CODES[a],l.url=t.url.toString(),l.requestUrl=this.requestUrl,l.redirectUrls=this.redirects,l.request=this,l.isFromCache=e.fromCache||!1,l.ip=this.ip,l.retryCount=this.retryCount,this[rd]=l.isFromCache,this[Vt]=Number(e.headers["content-length"])||void 0,this[Pn]=e,e.once("end",()=>{this[Vt]=this[zt],this.emit("downloadProgress",this.downloadProgress)}),e.once("error",p=>{e.destroy(),this._beforeError(new As(p,this))}),e.once("aborted",()=>{this._beforeError(new As({name:"Error",message:"The server aborted pending request",code:"ECONNRESET"},this))}),this.emit("downloadProgress",this.downloadProgress);let h=e.headers["set-cookie"];if(M.default.object(t.cookieJar)&&h){let p=h.map(async g=>t.cookieJar.setCookie(g,i.toString()));t.ignoreInvalidCookies&&(p=p.map(async g=>g.catch(()=>{})));try{await Promise.all(p)}catch(g){this._beforeError(g);return}}if(t.followRedirect&&e.headers.location&&bv.has(a)){if(e.resume(),this[fe]&&(this[ro](),delete this[fe],this[nd]()),(a===303&&t.method!=="GET"&&t.method!=="HEAD"||!t.methodRewriting)&&(t.method="GET","body"in t&&delete t.body,"json"in t&&delete t.json,"form"in t&&delete t.form,this[ft]=void 0,delete t.headers["content-length"]),this.redirects.length>=t.maxRedirects){this._beforeError(new In(this));return}try{let v=function(O){return O.protocol==="unix:"||O.hostname==="unix"},g=Buffer.from(e.headers.location,"binary").toString(),y=new ht.URL(g,i),C=y.toString();if(decodeURI(C),!v(i)&&v(y)){this._beforeError(new ae("Cannot redirect to UNIX socket",{},this));return}y.hostname!==i.hostname||y.port!==i.port?("host"in t.headers&&delete t.headers.host,"cookie"in t.headers&&delete t.headers.cookie,"authorization"in t.headers&&delete t.headers.authorization,(t.username||t.password)&&(t.username="",t.password="")):(y.username=t.username,y.password=t.password),this.redirects.push(C),t.url=y;for(let O of t.hooks.beforeRedirect)await O(t,l);this.emit("redirect",l,t),await this._makeRequest()}catch(g){this._beforeError(g);return}return}if(t.isStream&&t.throwHttpErrors&&!dv.isResponseOk(l)){this._beforeError(new Mn(l));return}e.on("readable",()=>{this[Rn]&&this._read()}),this.on("resume",()=>{e.resume()}),this.on("pause",()=>{e.pause()}),e.once("end",()=>{this.push(null)}),this.emit("response",e);for(let p of this[An])if(!p.headersSent){for(let g in e.headers){let y=t.decompress?g!=="content-encoding":!0,C=e.headers[g];y&&p.setHeader(g,C)}p.statusCode=a}}async _onResponse(e){try{await this._onResponseBase(e)}catch(t){this._beforeError(t)}}_onRequest(e){let{options:t}=this,{timeout:i,url:a}=t;sv.default(e),this[ro]=ed.default(e,i,a);let l=t.cache?"cacheableResponse":"response";e.once(l,g=>{this._onResponse(g)}),e.once("error",g=>{var y;e.destroy(),(y=e.res)===null||y===void 0||y.removeAllListeners("end"),g=g instanceof ed.TimeoutError?new Ln(g,this.timings,this):new ae(g.message,g,this),this._beforeError(g)}),this[nd]=cv.default(e,this,wv),this[fe]=e,this.emit("uploadProgress",this.uploadProgress);let h=this[ft],p=this.redirects.length===0?this:e;M.default.nodeStream(h)?(h.pipe(p),h.once("error",g=>{this._beforeError(new Nn(g,this))})):(this._unlockWrite(),M.default.undefined(h)?(this._cannotHaveBody||this._noPipe)&&(p.end(),this._lockWrite()):(this._writeRequest(h,void 0,()=>{}),p.end(),this._lockWrite())),this.emit("request",e)}async _createCacheableRequest(e,t){return new Promise((i,a)=>{Object.assign(t,lv.default(e)),delete t.url;let l,h=io.get(t.cache)(t,async p=>{p._readableState.autoDestroy=!1,l&&(await l).emit("cacheableResponse",p),i(p)});t.url=e,h.once("error",a),h.once("request",async p=>{l=p,i(l)})})}async _makeRequest(){var e,t,i,a,l;let{options:h}=this,{headers:p}=h;for(let N in p)if(M.default.undefined(p[N]))delete p[N];else if(M.default.null_(p[N]))throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${N}\` header`);if(h.decompress&&M.default.undefined(p["accept-encoding"])&&(p["accept-encoding"]=gv?"gzip, deflate, br":"gzip, deflate"),h.cookieJar){let N=await h.cookieJar.getCookieString(h.url.toString());M.default.nonEmptyString(N)&&(h.headers.cookie=N)}for(let N of h.hooks.beforeRequest){let W=await N(h);if(!M.default.undefined(W)){h.request=()=>W;break}}h.body&&this[ft]!==h.body&&(this[ft]=h.body);let{agent:g,request:y,timeout:C,url:v}=h;if(h.dnsCache&&!("lookup"in h)&&(h.lookup=h.dnsCache.lookup),v.hostname==="unix"){let N=/(?<socketPath>.+?):(?<path>.+)/.exec(`${v.pathname}${v.search}`);if(N?.groups){let{socketPath:W,path:Y}=N.groups;Object.assign(h,{socketPath:W,path:Y,host:""})}}let O=v.protocol==="https:",k;h.http2?k=iv.auto:k=O?tv.request:Qh.request;let T=(e=h.request)!==null&&e!==void 0?e:k,E=h.cache?this._createCacheableRequest:T;g&&!h.http2&&(h.agent=g[O?"https":"http"]),h[fe]=T,delete h.request,delete h.timeout;let S=h;if(S.shared=(t=h.cacheOptions)===null||t===void 0?void 0:t.shared,S.cacheHeuristic=(i=h.cacheOptions)===null||i===void 0?void 0:i.cacheHeuristic,S.immutableMinTimeToLive=(a=h.cacheOptions)===null||a===void 0?void 0:a.immutableMinTimeToLive,S.ignoreCargoCult=(l=h.cacheOptions)===null||l===void 0?void 0:l.ignoreCargoCult,h.dnsLookupIpVersion!==void 0)try{S.family=sd.dnsLookupIpVersionToFamily(h.dnsLookupIpVersion)}catch{throw new Error("Invalid `dnsLookupIpVersion` option value")}h.https&&("rejectUnauthorized"in h.https&&(S.rejectUnauthorized=h.https.rejectUnauthorized),h.https.checkServerIdentity&&(S.checkServerIdentity=h.https.checkServerIdentity),h.https.certificateAuthority&&(S.ca=h.https.certificateAuthority),h.https.certificate&&(S.cert=h.https.certificate),h.https.key&&(S.key=h.https.key),h.https.passphrase&&(S.passphrase=h.https.passphrase),h.https.pfx&&(S.pfx=h.https.pfx));try{let N=await E(v,S);M.default.undefined(N)&&(N=k(v,S)),h.request=y,h.timeout=C,h.agent=g,h.https&&("rejectUnauthorized"in h.https&&delete S.rejectUnauthorized,h.https.checkServerIdentity&&delete S.checkServerIdentity,h.https.certificateAuthority&&delete S.ca,h.https.certificate&&delete S.cert,h.https.key&&delete S.key,h.https.passphrase&&delete S.passphrase,h.https.pfx&&delete S.pfx),yv(N)?this._onRequest(N):this.writable?(this.once("finish",()=>{this._onResponse(N)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(N)}catch(N){throw N instanceof Xh.CacheError?new xn(N,this):new ae(N.message,N,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new ae(t.message,t,this)}this.destroy(e)}_beforeError(e){if(this[Yt])return;let{options:t}=this,i=this.retryCount+1;this[Yt]=!0,e instanceof ae||(e=new ae(e.message,e,this));let a=e,{response:l}=a;(async()=>{if(l&&!l.body){l.setEncoding(this._readableState.encoding);try{l.rawBody=await hv.default(l),l.body=l.rawBody.toString()}catch{}}if(this.listenerCount("retry")!==0){let h;try{let p;l&&"retry-after"in l.headers&&(p=Number(l.headers["retry-after"]),Number.isNaN(p)?(p=Date.parse(l.headers["retry-after"])-Date.now(),p<=0&&(p=1)):p*=1e3),h=await t.retry.calculateDelay({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:pv.default({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:0})})}catch(p){this._error(new ae(p.message,p,this));return}if(h){let p=async()=>{try{for(let g of this.options.hooks.beforeRetry)await g(this.options,a,i)}catch(g){this._error(new ae(g.message,e,this));return}this.destroyed||(this.destroy(),this.emit("retry",i,e))};this[ad]=setTimeout(p,h);return}}this._error(a)})()}_read(){this[Rn]=!0;let e=this[Pn];if(e&&!this[Yt]){e.readableLength&&(this[Rn]=!1);let t;for(;(t=e.read())!==null;){this[zt]+=t.length,this[id]=!0;let i=this.downloadProgress;i.percent<1&&this.emit("downloadProgress",i),this.push(t)}}}_write(e,t,i){let a=()=>{this._writeRequest(e,t,i)};this.requestInitialized?a():this[Ts].push(a)}_writeRequest(e,t,i){this[fe].destroyed||(this._progressCallbacks.push(()=>{this[Jt]+=Buffer.byteLength(e,t);let a=this.uploadProgress;a.percent<1&&this.emit("uploadProgress",a)}),this[fe].write(e,t,a=>{!a&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),i(a)}))}_final(e){let t=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();if(!(fe in this)){e();return}if(this[fe].destroyed){e();return}this[fe].end(i=>{i||(this[Kt]=this[Jt],this.emit("uploadProgress",this.uploadProgress),this[fe].emit("upload-complete")),e(i)})};this.requestInitialized?t():this[Ts].push(t)}_destroy(e,t){var i;this[Yt]=!0,clearTimeout(this[ad]),fe in this&&(this[ro](),!((i=this[Pn])===null||i===void 0)&&i.complete||this[fe].destroy()),e!==null&&!M.default.undefined(e)&&!(e instanceof ae)&&(e=new ae(e.message,e,this)),t(e)}get _isAboutToError(){return this[Yt]}get ip(){var e;return(e=this.socket)===null||e===void 0?void 0:e.remoteAddress}get aborted(){var e,t,i;return((t=(e=this[fe])===null||e===void 0?void 0:e.destroyed)!==null&&t!==void 0?t:this.destroyed)&&!(!((i=this[od])===null||i===void 0)&&i.complete)}get socket(){var e,t;return(t=(e=this[fe])===null||e===void 0?void 0:e.socket)!==null&&t!==void 0?t:void 0}get downloadProgress(){let e;return this[Vt]?e=this[zt]/this[Vt]:this[Vt]===this[zt]?e=1:e=0,{percent:e,transferred:this[zt],total:this[Vt]}}get uploadProgress(){let e;return this[Kt]?e=this[Jt]/this[Kt]:this[Kt]===this[Jt]?e=1:e=0,{percent:e,transferred:this[Jt],total:this[Kt]}}get timings(){var e;return(e=this[fe])===null||e===void 0?void 0:e.timings}get isFromCache(){return this[rd]}pipe(e,t){if(this[id])throw new Error("Failed to pipe. The response has been emitted already.");return e instanceof so.ServerResponse&&this[An].add(e),super.pipe(e,t)}unpipe(e){return e instanceof so.ServerResponse&&this[An].delete(e),super.unpipe(e),this}};Q.default=qn});var Ps=$(Be=>{"use strict";var Cv=Be&&Be.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Ev=Be&&Be.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Cv(e,s,t)};Object.defineProperty(Be,"__esModule",{value:!0});Be.CancelError=Be.ParseError=void 0;var cd=Rs(),oo=class extends cd.RequestError{constructor(e,t){let{options:i}=t.request;super(`${e.message} in "${i.url.toString()}"`,e,t.request),this.name="ParseError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_BODY_PARSE_FAILURE":this.code}};Be.ParseError=oo;var ao=class extends cd.RequestError{constructor(e){super("Promise was canceled",{},e),this.name="CancelError",this.code="ERR_CANCELED"}get isCanceled(){return!0}};Be.CancelError=ao;Ev(Rs(),Be)});var ud=$(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var ld=Ps(),Ov=(s,e,t,i)=>{let{rawBody:a}=s;try{if(e==="text")return a.toString(i);if(e==="json")return a.length===0?"":t(a.toString());if(e==="buffer")return a;throw new ld.ParseError({message:`Unknown body type '${e}'`,name:"Error"},s)}catch(l){throw new ld.ParseError(l,s)}};co.default=Ov});var lo=$(pt=>{"use strict";var kv=pt&&pt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Sv=pt&&pt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&kv(e,s,t)};Object.defineProperty(pt,"__esModule",{value:!0});var Tv=D("events"),Av=st(),Rv=cu(),Un=Ps(),hd=ud(),dd=Rs(),Pv=Wi(),Iv=Xi(),fd=Zi(),Mv=["request","response","redirect","uploadProgress","downloadProgress"];function pd(s){let e,t,i=new Tv.EventEmitter,a=new Rv((h,p,g)=>{let y=C=>{let v=new dd.default(void 0,s);v.retryCount=C,v._noPipe=!0,g(()=>v.destroy()),g.shouldReject=!1,g(()=>p(new Un.CancelError(v))),e=v,v.once("response",async T=>{var E;if(T.retryCount=C,T.request.aborted)return;let S;try{S=await Iv.default(v),T.rawBody=S}catch{return}if(v._isAboutToError)return;let N=((E=T.headers["content-encoding"])!==null&&E!==void 0?E:"").toLowerCase(),W=["gzip","deflate","br"].includes(N),{options:Y}=v;if(W&&!Y.decompress)T.body=S;else try{T.body=hd.default(T,Y.responseType,Y.parseJson,Y.encoding)}catch(se){if(T.body=S.toString(),fd.isResponseOk(T)){v._beforeError(se);return}}try{for(let[se,Z]of Y.hooks.afterResponse.entries())T=await Z(T,async Te=>{let Le=dd.default.normalizeArguments(void 0,{...Te,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},Y);Le.hooks.afterResponse=Le.hooks.afterResponse.slice(0,se);for(let gt of Le.hooks.beforeRetry)await gt(Le);let ot=pd(Le);return g(()=>{ot.catch(()=>{}),ot.cancel()}),ot})}catch(se){v._beforeError(new Un.RequestError(se.message,se,v));return}if(t=T,!fd.isResponseOk(T)){v._beforeError(new Un.HTTPError(T));return}v.destroy(),h(v.options.resolveBodyOnly?T.body:T)});let O=T=>{if(a.isCanceled)return;let{options:E}=v;if(T instanceof Un.HTTPError&&!E.throwHttpErrors){let{response:S}=T;h(v.options.resolveBodyOnly?S.body:S);return}p(T)};v.once("error",O);let k=v.options.body;v.once("retry",(T,E)=>{var S,N;if(k===((S=E.request)===null||S===void 0?void 0:S.options.body)&&Av.default.nodeStream((N=E.request)===null||N===void 0?void 0:N.options.body)){O(E);return}y(T)}),Pv.default(v,i,Mv)};y(0)});a.on=(h,p)=>(i.on(h,p),a);let l=h=>{let p=(async()=>{await a;let{options:g}=t.request;return hd.default(t,h,g.parseJson,g.encoding)})();return Object.defineProperties(p,Object.getOwnPropertyDescriptors(a)),p};return a.json=()=>{let{headers:h}=e.options;return!e.writableFinished&&h.accept===void 0&&(h.accept="application/json"),l("json")},a.buffer=()=>l("buffer"),a.text=()=>l("text"),a}pt.default=pd;Sv(Ps(),pt)});var gd=$(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var xv=Ps();function Nv(s,...e){let t=(async()=>{if(s instanceof xv.RequestError)try{for(let a of e)if(a)for(let l of a)s=await l(s)}catch(a){s=a}throw s})(),i=()=>t;return t.json=i,t.text=i,t.buffer=i,t.on=i,t}uo.default=Nv});var _d=$(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var md=st();function yd(s){for(let e of Object.values(s))(md.default.plainObject(e)||md.default.array(e))&&yd(e);return Object.freeze(s)}ho.default=yd});var vd=$(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0})});var fo=$(Ne=>{"use strict";var Lv=Ne&&Ne.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),jv=Ne&&Ne.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Lv(e,s,t)};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.defaultHandler=void 0;var wd=st(),xe=lo(),qv=gd(),Bn=Rs(),Uv=_d(),Dv={RequestError:xe.RequestError,CacheError:xe.CacheError,ReadError:xe.ReadError,HTTPError:xe.HTTPError,MaxRedirectsError:xe.MaxRedirectsError,TimeoutError:xe.TimeoutError,ParseError:xe.ParseError,CancelError:xe.CancelError,UnsupportedProtocolError:xe.UnsupportedProtocolError,UploadError:xe.UploadError},Bv=async s=>new Promise(e=>{setTimeout(e,s)}),{normalizeArguments:Dn}=Bn.default,Cd=(...s)=>{let e;for(let t of s)e=Dn(void 0,t,e);return e},$v=s=>s.isStream?new Bn.default(void 0,s):xe.default(s),Hv=s=>"defaults"in s&&"options"in s.defaults,Gv=["get","post","put","patch","head","delete"];Ne.defaultHandler=(s,e)=>e(s);var Ed=(s,e)=>{if(s)for(let t of s)t(e)},Od=s=>{s._rawHandlers=s.handlers,s.handlers=s.handlers.map(i=>(a,l)=>{let h,p=i(a,g=>(h=l(g),h));if(p!==h&&!a.isStream&&h){let g=p,{then:y,catch:C,finally:v}=g;Object.setPrototypeOf(g,Object.getPrototypeOf(h)),Object.defineProperties(g,Object.getOwnPropertyDescriptors(h)),g.then=y,g.catch=C,g.finally=v}return p});let e=(i,a={},l)=>{var h,p;let g=0,y=C=>s.handlers[g++](C,g===s.handlers.length?$v:y);if(wd.default.plainObject(i)){let C={...i,...a};Bn.setNonEnumerableProperties([i,a],C),a=C,i=void 0}try{let C;try{Ed(s.options.hooks.init,a),Ed((h=a.hooks)===null||h===void 0?void 0:h.init,a)}catch(O){C=O}let v=Dn(i,a,l??s.options);if(v[Bn.kIsNormalizedAlready]=!0,C)throw new xe.RequestError(C.message,C,v);return y(v)}catch(C){if(a.isStream)throw C;return qv.default(C,s.options.hooks.beforeError,(p=a.hooks)===null||p===void 0?void 0:p.beforeError)}};e.extend=(...i)=>{let a=[s.options],l=[...s._rawHandlers],h;for(let p of i)Hv(p)?(a.push(p.defaults.options),l.push(...p.defaults._rawHandlers),h=p.defaults.mutableDefaults):(a.push(p),"handlers"in p&&l.push(...p.handlers),h=p.mutableDefaults);return l=l.filter(p=>p!==Ne.defaultHandler),l.length===0&&l.push(Ne.defaultHandler),Od({options:Cd(...a),handlers:l,mutableDefaults:!!h})};let t=async function*(i,a){let l=Dn(i,a,s.options);l.resolveBodyOnly=!1;let h=l.pagination;if(!wd.default.object(h))throw new TypeError("`options.pagination` must be implemented");let p=[],{countLimit:g}=h,y=0;for(;y<h.requestLimit;){y!==0&&await Bv(h.backoff);let C=await e(void 0,void 0,l),v=await h.transform(C),O=[];for(let T of v)if(h.filter(T,p,O)&&(!h.shouldContinue(T,p,O)||(yield T,h.stackAllItems&&p.push(T),O.push(T),--g<=0)))return;let k=h.paginate(C,p,O);if(k===!1)return;k===C.request.options?l=C.request.options:k!==void 0&&(l=Dn(void 0,k,l)),y++}};e.paginate=t,e.paginate.all=async(i,a)=>{let l=[];for await(let h of t(i,a))l.push(h);return l},e.paginate.each=t,e.stream=(i,a)=>e(i,{...a,isStream:!0});for(let i of Gv)e[i]=(a,l)=>e(a,{...l,method:i}),e.stream[i]=(a,l)=>e(a,{...l,method:i,isStream:!0});return Object.assign(e,Dv),Object.defineProperty(e,"defaults",{value:s.mutableDefaults?s:Uv.default(s),writable:s.mutableDefaults,configurable:s.mutableDefaults,enumerable:!0}),e.mergeOptions=Cd,e};Ne.default=Od;jv(vd(),Ne)});var Hn=$((rt,$n)=>{"use strict";var Fv=rt&&rt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),kd=rt&&rt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Fv(e,s,t)};Object.defineProperty(rt,"__esModule",{value:!0});var Wv=D("url"),Sd=fo(),Vv={options:{method:"GET",retry:{limit:2,methods:["GET","PUT","HEAD","DELETE","OPTIONS","TRACE"],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"],maxRetryAfter:void 0,calculateDelay:({computedValue:s})=>s},timeout:{},headers:{"user-agent":"got (https://github.com/sindresorhus/got)"},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:"text",resolveBodyOnly:!1,maxRedirects:10,prefixUrl:"",methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:s=>s.request.options.responseType==="json"?s.body:JSON.parse(s.body),paginate:s=>{if(!Reflect.has(s.headers,"link"))return!1;let e=s.headers.link.split(","),t;for(let i of e){let a=i.split(";");if(a[1].includes("next")){t=a[0].trimStart().trim(),t=t.slice(1,-1);break}}return t?{url:new Wv.URL(t)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:s=>JSON.parse(s),stringifyJson:s=>JSON.stringify(s),cacheOptions:{}},handlers:[Sd.defaultHandler],mutableDefaults:!1},po=Sd.default(Vv);rt.default=po;$n.exports=po;$n.exports.default=po;$n.exports.__esModule=!0;kd(fo(),rt);kd(lo(),rt)});var Md=$((Ns,Oo)=>{(function(s,e){typeof Ns=="object"&&typeof Oo=="object"?Oo.exports=e(dn(),Hn()):typeof define=="function"&&define.amd?define(["ws","got"],e):typeof Ns=="object"?Ns.Ably=e(dn(),Hn()):s.Ably=e(s.ws,s.got)})(Ns,(s,e)=>{var t={},i={exports:t},a=Object.create,l=Object.defineProperty,h=Object.defineProperties,p=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,y=Object.getOwnPropertyNames,C=Object.getOwnPropertySymbols,v=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty,k=Object.prototype.propertyIsEnumerable,T=(r,n,o)=>n in r?l(r,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[n]=o,E=(r,n)=>{for(var o in n||(n={}))O.call(n,o)&&T(r,o,n[o]);if(C)for(var o of C(n))k.call(n,o)&&T(r,o,n[o]);return r},S=(r,n)=>h(r,g(n)),N=(r,n)=>{var o={};for(var c in r)O.call(r,c)&&n.indexOf(c)<0&&(o[c]=r[c]);if(r!=null&&C)for(var c of C(r))n.indexOf(c)<0&&k.call(r,c)&&(o[c]=r[c]);return o},W=(r,n)=>function(){return n||(0,r[y(r)[0]])((n={exports:{}}).exports,n),n.exports},Y=(r,n)=>{for(var o in n)l(r,o,{get:n[o],enumerable:!0})},se=(r,n,o,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of y(n))!O.call(r,u)&&u!==o&&l(r,u,{get:()=>n[u],enumerable:!(c=p(n,u))||c.enumerable});return r},Z=(r,n,o)=>(o=r!=null?a(v(r)):{},se(n||!r||!r.__esModule?l(o,"default",{value:r,enumerable:!0}):o,r)),Te=function(r,n){this[0]=r,this[1]=n},Le=(r,n,o)=>{var c=(m,_,A,I)=>{try{var q=o[m](_),j=(_=q.value)instanceof Te,G=q.done;Promise.resolve(j?_[0]:_).then(w=>j?c(m==="return"?m:"next",_[1]?{done:w.done,value:w.value}:w,A,I):A({value:w,done:G})).catch(w=>c("throw",w,A,I))}catch(w){I(w)}},u=m=>f[m]=_=>new Promise((A,I)=>c(m,_,A,I)),f={};return o=o.apply(r,n),f[Symbol.asyncIterator]=()=>f,u("next"),u("throw"),u("return"),f},ot=W({"node_modules/bops/from.js"(r,n){var o=D("buffer").Buffer,c=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(c)<6?function(f,m){return new o(f,m)}:function(f,m){return o.from(f,m)}}}),gt=W({"node_modules/bops/to.js"(r,n){n.exports=function(o,c){return o.toString(c)}}}),Vn=W({"node_modules/bops/is.js"(r,n){var o=D("buffer").Buffer;n.exports=function(c){return o.isBuffer(c)}}}),Jd=W({"node_modules/bops/subarray.js"(r,n){n.exports=function(o,c,u){return arguments.length===2?o.slice(c):o.slice(c,u)}}}),Yd=W({"node_modules/bops/join.js"(r,n){var o=D("buffer").Buffer;n.exports=function(c,u){return u!==void 0?o.concat(c,u):o.concat(c)}}}),Qd=W({"node_modules/bops/copy.js"(r,n){n.exports=o;function o(c,u,f,m,_){return c.copy(u,f,m,_)}}}),Xd=W({"node_modules/bops/create.js"(r,n){var o=D("buffer").Buffer,c=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(c)<6?function(f){return new o(f)}:function(f){return o.alloc(f)}}}),Zd=W({"node_modules/bops/read.js"(r,n){var o={},c=/read.+/,u;u=function(m){var _="return buf."+m+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],_)},n.exports=o;for(f in Buffer.prototype)c.test(f)&&(o[f]=u(f));var f}}),ef=W({"node_modules/bops/write.js"(r,n){var o=D("buffer").Buffer,c={},u=/write.+/,f;f=function(_){var A="return buf."+_+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],A)},n.exports=c;for(m in o.prototype)u.test(m)&&(c[m]=f(m));var m}}),tf=W({"node_modules/bops/index.js"(r,n){var o={};n.exports=o,o.from=ot(),o.to=gt(),o.is=Vn(),o.subarray=Jd(),o.join=Yd(),o.copy=Qd(),o.create=Xd(),c(Zd(),o),c(ef(),o);function c(u,f){for(var m in u)f[m]=u[m]}}}),sf=W({"node_modules/@ably/msgpack-js/msgpack.js"(r){"use strict";var n=tf();r.encode=function(w,R){var P=G(w,R);if(P!=0){var U=n.create(P);return j(w,U,0,R),U}},r.decode=I;var o=65536*65536,c=1/o;function u(w,R){return R=R||0,w.readInt32BE(R+0)*o+w.readUInt32BE(R+4)}function f(w,R){return R=R||0,w.readUInt32BE(R+0)*o+w.readUInt32BE(R+4)}function m(w,R,P){R<9223372036854776e3?(w.writeInt32BE(Math.floor(R*c),P),w.writeInt32BE(R&-1,P+4)):(w.writeUInt32BE(2147483647,P),w.writeUInt32BE(4294967295,P+4))}function _(w,R,P){R<18446744073709552e3?(w.writeUInt32BE(Math.floor(R*c),P),w.writeInt32BE(R&-1,P+4)):(w.writeUInt32BE(4294967295,P),w.writeUInt32BE(4294967295,P+4))}function A(w,R){this.offset=R||0,this.buffer=w,this.bufferLength=w.length}A.prototype.map=function(w){if(w*2>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a map of length ${w})`);for(var R={},P=0;P<w;P++){var U=this.parse();R[U]=this.parse()}return R},A.prototype.bin=A.prototype.buf=function(w){if(w>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a binary of length ${w})`);var R=n.subarray(this.buffer,this.offset,this.offset+w);return this.offset+=w,R},A.prototype.str=function(w){if(w>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a string of length ${w})`);var R=n.to(n.subarray(this.buffer,this.offset,this.offset+w));return this.offset+=w,R},A.prototype.array=function(w){if(w>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced an array of length ${w})`);for(var R=new Array(w),P=0;P<w;P++)R[P]=this.parse();return R},A.prototype.parse=function(){var w=this.buffer[this.offset],R,P,U;if(w===void 0)throw new Error("malformed messagepack (referenced offset is outside buffer)");if(!(w&128))return this.offset++,w;if((w&240)===128)return P=w&15,this.offset++,this.map(P);if((w&240)===144)return P=w&15,this.offset++,this.array(P);if((w&224)===160)return P=w&31,this.offset++,this.str(P);if((w&224)===224)return R=n.readInt8(this.buffer,this.offset),this.offset++,R;switch(w){case 192:return this.offset++,null;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.bin(P);case 197:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.bin(P);case 198:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.bin(P);case 199:return P=n.readUInt8(this.buffer,this.offset+1),U=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,[U,this.bin(P)];case 200:return P=n.readUInt16BE(this.buffer,this.offset+1),U=n.readUInt8(this.buffer,this.offset+3),this.offset+=4,[U,this.bin(P)];case 201:return P=n.readUInt32BE(this.buffer,this.offset+1),U=n.readUInt8(this.buffer,this.offset+5),this.offset+=6,[U,this.bin(P)];case 202:return R=n.readFloatBE(this.buffer,this.offset+1),this.offset+=5,R;case 203:return R=n.readDoubleBE(this.buffer,this.offset+1),this.offset+=9,R;case 204:return R=this.buffer[this.offset+1],this.offset+=2,R;case 205:return R=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 206:return R=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 207:return R=f(this.buffer,this.offset+1),this.offset+=9,R;case 208:return R=n.readInt8(this.buffer,this.offset+1),this.offset+=2,R;case 209:return R=n.readInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 210:return R=n.readInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 211:return R=u(this.buffer,this.offset+1),this.offset+=9,R;case 212:return U=n.readUInt8(this.buffer,this.offset+1),R=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,U===0&&R===0?void 0:[U,R];case 213:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(2)];case 214:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(4)];case 215:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(8)];case 216:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(16)];case 217:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.str(P);case 218:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.str(P);case 219:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.str(P);case 220:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.array(P);case 221:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.array(P);case 222:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.map(P);case 223:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.map(P)}throw new Error("Unknown type 0x"+w.toString(16))};function I(w){var R=new A(w),P=R.parse();if(R.offset!==w.length)throw new Error(w.length-R.offset+" trailing bytes");return P}function q(w,R){return Object.keys(w).filter(function(P){var U=w[P],H=typeof U;return(!R||U!=null)&&(H!=="function"||!!U.toJSON)})}function j(w,R,P,U,H){var V=typeof w,F,X;if(V==="string"){if(w=n.from(w),F=w.length,F<32)return R[P]=F|160,n.copy(w,R,P+1),1+F;if(F<256)return R[P]=217,n.writeUInt8(R,F,P+1),n.copy(w,R,P+2),2+F;if(F<65536)return R[P]=218,n.writeUInt16BE(R,F,P+1),n.copy(w,R,P+3),3+F;if(F<4294967296)return R[P]=219,n.writeUInt32BE(R,F,P+1),n.copy(w,R,P+5),5+F}if(n.is(w)){if(F=w.length,F<256)return R[P]=196,n.writeUInt8(R,F,P+1),n.copy(w,R,P+2),2+F;if(F<65536)return R[P]=197,n.writeUInt16BE(R,F,P+1),n.copy(w,R,P+3),3+F;if(F<4294967296)return R[P]=198,n.writeUInt32BE(R,F,P+1),n.copy(w,R,P+5),5+F}if(V==="number"){if(Math.floor(w)!==w)return R[P]=203,n.writeDoubleBE(R,w,P+1),9;if(w>=0){if(w<128)return R[P]=w,1;if(w<256)return R[P]=204,R[P+1]=w,2;if(w<65536)return R[P]=205,n.writeUInt16BE(R,w,P+1),3;if(w<4294967296)return R[P]=206,n.writeUInt32BE(R,w,P+1),5;if(w<18446744073709552e3)return R[P]=207,_(R,w,P+1),9;throw new Error("Number too big 0x"+w.toString(16))}if(w>=-32)return n.writeInt8(R,w,P),1;if(w>=-128)return R[P]=208,n.writeInt8(R,w,P+1),2;if(w>=-32768)return R[P]=209,n.writeInt16BE(R,w,P+1),3;if(w>=-2147483648)return R[P]=210,n.writeInt32BE(R,w,P+1),5;if(w>=-9223372036854776e3)return R[P]=211,m(R,w,P+1),9;throw new Error("Number too small -0x"+w.toString(16).substr(1))}if(V==="undefined")return U&&H?0:(R[P]=212,R[P+1]=0,R[P+2]=0,3);if(w===null)return U&&H?0:(R[P]=192,1);if(V==="boolean")return R[P]=w?195:194,1;if(typeof w.toJSON=="function")return j(w.toJSON(),R,P,U);if(V==="object"){X=0;var Ce=Array.isArray(w);if(Ce)F=w.length;else{var _e=q(w,U);F=_e.length}if(F<16?(R[P]=F|(Ce?144:128),X=1):F<65536?(R[P]=Ce?220:222,n.writeUInt16BE(R,F,P+1),X=3):F<4294967296&&(R[P]=Ce?221:223,n.writeUInt32BE(R,F,P+1),X=5),Ce)for(var ze=0;ze<F;ze++)X+=j(w[ze],R,P+X,U);else for(var ze=0;ze<F;ze++){var mc=_e[ze];X+=j(mc,R,P+X),X+=j(w[mc],R,P+X,U,!0)}return X}if(V!=="function")throw new Error("Unknown type "+V)}function G(w,R,P){var U=typeof w,H,V;if(U==="string"){if(H=n.from(w).length,H<32)return 1+H;if(H<256)return 2+H;if(H<65536)return 3+H;if(H<4294967296)return 5+H}if(n.is(w)){if(H=w.length,H<256)return 2+H;if(H<65536)return 3+H;if(H<4294967296)return 5+H}if(U==="number"){if(Math.floor(w)!==w)return 9;if(w>=0){if(w<128)return 1;if(w<256)return 2;if(w<65536)return 3;if(w<4294967296)return 5;if(w<18446744073709552e3)return 9;throw new Error("Number too big 0x"+w.toString(16))}if(w>=-32)return 1;if(w>=-128)return 2;if(w>=-32768)return 3;if(w>=-2147483648)return 5;if(w>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+w.toString(16).substr(1))}if(U==="boolean")return 1;if(w===null)return R&&P?0:1;if(w===void 0)return R&&P?0:3;if(typeof w.toJSON=="function")return G(w.toJSON(),R);if(U==="object"){if(V=0,Array.isArray(w)){H=w.length;for(var F=0;F<H;F++)V+=G(w[F],R)}else{var X=q(w,R);H=X.length;for(var F=0;F<H;F++){var Ce=X[F];V+=G(Ce)+G(w[Ce],R,!0)}}if(H<16)return 1+V;if(H<65536)return 3+V;if(H<4294967296)return 5+V;throw new Error("Array or object too long 0x"+H.toString(16))}if(U==="function")return 0;throw new Error("Unknown type "+U)}}}),L=class{},Po=typeof global<"u"?global:typeof window<"u"?window:self;function Ls(r,n){return`${r}`.padStart(n?3:2,"0")}function nf(r){return L.Config.logTimestamps?function(n){let o=new Date;r(Ls(o.getHours())+":"+Ls(o.getMinutes())+":"+Ls(o.getSeconds())+"."+Ls(o.getMilliseconds(),1)+" "+n)}:function(n){r(n)}}var rf=()=>{var r;let n,o;return typeof((r=Po?.console)==null?void 0:r.log)=="function"?(n=function(...c){console.log.apply(console,c)},o=console.warn?function(...c){console.warn.apply(console,c)}:n):n=o=function(){},[n,o].map(nf)},Ge=class Is{constructor(){this.deprecated=(n,o)=>{this.deprecationWarning(`${n} is deprecated and will be removed in a future version. ${o}`)},this.shouldLog=n=>n<=this.logLevel,this.setLog=(n,o)=>{n!==void 0&&(this.logLevel=n),o!==void 0&&(this.logHandler=this.logErrorHandler=o)},this.logLevel=Is.defaultLogLevel,this.logHandler=Is.defaultLogHandler,this.logErrorHandler=Is.defaultLogErrorHandler}static initLogHandlers(){let[n,o]=rf();this.defaultLogHandler=n,this.defaultLogErrorHandler=o,this.defaultLogger=new Is}static logActionNoStrip(n,o,c,u){n.logAction(o,c,u)}logAction(n,o,c){this.shouldLog(n)&&(n===1?this.logErrorHandler:this.logHandler)("Ably: "+o+": "+c,n)}renamedClientOption(n,o){this.deprecationWarning(`The \`${n}\` client option has been renamed to \`${o}\`. Please update your code to use \`${o}\` instead. \`${n}\` will be removed in a future version.`)}renamedMethod(n,o,c){this.deprecationWarning(`\`${n}\`\u2019s \`${o}\` method has been renamed to \`${c}\`. Please update your code to use \`${c}\` instead. \`${o}\` will be removed in a future version.`)}deprecationWarning(n){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${n}`,1)}};Ge.defaultLogLevel=1,Ge.LOG_NONE=0,Ge.LOG_ERROR=1,Ge.LOG_MAJOR=2,Ge.LOG_MINOR=3,Ge.LOG_MICRO=4,Ge.logAction=(r,n,o,c)=>{Ge.logActionNoStrip(r,n,o,c)};var of=Ge,d=of,Zt={};Y(Zt,{Format:()=>Bo,allSame:()=>ff,allToLowerCase:()=>Vo,allToUpperCase:()=>zo,arrChooseN:()=>Wo,arrDeleteValue:()=>qo,arrEquals:()=>Qo,arrIntersect:()=>Lo,arrIntersectOb:()=>jo,arrPopRandomElement:()=>zn,arrWithoutValue:()=>df,cheapRandStr:()=>Go,containsValue:()=>hf,copy:()=>es,createMissingPluginError:()=>ss,dataSizeBytes:()=>Ho,decodeBody:()=>ue,encodeBody:()=>je,ensureArray:()=>Mo,forInOwnNonNullProperties:()=>Do,getBackoffCoefficient:()=>Ko,getGlobalObject:()=>pf,getJitterCoefficient:()=>Jo,getRetryTime:()=>Yn,inherits:()=>uf,inspectBody:()=>$o,inspectError:()=>ee,intersect:()=>No,isEmpty:()=>cf,isErrorInfoOrPartialErrorInfo:()=>Jn,isNil:()=>Fe,isObject:()=>kt,keysArray:()=>js,listenerToAsyncIterator:()=>gf,matchDerivedChannel:()=>Yo,mixin:()=>J,parseQueryString:()=>qs,prototypicalClone:()=>xo,randomString:()=>Fo,shallowClone:()=>lf,shallowEquals:()=>Qn,stringifyValues:()=>Kn,throwMissingPluginError:()=>pe,toBase64:()=>Us,toQueryString:()=>ts,valuesArray:()=>Uo,whenPromiseSettles:()=>Oe,withTimeoutAsync:()=>Xo});function Io(r){let n="["+r.constructor.name;return r.message&&(n+=": "+r.message),r.statusCode&&(n+="; statusCode="+r.statusCode),r.code&&(n+="; code="+r.code),r.cause&&(n+="; cause="+ee(r.cause)),r.href&&!(r.message&&r.message.indexOf("help.ably.io")>-1)&&(n+="; see "+r.href+" "),n+="]",n}var x=class go extends Error{constructor(n,o,c,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,go.prototype),this.code=o,this.statusCode=c,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:c,statusCode:u}=n;if(typeof o!="string"||typeof c!="number"||typeof u!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new go(o,c,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}},Ee=class mo extends Error{constructor(n,o,c,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,mo.prototype),this.code=o,this.statusCode=c,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:c,statusCode:u}=n;if(typeof o!="string"||!Fe(c)&&typeof c!="number"||!Fe(u)&&typeof u!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new mo(o,c,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}};function af(r){return Math.floor(Math.random()*r.length)}function J(r,...n){for(let o=0;o<n.length;o++){let c=n[o];if(!c)break;for(let u in c)Object.prototype.hasOwnProperty.call(c,u)&&(r[u]=c[u])}return r}function es(r){return J({},r)}function Mo(r){return Fe(r)?[]:Array.isArray(r)?r:[r]}function kt(r){return Object.prototype.toString.call(r)=="[object Object]"}function cf(r){for(let n in r)return!1;return!0}function Fe(r){return r==null}function lf(r){let n=new Object;for(let o in r)n[o]=r[o];return n}function xo(r,n){class o{}o.prototype=r;let c=new o;return n&&J(c,n),c}var uf=function(r,n){if(L.Config.inherits){L.Config.inherits(r,n);return}r.super_=n,r.prototype=xo(n.prototype,{constructor:r})};function hf(r,n){for(let o in r)if(r[o]==n)return!0;return!1}function No(r,n){return Array.isArray(n)?Lo(r,n):jo(r,n)}function Lo(r,n){let o=[];for(let c=0;c<r.length;c++){let u=r[c];n.indexOf(u)!=-1&&o.push(u)}return o}function jo(r,n){let o=[];for(let c=0;c<r.length;c++){let u=r[c];u in n&&o.push(u)}return o}function qo(r,n){let o=r.indexOf(n),c=o!=-1;return c&&r.splice(o,1),c}function df(r,n){let o=r.slice();return qo(o,n),o}function js(r,n){let o=[];for(let c in r)n&&!Object.prototype.hasOwnProperty.call(r,c)||o.push(c);return o}function Uo(r,n){let o=[];for(let c in r)n&&!Object.prototype.hasOwnProperty.call(r,c)||o.push(r[c]);return o}function Do(r,n){for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&n(o)}function ff(r,n){if(r.length===0)return!0;let o=r[0][n];return r.every(function(c){return c[n]===o})}var Bo=(r=>(r.msgpack="msgpack",r.json="json",r))(Bo||{});function zn(r){return r.splice(af(r),1)[0]}function ts(r){let n=[];if(r)for(let o in r)n.push(encodeURIComponent(o)+"="+encodeURIComponent(r[o]));return n.length?"?"+n.join("&"):""}function Kn(r){return Object.fromEntries(Object.entries(r).map(([n,o])=>[n,String(o)]))}function qs(r){let n,o=/([^?&=]+)=?([^&]*)/g,c={};for(;n=o.exec(r);)c[decodeURIComponent(n[1])]=decodeURIComponent(n[2]);return c}function Jn(r){return typeof r=="object"&&r!==null&&(r instanceof x||r instanceof Ee)}function ee(r){var n,o;return r instanceof Error||((n=r?.constructor)==null?void 0:n.name)==="ErrorInfo"||((o=r?.constructor)==null?void 0:o.name)==="PartialErrorInfo"?r.toString():L.Config.inspect(r)}function $o(r){return L.BufferUtils.isBuffer(r)?r.toString():typeof r=="string"?r:L.Config.inspect(r)}function Ho(r){if(L.BufferUtils.isBuffer(r))return L.BufferUtils.byteLength(r);if(typeof r=="string")return L.Config.stringByteSize(r);if(typeof r=="number")return 8;if(typeof r=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof r}`)}function Go(){return String(Math.random()).substr(2)}var Fo=async r=>{let n=await L.Config.getRandomArrayBuffer(r);return L.BufferUtils.base64Encode(n)};function Wo(r,n){let o=Math.min(n,r.length),c=r.slice(),u=[];for(let f=0;f<o;f++)u.push(zn(c));return u}function Oe(r,n){r.then(o=>{n?.(null,o)}).catch(o=>{n?.(o)})}function ue(r,n,o){return o=="msgpack"?(n||pe("MsgPack"),n.decode(r)):JSON.parse(String(r))}function je(r,n,o){return o=="msgpack"?(n||pe("MsgPack"),n.encode(r,!0)):JSON.stringify(r)}function Vo(r){return r.map(function(n){return n&&n.toLowerCase()})}function zo(r){return r.map(function(n){return n&&n.toUpperCase()})}function Ko(r){return Math.min((r+2)/3,2)}function Jo(){return 1-Math.random()*.2}function Yn(r,n){return r*Ko(n)*Jo()}function pf(){return typeof global<"u"?global:typeof window<"u"?window:self}function Qn(r,n){return Object.keys(r).every(o=>r[o]===n[o])&&Object.keys(n).every(o=>n[o]===r[o])}function Yo(r){let n=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=r.match(n);if(!o||!o.length||o.length<5)throw new x("regex match failed",400,40010);if(o[2])throw new x(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function Us(r){let n=L.BufferUtils,o=n.utf8Encode(r);return n.base64Encode(o)}function Qo(r,n){return r.length===n.length&&r.every(function(o,c){return o===n[c]})}function ss(r){return new x(`${r} plugin not provided`,40019,400)}function pe(r){throw ss(r)}async function Xo(r,n=5e3,o="Timeout expired"){let c=new x(o,5e4,500);return Promise.race([r,new Promise((u,f)=>setTimeout(()=>f(c),n))])}function gf(r){return Le(this,null,function*(){let n=[],o=null,c=r(u=>{if(o){let f=o;o=null,f(u)}else n.push(u)});try{for(;;)if(n.length>0)yield n.shift();else{if(o)throw new x("Concurrent next() calls are not supported",4e4,400);yield yield new Te(new Promise(f=>{o=f}))}}finally{c()}})}var Zo="2.17.0",mf="ably-js/"+Zo,qe={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:Zo,protocolVersion:5,agent:mf,getPort:yf,getHttpScheme:_f,getPrimaryDomainFromEndpoint:ta,getEndpointFallbackHosts:sa,getFallbackHosts:ra,getHosts:bf,checkHost:ia,objectifyOptions:wf,normaliseOptions:Ef,defaultGetHeaders:Of,defaultPostHeaders:kf};function yf(r,n){return n||r.tls?r.tlsPort:r.port}function _f(r){return r.tls?"https://":"http://"}function ea(r){return r.includes(".")||r.includes("::")||r==="localhost"}function ta(r){return ea(r)?r:r.startsWith("nonprod:")?`${r.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${r}.realtime.ably.net`}function sa(r){if(ea(r))return[];if(r.startsWith("nonprod:")){let n=r.replace("nonprod:","");return na(n,"ably-realtime-nonprod.com")}return na(r,"ably-realtime.com")}function na(r,n){return["a","b","c","d","e"].map(o=>`${r}.${o}.fallback.${n}`)}function ra(r){let n=r.fallbackHosts,o=typeof r.httpMaxRetryCount<"u"?r.httpMaxRetryCount:qe.httpMaxRetryCount;return n?Wo(n,o):[]}function bf(r){return[r.primaryDomain].concat(ra(r))}function ia(r){if(typeof r!="string")throw new x("host must be a string; was a "+typeof r,4e4,400);if(!r.length)throw new x("host must not be zero-length",4e4,400)}function vf(r){let n={};for(let o in qe.TIMEOUTS)n[o]=r[o]||qe.TIMEOUTS[o];return n}function Xn(r){let n=qe.agent;if(r.agents)for(var o in r.agents)n+=" "+o+"/"+r.agents[o];return n}function wf(r,n,o,c,u){if(r===void 0){let m=n?`${o} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${o} must be initialized with a client options object`;throw d.logAction(c,d.LOG_ERROR,`${o}()`,m),new Error(m)}let f;if(typeof r=="string")if(r.indexOf(":")==-1){if(!n){let m=`${o} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw d.logAction(c,d.LOG_ERROR,`${o}()`,m),new Error(m)}f={token:r}}else{if(!n){let m=`${o} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw d.logAction(c,d.LOG_ERROR,`${o}()`,m),new Error(m)}f={key:r}}else f=r;return u&&(f=S(E({},f),{plugins:E(E({},u),f.plugins)})),f}function Cf(r){if(r.endpoint&&(r.environment||r.restHost||r.realtimeHost))throw new x("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(r.environment&&(r.restHost||r.realtimeHost))throw new x("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function Ef(r,n,o){let c=o??d.defaultLogger;r.environment&&c.deprecated("The `environment` client option","Use the `endpoint` client option instead."),r.restHost&&c.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),r.realtimeHost&&c.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),Cf(r),typeof r.recover=="function"&&r.closeOnUnload===!0&&(d.logAction(c,d.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),r.recover=void 0),"closeOnUnload"in r||(r.closeOnUnload=!r.recover),"queueMessages"in r||(r.queueMessages=!0);let u=r.endpoint||qe.ENDPOINT;!r.fallbackHosts&&!r.restHost&&!r.realtimeHost&&!r.port&&!r.tlsPort&&(r.fallbackHosts=sa(r.environment||u));let f=r.environment&&`${r.environment}.realtime.ably.net`,_=r.restHost||r.realtimeHost||f||ta(u);(r.fallbackHosts||[]).concat(_).forEach(ia),r.port=r.port||qe.PORT,r.tlsPort=r.tlsPort||qe.TLS_PORT,"tls"in r||(r.tls=!0);let A=vf(r);n?"useBinaryProtocol"in r?r.useBinaryProtocol=L.Config.supportsBinary&&r.useBinaryProtocol:r.useBinaryProtocol=L.Config.preferBinary:r.useBinaryProtocol=!1;let I={};r.clientId&&(I["X-Ably-ClientId"]=L.BufferUtils.base64Encode(L.BufferUtils.utf8Encode(r.clientId))),"idempotentRestPublishing"in r||(r.idempotentRestPublishing=!0);let q=null,j=r.connectivityCheckUrl;if(r.connectivityCheckUrl){let[w,R]=r.connectivityCheckUrl.split("?");q=R?qs(R):{},w.indexOf("://")===-1&&(w="https://"+w),j=w}let G=r.wsConnectivityCheckUrl;return G&&G.indexOf("://")===-1&&(G="wss://"+G),S(E({},r),{primaryDomain:_,maxMessageSize:r.maxMessageSize||qe.maxMessageSize,timeouts:A,connectivityCheckParams:q,connectivityCheckUrl:j,wsConnectivityCheckUrl:G,headers:I})}function Ds(r,n,o){let c=o||{};if(c.cipher){r||pe("Crypto");let u=r.getCipher(c.cipher,n);c.cipher=u.cipherParams,c.channelCipher=u.cipher}else"cipher"in c&&(c.cipher=void 0,c.channelCipher=null);return c}var oa={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},aa={format:"json",protocolVersion:qe.protocolVersion};function Of(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){return{accept:oa[n??(r.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}function kf(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){let c=oa[n??(r.useBinaryProtocol?"msgpack":"json")];return{accept:c,"content-type":c,"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}var K=qe;function Sf(r){return Object.assign(qe,r)}var Tf=class Td{constructor(n,o){this.logger=n,this.members=o||[]}call(n,o){for(let c of this.members)if(c)try{c(n,o)}catch(u){d.logAction(this.logger,d.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+u+"; stack = "+u.stack)}}push(...n){this.members.push(...n)}createPromise(){return new Promise((n,o)=>{this.push((c,u)=>{c?o(c):n(u)})})}resolveAll(n){this.call(null,n)}rejectAll(n){this.call(n)}static create(n,o){let c=new Td(n,o);return Object.assign((u,f)=>c.call(u,f),{push:u=>c.push(u),createPromise:()=>c.createPromise(),resolveAll:u=>c.resolveAll(u),rejectAll:u=>c.rejectAll(u)})}},ca=Tf,la=(r=>(r.Get="get",r.Delete="delete",r.Post="post",r.Put="put",r.Patch="patch",r))(la||{}),ce=la,ua=(r=>(r[r.Success=200]="Success",r[r.NoContent=204]="NoContent",r[r.BadRequest=400]="BadRequest",r[r.Unauthorized=401]="Unauthorized",r[r.Forbidden=403]="Forbidden",r[r.RequestTimeout=408]="RequestTimeout",r[r.InternalServerError=500]="InternalServerError",r))(ua||{});function Af(r){return r>=200&&r<400}var ns=ua,Zn=Math.pow(2,17);function Rf(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function Pf(r){return!!r.connection}function ha(r){return Jn(r)?(r.code||(r.statusCode===403?r.code=40300:(r.code=40170,r.statusCode=401)),r):new x(ee(r),r.code||40170,r.statusCode||401)}var If=(r,n)=>{let o=L.BufferUtils,c=o.utf8Encode(r),u=o.utf8Encode(n),f=o.hmacSha256(c,u);return o.base64Encode(f)};function da(r){if(!r)return"";typeof r=="string"&&(r=JSON.parse(r));let n=Object.create(null),o=js(r,!0);if(!o)return"";o.sort();for(let c=0;c<o.length;c++)n[o[c]]=r[o[c]].sort();return JSON.stringify(n)}function fa(r,n){if(r.authCallback)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authCallback");else if(r.authUrl)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authUrl");else if(r.key)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(r.tokenDetails)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let o="authOptions must include valid authentication parameters";throw d.logAction(n,d.LOG_ERROR,"Auth()",o),new Error(o)}}function Mf(r){return"useTokenAuth"in r&&!r.useTokenAuth}function pa(r){return r.useTokenAuth||!Mf(r)&&(r.authCallback||r.authUrl||r.token||r.tokenDetails)}function xf(r){return!r.key&&!r.authCallback&&!r.authUrl}var Nf=0;function Lf(){return Nf++}var jf=class{constructor(r,n){if(this.authOptions={},this.client=r,this.tokenParams=n.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,pa(n))xf(n)&&d.logAction(this.logger,d.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(n.defaultTokenParams,n),fa(this.authOptions,this.logger);else{if(!n.key){let o="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()",o),new x(o,40160,401)}d.logAction(this.logger,d.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(n)}}get logger(){return this.client.logger}async authorize(r,n){if(n&&n.key&&this.authOptions.key!==n.key)throw new x("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(r??null,n??null);return Pf(this.client)?new Promise((c,u)=>{this.client.connection.connectionManager.onAuthUpdated(o,(f,m)=>f?u(f):c(m))}):o}catch(o){throw this.client.connection&&o.statusCode===ns.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(r,n){this.tokenDetails=null,this._saveTokenOptions(r,n),fa(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(r,n){let o=n||this.authOptions,c=r||es(this.tokenParams),u,f=this.client;if(o.authCallback)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),u=o.authCallback;else if(o.authUrl)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),u=(_,A)=>{let I=J({accept:"application/json, text/plain"},o.authHeaders),q=o.authMethod&&o.authMethod.toLowerCase()==="post",j,G=o.authUrl.indexOf("?");G>-1&&(j=qs(o.authUrl.slice(G)),o.authUrl=o.authUrl.slice(0,G),q||(o.authParams=J(j,o.authParams)));let w=J({},o.authParams||{},_),R=P=>{var U,H;let V=(U=P.body)!=null?U:null,F=null;if(P.error)d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+ee(P.error));else{let _e=(H=P.headers["content-type"])!=null?H:null;Array.isArray(_e)?F=_e.join(", "):F=_e,d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+F+"; body: "+$o(V))}if(P.error){A(P.error,null);return}if(P.unpacked){A(null,V);return}if(L.BufferUtils.isBuffer(V)&&(V=V.toString()),!F){A(new x("authUrl response is missing a content-type header",40170,401),null);return}let X=F.indexOf("application/json")>-1,Ce=F.indexOf("text/plain")>-1||F.indexOf("application/jwt")>-1;if(!X&&!Ce){A(new x("authUrl responded with unacceptable content-type "+F+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(X){if(V.length>Zn){A(new x("authUrl response exceeded max permitted length",40170,401),null);return}try{V=JSON.parse(V)}catch(_e){A(new x("Unexpected error processing authURL response; err = "+_e.message,40170,401),null);return}}A(null,V,F)};if(d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+o.authUrl+"; Params: "+JSON.stringify(w)+"; method: "+(q?"POST":"GET")),q){let P=I||{};P["content-type"]="application/x-www-form-urlencoded";let U=ts(w).slice(1);Oe(this.client.http.doUri(ce.Post,o.authUrl,P,U,j),(H,V)=>R(H||V))}else Oe(this.client.http.doUri(ce.Get,o.authUrl,I||{},null,w),(P,U)=>R(P||U))};else if(o.key)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),u=(_,A)=>{Oe(this.createTokenRequest(_,o),(I,q)=>A(I,q??null))};else{let _="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new x(_,40171,403)}"capability"in c&&(c.capability=da(c.capability));let m=(_,A)=>{let I=_.keyName,q="/keys/"+I+"/requestToken",j=function(w){return f.baseUri(w)+q},G=K.defaultPostHeaders(this.client.options,{format:"json"});o.requestHeaders&&J(G,o.requestHeaders),d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+q+"; Token params: "+JSON.stringify(_)),Oe(this.client.http.do(ce.Post,j,G,JSON.stringify(_),null),(w,R)=>w?A(w):A(R.error,R.body,R.unpacked))};return new Promise((_,A)=>{let I=!1,q=this.client.options.timeouts.realtimeRequestTimeout,j=setTimeout(()=>{I=!0;let G="Token request callback timed out after "+q/1e3+" seconds";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",G),A(new x(G,40170,401))},q);u(c,(G,w,R)=>{if(I)return;if(clearTimeout(j),G){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ee(G)),A(ha(G));return}if(typeof w=="string"){w.length===0?A(new x("Token string is empty",40170,401)):w.length>Zn?A(new x("Token string exceeded max permitted length (was "+w.length+" bytes)",40170,401)):w==="undefined"||w==="null"?A(new x("Token string was literal null/undefined",40170,401)):w[0]==="{"&&!(R&&R.indexOf("application/jwt")>-1)?A(new x("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):_({token:w});return}if(typeof w!="object"||w===null){let U="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof w;d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",U),A(new x(U,40170,401));return}let P=JSON.stringify(w).length;if(P>Zn&&!o.suppressMaxLengthCheck){A(new x("Token request/details object exceeded max permitted stringified size (was "+P+" bytes)",40170,401));return}if("issued"in w){_(w);return}if(!("keyName"in w)){let U="Expected token request callback to call back with a token string, token request object, or token details object";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",U),A(new x(U,40170,401));return}m(w,(U,H,V)=>{if(U){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+ee(U)),A(ha(U));return}V||(H=JSON.parse(H)),d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","token received"),_(H)})})})}async createTokenRequest(r,n){n=n||this.authOptions,r=r||es(this.tokenParams);let o=n.key;if(!o)throw new x("No key specified",40101,403);let c=o.split(":"),u=c[0],f=c[1];if(!f)throw new x("Invalid key specified",40101,403);if(r.clientId==="")throw new x("clientId can\u2019t be an empty string",40012,400);"capability"in r&&(r.capability=da(r.capability));let m=J({keyName:u},r),_=r.clientId||"",A=r.ttl||"",I=r.capability||"";m.timestamp||(m.timestamp=await this._getTimestamp(n&&n.queryTime));let q=m.nonce||(m.nonce=Rf()),j=m.timestamp,G=m.keyName+`
|
|
39
|
-
`+
|
|
38
|
+
`)}`}}};Q.RequestError=ae;var In=class extends ae{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name="MaxRedirectsError",this.code="ERR_TOO_MANY_REDIRECTS"}};Q.MaxRedirectsError=In;var Mn=class extends ae{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name="HTTPError",this.code="ERR_NON_2XX_3XX_RESPONSE"}};Q.HTTPError=Mn;var xn=class extends ae{constructor(e,t){super(e.message,e,t),this.name="CacheError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_CACHE_ACCESS":this.code}};Q.CacheError=xn;var Nn=class extends ae{constructor(e,t){super(e.message,e,t),this.name="UploadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_UPLOAD":this.code}};Q.UploadError=Nn;var Ln=class extends ae{constructor(e,t,i){super(e.message,e,i),this.name="TimeoutError",this.event=e.event,this.timings=t}};Q.TimeoutError=Ln;var As=class extends ae{constructor(e,t){super(e.message,e,t),this.name="ReadError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_READING_RESPONSE_STREAM":this.code}};Q.ReadError=As;var jn=class extends ae{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name="UnsupportedProtocolError",this.code="ERR_UNSUPPORTED_PROTOCOL"}};Q.UnsupportedProtocolError=jn;var Sv=["socket","connect","continue","information","upgrade","timeout"],Dn=class extends Qh.Duplex{constructor(e,t={},i){super({autoDestroy:!1,highWaterMark:0}),this[zt]=0,this[Jt]=0,this.requestInitialized=!1,this[An]=new Set,this.redirects=[],this[Yt]=!1,this[Rn]=!1,this[Ts]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),l=()=>this._lockWrite();this.on("pipe",m=>{m.prependListener("data",a),m.on("data",l),m.prependListener("end",a),m.on("end",l)}),this.on("unpipe",m=>{m.off("data",a),m.off("data",l),m.off("end",a),m.off("end",l)}),this.on("pipe",m=>{m instanceof so.IncomingMessage&&(this.options.headers={...m.headers,...this.options.headers})});let{json:h,body:p,form:g}=t;if((h||p||g)&&this._lockWrite(),Q.kIsNormalizedAlready in t)this.options=t;else try{this.options=this.constructor.normalizeArguments(e,t,i)}catch(m){M.default.nodeStream(t.body)&&t.body.destroy(),this.destroy(m);return}(async()=>{var m;try{this.options.body instanceof iv.ReadStream&&await Ev(this.options.body);let{url:v}=this.options;if(!v)throw new TypeError("Missing `url` property");if(this.requestUrl=v.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(m=this[fe])===null||m===void 0||m.destroy();return}for(let C of this[Ts])C();this[Ts].length=0,this.requestInitialized=!0}catch(v){if(v instanceof ae){this._beforeError(v);return}this.destroyed||this.destroy(v)}})()}static normalizeArguments(e,t,i){var a,l,h,p,g;let m=t;if(M.default.object(e)&&!M.default.urlInstance(e))t={...i,...e,...t};else{if(e&&t&&t.url!==void 0)throw new TypeError("The `url` option is mutually exclusive with the `input` argument");t={...i,...t},e!==void 0&&(t.url=e),M.default.urlInstance(t.url)&&(t.url=new ht.URL(t.url.toString()))}if(t.cache===!1&&(t.cache=void 0),t.dnsCache===!1&&(t.dnsCache=void 0),M.assert.any([M.default.string,M.default.undefined],t.method),M.assert.any([M.default.object,M.default.undefined],t.headers),M.assert.any([M.default.string,M.default.urlInstance,M.default.undefined],t.prefixUrl),M.assert.any([M.default.object,M.default.undefined],t.cookieJar),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.searchParams),M.assert.any([M.default.object,M.default.string,M.default.undefined],t.cache),M.assert.any([M.default.object,M.default.number,M.default.undefined],t.timeout),M.assert.any([M.default.object,M.default.undefined],t.context),M.assert.any([M.default.object,M.default.undefined],t.hooks),M.assert.any([M.default.boolean,M.default.undefined],t.decompress),M.assert.any([M.default.boolean,M.default.undefined],t.ignoreInvalidCookies),M.assert.any([M.default.boolean,M.default.undefined],t.followRedirect),M.assert.any([M.default.number,M.default.undefined],t.maxRedirects),M.assert.any([M.default.boolean,M.default.undefined],t.throwHttpErrors),M.assert.any([M.default.boolean,M.default.undefined],t.http2),M.assert.any([M.default.boolean,M.default.undefined],t.allowGetBody),M.assert.any([M.default.string,M.default.undefined],t.localAddress),M.assert.any([nd.isDnsLookupIpVersion,M.default.undefined],t.dnsLookupIpVersion),M.assert.any([M.default.object,M.default.undefined],t.https),M.assert.any([M.default.boolean,M.default.undefined],t.rejectUnauthorized),t.https&&(M.assert.any([M.default.boolean,M.default.undefined],t.https.rejectUnauthorized),M.assert.any([M.default.function_,M.default.undefined],t.https.checkServerIdentity),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificateAuthority),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.key),M.assert.any([M.default.string,M.default.object,M.default.array,M.default.undefined],t.https.certificate),M.assert.any([M.default.string,M.default.undefined],t.https.passphrase),M.assert.any([M.default.string,M.default.buffer,M.default.array,M.default.undefined],t.https.pfx)),M.assert.any([M.default.object,M.default.undefined],t.cacheOptions),M.default.string(t.method)?t.method=t.method.toUpperCase():t.method="GET",t.headers===i?.headers?t.headers={...t.headers}:t.headers=hv({...i?.headers,...t.headers}),"slashes"in t)throw new TypeError("The legacy `url.Url` has been deprecated. Use `URL` instead.");if("auth"in t)throw new TypeError("Parameter `auth` is deprecated. Use `username` / `password` instead.");if("searchParams"in t&&t.searchParams&&t.searchParams!==i?.searchParams){let S;if(M.default.string(t.searchParams)||t.searchParams instanceof ht.URLSearchParams)S=new ht.URLSearchParams(t.searchParams);else{wv(t.searchParams),S=new ht.URLSearchParams;for(let A in t.searchParams){let E=t.searchParams[A];E===null?S.append(A,""):E!==void 0&&S.append(A,E)}}(a=i?.searchParams)===null||a===void 0||a.forEach((A,E)=>{S.has(E)||S.append(E,A)}),t.searchParams=S}if(t.username=(l=t.username)!==null&&l!==void 0?l:"",t.password=(h=t.password)!==null&&h!==void 0?h:"",M.default.undefined(t.prefixUrl)?t.prefixUrl=(p=i?.prefixUrl)!==null&&p!==void 0?p:"":(t.prefixUrl=t.prefixUrl.toString(),t.prefixUrl!==""&&!t.prefixUrl.endsWith("/")&&(t.prefixUrl+="/")),M.default.string(t.url)){if(t.url.startsWith("/"))throw new Error("`input` must not start with a slash when using `prefixUrl`");t.url=sd.default(t.prefixUrl+t.url,t)}else(M.default.undefined(t.url)&&t.prefixUrl!==""||t.protocol)&&(t.url=sd.default(t.prefixUrl,t));if(t.url){"port"in t&&delete t.port;let{prefixUrl:S}=t;Object.defineProperty(t,"prefixUrl",{set:E=>{let O=t.url;if(!O.href.startsWith(E))throw new Error(`Cannot change \`prefixUrl\` from ${S} to ${E}: ${O.href}`);t.url=new ht.URL(E+O.href.slice(S.length)),S=E},get:()=>S});let{protocol:A}=t.url;if(A==="unix:"&&(A="http:",t.url=new ht.URL(`http://unix${t.url.pathname}${t.url.search}`)),t.searchParams&&(t.url.search=t.searchParams.toString()),A!=="http:"&&A!=="https:")throw new jn(t);t.username===""?t.username=t.url.username:t.url.username=t.username,t.password===""?t.password=t.url.password:t.url.password=t.password}let{cookieJar:v}=t;if(v){let{setCookie:S,getCookieString:A}=v;M.assert.function_(S),M.assert.function_(A),S.length===4&&A.length===0&&(S=Yh.promisify(S.bind(t.cookieJar)),A=Yh.promisify(A.bind(t.cookieJar)),t.cookieJar={setCookie:S,getCookieString:A})}let{cache:C}=t;if(C&&(io.has(C)||io.set(C,new Zh((S,A)=>{let E=S[fe](S,A);return M.default.promise(E)&&(E.once=(O,N)=>{if(O==="error")E.catch(N);else if(O==="abort")(async()=>{try{(await E).once("abort",N)}catch{}})();else throw new Error(`Unknown HTTP2 promise event: ${O}`);return E}),E},C))),t.cacheOptions={...t.cacheOptions},t.dnsCache===!0)no||(no=new cv.default),t.dnsCache=no;else if(!M.default.undefined(t.dnsCache)&&!t.dnsCache.lookup)throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${M.default(t.dnsCache)}`);M.default.number(t.timeout)?t.timeout={request:t.timeout}:i&&t.timeout!==i.timeout?t.timeout={...i.timeout,...t.timeout}:t.timeout={...t.timeout},t.context||(t.context={});let k=t.hooks===i?.hooks;t.hooks={...t.hooks};for(let S of Q.knownHookEvents)if(S in t.hooks)if(M.default.array(t.hooks[S]))t.hooks[S]=[...t.hooks[S]];else throw new TypeError(`Parameter \`${S}\` must be an Array, got ${M.default(t.hooks[S])}`);else t.hooks[S]=[];if(i&&!k)for(let S of Q.knownHookEvents)i.hooks[S].length>0&&(t.hooks[S]=[...i.hooks[S],...t.hooks[S]]);if("family"in t&&dt.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'),i?.https&&(t.https={...i.https,...t.https}),"rejectUnauthorized"in t&&dt.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'),"checkServerIdentity"in t&&dt.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'),"ca"in t&&dt.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'),"key"in t&&dt.default('"options.key" was never documented, please use "options.https.key"'),"cert"in t&&dt.default('"options.cert" was never documented, please use "options.https.certificate"'),"passphrase"in t&&dt.default('"options.passphrase" was never documented, please use "options.https.passphrase"'),"pfx"in t&&dt.default('"options.pfx" was never documented, please use "options.https.pfx"'),"followRedirects"in t)throw new TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");if(t.agent){for(let S in t.agent)if(S!=="http"&&S!=="https"&&S!=="http2")throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${S}\``)}return t.maxRedirects=(g=t.maxRedirects)!==null&&g!==void 0?g:0,Q.setNonEnumerableProperties([i,m],t),_v.default(t,i)}_lockWrite(){let e=()=>{throw new TypeError("The payload has been already provided")};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:e}=this,{headers:t}=e,i=!M.default.undefined(e.form),a=!M.default.undefined(e.json),l=!M.default.undefined(e.body),h=i||a||l,p=Q.withoutBody.has(e.method)&&!(e.method==="GET"&&e.allowGetBody);if(this._cannotHaveBody=p,h){if(p)throw new TypeError(`The \`${e.method}\` method cannot be used with a body`);if([l,i,a].filter(g=>g).length>1)throw new TypeError("The `body`, `json` and `form` options are mutually exclusive");if(l&&!(e.body instanceof Qh.Readable)&&!M.default.string(e.body)&&!M.default.buffer(e.body)&&!ed.default(e.body))throw new TypeError("The `body` option must be a stream.Readable, string or Buffer");if(i&&!M.default.object(e.form))throw new TypeError("The `form` option must be an Object");{let g=!M.default.string(t["content-type"]);l?(ed.default(e.body)&&g&&(t["content-type"]=`multipart/form-data; boundary=${e.body.getBoundary()}`),this[ft]=e.body):i?(g&&(t["content-type"]="application/x-www-form-urlencoded"),this[ft]=new ht.URLSearchParams(e.form).toString()):(g&&(t["content-type"]="application/json"),this[ft]=e.stringifyJson(e.json));let m=await dv.default(this[ft],e.headers);M.default.undefined(t["content-length"])&&M.default.undefined(t["transfer-encoding"])&&!p&&!M.default.undefined(m)&&(t["content-length"]=String(m))}}else p?this._lockWrite():this._unlockWrite();this[Kt]=Number(t["content-length"])||void 0}async _onResponseBase(e){let{options:t}=this,{url:i}=t;this[ad]=e,t.decompress&&(e=lv(e));let a=e.statusCode,l=e;l.statusMessage=l.statusMessage?l.statusMessage:Xh.STATUS_CODES[a],l.url=t.url.toString(),l.requestUrl=this.requestUrl,l.redirectUrls=this.redirects,l.request=this,l.isFromCache=e.fromCache||!1,l.ip=this.ip,l.retryCount=this.retryCount,this[id]=l.isFromCache,this[Vt]=Number(e.headers["content-length"])||void 0,this[Pn]=e,e.once("end",()=>{this[Vt]=this[zt],this.emit("downloadProgress",this.downloadProgress)}),e.once("error",p=>{e.destroy(),this._beforeError(new As(p,this))}),e.once("aborted",()=>{this._beforeError(new As({name:"Error",message:"The server aborted pending request",code:"ECONNRESET"},this))}),this.emit("downloadProgress",this.downloadProgress);let h=e.headers["set-cookie"];if(M.default.object(t.cookieJar)&&h){let p=h.map(async g=>t.cookieJar.setCookie(g,i.toString()));t.ignoreInvalidCookies&&(p=p.map(async g=>g.catch(()=>{})));try{await Promise.all(p)}catch(g){this._beforeError(g);return}}if(t.followRedirect&&e.headers.location&&kv.has(a)){if(e.resume(),this[fe]&&(this[ro](),delete this[fe],this[rd]()),(a===303&&t.method!=="GET"&&t.method!=="HEAD"||!t.methodRewriting)&&(t.method="GET","body"in t&&delete t.body,"json"in t&&delete t.json,"form"in t&&delete t.form,this[ft]=void 0,delete t.headers["content-length"]),this.redirects.length>=t.maxRedirects){this._beforeError(new In(this));return}try{let C=function(k){return k.protocol==="unix:"||k.hostname==="unix"},g=Buffer.from(e.headers.location,"binary").toString(),m=new ht.URL(g,i),v=m.toString();if(decodeURI(v),!C(i)&&C(m)){this._beforeError(new ae("Cannot redirect to UNIX socket",{},this));return}m.hostname!==i.hostname||m.port!==i.port?("host"in t.headers&&delete t.headers.host,"cookie"in t.headers&&delete t.headers.cookie,"authorization"in t.headers&&delete t.headers.authorization,(t.username||t.password)&&(t.username="",t.password="")):(m.username=t.username,m.password=t.password),this.redirects.push(v),t.url=m;for(let k of t.hooks.beforeRedirect)await k(t,l);this.emit("redirect",l,t),await this._makeRequest()}catch(g){this._beforeError(g);return}return}if(t.isStream&&t.throwHttpErrors&&!yv.isResponseOk(l)){this._beforeError(new Mn(l));return}e.on("readable",()=>{this[Rn]&&this._read()}),this.on("resume",()=>{e.resume()}),this.on("pause",()=>{e.pause()}),e.once("end",()=>{this.push(null)}),this.emit("response",e);for(let p of this[An])if(!p.headersSent){for(let g in e.headers){let m=t.decompress?g!=="content-encoding":!0,v=e.headers[g];m&&p.setHeader(g,v)}p.statusCode=a}}async _onResponse(e){try{await this._onResponseBase(e)}catch(t){this._beforeError(t)}}_onRequest(e){let{options:t}=this,{timeout:i,url:a}=t;av.default(e),this[ro]=td.default(e,i,a);let l=t.cache?"cacheableResponse":"response";e.once(l,g=>{this._onResponse(g)}),e.once("error",g=>{var m;e.destroy(),(m=e.res)===null||m===void 0||m.removeAllListeners("end"),g=g instanceof td.TimeoutError?new Ln(g,this.timings,this):new ae(g.message,g,this),this._beforeError(g)}),this[rd]=fv.default(e,this,Sv),this[fe]=e,this.emit("uploadProgress",this.uploadProgress);let h=this[ft],p=this.redirects.length===0?this:e;M.default.nodeStream(h)?(h.pipe(p),h.once("error",g=>{this._beforeError(new Nn(g,this))})):(this._unlockWrite(),M.default.undefined(h)?(this._cannotHaveBody||this._noPipe)&&(p.end(),this._lockWrite()):(this._writeRequest(h,void 0,()=>{}),p.end(),this._lockWrite())),this.emit("request",e)}async _createCacheableRequest(e,t){return new Promise((i,a)=>{Object.assign(t,pv.default(e)),delete t.url;let l,h=io.get(t.cache)(t,async p=>{p._readableState.autoDestroy=!1,l&&(await l).emit("cacheableResponse",p),i(p)});t.url=e,h.once("error",a),h.once("request",async p=>{l=p,i(l)})})}async _makeRequest(){var e,t,i,a,l;let{options:h}=this,{headers:p}=h;for(let N in p)if(M.default.undefined(p[N]))delete p[N];else if(M.default.null_(p[N]))throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${N}\` header`);if(h.decompress&&M.default.undefined(p["accept-encoding"])&&(p["accept-encoding"]=vv?"gzip, deflate, br":"gzip, deflate"),h.cookieJar){let N=await h.cookieJar.getCookieString(h.url.toString());M.default.nonEmptyString(N)&&(h.headers.cookie=N)}for(let N of h.hooks.beforeRequest){let H=await N(h);if(!M.default.undefined(H)){h.request=()=>H;break}}h.body&&this[ft]!==h.body&&(this[ft]=h.body);let{agent:g,request:m,timeout:v,url:C}=h;if(h.dnsCache&&!("lookup"in h)&&(h.lookup=h.dnsCache.lookup),C.hostname==="unix"){let N=/(?<socketPath>.+?):(?<path>.+)/.exec(`${C.pathname}${C.search}`);if(N?.groups){let{socketPath:H,path:K}=N.groups;Object.assign(h,{socketPath:H,path:K,host:""})}}let k=C.protocol==="https:",S;h.http2?S=uv.auto:S=k?ov.request:Xh.request;let A=(e=h.request)!==null&&e!==void 0?e:S,E=h.cache?this._createCacheableRequest:A;g&&!h.http2&&(h.agent=g[k?"https":"http"]),h[fe]=A,delete h.request,delete h.timeout;let O=h;if(O.shared=(t=h.cacheOptions)===null||t===void 0?void 0:t.shared,O.cacheHeuristic=(i=h.cacheOptions)===null||i===void 0?void 0:i.cacheHeuristic,O.immutableMinTimeToLive=(a=h.cacheOptions)===null||a===void 0?void 0:a.immutableMinTimeToLive,O.ignoreCargoCult=(l=h.cacheOptions)===null||l===void 0?void 0:l.ignoreCargoCult,h.dnsLookupIpVersion!==void 0)try{O.family=nd.dnsLookupIpVersionToFamily(h.dnsLookupIpVersion)}catch{throw new Error("Invalid `dnsLookupIpVersion` option value")}h.https&&("rejectUnauthorized"in h.https&&(O.rejectUnauthorized=h.https.rejectUnauthorized),h.https.checkServerIdentity&&(O.checkServerIdentity=h.https.checkServerIdentity),h.https.certificateAuthority&&(O.ca=h.https.certificateAuthority),h.https.certificate&&(O.cert=h.https.certificate),h.https.key&&(O.key=h.https.key),h.https.passphrase&&(O.passphrase=h.https.passphrase),h.https.pfx&&(O.pfx=h.https.pfx));try{let N=await E(C,O);M.default.undefined(N)&&(N=S(C,O)),h.request=m,h.timeout=v,h.agent=g,h.https&&("rejectUnauthorized"in h.https&&delete O.rejectUnauthorized,h.https.checkServerIdentity&&delete O.checkServerIdentity,h.https.certificateAuthority&&delete O.ca,h.https.certificate&&delete O.cert,h.https.key&&delete O.key,h.https.passphrase&&delete O.passphrase,h.https.pfx&&delete O.pfx),Cv(N)?this._onRequest(N):this.writable?(this.once("finish",()=>{this._onResponse(N)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(N)}catch(N){throw N instanceof Zh.CacheError?new xn(N,this):new ae(N.message,N,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new ae(t.message,t,this)}this.destroy(e)}_beforeError(e){if(this[Yt])return;let{options:t}=this,i=this.retryCount+1;this[Yt]=!0,e instanceof ae||(e=new ae(e.message,e,this));let a=e,{response:l}=a;(async()=>{if(l&&!l.body){l.setEncoding(this._readableState.encoding);try{l.rawBody=await mv.default(l),l.body=l.rawBody.toString()}catch{}}if(this.listenerCount("retry")!==0){let h;try{let p;l&&"retry-after"in l.headers&&(p=Number(l.headers["retry-after"]),Number.isNaN(p)?(p=Date.parse(l.headers["retry-after"])-Date.now(),p<=0&&(p=1)):p*=1e3),h=await t.retry.calculateDelay({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:bv.default({attemptCount:i,retryOptions:t.retry,error:a,retryAfter:p,computedValue:0})})}catch(p){this._error(new ae(p.message,p,this));return}if(h){let p=async()=>{try{for(let g of this.options.hooks.beforeRetry)await g(this.options,a,i)}catch(g){this._error(new ae(g.message,e,this));return}this.destroyed||(this.destroy(),this.emit("retry",i,e))};this[cd]=setTimeout(p,h);return}}this._error(a)})()}_read(){this[Rn]=!0;let e=this[Pn];if(e&&!this[Yt]){e.readableLength&&(this[Rn]=!1);let t;for(;(t=e.read())!==null;){this[zt]+=t.length,this[od]=!0;let i=this.downloadProgress;i.percent<1&&this.emit("downloadProgress",i),this.push(t)}}}_write(e,t,i){let a=()=>{this._writeRequest(e,t,i)};this.requestInitialized?a():this[Ts].push(a)}_writeRequest(e,t,i){this[fe].destroyed||(this._progressCallbacks.push(()=>{this[Jt]+=Buffer.byteLength(e,t);let a=this.uploadProgress;a.percent<1&&this.emit("uploadProgress",a)}),this[fe].write(e,t,a=>{!a&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),i(a)}))}_final(e){let t=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();if(!(fe in this)){e();return}if(this[fe].destroyed){e();return}this[fe].end(i=>{i||(this[Kt]=this[Jt],this.emit("uploadProgress",this.uploadProgress),this[fe].emit("upload-complete")),e(i)})};this.requestInitialized?t():this[Ts].push(t)}_destroy(e,t){var i;this[Yt]=!0,clearTimeout(this[cd]),fe in this&&(this[ro](),!((i=this[Pn])===null||i===void 0)&&i.complete||this[fe].destroy()),e!==null&&!M.default.undefined(e)&&!(e instanceof ae)&&(e=new ae(e.message,e,this)),t(e)}get _isAboutToError(){return this[Yt]}get ip(){var e;return(e=this.socket)===null||e===void 0?void 0:e.remoteAddress}get aborted(){var e,t,i;return((t=(e=this[fe])===null||e===void 0?void 0:e.destroyed)!==null&&t!==void 0?t:this.destroyed)&&!(!((i=this[ad])===null||i===void 0)&&i.complete)}get socket(){var e,t;return(t=(e=this[fe])===null||e===void 0?void 0:e.socket)!==null&&t!==void 0?t:void 0}get downloadProgress(){let e;return this[Vt]?e=this[zt]/this[Vt]:this[Vt]===this[zt]?e=1:e=0,{percent:e,transferred:this[zt],total:this[Vt]}}get uploadProgress(){let e;return this[Kt]?e=this[Jt]/this[Kt]:this[Kt]===this[Jt]?e=1:e=0,{percent:e,transferred:this[Jt],total:this[Kt]}}get timings(){var e;return(e=this[fe])===null||e===void 0?void 0:e.timings}get isFromCache(){return this[id]}pipe(e,t){if(this[od])throw new Error("Failed to pipe. The response has been emitted already.");return e instanceof so.ServerResponse&&this[An].add(e),super.pipe(e,t)}unpipe(e){return e instanceof so.ServerResponse&&this[An].delete(e),super.unpipe(e),this}};Q.default=Dn});var Ps=$(Be=>{"use strict";var Tv=Be&&Be.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Av=Be&&Be.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Tv(e,s,t)};Object.defineProperty(Be,"__esModule",{value:!0});Be.CancelError=Be.ParseError=void 0;var ld=Rs(),oo=class extends ld.RequestError{constructor(e,t){let{options:i}=t.request;super(`${e.message} in "${i.url.toString()}"`,e,t.request),this.name="ParseError",this.code=this.code==="ERR_GOT_REQUEST_ERROR"?"ERR_BODY_PARSE_FAILURE":this.code}};Be.ParseError=oo;var ao=class extends ld.RequestError{constructor(e){super("Promise was canceled",{},e),this.name="CancelError",this.code="ERR_CANCELED"}get isCanceled(){return!0}};Be.CancelError=ao;Av(Rs(),Be)});var hd=$(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var ud=Ps(),Rv=(s,e,t,i)=>{let{rawBody:a}=s;try{if(e==="text")return a.toString(i);if(e==="json")return a.length===0?"":t(a.toString());if(e==="buffer")return a;throw new ud.ParseError({message:`Unknown body type '${e}'`,name:"Error"},s)}catch(l){throw new ud.ParseError(l,s)}};co.default=Rv});var lo=$(pt=>{"use strict";var Pv=pt&&pt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Iv=pt&&pt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Pv(e,s,t)};Object.defineProperty(pt,"__esModule",{value:!0});var Mv=q("events"),xv=st(),Nv=lu(),Un=Ps(),dd=hd(),fd=Rs(),Lv=Wi(),jv=Xi(),pd=Zi(),Dv=["request","response","redirect","uploadProgress","downloadProgress"];function gd(s){let e,t,i=new Mv.EventEmitter,a=new Nv((h,p,g)=>{let m=v=>{let C=new fd.default(void 0,s);C.retryCount=v,C._noPipe=!0,g(()=>C.destroy()),g.shouldReject=!1,g(()=>p(new Un.CancelError(C))),e=C,C.once("response",async A=>{var E;if(A.retryCount=v,A.request.aborted)return;let O;try{O=await jv.default(C),A.rawBody=O}catch{return}if(C._isAboutToError)return;let N=((E=A.headers["content-encoding"])!==null&&E!==void 0?E:"").toLowerCase(),H=["gzip","deflate","br"].includes(N),{options:K}=C;if(H&&!K.decompress)A.body=O;else try{A.body=dd.default(A,K.responseType,K.parseJson,K.encoding)}catch(se){if(A.body=O.toString(),pd.isResponseOk(A)){C._beforeError(se);return}}try{for(let[se,Z]of K.hooks.afterResponse.entries())A=await Z(A,async Te=>{let Le=fd.default.normalizeArguments(void 0,{...Te,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},K);Le.hooks.afterResponse=Le.hooks.afterResponse.slice(0,se);for(let gt of Le.hooks.beforeRetry)await gt(Le);let ot=gd(Le);return g(()=>{ot.catch(()=>{}),ot.cancel()}),ot})}catch(se){C._beforeError(new Un.RequestError(se.message,se,C));return}if(t=A,!pd.isResponseOk(A)){C._beforeError(new Un.HTTPError(A));return}C.destroy(),h(C.options.resolveBodyOnly?A.body:A)});let k=A=>{if(a.isCanceled)return;let{options:E}=C;if(A instanceof Un.HTTPError&&!E.throwHttpErrors){let{response:O}=A;h(C.options.resolveBodyOnly?O.body:O);return}p(A)};C.once("error",k);let S=C.options.body;C.once("retry",(A,E)=>{var O,N;if(S===((O=E.request)===null||O===void 0?void 0:O.options.body)&&xv.default.nodeStream((N=E.request)===null||N===void 0?void 0:N.options.body)){k(E);return}m(A)}),Lv.default(C,i,Dv)};m(0)});a.on=(h,p)=>(i.on(h,p),a);let l=h=>{let p=(async()=>{await a;let{options:g}=t.request;return dd.default(t,h,g.parseJson,g.encoding)})();return Object.defineProperties(p,Object.getOwnPropertyDescriptors(a)),p};return a.json=()=>{let{headers:h}=e.options;return!e.writableFinished&&h.accept===void 0&&(h.accept="application/json"),l("json")},a.buffer=()=>l("buffer"),a.text=()=>l("text"),a}pt.default=gd;Iv(Ps(),pt)});var md=$(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var Uv=Ps();function qv(s,...e){let t=(async()=>{if(s instanceof Uv.RequestError)try{for(let a of e)if(a)for(let l of a)s=await l(s)}catch(a){s=a}throw s})(),i=()=>t;return t.json=i,t.text=i,t.buffer=i,t.on=i,t}uo.default=qv});var bd=$(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var yd=st();function _d(s){for(let e of Object.values(s))(yd.default.plainObject(e)||yd.default.array(e))&&_d(e);return Object.freeze(s)}ho.default=_d});var wd=$(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0})});var fo=$(Ne=>{"use strict";var Bv=Ne&&Ne.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),$v=Ne&&Ne.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Bv(e,s,t)};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.defaultHandler=void 0;var Cd=st(),xe=lo(),Hv=md(),Bn=Rs(),Gv=bd(),Fv={RequestError:xe.RequestError,CacheError:xe.CacheError,ReadError:xe.ReadError,HTTPError:xe.HTTPError,MaxRedirectsError:xe.MaxRedirectsError,TimeoutError:xe.TimeoutError,ParseError:xe.ParseError,CancelError:xe.CancelError,UnsupportedProtocolError:xe.UnsupportedProtocolError,UploadError:xe.UploadError},Wv=async s=>new Promise(e=>{setTimeout(e,s)}),{normalizeArguments:qn}=Bn.default,Ed=(...s)=>{let e;for(let t of s)e=qn(void 0,t,e);return e},Vv=s=>s.isStream?new Bn.default(void 0,s):xe.default(s),zv=s=>"defaults"in s&&"options"in s.defaults,Kv=["get","post","put","patch","head","delete"];Ne.defaultHandler=(s,e)=>e(s);var kd=(s,e)=>{if(s)for(let t of s)t(e)},Od=s=>{s._rawHandlers=s.handlers,s.handlers=s.handlers.map(i=>(a,l)=>{let h,p=i(a,g=>(h=l(g),h));if(p!==h&&!a.isStream&&h){let g=p,{then:m,catch:v,finally:C}=g;Object.setPrototypeOf(g,Object.getPrototypeOf(h)),Object.defineProperties(g,Object.getOwnPropertyDescriptors(h)),g.then=m,g.catch=v,g.finally=C}return p});let e=(i,a={},l)=>{var h,p;let g=0,m=v=>s.handlers[g++](v,g===s.handlers.length?Vv:m);if(Cd.default.plainObject(i)){let v={...i,...a};Bn.setNonEnumerableProperties([i,a],v),a=v,i=void 0}try{let v;try{kd(s.options.hooks.init,a),kd((h=a.hooks)===null||h===void 0?void 0:h.init,a)}catch(k){v=k}let C=qn(i,a,l??s.options);if(C[Bn.kIsNormalizedAlready]=!0,v)throw new xe.RequestError(v.message,v,C);return m(C)}catch(v){if(a.isStream)throw v;return Hv.default(v,s.options.hooks.beforeError,(p=a.hooks)===null||p===void 0?void 0:p.beforeError)}};e.extend=(...i)=>{let a=[s.options],l=[...s._rawHandlers],h;for(let p of i)zv(p)?(a.push(p.defaults.options),l.push(...p.defaults._rawHandlers),h=p.defaults.mutableDefaults):(a.push(p),"handlers"in p&&l.push(...p.handlers),h=p.mutableDefaults);return l=l.filter(p=>p!==Ne.defaultHandler),l.length===0&&l.push(Ne.defaultHandler),Od({options:Ed(...a),handlers:l,mutableDefaults:!!h})};let t=async function*(i,a){let l=qn(i,a,s.options);l.resolveBodyOnly=!1;let h=l.pagination;if(!Cd.default.object(h))throw new TypeError("`options.pagination` must be implemented");let p=[],{countLimit:g}=h,m=0;for(;m<h.requestLimit;){m!==0&&await Wv(h.backoff);let v=await e(void 0,void 0,l),C=await h.transform(v),k=[];for(let A of C)if(h.filter(A,p,k)&&(!h.shouldContinue(A,p,k)||(yield A,h.stackAllItems&&p.push(A),k.push(A),--g<=0)))return;let S=h.paginate(v,p,k);if(S===!1)return;S===v.request.options?l=v.request.options:S!==void 0&&(l=qn(void 0,S,l)),m++}};e.paginate=t,e.paginate.all=async(i,a)=>{let l=[];for await(let h of t(i,a))l.push(h);return l},e.paginate.each=t,e.stream=(i,a)=>e(i,{...a,isStream:!0});for(let i of Kv)e[i]=(a,l)=>e(a,{...l,method:i}),e.stream[i]=(a,l)=>e(a,{...l,method:i,isStream:!0});return Object.assign(e,Fv),Object.defineProperty(e,"defaults",{value:s.mutableDefaults?s:Gv.default(s),writable:s.mutableDefaults,configurable:s.mutableDefaults,enumerable:!0}),e.mergeOptions=Ed,e};Ne.default=Od;$v(wd(),Ne)});var Hn=$((rt,$n)=>{"use strict";var Jv=rt&&rt.__createBinding||(Object.create?function(s,e,t,i){i===void 0&&(i=t),Object.defineProperty(s,i,{enumerable:!0,get:function(){return e[t]}})}:function(s,e,t,i){i===void 0&&(i=t),s[i]=e[t]}),Sd=rt&&rt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Jv(e,s,t)};Object.defineProperty(rt,"__esModule",{value:!0});var Yv=q("url"),Td=fo(),Qv={options:{method:"GET",retry:{limit:2,methods:["GET","PUT","HEAD","DELETE","OPTIONS","TRACE"],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"],maxRetryAfter:void 0,calculateDelay:({computedValue:s})=>s},timeout:{},headers:{"user-agent":"got (https://github.com/sindresorhus/got)"},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:"text",resolveBodyOnly:!1,maxRedirects:10,prefixUrl:"",methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:s=>s.request.options.responseType==="json"?s.body:JSON.parse(s.body),paginate:s=>{if(!Reflect.has(s.headers,"link"))return!1;let e=s.headers.link.split(","),t;for(let i of e){let a=i.split(";");if(a[1].includes("next")){t=a[0].trimStart().trim(),t=t.slice(1,-1);break}}return t?{url:new Yv.URL(t)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:s=>JSON.parse(s),stringifyJson:s=>JSON.stringify(s),cacheOptions:{}},handlers:[Td.defaultHandler],mutableDefaults:!1},po=Td.default(Qv);rt.default=po;$n.exports=po;$n.exports.default=po;$n.exports.__esModule=!0;Sd(fo(),rt);Sd(lo(),rt)});var xd=$((Ns,ko)=>{(function(s,e){typeof Ns=="object"&&typeof ko=="object"?ko.exports=e(dn(),Hn()):typeof define=="function"&&define.amd?define(["ws","got"],e):typeof Ns=="object"?Ns.Ably=e(dn(),Hn()):s.Ably=e(s.ws,s.got)})(Ns,(s,e)=>{var t={},i={exports:t},a=Object.create,l=Object.defineProperty,h=Object.defineProperties,p=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,v=Object.getOwnPropertySymbols,C=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,A=(r,n,o)=>n in r?l(r,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[n]=o,E=(r,n)=>{for(var o in n||(n={}))k.call(n,o)&&A(r,o,n[o]);if(v)for(var o of v(n))S.call(n,o)&&A(r,o,n[o]);return r},O=(r,n)=>h(r,g(n)),N=(r,n)=>{var o={};for(var c in r)k.call(r,c)&&n.indexOf(c)<0&&(o[c]=r[c]);if(r!=null&&v)for(var c of v(r))n.indexOf(c)<0&&S.call(r,c)&&(o[c]=r[c]);return o},H=(r,n)=>function(){return n||(0,r[m(r)[0]])((n={exports:{}}).exports,n),n.exports},K=(r,n)=>{for(var o in n)l(r,o,{get:n[o],enumerable:!0})},se=(r,n,o,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of m(n))!k.call(r,u)&&u!==o&&l(r,u,{get:()=>n[u],enumerable:!(c=p(n,u))||c.enumerable});return r},Z=(r,n,o)=>(o=r!=null?a(C(r)):{},se(n||!r||!r.__esModule?l(o,"default",{value:r,enumerable:!0}):o,r)),Te=function(r,n){this[0]=r,this[1]=n},Le=(r,n,o)=>{var c=(y,_,T,I)=>{try{var D=o[y](_),j=(_=D.value)instanceof Te,F=D.done;Promise.resolve(j?_[0]:_).then(w=>j?c(y==="return"?y:"next",_[1]?{done:w.done,value:w.value}:w,T,I):T({value:w,done:F})).catch(w=>c("throw",w,T,I))}catch(w){I(w)}},u=y=>f[y]=_=>new Promise((T,I)=>c(y,_,T,I)),f={};return o=o.apply(r,n),f[Symbol.asyncIterator]=()=>f,u("next"),u("throw"),u("return"),f},ot=H({"node_modules/bops/from.js"(r,n){var o=q("buffer").Buffer,c=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(c)<6?function(f,y){return new o(f,y)}:function(f,y){return o.from(f,y)}}}),gt=H({"node_modules/bops/to.js"(r,n){n.exports=function(o,c){return o.toString(c)}}}),Vn=H({"node_modules/bops/is.js"(r,n){var o=q("buffer").Buffer;n.exports=function(c){return o.isBuffer(c)}}}),Yd=H({"node_modules/bops/subarray.js"(r,n){n.exports=function(o,c,u){return arguments.length===2?o.slice(c):o.slice(c,u)}}}),Qd=H({"node_modules/bops/join.js"(r,n){var o=q("buffer").Buffer;n.exports=function(c,u){return u!==void 0?o.concat(c,u):o.concat(c)}}}),Xd=H({"node_modules/bops/copy.js"(r,n){n.exports=o;function o(c,u,f,y,_){return c.copy(u,f,y,_)}}}),Zd=H({"node_modules/bops/create.js"(r,n){var o=q("buffer").Buffer,c=((process||{}).version||"v0.0.0").slice(1).split(".")[0];n.exports=Number(c)<6?function(f){return new o(f)}:function(f){return o.alloc(f)}}}),ef=H({"node_modules/bops/read.js"(r,n){var o={},c=/read.+/,u;u=function(y){var _="return buf."+y+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],_)},n.exports=o;for(f in Buffer.prototype)c.test(f)&&(o[f]=u(f));var f}}),tf=H({"node_modules/bops/write.js"(r,n){var o=q("buffer").Buffer,c={},u=/write.+/,f;f=function(_){var T="return buf."+_+"("+["a","b","c"].join(",")+")";return new Function(["buf","a","b","c"],T)},n.exports=c;for(y in o.prototype)u.test(y)&&(c[y]=f(y));var y}}),sf=H({"node_modules/bops/index.js"(r,n){var o={};n.exports=o,o.from=ot(),o.to=gt(),o.is=Vn(),o.subarray=Yd(),o.join=Qd(),o.copy=Xd(),o.create=Zd(),c(ef(),o),c(tf(),o);function c(u,f){for(var y in u)f[y]=u[y]}}}),nf=H({"node_modules/@ably/msgpack-js/msgpack.js"(r){"use strict";var n=sf();r.encode=function(w,R){var P=F(w,R);if(P!=0){var U=n.create(P);return j(w,U,0,R),U}},r.decode=I;var o=65536*65536,c=1/o;function u(w,R){return R=R||0,w.readInt32BE(R+0)*o+w.readUInt32BE(R+4)}function f(w,R){return R=R||0,w.readUInt32BE(R+0)*o+w.readUInt32BE(R+4)}function y(w,R,P){R<9223372036854776e3?(w.writeInt32BE(Math.floor(R*c),P),w.writeInt32BE(R&-1,P+4)):(w.writeUInt32BE(2147483647,P),w.writeUInt32BE(4294967295,P+4))}function _(w,R,P){R<18446744073709552e3?(w.writeUInt32BE(Math.floor(R*c),P),w.writeInt32BE(R&-1,P+4)):(w.writeUInt32BE(4294967295,P),w.writeUInt32BE(4294967295,P+4))}function T(w,R){this.offset=R||0,this.buffer=w,this.bufferLength=w.length}T.prototype.map=function(w){if(w*2>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a map of length ${w})`);for(var R={},P=0;P<w;P++){var U=this.parse();R[U]=this.parse()}return R},T.prototype.bin=T.prototype.buf=function(w){if(w>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a binary of length ${w})`);var R=n.subarray(this.buffer,this.offset,this.offset+w);return this.offset+=w,R},T.prototype.str=function(w){if(w>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced a string of length ${w})`);var R=n.to(n.subarray(this.buffer,this.offset,this.offset+w));return this.offset+=w,R},T.prototype.array=function(w){if(w>this.bufferLength)throw new Error(`malformed messagepack detected: buffer size was ${this.bufferLength}, but referenced an array of length ${w})`);for(var R=new Array(w),P=0;P<w;P++)R[P]=this.parse();return R},T.prototype.parse=function(){var w=this.buffer[this.offset],R,P,U;if(w===void 0)throw new Error("malformed messagepack (referenced offset is outside buffer)");if(!(w&128))return this.offset++,w;if((w&240)===128)return P=w&15,this.offset++,this.map(P);if((w&240)===144)return P=w&15,this.offset++,this.array(P);if((w&224)===160)return P=w&31,this.offset++,this.str(P);if((w&224)===224)return R=n.readInt8(this.buffer,this.offset),this.offset++,R;switch(w){case 192:return this.offset++,null;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.bin(P);case 197:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.bin(P);case 198:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.bin(P);case 199:return P=n.readUInt8(this.buffer,this.offset+1),U=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,[U,this.bin(P)];case 200:return P=n.readUInt16BE(this.buffer,this.offset+1),U=n.readUInt8(this.buffer,this.offset+3),this.offset+=4,[U,this.bin(P)];case 201:return P=n.readUInt32BE(this.buffer,this.offset+1),U=n.readUInt8(this.buffer,this.offset+5),this.offset+=6,[U,this.bin(P)];case 202:return R=n.readFloatBE(this.buffer,this.offset+1),this.offset+=5,R;case 203:return R=n.readDoubleBE(this.buffer,this.offset+1),this.offset+=9,R;case 204:return R=this.buffer[this.offset+1],this.offset+=2,R;case 205:return R=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 206:return R=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 207:return R=f(this.buffer,this.offset+1),this.offset+=9,R;case 208:return R=n.readInt8(this.buffer,this.offset+1),this.offset+=2,R;case 209:return R=n.readInt16BE(this.buffer,this.offset+1),this.offset+=3,R;case 210:return R=n.readInt32BE(this.buffer,this.offset+1),this.offset+=5,R;case 211:return R=u(this.buffer,this.offset+1),this.offset+=9,R;case 212:return U=n.readUInt8(this.buffer,this.offset+1),R=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,U===0&&R===0?void 0:[U,R];case 213:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(2)];case 214:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(4)];case 215:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(8)];case 216:return U=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[U,this.bin(16)];case 217:return P=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,this.str(P);case 218:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.str(P);case 219:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.str(P);case 220:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.array(P);case 221:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.array(P);case 222:return P=n.readUInt16BE(this.buffer,this.offset+1),this.offset+=3,this.map(P);case 223:return P=n.readUInt32BE(this.buffer,this.offset+1),this.offset+=5,this.map(P)}throw new Error("Unknown type 0x"+w.toString(16))};function I(w){var R=new T(w),P=R.parse();if(R.offset!==w.length)throw new Error(w.length-R.offset+" trailing bytes");return P}function D(w,R){return Object.keys(w).filter(function(P){var U=w[P],G=typeof U;return(!R||U!=null)&&(G!=="function"||!!U.toJSON)})}function j(w,R,P,U,G){var V=typeof w,W,X;if(V==="string"){if(w=n.from(w),W=w.length,W<32)return R[P]=W|160,n.copy(w,R,P+1),1+W;if(W<256)return R[P]=217,n.writeUInt8(R,W,P+1),n.copy(w,R,P+2),2+W;if(W<65536)return R[P]=218,n.writeUInt16BE(R,W,P+1),n.copy(w,R,P+3),3+W;if(W<4294967296)return R[P]=219,n.writeUInt32BE(R,W,P+1),n.copy(w,R,P+5),5+W}if(n.is(w)){if(W=w.length,W<256)return R[P]=196,n.writeUInt8(R,W,P+1),n.copy(w,R,P+2),2+W;if(W<65536)return R[P]=197,n.writeUInt16BE(R,W,P+1),n.copy(w,R,P+3),3+W;if(W<4294967296)return R[P]=198,n.writeUInt32BE(R,W,P+1),n.copy(w,R,P+5),5+W}if(V==="number"){if(Math.floor(w)!==w)return R[P]=203,n.writeDoubleBE(R,w,P+1),9;if(w>=0){if(w<128)return R[P]=w,1;if(w<256)return R[P]=204,R[P+1]=w,2;if(w<65536)return R[P]=205,n.writeUInt16BE(R,w,P+1),3;if(w<4294967296)return R[P]=206,n.writeUInt32BE(R,w,P+1),5;if(w<18446744073709552e3)return R[P]=207,_(R,w,P+1),9;throw new Error("Number too big 0x"+w.toString(16))}if(w>=-32)return n.writeInt8(R,w,P),1;if(w>=-128)return R[P]=208,n.writeInt8(R,w,P+1),2;if(w>=-32768)return R[P]=209,n.writeInt16BE(R,w,P+1),3;if(w>=-2147483648)return R[P]=210,n.writeInt32BE(R,w,P+1),5;if(w>=-9223372036854776e3)return R[P]=211,y(R,w,P+1),9;throw new Error("Number too small -0x"+w.toString(16).substr(1))}if(V==="undefined")return U&&G?0:(R[P]=212,R[P+1]=0,R[P+2]=0,3);if(w===null)return U&&G?0:(R[P]=192,1);if(V==="boolean")return R[P]=w?195:194,1;if(typeof w.toJSON=="function")return j(w.toJSON(),R,P,U);if(V==="object"){X=0;var Ce=Array.isArray(w);if(Ce)W=w.length;else{var _e=D(w,U);W=_e.length}if(W<16?(R[P]=W|(Ce?144:128),X=1):W<65536?(R[P]=Ce?220:222,n.writeUInt16BE(R,W,P+1),X=3):W<4294967296&&(R[P]=Ce?221:223,n.writeUInt32BE(R,W,P+1),X=5),Ce)for(var ze=0;ze<W;ze++)X+=j(w[ze],R,P+X,U);else for(var ze=0;ze<W;ze++){var mc=_e[ze];X+=j(mc,R,P+X),X+=j(w[mc],R,P+X,U,!0)}return X}if(V!=="function")throw new Error("Unknown type "+V)}function F(w,R,P){var U=typeof w,G,V;if(U==="string"){if(G=n.from(w).length,G<32)return 1+G;if(G<256)return 2+G;if(G<65536)return 3+G;if(G<4294967296)return 5+G}if(n.is(w)){if(G=w.length,G<256)return 2+G;if(G<65536)return 3+G;if(G<4294967296)return 5+G}if(U==="number"){if(Math.floor(w)!==w)return 9;if(w>=0){if(w<128)return 1;if(w<256)return 2;if(w<65536)return 3;if(w<4294967296)return 5;if(w<18446744073709552e3)return 9;throw new Error("Number too big 0x"+w.toString(16))}if(w>=-32)return 1;if(w>=-128)return 2;if(w>=-32768)return 3;if(w>=-2147483648)return 5;if(w>=-9223372036854776e3)return 9;throw new Error("Number too small -0x"+w.toString(16).substr(1))}if(U==="boolean")return 1;if(w===null)return R&&P?0:1;if(w===void 0)return R&&P?0:3;if(typeof w.toJSON=="function")return F(w.toJSON(),R);if(U==="object"){if(V=0,Array.isArray(w)){G=w.length;for(var W=0;W<G;W++)V+=F(w[W],R)}else{var X=D(w,R);G=X.length;for(var W=0;W<G;W++){var Ce=X[W];V+=F(Ce)+F(w[Ce],R,!0)}}if(G<16)return 1+V;if(G<65536)return 3+V;if(G<4294967296)return 5+V;throw new Error("Array or object too long 0x"+G.toString(16))}if(U==="function")return 0;throw new Error("Unknown type "+U)}}}),L=class{},Po=typeof global<"u"?global:typeof window<"u"?window:self;function Ls(r,n){return`${r}`.padStart(n?3:2,"0")}function rf(r){return L.Config.logTimestamps?function(n){let o=new Date;r(Ls(o.getHours())+":"+Ls(o.getMinutes())+":"+Ls(o.getSeconds())+"."+Ls(o.getMilliseconds(),1)+" "+n)}:function(n){r(n)}}var of=()=>{var r;let n,o;return typeof((r=Po?.console)==null?void 0:r.log)=="function"?(n=function(...c){console.log.apply(console,c)},o=console.warn?function(...c){console.warn.apply(console,c)}:n):n=o=function(){},[n,o].map(rf)},Ge=class Is{constructor(){this.deprecated=(n,o)=>{this.deprecationWarning(`${n} is deprecated and will be removed in a future version. ${o}`)},this.shouldLog=n=>n<=this.logLevel,this.setLog=(n,o)=>{n!==void 0&&(this.logLevel=n),o!==void 0&&(this.logHandler=this.logErrorHandler=o)},this.logLevel=Is.defaultLogLevel,this.logHandler=Is.defaultLogHandler,this.logErrorHandler=Is.defaultLogErrorHandler}static initLogHandlers(){let[n,o]=of();this.defaultLogHandler=n,this.defaultLogErrorHandler=o,this.defaultLogger=new Is}static logActionNoStrip(n,o,c,u){n.logAction(o,c,u)}logAction(n,o,c){this.shouldLog(n)&&(n===1?this.logErrorHandler:this.logHandler)("Ably: "+o+": "+c,n)}renamedClientOption(n,o){this.deprecationWarning(`The \`${n}\` client option has been renamed to \`${o}\`. Please update your code to use \`${o}\` instead. \`${n}\` will be removed in a future version.`)}renamedMethod(n,o,c){this.deprecationWarning(`\`${n}\`\u2019s \`${o}\` method has been renamed to \`${c}\`. Please update your code to use \`${c}\` instead. \`${o}\` will be removed in a future version.`)}deprecationWarning(n){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${n}`,1)}};Ge.defaultLogLevel=1,Ge.LOG_NONE=0,Ge.LOG_ERROR=1,Ge.LOG_MAJOR=2,Ge.LOG_MINOR=3,Ge.LOG_MICRO=4,Ge.logAction=(r,n,o,c)=>{Ge.logActionNoStrip(r,n,o,c)};var af=Ge,d=af,Zt={};K(Zt,{Format:()=>Bo,allSame:()=>pf,allToLowerCase:()=>Vo,allToUpperCase:()=>zo,arrChooseN:()=>Wo,arrDeleteValue:()=>Do,arrEquals:()=>Qo,arrIntersect:()=>Lo,arrIntersectOb:()=>jo,arrPopRandomElement:()=>zn,arrWithoutValue:()=>ff,cheapRandStr:()=>Go,containsValue:()=>df,copy:()=>es,createMissingPluginError:()=>ss,dataSizeBytes:()=>Ho,decodeBody:()=>ue,encodeBody:()=>je,ensureArray:()=>Mo,forInOwnNonNullProperties:()=>qo,getBackoffCoefficient:()=>Ko,getGlobalObject:()=>gf,getJitterCoefficient:()=>Jo,getRetryTime:()=>Yn,inherits:()=>hf,inspectBody:()=>$o,inspectError:()=>ee,intersect:()=>No,isEmpty:()=>lf,isErrorInfoOrPartialErrorInfo:()=>Jn,isNil:()=>Fe,isObject:()=>Ot,keysArray:()=>js,listenerToAsyncIterator:()=>mf,matchDerivedChannel:()=>Yo,mixin:()=>Y,parseQueryString:()=>Ds,prototypicalClone:()=>xo,randomString:()=>Fo,shallowClone:()=>uf,shallowEquals:()=>Qn,stringifyValues:()=>Kn,throwMissingPluginError:()=>pe,toBase64:()=>Us,toQueryString:()=>ts,valuesArray:()=>Uo,whenPromiseSettles:()=>ke,withTimeoutAsync:()=>Xo});function Io(r){let n="["+r.constructor.name;return r.message&&(n+=": "+r.message),r.statusCode&&(n+="; statusCode="+r.statusCode),r.code&&(n+="; code="+r.code),r.cause&&(n+="; cause="+ee(r.cause)),r.href&&!(r.message&&r.message.indexOf("help.ably.io")>-1)&&(n+="; see "+r.href+" "),n+="]",n}var x=class go extends Error{constructor(n,o,c,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,go.prototype),this.code=o,this.statusCode=c,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:c,statusCode:u}=n;if(typeof o!="string"||typeof c!="number"||typeof u!="number")throw new Error("ErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new go(o,c,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}},Ee=class mo extends Error{constructor(n,o,c,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,mo.prototype),this.code=o,this.statusCode=c,this.cause=u}toString(){return Io(this)}static fromValues(n){let{message:o,code:c,statusCode:u}=n;if(typeof o!="string"||!Fe(c)&&typeof c!="number"||!Fe(u)&&typeof u!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new mo(o,c,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}};function cf(r){return Math.floor(Math.random()*r.length)}function Y(r,...n){for(let o=0;o<n.length;o++){let c=n[o];if(!c)break;for(let u in c)Object.prototype.hasOwnProperty.call(c,u)&&(r[u]=c[u])}return r}function es(r){return Y({},r)}function Mo(r){return Fe(r)?[]:Array.isArray(r)?r:[r]}function Ot(r){return Object.prototype.toString.call(r)=="[object Object]"}function lf(r){for(let n in r)return!1;return!0}function Fe(r){return r==null}function uf(r){let n=new Object;for(let o in r)n[o]=r[o];return n}function xo(r,n){class o{}o.prototype=r;let c=new o;return n&&Y(c,n),c}var hf=function(r,n){if(L.Config.inherits){L.Config.inherits(r,n);return}r.super_=n,r.prototype=xo(n.prototype,{constructor:r})};function df(r,n){for(let o in r)if(r[o]==n)return!0;return!1}function No(r,n){return Array.isArray(n)?Lo(r,n):jo(r,n)}function Lo(r,n){let o=[];for(let c=0;c<r.length;c++){let u=r[c];n.indexOf(u)!=-1&&o.push(u)}return o}function jo(r,n){let o=[];for(let c=0;c<r.length;c++){let u=r[c];u in n&&o.push(u)}return o}function Do(r,n){let o=r.indexOf(n),c=o!=-1;return c&&r.splice(o,1),c}function ff(r,n){let o=r.slice();return Do(o,n),o}function js(r,n){let o=[];for(let c in r)n&&!Object.prototype.hasOwnProperty.call(r,c)||o.push(c);return o}function Uo(r,n){let o=[];for(let c in r)n&&!Object.prototype.hasOwnProperty.call(r,c)||o.push(r[c]);return o}function qo(r,n){for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&n(o)}function pf(r,n){if(r.length===0)return!0;let o=r[0][n];return r.every(function(c){return c[n]===o})}var Bo=(r=>(r.msgpack="msgpack",r.json="json",r))(Bo||{});function zn(r){return r.splice(cf(r),1)[0]}function ts(r){let n=[];if(r)for(let o in r)n.push(encodeURIComponent(o)+"="+encodeURIComponent(r[o]));return n.length?"?"+n.join("&"):""}function Kn(r){return Object.fromEntries(Object.entries(r).map(([n,o])=>[n,String(o)]))}function Ds(r){let n,o=/([^?&=]+)=?([^&]*)/g,c={};for(;n=o.exec(r);)c[decodeURIComponent(n[1])]=decodeURIComponent(n[2]);return c}function Jn(r){return typeof r=="object"&&r!==null&&(r instanceof x||r instanceof Ee)}function ee(r){var n,o;return r instanceof Error||((n=r?.constructor)==null?void 0:n.name)==="ErrorInfo"||((o=r?.constructor)==null?void 0:o.name)==="PartialErrorInfo"?r.toString():L.Config.inspect(r)}function $o(r){return L.BufferUtils.isBuffer(r)?r.toString():typeof r=="string"?r:L.Config.inspect(r)}function Ho(r){if(L.BufferUtils.isBuffer(r))return L.BufferUtils.byteLength(r);if(typeof r=="string")return L.Config.stringByteSize(r);if(typeof r=="number")return 8;if(typeof r=="boolean")return 1;throw new Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof r}`)}function Go(){return String(Math.random()).substr(2)}var Fo=async r=>{let n=await L.Config.getRandomArrayBuffer(r);return L.BufferUtils.base64Encode(n)};function Wo(r,n){let o=Math.min(n,r.length),c=r.slice(),u=[];for(let f=0;f<o;f++)u.push(zn(c));return u}function ke(r,n){r.then(o=>{n?.(null,o)}).catch(o=>{n?.(o)})}function ue(r,n,o){return o=="msgpack"?(n||pe("MsgPack"),n.decode(r)):JSON.parse(String(r))}function je(r,n,o){return o=="msgpack"?(n||pe("MsgPack"),n.encode(r,!0)):JSON.stringify(r)}function Vo(r){return r.map(function(n){return n&&n.toLowerCase()})}function zo(r){return r.map(function(n){return n&&n.toUpperCase()})}function Ko(r){return Math.min((r+2)/3,2)}function Jo(){return 1-Math.random()*.2}function Yn(r,n){return r*Ko(n)*Jo()}function gf(){return typeof global<"u"?global:typeof window<"u"?window:self}function Qn(r,n){return Object.keys(r).every(o=>r[o]===n[o])&&Object.keys(n).every(o=>n[o]===r[o])}function Yo(r){let n=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=r.match(n);if(!o||!o.length||o.length<5)throw new x("regex match failed",400,40010);if(o[2])throw new x(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function Us(r){let n=L.BufferUtils,o=n.utf8Encode(r);return n.base64Encode(o)}function Qo(r,n){return r.length===n.length&&r.every(function(o,c){return o===n[c]})}function ss(r){return new x(`${r} plugin not provided`,40019,400)}function pe(r){throw ss(r)}async function Xo(r,n=5e3,o="Timeout expired"){let c=new x(o,5e4,500);return Promise.race([r,new Promise((u,f)=>setTimeout(()=>f(c),n))])}function mf(r){return Le(this,null,function*(){let n=[],o=null,c=r(u=>{if(o){let f=o;o=null,f(u)}else n.push(u)});try{for(;;)if(n.length>0)yield n.shift();else{if(o)throw new x("Concurrent next() calls are not supported",4e4,400);yield yield new Te(new Promise(f=>{o=f}))}}finally{c()}})}var Zo="2.17.0",yf="ably-js/"+Zo,De={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:Zo,protocolVersion:5,agent:yf,getPort:_f,getHttpScheme:bf,getPrimaryDomainFromEndpoint:ta,getEndpointFallbackHosts:sa,getFallbackHosts:ra,getHosts:vf,checkHost:ia,objectifyOptions:Cf,normaliseOptions:kf,defaultGetHeaders:Of,defaultPostHeaders:Sf};function _f(r,n){return n||r.tls?r.tlsPort:r.port}function bf(r){return r.tls?"https://":"http://"}function ea(r){return r.includes(".")||r.includes("::")||r==="localhost"}function ta(r){return ea(r)?r:r.startsWith("nonprod:")?`${r.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${r}.realtime.ably.net`}function sa(r){if(ea(r))return[];if(r.startsWith("nonprod:")){let n=r.replace("nonprod:","");return na(n,"ably-realtime-nonprod.com")}return na(r,"ably-realtime.com")}function na(r,n){return["a","b","c","d","e"].map(o=>`${r}.${o}.fallback.${n}`)}function ra(r){let n=r.fallbackHosts,o=typeof r.httpMaxRetryCount<"u"?r.httpMaxRetryCount:De.httpMaxRetryCount;return n?Wo(n,o):[]}function vf(r){return[r.primaryDomain].concat(ra(r))}function ia(r){if(typeof r!="string")throw new x("host must be a string; was a "+typeof r,4e4,400);if(!r.length)throw new x("host must not be zero-length",4e4,400)}function wf(r){let n={};for(let o in De.TIMEOUTS)n[o]=r[o]||De.TIMEOUTS[o];return n}function Xn(r){let n=De.agent;if(r.agents)for(var o in r.agents)n+=" "+o+"/"+r.agents[o];return n}function Cf(r,n,o,c,u){if(r===void 0){let y=n?`${o} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${o} must be initialized with a client options object`;throw d.logAction(c,d.LOG_ERROR,`${o}()`,y),new Error(y)}let f;if(typeof r=="string")if(r.indexOf(":")==-1){if(!n){let y=`${o} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw d.logAction(c,d.LOG_ERROR,`${o}()`,y),new Error(y)}f={token:r}}else{if(!n){let y=`${o} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw d.logAction(c,d.LOG_ERROR,`${o}()`,y),new Error(y)}f={key:r}}else f=r;return u&&(f=O(E({},f),{plugins:E(E({},u),f.plugins)})),f}function Ef(r){if(r.endpoint&&(r.environment||r.restHost||r.realtimeHost))throw new x("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(r.environment&&(r.restHost||r.realtimeHost))throw new x("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function kf(r,n,o){let c=o??d.defaultLogger;r.environment&&c.deprecated("The `environment` client option","Use the `endpoint` client option instead."),r.restHost&&c.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),r.realtimeHost&&c.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead."),Ef(r),typeof r.recover=="function"&&r.closeOnUnload===!0&&(d.logAction(c,d.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),r.recover=void 0),"closeOnUnload"in r||(r.closeOnUnload=!r.recover),"queueMessages"in r||(r.queueMessages=!0);let u=r.endpoint||De.ENDPOINT;!r.fallbackHosts&&!r.restHost&&!r.realtimeHost&&!r.port&&!r.tlsPort&&(r.fallbackHosts=sa(r.environment||u));let f=r.environment&&`${r.environment}.realtime.ably.net`,_=r.restHost||r.realtimeHost||f||ta(u);(r.fallbackHosts||[]).concat(_).forEach(ia),r.port=r.port||De.PORT,r.tlsPort=r.tlsPort||De.TLS_PORT,"tls"in r||(r.tls=!0);let T=wf(r);n?"useBinaryProtocol"in r?r.useBinaryProtocol=L.Config.supportsBinary&&r.useBinaryProtocol:r.useBinaryProtocol=L.Config.preferBinary:r.useBinaryProtocol=!1;let I={};r.clientId&&(I["X-Ably-ClientId"]=L.BufferUtils.base64Encode(L.BufferUtils.utf8Encode(r.clientId))),"idempotentRestPublishing"in r||(r.idempotentRestPublishing=!0);let D=null,j=r.connectivityCheckUrl;if(r.connectivityCheckUrl){let[w,R]=r.connectivityCheckUrl.split("?");D=R?Ds(R):{},w.indexOf("://")===-1&&(w="https://"+w),j=w}let F=r.wsConnectivityCheckUrl;return F&&F.indexOf("://")===-1&&(F="wss://"+F),O(E({},r),{primaryDomain:_,maxMessageSize:r.maxMessageSize||De.maxMessageSize,timeouts:T,connectivityCheckParams:D,connectivityCheckUrl:j,wsConnectivityCheckUrl:F,headers:I})}function qs(r,n,o){let c=o||{};if(c.cipher){r||pe("Crypto");let u=r.getCipher(c.cipher,n);c.cipher=u.cipherParams,c.channelCipher=u.cipher}else"cipher"in c&&(c.cipher=void 0,c.channelCipher=null);return c}var oa={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},aa={format:"json",protocolVersion:De.protocolVersion};function Of(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){return{accept:oa[n??(r.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}function Sf(r,{format:n,protocolVersion:o=aa.protocolVersion}={}){let c=oa[n??(r.useBinaryProtocol?"msgpack":"json")];return{accept:c,"content-type":c,"X-Ably-Version":o.toString(),"Ably-Agent":Xn(r)}}var J=De;function Tf(r){return Object.assign(De,r)}var Af=class Ad{constructor(n,o){this.logger=n,this.members=o||[]}call(n,o){for(let c of this.members)if(c)try{c(n,o)}catch(u){d.logAction(this.logger,d.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+u+"; stack = "+u.stack)}}push(...n){this.members.push(...n)}createPromise(){return new Promise((n,o)=>{this.push((c,u)=>{c?o(c):n(u)})})}resolveAll(n){this.call(null,n)}rejectAll(n){this.call(n)}static create(n,o){let c=new Ad(n,o);return Object.assign((u,f)=>c.call(u,f),{push:u=>c.push(u),createPromise:()=>c.createPromise(),resolveAll:u=>c.resolveAll(u),rejectAll:u=>c.rejectAll(u)})}},ca=Af,la=(r=>(r.Get="get",r.Delete="delete",r.Post="post",r.Put="put",r.Patch="patch",r))(la||{}),ce=la,ua=(r=>(r[r.Success=200]="Success",r[r.NoContent=204]="NoContent",r[r.BadRequest=400]="BadRequest",r[r.Unauthorized=401]="Unauthorized",r[r.Forbidden=403]="Forbidden",r[r.RequestTimeout=408]="RequestTimeout",r[r.InternalServerError=500]="InternalServerError",r))(ua||{});function Rf(r){return r>=200&&r<400}var ns=ua,Zn=Math.pow(2,17);function Pf(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function If(r){return!!r.connection}function ha(r){return Jn(r)?(r.code||(r.statusCode===403?r.code=40300:(r.code=40170,r.statusCode=401)),r):new x(ee(r),r.code||40170,r.statusCode||401)}var Mf=(r,n)=>{let o=L.BufferUtils,c=o.utf8Encode(r),u=o.utf8Encode(n),f=o.hmacSha256(c,u);return o.base64Encode(f)};function da(r){if(!r)return"";typeof r=="string"&&(r=JSON.parse(r));let n=Object.create(null),o=js(r,!0);if(!o)return"";o.sort();for(let c=0;c<o.length;c++)n[o[c]]=r[o[c]].sort();return JSON.stringify(n)}function fa(r,n){if(r.authCallback)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authCallback");else if(r.authUrl)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with authUrl");else if(r.key)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(r.tokenDetails)d.logAction(n,d.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let o="authOptions must include valid authentication parameters";throw d.logAction(n,d.LOG_ERROR,"Auth()",o),new Error(o)}}function xf(r){return"useTokenAuth"in r&&!r.useTokenAuth}function pa(r){return r.useTokenAuth||!xf(r)&&(r.authCallback||r.authUrl||r.token||r.tokenDetails)}function Nf(r){return!r.key&&!r.authCallback&&!r.authUrl}var Lf=0;function jf(){return Lf++}var Df=class{constructor(r,n){if(this.authOptions={},this.client=r,this.tokenParams=n.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,pa(n))Nf(n)&&d.logAction(this.logger,d.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(n.defaultTokenParams,n),fa(this.authOptions,this.logger);else{if(!n.key){let o="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()",o),new x(o,40160,401)}d.logAction(this.logger,d.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(n)}}get logger(){return this.client.logger}async authorize(r,n){if(n&&n.key&&this.authOptions.key!==n.key)throw new x("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(r??null,n??null);return If(this.client)?new Promise((c,u)=>{this.client.connection.connectionManager.onAuthUpdated(o,(f,y)=>f?u(f):c(y))}):o}catch(o){throw this.client.connection&&o.statusCode===ns.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(r,n){this.tokenDetails=null,this._saveTokenOptions(r,n),fa(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(r,n){let o=n||this.authOptions,c=r||es(this.tokenParams),u,f=this.client;if(o.authCallback)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),u=o.authCallback;else if(o.authUrl)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),u=(_,T)=>{let I=Y({accept:"application/json, text/plain"},o.authHeaders),D=o.authMethod&&o.authMethod.toLowerCase()==="post",j,F=o.authUrl.indexOf("?");F>-1&&(j=Ds(o.authUrl.slice(F)),o.authUrl=o.authUrl.slice(0,F),D||(o.authParams=Y(j,o.authParams)));let w=Y({},o.authParams||{},_),R=P=>{var U,G;let V=(U=P.body)!=null?U:null,W=null;if(P.error)d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+ee(P.error));else{let _e=(G=P.headers["content-type"])!=null?G:null;Array.isArray(_e)?W=_e.join(", "):W=_e,d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+W+"; body: "+$o(V))}if(P.error){T(P.error,null);return}if(P.unpacked){T(null,V);return}if(L.BufferUtils.isBuffer(V)&&(V=V.toString()),!W){T(new x("authUrl response is missing a content-type header",40170,401),null);return}let X=W.indexOf("application/json")>-1,Ce=W.indexOf("text/plain")>-1||W.indexOf("application/jwt")>-1;if(!X&&!Ce){T(new x("authUrl responded with unacceptable content-type "+W+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(X){if(V.length>Zn){T(new x("authUrl response exceeded max permitted length",40170,401),null);return}try{V=JSON.parse(V)}catch(_e){T(new x("Unexpected error processing authURL response; err = "+_e.message,40170,401),null);return}}T(null,V,W)};if(d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+o.authUrl+"; Params: "+JSON.stringify(w)+"; method: "+(D?"POST":"GET")),D){let P=I||{};P["content-type"]="application/x-www-form-urlencoded";let U=ts(w).slice(1);ke(this.client.http.doUri(ce.Post,o.authUrl,P,U,j),(G,V)=>R(G||V))}else ke(this.client.http.doUri(ce.Get,o.authUrl,I||{},null,w),(P,U)=>R(P||U))};else if(o.key)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),u=(_,T)=>{ke(this.createTokenRequest(_,o),(I,D)=>T(I,D??null))};else{let _="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";throw d.logAction(this.logger,d.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new x(_,40171,403)}"capability"in c&&(c.capability=da(c.capability));let y=(_,T)=>{let I=_.keyName,D="/keys/"+I+"/requestToken",j=function(w){return f.baseUri(w)+D},F=J.defaultPostHeaders(this.client.options,{format:"json"});o.requestHeaders&&Y(F,o.requestHeaders),d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+D+"; Token params: "+JSON.stringify(_)),ke(this.client.http.do(ce.Post,j,F,JSON.stringify(_),null),(w,R)=>w?T(w):T(R.error,R.body,R.unpacked))};return new Promise((_,T)=>{let I=!1,D=this.client.options.timeouts.realtimeRequestTimeout,j=setTimeout(()=>{I=!0;let F="Token request callback timed out after "+D/1e3+" seconds";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",F),T(new x(F,40170,401))},D);u(c,(F,w,R)=>{if(I)return;if(clearTimeout(j),F){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ee(F)),T(ha(F));return}if(typeof w=="string"){w.length===0?T(new x("Token string is empty",40170,401)):w.length>Zn?T(new x("Token string exceeded max permitted length (was "+w.length+" bytes)",40170,401)):w==="undefined"||w==="null"?T(new x("Token string was literal null/undefined",40170,401)):w[0]==="{"&&!(R&&R.indexOf("application/jwt")>-1)?T(new x("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)):_({token:w});return}if(typeof w!="object"||w===null){let U="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof w;d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",U),T(new x(U,40170,401));return}let P=JSON.stringify(w).length;if(P>Zn&&!o.suppressMaxLengthCheck){T(new x("Token request/details object exceeded max permitted stringified size (was "+P+" bytes)",40170,401));return}if("issued"in w){_(w);return}if(!("keyName"in w)){let U="Expected token request callback to call back with a token string, token request object, or token details object";d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()",U),T(new x(U,40170,401));return}y(w,(U,G,V)=>{if(U){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+ee(U)),T(ha(U));return}V||(G=JSON.parse(G)),d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","token received"),_(G)})})})}async createTokenRequest(r,n){n=n||this.authOptions,r=r||es(this.tokenParams);let o=n.key;if(!o)throw new x("No key specified",40101,403);let c=o.split(":"),u=c[0],f=c[1];if(!f)throw new x("Invalid key specified",40101,403);if(r.clientId==="")throw new x("clientId can\u2019t be an empty string",40012,400);"capability"in r&&(r.capability=da(r.capability));let y=Y({keyName:u},r),_=r.clientId||"",T=r.ttl||"",I=r.capability||"";y.timestamp||(y.timestamp=await this._getTimestamp(n&&n.queryTime));let D=y.nonce||(y.nonce=Pf()),j=y.timestamp,F=y.keyName+`
|
|
39
|
+
`+T+`
|
|
40
40
|
`+I+`
|
|
41
41
|
`+_+`
|
|
42
42
|
`+j+`
|
|
43
|
-
`+
|
|
44
|
-
`;return m.mac=m.mac||If(G,f),d.logAction(this.logger,d.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),m}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let r=await this._ensureValidAuthCredentials(!1);if(!r)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:r.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{let r=await this._ensureValidAuthCredentials(!1);if(!r)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Us(r.token)}}}_saveBasicOptions(r){this.method="basic",this.key=r.key,this.basicKey=Us(r.key),this.authOptions=r||{},"clientId"in r&&this._userSetClientId(r.clientId)}_saveTokenOptions(r,n){this.method="token",r&&(this.tokenParams=r),n&&(n.token&&(n.tokenDetails=typeof n.token=="string"?{token:n.token}:n.token),n.tokenDetails&&(this.tokenDetails=n.tokenDetails),"clientId"in n&&this._userSetClientId(n.clientId),this.authOptions=n)}async _ensureValidAuthCredentials(r){let n=this.tokenDetails;if(n){if(this._tokenClientIdMismatch(n.clientId))throw new x("Mismatch between clientId in token ("+n.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!n.expires||n.expires>=this.client.getTimestampUsingOffset())return d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+n.expires),n;d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let o=(this.waitingForTokenRequest||(this.waitingForTokenRequest=ca.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!r)return o;let c=this.currentTokenRequestId=Lf(),u,f=null;try{u=await this.requestToken(this.tokenParams,this.authOptions)}catch(_){f=_}if(this.currentTokenRequestId>c)return d.logAction(this.logger,d.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),o;this.currentTokenRequestId=null;let m=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,f?(m?.rejectAll(f),o):(m?.resolveAll(this.tokenDetails=u),o)}_userSetClientId(r){if(typeof r=="string"||r===null){if(r==="*")throw new x('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{let n=this._uncheckedSetClientId(r);if(n)throw n}}else throw new x("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(r){if(this._tokenClientIdMismatch(r)){let n="Unexpected clientId mismatch: client has "+this.clientId+", requested "+r,o=new x(n,40102,401);return d.logAction(this.logger,d.LOG_ERROR,"Auth._uncheckedSetClientId()",n),o}else return this.clientId=this.tokenParams.clientId=r,null}_tokenClientIdMismatch(r){return!!(this.clientId&&this.clientId!=="*"&&r&&r!=="*"&&this.clientId!==r)}static isTokenErr(r){return r.code&&r.code>=40140&&r.code<40150}revokeTokens(r,n){return this.client.rest.revokeTokens(r,n)}async _getTimestamp(r){return this.client.getTimestamp(r||!!this.authOptions.queryTime)}},We=jf;function er(r){let n=[];if(r)for(let o in r)n.push(o+"="+r[o]);return n.join("&")}function St(r,n){return r+(n?"?":"")+er(n)}function qf(r,n,o,c,u){r.error?d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received Error; "+St(o,c)+"; Error: "+ee(r.error)):d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received; "+St(o,c)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+r.body))}function Uf(r,n,o,c,u){u.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(u,d.LOG_MICRO,"Http."+r+"()","Sending; "+St(n,c)+"; Body"+(L.BufferUtils.isBuffer(o)?" (Base64): "+L.BufferUtils.base64Encode(o):": "+o))}var tr=class{constructor(r){this.client=r,this.platformHttp=new L.Http(r),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var r,n;return(n=(r=this.client)==null?void 0:r.logger)!=null?n:d.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(r){let n=r.connection,o=n&&n.connectionManager.host;return o?[o].concat(K.getFallbackHosts(r.options)):K.getHosts(r.options)}async do(r,n,o,c,u){try{let f=this.client;if(!f)return{error:new x("http.do called without client",5e4,500)};let m=typeof n=="function"?n:function(j){return f.baseUri(j)+n},_=f._currentFallback;if(_)if(_.validUntil>Date.now()){let j=await this.doUri(r,m(_.host),o,c,u);return j.error&&this.platformHttp.shouldFallback(j.error)?(f._currentFallback=null,this.do(r,n,o,c,u)):j}else f._currentFallback=null;let A=this._getHosts(f);if(A.length===1)return this.doUri(r,m(A[0]),o,c,u);let I=null,q=async(j,G)=>{let w=j.shift();I=I??new Date;let R=await this.doUri(r,m(w),o,c,u);return R.error&&this.platformHttp.shouldFallback(R.error)&&j.length?Date.now()-I.getTime()>f.options.timeouts.httpMaxRetryDuration?{error:new x(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${f.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:q(j,!0):(G&&(f._currentFallback={host:w,validUntil:Date.now()+f.options.timeouts.fallbackRetryTimeout}),R)};return q(A)}catch(f){return{error:new x(`Unexpected error in Http.do: ${ee(f)}`,500,5e4)}}}async doUri(r,n,o,c,u){try{Uf(r,n,c,u,this.logger);let f=await this.platformHttp.doUri(r,n,o,c,u);return this.logger.shouldLog(d.LOG_MICRO)&&qf(f,r,n,u,this.logger),f}catch(f){return{error:new x(`Unexpected error in Http.doUri: ${ee(f)}`,500,5e4)}}}};function Df(r,n,o,c){try{o.apply(n,c)}catch(u){d.logAction(r,d.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+u+"; stack = "+(u&&u.stack))}}function sr(r,n,o){let c,u,f;for(let m=0;m<r.length;m++)if(c=r[m],o&&(c=c[o]),Array.isArray(c)){for(;(u=c.indexOf(n))!==-1;)c.splice(u,1);o&&c.length===0&&delete r[m][o]}else if(kt(c))for(f in c)Object.prototype.hasOwnProperty.call(c,f)&&Array.isArray(c[f])&&sr([c],n,f)}var Bf=class{constructor(r){this.logger=r,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...r){if(r.length===1){let n=r[0];if(typeof n=="function")this.any.push(n);else throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r))}if(r.length===2){let[n,o]=r;if(typeof o!="function")throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r));if(Fe(n))this.any.push(o);else if(Array.isArray(n))n.forEach(c=>{this.on(c,o)});else{if(typeof n!="string")throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r));(this.events[n]||(this.events[n]=[])).push(o)}}}off(...r){if(r.length==0||Fe(r[0])&&Fe(r[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[n,o]=r,c=null,u=null;if(r.length===1||!o)typeof n=="function"?c=n:u=n;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));[u,c]=[n,o]}if(c&&Fe(u)){sr([this.any,this.events,this.anyOnce,this.eventsOnce],c);return}if(Array.isArray(u)){u.forEach(f=>{this.off(f,c)});return}if(typeof u!="string")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));c?sr([this.events,this.eventsOnce],c,u):(delete this.events[u],delete this.eventsOnce[u])}listeners(r){if(r){let n=this.events[r]||[];return this.eventsOnce[r]&&Array.prototype.push.apply(n,this.eventsOnce[r]),n.length?n:null}return this.any.length?this.any:null}emit(r,...n){let o={event:r},c=[];this.anyOnce.length&&(Array.prototype.push.apply(c,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(c,this.any);let u=this.eventsOnce[r];u&&(Array.prototype.push.apply(c,u),delete this.eventsOnce[r]);let f=this.events[r];f&&Array.prototype.push.apply(c,f),c.forEach(m=>{Df(this.logger,o,m,n)})}once(...r){let n=r.length;if(n===0||n===1&&typeof r[0]!="function"){let u=r[0];return new Promise(f=>{this.once(u,f)})}let[o,c]=r;if(r.length===1&&typeof o=="function")this.anyOnce.push(o);else if(Fe(o)){if(typeof c!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));this.anyOnce.push(c)}else if(Array.isArray(o)){let u=this,f=function(){let m=Array.prototype.slice.call(arguments);if(o.forEach(function(_){u.off(_,f)}),typeof c!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));c.apply(this,m)};o.forEach(function(m){u.on(m,f)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));let u=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(c){if(typeof c!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));u.push(c)}}}async whenState(r,n){if(typeof r!="string"||typeof n!="string")throw new Error("whenState requires a valid state String argument");return r===n?null:this.once(r)}},he=Bf,z={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},ga=[];Object.keys(z).forEach(function(r){ga[z[r]]=r});var ve={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},$f=Object.keys(ve);ve.MODE_ALL=ve.PRESENCE|ve.PUBLISH|ve.SUBSCRIBE|ve.PRESENCE_SUBSCRIBE|ve.ANNOTATION_PUBLISH|ve.ANNOTATION_SUBSCRIBE|ve.OBJECT_SUBSCRIBE|ve.OBJECT_PUBLISH;var ma=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Hf(r){return!r||!r.channelOptions?{channelOptions:r,plugins:{},baseEncodedPreviousPayload:void 0}:r}function ya(r,n,o){if(o&&o.cipher){r||pe("Crypto");let c=r.getCipher(o.cipher,n);return{cipher:c.cipherParams,channelCipher:c.cipher}}return o??{}}async function Gf(r,n){let{data:o,encoding:c}=await _a(r.data,r.encoding,n);return r.data=o,r.encoding=c,r}async function _a(r,n,o){let c=o.channelCipher,u=r,f=n?n+"/":"";L.BufferUtils.isBuffer(u)||(u=L.BufferUtils.utf8Encode(String(u)),f=f+"utf-8/");let m=await c.encrypt(u);return f=f+"cipher+"+c.algorithm,{data:m,encoding:f}}async function nr(r,n){let{data:o,encoding:c}=ba(r.data,r.encoding);return r.data=o,r.encoding=c,n!=null&&n.cipher?Gf(r,n):r}function ba(r,n){if(typeof r=="string"||L.BufferUtils.isBuffer(r)||r===null||r===void 0)return{data:r,encoding:n};if(kt(r)||Array.isArray(r))return{data:JSON.stringify(r),encoding:n?n+"/json":"json"};throw new x("Data type is unsupported",40013,400)}async function rr(r,n){let{data:o,encoding:c,error:u}=await va(r.data,r.encoding,n);if(r.data=o,r.encoding=c,u)throw u}async function va(r,n,o){let c=Hf(o),u=r,f=r,m=n,_;if(n){let A=n.split("/"),I,q=A.length,j="";try{for(;(I=q)>0;){let G=A[--q].match(/([-\w]+)(\+([\w-]+))?/);if(!G)break;switch(j=G[1],j){case"base64":f=L.BufferUtils.base64Decode(String(f)),I==A.length&&(u=f);continue;case"utf-8":f=L.BufferUtils.utf8Decode(f);continue;case"json":f=JSON.parse(f);continue;case"cipher":if(c.channelOptions!=null&&c.channelOptions.cipher&&c.channelOptions.channelCipher){let w=G[3],R=c.channelOptions.channelCipher;if(w!=R.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");f=await R.decrypt(f);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!c.plugins||!c.plugins.vcdiff)throw new x("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new x("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let w=c.baseEncodedPreviousPayload;typeof w=="string"&&(w=L.BufferUtils.utf8Encode(w));let R=L.BufferUtils.toBuffer(w);f=L.BufferUtils.toBuffer(f),f=L.BufferUtils.arrayBufferViewToBuffer(c.plugins.vcdiff.decode(f,R)),u=f}catch(w){throw new x("Vcdiff delta decode failed with "+w,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(G){let w=G;_=new x(`Error processing the ${j} encoding, decoder returned \u2018${w.message}\u2019`,w.code||40013,400)}finally{m=I<=0?null:A.slice(0,I).join("/")}}return _?{error:_,data:f,encoding:m}:(c.baseEncodedPreviousPayload=u,{data:f,encoding:m})}function ir(...r){let n=r.length>0?"json":"msgpack",{data:o,encoding:c}=wa(this.data,this.encoding,n);return Object.assign({},this,{encoding:c,data:o})}function wa(r,n,o){return!r||!L.BufferUtils.isBuffer(r)?{data:r,encoding:n}:o==="msgpack"?{data:L.BufferUtils.toBuffer(r),encoding:n}:{data:L.BufferUtils.base64Encode(r),encoding:n?n+"/base64":"base64"}}var Bs={encryptData:_a,encodeData:ba,encodeDataForWire:wa,decodeData:va};function $s(r){let{id:n,connectionId:o,timestamp:c}=r,u;switch(r.action){case z.MESSAGE:{u=r.messages;break}case z.PRESENCE:case z.SYNC:u=r.presence;break;case z.ANNOTATION:u=r.annotations;break;case z.OBJECT:case z.OBJECT_SYNC:u=r.state;break;default:throw new x("Unexpected action "+r.action,4e4,400)}for(let f=0;f<u.length;f++){let m=u[f];m.connectionId||(m.connectionId=o),m.timestamp||(m.timestamp=c),n&&!m.id&&(m.id=n+":"+f)}}function Tt(r,n){let o="["+n;for(let c in r)c==="data"?typeof r.data=="string"?o+="; data="+r.data:L.BufferUtils.isBuffer(r.data)?o+="; data (buffer)="+L.BufferUtils.base64Encode(r.data):typeof r.data<"u"&&(o+="; data (json)="+JSON.stringify(r.data)):c&&(c==="extras"||c==="operation")?o+="; "+c+"="+JSON.stringify(r[c]):c==="version"?o+="; version="+JSON.stringify(r[c]):c==="annotations"?o+="; annotations="+JSON.stringify(r[c]):r[c]!==void 0&&(o+="; "+c+"="+r[c]);return o+="]",o}var At=class{},Ca=class{constructor(r){this.Platform=L,this.ErrorInfo=x,this.Logger=d,this.Defaults=K,this.Utils=Zt,this.EventEmitter=he,this.MessageEncoding=Bs;var n,o,c,u,f,m,_,A,I,q;this._additionalHTTPRequestImplementations=(n=r.plugins)!=null?n:null,this.logger=new d,this.logger.setLog(r.logLevel,r.logHandler),d.logAction(this.logger,d.LOG_MICRO,"BaseClient()","initialized with clientOptions "+L.Config.inspect(r)),this._MsgPack=(c=(o=r.plugins)==null?void 0:o.MsgPack)!=null?c:null;let j=this.options=K.normaliseOptions(r,this._MsgPack,this.logger);if(j.key){let G=j.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!G){let w="invalid key parameter";throw d.logAction(this.logger,d.LOG_ERROR,"BaseClient()",w),new x(w,40400,404)}j.keyName=G[1],j.keySecret=G[2]}if("clientId"in j)if(typeof j.clientId=="string"||j.clientId===null){if(j.clientId==="*")throw new x('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new x("clientId must be either a string or null",40012,400);d.logAction(this.logger,d.LOG_MINOR,"BaseClient()","started; version = "+K.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new tr(this),this.auth=new We(this,j),this._rest=(u=r.plugins)!=null&&u.Rest?new r.plugins.Rest(this):null,this._Crypto=(m=(f=r.plugins)==null?void 0:f.Crypto)!=null?m:null,this.__FilteredSubscriptions=(A=(_=r.plugins)==null?void 0:_.MessageInteractions)!=null?A:null,this._Annotations=(q=(I=r.plugins)==null?void 0:I.Annotations)!=null?q:null}get rest(){return this._rest||pe("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||pe("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var r;return(!((r=this.options.plugins)!=null&&r.Push)||!this.push.LocalDevice)&&pe("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(r){return K.getHttpScheme(this.options)+r+":"+K.getPort(this.options,!1)}async stats(r){return this.rest.stats(r)}async time(r){return this.rest.time(r)}async request(r,n,o,c,u,f){return this.rest.request(r,n,o,c,u,f)}batchPublish(r){return this.rest.batchPublish(r)}batchPresence(r){return this.rest.batchPresence(r)}setLog(r){this.logger.setLog(r.level,r.handler)}async getTimestamp(r){return!this.isTimeOffsetSet()&&r?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};Ca.Platform=L;var Ea=Ca,Ff=class Qt{toJSON(){var n,o,c;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(n=this.push)==null?void 0:n.recipient,state:(o=this.push)==null?void 0:o.state,error:(c=this.push)==null?void 0:c.error}}}toString(){var n,o,c,u;let f="[DeviceDetails";return this.id&&(f+="; id="+this.id),this.platform&&(f+="; platform="+this.platform),this.formFactor&&(f+="; formFactor="+this.formFactor),this.clientId&&(f+="; clientId="+this.clientId),this.metadata&&(f+="; metadata="+this.metadata),this.deviceIdentityToken&&(f+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(n=this.push)!=null&&n.recipient&&(f+="; push.recipient="+JSON.stringify(this.push.recipient)),(o=this.push)!=null&&o.state&&(f+="; push.state="+this.push.state),(c=this.push)!=null&&c.error&&(f+="; push.error="+JSON.stringify(this.push.error)),(u=this.push)!=null&&u.metadata&&(f+="; push.metadata="+this.push.metadata),f+="]",f}static toRequestBody(n,o,c){return je(n,o,c)}static fromResponseBody(n,o,c){return c&&(n=ue(n,o,c)),Array.isArray(n)?Qt.fromValuesArray(n):Qt.fromValues(n)}static fromValues(n){return n.error=n.error&&x.fromValues(n.error),Object.assign(new Qt,n)}static fromLocalDevice(n){return Object.assign(new Qt,n)}static fromValuesArray(n){let o=n.length,c=new Array(o);for(let u=0;u<o;u++)c[u]=Qt.fromValues(n[u]);return c}},Rt=Ff;async function Oa(r,n,o,c){if(r.http.supportsAuthHeaders){let u=await r.auth.getAuthHeaders();return c(J(u,n),o)}else{let u=await r.auth.getAuthParams();return c(n,J(u,o))}}function Wf(r,n,o){if(r.err&&!r.body)return{err:r.err};if(r.statusCode===ns.NoContent)return S(E({},r),{body:[],unpacked:!0});let c=r.body;if(!r.unpacked)try{c=ue(c,n,o)}catch(_){return Jn(_)?{err:_}:{err:new Ee(ee(_),null)}}if(!c)return{err:new Ee("unenvelope(): Response body is missing",null)};let{statusCode:u,response:f,headers:m}=c;if(u===void 0)return S(E({},r),{body:c,unpacked:!0});if(u<200||u>=300){let _=f&&f.error||r.err;return _||(_=new Error("Error in unenveloping "+c),_.statusCode=u),{err:_,body:f,headers:m,unpacked:!0,statusCode:u}}return{err:r.err,body:f,headers:m,unpacked:!0,statusCode:u}}function Vf(r,n,o,c,u){r.err?d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received Error; "+St(o,c)+"; Error: "+ee(r.err)):d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received; "+St(o,c)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body: "+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+L.Config.inspect(r.body)))}var zf=class Xt{static async get(n,o,c,u,f,m){return Xt.do(ce.Get,n,o,null,c,u,f,m??!1)}static async delete(n,o,c,u,f,m){return Xt.do(ce.Delete,n,o,null,c,u,f,m)}static async post(n,o,c,u,f,m,_){return Xt.do(ce.Post,n,o,c,u,f,m,_)}static async patch(n,o,c,u,f,m,_){return Xt.do(ce.Patch,n,o,c,u,f,m,_)}static async put(n,o,c,u,f,m,_){return Xt.do(ce.Put,n,o,c,u,f,m,_)}static async do(n,o,c,u,f,m,_,A){_&&((m=m||{}).envelope=_);let I=o.logger;async function q(G,w){var R;if(I.shouldLog(d.LOG_MICRO)){let U=u;if(((R=G["content-type"])==null?void 0:R.indexOf("msgpack"))>0)try{o._MsgPack||pe("MsgPack"),U=o._MsgPack.decode(u)}catch(H){d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending MsgPack Decoding Error: "+ee(H))}d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending; "+St(c,w)+"; Body: "+U)}let P=await o.http.do(n,c,G,u,w);return P.error&&We.isTokenErr(P.error)?(await o.auth.authorize(null,null),Oa(o,G,w,q)):{err:P.error,body:P.body,headers:P.headers,unpacked:P.unpacked,statusCode:P.statusCode}}let j=await Oa(o,f,m,q);if(_&&(j=Wf(j,o._MsgPack,_)),I.shouldLog(d.LOG_MICRO)&&Vf(j,n,c,m,I),A){if(j.err)throw j.err;{let G=E({},j);return delete G.err,G}}return j}},ie=zf;function Kf(r){let n=r.match(/^\.\/(\w+)\?(.*)$/);return n&&n[2]&&qs(n[2])}function Jf(r){typeof r=="string"&&(r=r.split(","));let n={};for(let o=0;o<r.length;o++){let c=r[o].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(c){let u=Kf(c[1]);u&&(n[c[2]]=u)}}return n}function Yf(r,n,o){return!(o&&(n||typeof r.code=="number"))}var Qf=class{constructor(r,n,o,c,u,f){this.client=r,this.path=n,this.headers=o,this.envelope=c??null,this.bodyHandler=u,this.useHttpPaginatedResponse=f||!1}get logger(){return this.client.logger}async get(r){let n=await ie.get(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async delete(r){let n=await ie.delete(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async post(r,n){let o=await ie.post(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async put(r,n){let o=await ie.put(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async patch(r,n){let o=await ie.patch(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async handlePage(r){if(r.err&&Yf(r.err,r.body,this.useHttpPaginatedResponse))throw d.logAction(this.logger,d.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+ee(r.err)),r.err;let n,o,c;try{n=r.statusCode==ns.NoContent?[]:await this.bodyHandler(r.body,r.headers||{},r.unpacked)}catch(u){throw r.err||u}return r.headers&&(o=r.headers.Link||r.headers.link)&&(c=Jf(o)),this.useHttpPaginatedResponse?new Xf(this,n,r.headers||{},r.statusCode,c,r.err):new ka(this,n,c)}},ka=class{constructor(r,n,o){this.resource=r,this.items=n,this._relParams=o}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new x("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new x("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&"first"in this._relParams}hasCurrent(){return this._relParams!=null&&"current"in this._relParams}hasNext(){return this._relParams!=null&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(r){let n=this.resource,o=await ie.get(n.client,n.path,n.headers,r,n.envelope,!1);return n.handlePage(o)}},Xf=class extends ka{constructor(r,n,o,c,u,f){super(r,n,u),this.statusCode=c,this.success=c<300&&c>=200,this.headers=o,this.errorCode=f&&f.code,this.errorMessage=f&&f.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},Ue=Qf,Sa=class Ms{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let n="[PushChannelSubscription";return this.channel&&(n+="; channel="+this.channel),this.deviceId&&(n+="; deviceId="+this.deviceId),this.clientId&&(n+="; clientId="+this.clientId),n+="]",n}static fromResponseBody(n,o,c){return c&&(n=ue(n,o,c)),Array.isArray(n)?Ms.fromValuesArray(n):Ms.fromValues(n)}static fromValues(n){return Object.assign(new Ms,n)}static fromValuesArray(n){let o=n.length,c=new Array(o);for(let u=0;u<o;u++)c[u]=Ms.fromValues(n[u]);return c}};Sa.toRequestBody=je;var Zf=Sa,Hs=Zf,ep=class{constructor(r){var n;this.client=r,this.admin=new tp(r),L.Config.push&&((n=r.options.plugins)!=null&&n.Push)&&(this.stateMachine=new r.options.plugins.Push.ActivationStateMachine(r),this.LocalDevice=r.options.plugins.Push.localDeviceFactory(Rt))}async activate(r,n){await new Promise((o,c)=>{var u;if(!((u=this.client.options.plugins)!=null&&u.Push)){c(ss("Push"));return}if(!this.stateMachine){c(new x("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){c(new x("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=f=>{if(f){c(f);return}o()},this.stateMachine.updateFailedCallback=n,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,r))})}async deactivate(r){await new Promise((n,o)=>{var c;if(!((c=this.client.options.plugins)!=null&&c.Push)){o(ss("Push"));return}if(!this.stateMachine){o(new x("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){o(new x("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=u=>{if(u){o(u);return}n()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,r))})}},tp=class{constructor(r){this.client=r,this.deviceRegistrations=new sp(r),this.channelSubscriptions=new np(r)}async publish(r,n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=K.defaultPostHeaders(o.options),f={},m=J({recipient:r},n);J(u,o.options.headers),o.options.pushFullWait&&J(f,{fullWait:"true"});let _=je(m,o._MsgPack,c);await ie.post(o,"/push/publish",_,u,f,null,!0)}},sp=class{constructor(r){this.client=r}async save(r){let n=this.client,o=Rt.fromValues(r),c=n.options.useBinaryProtocol?"msgpack":"json",u=K.defaultPostHeaders(n.options),f={};J(u,n.options.headers),n.options.pushFullWait&&J(f,{fullWait:"true"});let m=je(o,n._MsgPack,c),_=await ie.put(n,"/push/deviceRegistrations/"+encodeURIComponent(r.id),m,u,f,null,!0);return Rt.fromResponseBody(_.body,n._MsgPack,_.unpacked?void 0:c)}async get(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=K.defaultGetHeaders(n.options),u=r.id||r;if(typeof u!="string"||!u.length)throw new x("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);J(c,n.options.headers);let f=await ie.get(n,"/push/deviceRegistrations/"+encodeURIComponent(u),c,{},null,!0);return Rt.fromResponseBody(f.body,n._MsgPack,f.unpacked?void 0:o)}async list(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:o,u=K.defaultGetHeaders(n.options);return J(u,n.options.headers),new Ue(n,"/push/deviceRegistrations",u,c,async function(f,m,_){return Rt.fromResponseBody(f,n._MsgPack,_?void 0:o)}).get(r)}async remove(r){let n=this.client,o=K.defaultGetHeaders(n.options),c={},u=r.id||r;if(typeof u!="string"||!u.length)throw new x("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);J(o,n.options.headers),n.options.pushFullWait&&J(c,{fullWait:"true"}),await ie.delete(n,"/push/deviceRegistrations/"+encodeURIComponent(u),o,c,null,!0)}async removeWhere(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=K.defaultGetHeaders(n.options,{format:o});J(c,n.options.headers),n.options.pushFullWait&&J(r,{fullWait:"true"}),await ie.delete(n,"/push/deviceRegistrations",c,r,null,!0)}},np=class Ad{constructor(n){this.remove=Ad.prototype.removeWhere,this.client=n}async save(n){let o=this.client,c=Hs.fromValues(n),u=o.options.useBinaryProtocol?"msgpack":"json",f=K.defaultPostHeaders(o.options),m={};J(f,o.options.headers),o.options.pushFullWait&&J(m,{fullWait:"true"});let _=je(c,o._MsgPack,u),A=await ie.post(o,"/push/channelSubscriptions",_,f,m,null,!0);return Hs.fromResponseBody(A.body,o._MsgPack,A.unpacked?void 0:u)}async list(n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:c,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Ue(o,"/push/channelSubscriptions",f,u,async function(m,_,A){return Hs.fromResponseBody(m,o._MsgPack,A?void 0:c)}).get(n)}async removeWhere(n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=K.defaultGetHeaders(o.options,{format:c});J(u,o.options.headers),o.options.pushFullWait&&J(n,{fullWait:"true"}),await ie.delete(o,"/push/channelSubscriptions",u,n,null,!0)}async listChannels(n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:c,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),o.options.pushFullWait&&J(n,{fullWait:"true"}),new Ue(o,"/push/channels",f,u,async function(m,_,A){let I=!A&&c?ue(m,o._MsgPack,c):m;for(let q=0;q<I.length;q++)I[q]=String(I[q]);return I}).get(n)}},rp=ep,Ta=["absent","present","enter","leave","update"];async function Aa(r,n,o,c){let u=ya(n,r,c??null);return rs.fromValues(o).decode(u,r)}async function ip(r,n,o,c){return Promise.all(o.map(function(u){return Aa(r,n,u,c)}))}async function op(r,n){return rs.fromValues(r).decode(n.channelOptions,n.logger)}async function Ra(r,n){return Promise.all(r.map(function(o){return op(o,n)}))}var Pa=class xs extends At{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");let n=this.id.split(":");return{connectionId:n[0],msgSerial:parseInt(n[1],10),index:parseInt(n[2],10)}}async encode(n){let o=Object.assign(new rs,this,{action:Ta.indexOf(this.action||"present")});return nr(o,n)}static fromValues(n){return Object.assign(new xs,n)}static fromValuesArray(n){return n.map(o=>xs.fromValues(o))}static fromData(n){return n instanceof xs?n:xs.fromValues({data:n})}toString(){return Tt(this,"PresenceMessage")}},rs=class yo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new yo,n)}static fromValuesArray(n){return n.map(o=>yo.fromValues(o))}async decode(n,o){let c=Object.assign(new Pa,S(E({},this),{action:Ta[this.action]}));try{await rr(c,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WirePresenceMessage.decode()",ee(u))}return c}toString(){return Tt(this,"WirePresenceMessage")}},Ve=Pa,ap=class{constructor(r){this.channel=r}get logger(){return this.channel.logger}async get(r){d.logAction(this.logger,d.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);let n=this.channel.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=this.channel.client.http.supportsLinkHeaders?void 0:o,u=K.defaultGetHeaders(n.options);return J(u,n.options.headers),new Ue(n,this.channel.client.rest.presenceMixin.basePath(this),u,c,async(f,m,_)=>{let A=_?f:ue(f,n._MsgPack,o);return Ra(A,this.channel)}).get(r)}async history(r){return d.logAction(this.logger,d.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,r)}},cp=ap,Ia=["message.create","message.update","message.delete","meta","message.summary","message.append"];function lp(r){return Ia[r||0]||"unknown"}function up(r){let n=0;return r.name&&(n+=r.name.length),r.clientId&&(n+=r.clientId.length),r.extras&&(n+=JSON.stringify(r.extras).length),r.data&&(n+=Ho(r.data)),n}async function Ma(r,n,o,c){let u=ya(n,r,c??null);return is.fromValues(o).decode(u,r)}async function hp(r,n,o,c){return Promise.all(o.map(function(u){return Ma(r,n,u,c)}))}async function xa(r,n){return is.fromValues(r).decode(n.channelOptions,n.logger)}async function Na(r,n){return Promise.all(r.map(function(o){return xa(o,n)}))}async function La(r,n){return Promise.all(r.map(o=>o.encode(n)))}var ja=je;function qa(r){let n,o=0;for(let c=0;c<r.length;c++)n=r[c],o+=n.size||(n.size=up(n));return o}var Ua=class _o extends At{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(let[n,o]of Object.entries(this.annotations.summary))if(n.endsWith(":distinct.v1")||n.endsWith(":unique.v1")||n.endsWith(":multiple.v1"))for(let[,c]of Object.entries(o))c.clipped||(c.clipped=!1);else n.endsWith(":flag.v1")&&(o.clipped||(o.clipped=!1))}async encode(n){let o=Object.assign(new is,this,{action:Ia.indexOf(this.action||"message.create")});return nr(o,n)}static fromValues(n){return Object.assign(new _o,n)}static fromValuesArray(n){return n.map(o=>_o.fromValues(o))}toString(){return Tt(this,"Message")}},is=class bo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new bo,n)}static fromValuesArray(n){return n.map(o=>bo.fromValues(o))}async decodeWithErr(n,o){let c=Object.assign(new Ua,S(E({},this),{action:lp(this.action)})),u;try{await rr(c,n)}catch(f){d.logAction(o,d.LOG_ERROR,"WireMessage.decode()",ee(f)),u=f}return c.expandFields(),{decoded:c,err:u}}async decode(n,o){let{decoded:c}=await this.decodeWithErr(n,o);return c}toString(){return Tt(this,"WireMessage")}},$e=Ua,dp=9;function fp(r){return r.every(function(n){return!n.id})}var pp=class{constructor(r,n,o){this._annotations=null;var c,u;d.logAction(r.logger,d.LOG_MINOR,"RestChannel()","started; name = "+n),this.name=n,this.client=r,this.presence=new cp(this),this.channelOptions=Ds((c=r._Crypto)!=null?c:null,this.logger,o),(u=r.options.plugins)!=null&&u.Push&&(this._push=new r.options.plugins.Push.PushChannel(this)),r._Annotations&&(this._annotations=new r._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||pe("Annotations"),this._annotations}get push(){return this._push||pe("Push"),this._push}get logger(){return this.client.logger}setOptions(r){var n;this.channelOptions=Ds((n=this.client._Crypto)!=null?n:null,this.logger,r)}async history(r){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,r)}async publish(...r){let n=r[0],o=r[1],c,u;if(typeof n=="string"||n===null)c=[$e.fromValues({name:n,data:o})],u=r[2];else if(kt(n))c=[$e.fromValues(n)],u=r[1];else if(Array.isArray(n))c=$e.fromValuesArray(n),u=r[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);u||(u={});let f=this.client,m=f.options,_=m.useBinaryProtocol?"msgpack":"json",A=f.options.idempotentRestPublishing,I=K.defaultPostHeaders(f.options);if(J(I,m.headers),A&&fp(c)){let w=await Fo(dp);c.forEach(function(R,P){R.id=w+":"+P.toString()})}let q=await La(c,this.channelOptions),j=qa(q),G=m.maxMessageSize;if(j>G)throw new x(`Maximum size of messages that can be published at once exceeded (was ${j} bytes; limit is ${G} bytes)`,40009,400);return this._publish(ja(q,f._MsgPack,_),I,u)}async _publish(r,n,o){let c=this.client,u=c.options.useBinaryProtocol?"msgpack":"json",{body:f,unpacked:m}=await ie.post(c,c.rest.channelMixin.basePath(this)+"/messages",r,n,o,null,!0),_=(m?f:ue(f,c._MsgPack,u))||{};return delete _.channel,delete _.messageId,_}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(r){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,r)}async updateMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",r,n,o)}async deleteMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",r,n,o)}async appendMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",r,n,o)}async getMessageVersions(r,n){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,r,n)}},gp=pp,mp=class Rd{constructor(n){this.entries=n&&n.entries||void 0,this.schema=n&&n.schema||void 0,this.appId=n&&n.appId||void 0,this.inProgress=n&&n.inProgress||void 0,this.unit=n&&n.unit||void 0,this.intervalId=n&&n.intervalId||void 0}static fromValues(n){return new Rd(n)}},yp=mp,Da=class{static basePath(r){return"/channels/"+encodeURIComponent(r.name)}static history(r,n){let o=r.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=r.client.http.supportsLinkHeaders?void 0:c,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Ue(o,this.basePath(r)+"/messages",f,u,async function(m,_,A){let I=A?m:ue(m,o._MsgPack,c);return Na(I,r)}).get(n)}static async status(r){let n=r.client.options.useBinaryProtocol?"msgpack":"json",o=K.defaultPostHeaders(r.client.options);return(await ie.get(r.client,this.basePath(r),o,{},n,!0)).body}static async getMessage(r,n){let o=typeof n=="string"?n:n.serial;if(!o)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let c=r.client,u=c.options.useBinaryProtocol?"msgpack":"json",f=K.defaultGetHeaders(c.options);J(f,c.options.headers);let{body:m,unpacked:_}=await ie.get(c,this.basePath(r)+"/messages/"+encodeURIComponent(o),f,{},null,!0),A=_?m:ue(m,c._MsgPack,u);return xa(A,r)}static async updateDeleteMessage(r,n,o,c,u){if(!o.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let f=r.client,m=f.options.useBinaryProtocol?"msgpack":"json",_=K.defaultPostHeaders(f.options);J(_,f.options.headers);let A=$e.fromValues(o);A.action=n,A.version=c;let I=await A.encode(r.channelOptions),q=ja(I,f._MsgPack,m),j=ie.patch,{body:G,unpacked:w}=await j(f,this.basePath(r)+"/messages/"+encodeURIComponent(o.serial),q,_,u||{},null,!0);return(w?G:ue(G,f._MsgPack,m))||{versionSerial:null}}static getMessageVersions(r,n,o){let c=typeof n=="string"?n:n.serial;if(!c)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let u=r.client,f=u.options.useBinaryProtocol?"msgpack":"json",m=r.client.http.supportsLinkHeaders?void 0:f,_=K.defaultGetHeaders(u.options);return J(_,u.options.headers),new Ue(u,this.basePath(r)+"/messages/"+encodeURIComponent(c)+"/versions",_,m,async(A,I,q)=>{let j=q?A:ue(A,u._MsgPack,f);return Na(j,r)}).get(o||{})}},_p=class{static basePath(r){return Da.basePath(r.channel)+"/presence"}static async history(r,n){let o=r.channel.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=r.channel.client.http.supportsLinkHeaders?void 0:c,f=K.defaultGetHeaders(o.options);return J(f,o.options.headers),new Ue(o,this.basePath(r)+"/history",f,u,async(m,_,A)=>{let I=A?m:ue(m,o._MsgPack,c);return Ra(I,r.channel)}).get(n)}},Ba=class{constructor(r){this.channelMixin=Da,this.presenceMixin=_p,this.Resource=ie,this.PaginatedResource=Ue,this.DeviceDetails=Rt,this.PushChannelSubscription=Hs,this.client=r,this.channels=new bp(this.client),this.push=new rp(this.client)}async stats(r){let n=K.defaultGetHeaders(this.client.options),o=this.client.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:o;return J(n,this.client.options.headers),new Ue(this.client,"/stats",n,c,async(u,f,m)=>{let _=m?u:ue(u,this.client._MsgPack,o);for(let A=0;A<_.length;A++)_[A]=yp.fromValues(_[A]);return _}).get(r)}async time(r){let n=K.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&J(n,this.client.options.headers);let o=_=>this.client.baseUri(_)+"/time",{error:c,body:u,unpacked:f}=await this.client.http.do(ce.Get,o,n,null,r);if(c)throw c;f||(u=JSON.parse(u));let m=u[0];if(!m)throw new x("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=m-Date.now(),m}async request(r,n,o,c,u,f){var m;let[_,A,I]=this.client.options.useBinaryProtocol?(this.client._MsgPack||pe("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],q=this.client.http.supportsLinkHeaders?void 0:I;c=c||{};let j=r.toLowerCase(),G=j=="get"?K.defaultGetHeaders(this.client.options,{format:I,protocolVersion:o}):K.defaultPostHeaders(this.client.options,{format:I,protocolVersion:o});typeof u!="string"&&(u=(m=_(u))!=null?m:null),J(G,this.client.options.headers),f&&J(G,f);let w=new Ue(this.client,n,G,q,async function(R,P,U){return Mo(U?R:A(R))},!0);if(!L.Http.methods.includes(j))throw new x("Unsupported method "+j,40500,405);return L.Http.methodsWithBody.includes(j)?w[j](c,u):w[j](c)}async batchPublish(r){let n,o;Array.isArray(r)?(n=r,o=!1):(n=[r],o=!0);let c=this.client.options.useBinaryProtocol?"msgpack":"json",u=K.defaultPostHeaders(this.client.options);this.client.options.headers&&J(u,this.client.options.headers);let f=je(n,this.client._MsgPack,c),m=await ie.post(this.client,"/messages",f,u,{},null,!0),_=m.unpacked?m.body:ue(m.body,this.client._MsgPack,c);return o?_[0]:_}async batchPresence(r){let n=this.client.options.useBinaryProtocol?"msgpack":"json",o=K.defaultGetHeaders(this.client.options);this.client.options.headers&&J(o,this.client.options.headers);let c=r.join(","),u=await ie.get(this.client,"/presence",o,{channels:c},null,!0);return u.unpacked?u.body:ue(u.body,this.client._MsgPack,n)}async revokeTokens(r,n){if(pa(this.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);let o=this.client.options.keyName,c=n??{},u=E({targets:r.map(I=>`${I.type}:${I.value}`)},c),f=this.client.options.useBinaryProtocol?"msgpack":"json",m=K.defaultPostHeaders(this.client.options);this.client.options.headers&&J(m,this.client.options.headers);let _=je(u,this.client._MsgPack,f),A=await ie.post(this.client,`/keys/${o}/revokeTokens`,_,m,{},null,!0);return A.unpacked?A.body:ue(A.body,this.client._MsgPack,f)}},bp=class{constructor(r){this.client=r,this.all=Object.create(null)}get(r,n){r=String(r);let o=this.all[r];return o?n&&o.setOptions(n):this.all[r]=o=new gp(this.client,r,n),o}release(r){delete this.all[String(r)]}},vp=class extends Ea{constructor(r){super(K.objectifyOptions(r,!1,"BaseRest",d.defaultLogger,{Rest:Ba}))}},$a={Rest:Ba},Ha=class extends $e{static async fromEncoded(r,n){return Ma(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return hp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return $e.fromValues(r)}},Ga=class extends Ve{static async fromEncoded(r,n){return Aa(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return ip(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Ve.fromValues(r)}},Fa=["annotation.create","annotation.delete"];async function Wa(r,n,o){return Pt.fromValues(n).decode(o||{},r)}async function wp(r,n,o){return Promise.all(n.map(function(c){return Wa(r,c,o)}))}async function Cp(r,n){return Pt.fromValues(r).decode(n.channelOptions,n.logger)}async function Ep(r,n){return Promise.all(r.map(function(o){return Cp(o,n)}))}var Va=class vo extends At{async encode(){let n=Object.assign(new Pt,this,{action:Fa.indexOf(this.action||"annotation.create")});return nr(n,{})}static fromValues(n){return Object.assign(new vo,n)}static fromValuesArray(n){return n.map(o=>vo.fromValues(o))}toString(){return Tt(this,"Annotation")}},Pt=class wo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new wo,n)}static fromValuesArray(n){return n.map(o=>wo.fromValues(o))}async decode(n,o){let c=Object.assign(new Va,S(E({},this),{action:Fa[this.action]}));try{await rr(c,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WireAnnotation.decode()",ee(u))}return c}toString(){return Tt(this,"WireAnnotation")}},It=Va,za=class extends It{static async fromEncoded(r,n){return Wa(d.defaultLogger,r,n)}static async fromEncodedArray(r,n){return wp(d.defaultLogger,r,n)}static fromValues(r){return It.fromValues(r)}};function Ka(r){let n;switch(typeof r){case"string":n=r;break;case"object":n=r.serial;break}if(!n||typeof n!="string")throw new x("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return n}function Ja(r,n){let o=Ka(r);if(!n||typeof n!="object")throw new x("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let c=It.fromValues(n);return c.messageSerial=o,c.action||(c.action="annotation.create"),c}function Ya(r,n){return r.client.rest.channelMixin.basePath(r)+"/messages/"+encodeURIComponent(n)+"/annotations"}var Op=class{constructor(r){this.channel=r}async publish(r,n){let o=Ja(r,n),c=await o.encode(),u=this.channel.client,f=u.options,m=f.useBinaryProtocol?"msgpack":"json",_=K.defaultPostHeaders(u.options),A={};J(_,u.options.headers);let I=je([c],u._MsgPack,m);await ie.post(u,Ya(this.channel,o.messageSerial),I,_,A,null,!0)}async delete(r,n){return n.action="annotation.delete",this.publish(r,n)}async get(r,n){let o=this.channel.client,c=Ka(r),u=o.options.useBinaryProtocol?"msgpack":"json",f=o.http.supportsLinkHeaders?void 0:u,m=K.defaultGetHeaders(o.options);return J(m,o.options.headers),new Ue(o,Ya(this.channel,c),m,f,async(_,A,I)=>{let q=I?_:ue(_,o._MsgPack,u);return Ep(q,this.channel)}).get(n)}},Gs=Op,kp=je;function Fs(r){let n=[];if(r)for(let o=0;o<r.length;o++)n.push(r[o].toString());return"[ "+n.join(", ")+" ]"}function Sp(r,n,o,c,u,f){let m=ue(r,n,f);return or(m,o,c,u)}function or(r,n,o,c){let u;r.error&&(u=x.fromValues(r.error));let f;r.messages&&(f=is.fromValuesArray(r.messages));let m;n&&r.presence&&(m=n.WirePresenceMessage.fromValuesArray(r.presence));let _;o&&r.annotations&&(_=o.WireAnnotation.fromValuesArray(r.annotations));let A;return c&&r.state&&(A=c.WireObjectMessage.fromValuesArray(r.state,Zt,Bs)),Object.assign(new cr,S(E({},r),{presence:m,messages:f,annotations:_,state:A,error:u}))}function Tp(r){return n=>{var o;return or(n,{PresenceMessage:Ve,WirePresenceMessage:rs},{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs},(o=r?.LiveObjectsPlugin)!=null?o:null)}}function we(r){return Object.assign(new cr,r)}function ar(r,n,o,c){let u="[ProtocolMessage";r.action!==void 0&&(u+="; action="+ga[r.action]||r.action);let f=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],m;for(let _=0;_<f.length;_++)m=f[_],r[m]!==void 0&&(u+="; "+m+"="+r[m]);if(r.messages&&(u+="; messages="+Fs(is.fromValuesArray(r.messages))),r.presence&&n&&(u+="; presence="+Fs(n.WirePresenceMessage.fromValuesArray(r.presence))),r.annotations&&o&&(u+="; annotations="+Fs(o.WireAnnotation.fromValuesArray(r.annotations))),r.state&&c&&(u+="; state="+Fs(c.WireObjectMessage.fromValuesArray(r.state,Zt,Bs))),r.error&&(u+="; error="+x.fromValues(r.error).toString()),r.auth&&r.auth.accessToken&&(u+="; token="+r.auth.accessToken),r.flags&&(u+="; flags="+$f.filter(r.hasFlag).join(",")),r.params){let _="";Do(r.params,function(A){_.length>0&&(_+="; "),_+=A+"="+r.params[A]}),_.length>0&&(u+="; params=["+_+"]")}return u+="]",u}var cr=class{constructor(){this.hasFlag=r=>(this.flags&ve[r])>0}setFlag(r){return this.flags=this.flags|ve[r]}getMode(){return(this.flags||0)&ve.MODE_ALL}encodeModesToFlags(r){r.forEach(n=>this.setFlag(n))}decodeModesFromFlags(){let r=[];return ma.forEach(n=>{this.hasFlag(n)&&r.push(n)}),r.length>0?r:void 0}},Ap=cr,Rp=class{constructor(r,n,o,c,u){this.previous=r,this.current=n,n==="attached"&&(this.resumed=o,this.hasBacklog=c),u&&(this.reason=u)}},lr=Rp,Qa=function(){};function Pp(r){if(r&&"params"in r&&!kt(r.params))return new x("options.params must be an object",4e4,400);if(r&&"modes"in r){if(!Array.isArray(r.modes))return new x("options.modes must be an array",4e4,400);for(let n=0;n<r.modes.length;n++){let o=r.modes[n];if(!o||typeof o!="string"||!ma.includes(String.prototype.toUpperCase.call(o)))return new x("Invalid channel mode: "+o,4e4,400)}}}var Ip=class Co extends he{constructor(n,o,c){var u,f,m;super(n.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(_){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let A=this.client.rest.channelMixin;if(_&&_.untilAttach){if(this.state!=="attached")throw new x("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new x("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete _.untilAttach,_.from_serial=this.properties.attachSerial}return A.history(this,_)},this.whenState=_=>he.prototype.whenState.call(this,_,this.state),d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=Ds((u=n._Crypto)!=null?u:null,this.logger,c),this.client=n,this._presence=n._RealtimePresence?new n._RealtimePresence.RealtimePresence(this):null,n._Annotations&&(this._annotations=new n._Annotations.RealtimeAnnotations(this)),this.connectionManager=n.connection.connectionManager,this.state="initialized",this.subscriptions=new he(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(c),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:n.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new he(this.logger),(f=n.options.plugins)!=null&&f.Push&&(this._push=new n.options.plugins.Push.PushChannel(this)),(m=n.options.plugins)!=null&&m.LiveObjects&&(this._object=new n.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||pe("RealtimePresence"),this._presence}get annotations(){return this._annotations||pe("Annotations"),this._annotations}get push(){return this._push||pe("Push"),this._push}get object(){return this._object||pe("LiveObjects"),this._object}invalidStateError(){return new x("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(n){return n=Array.prototype.slice.call(n),typeof n[0]=="function"&&n.unshift(null),n}async setOptions(n){var o;let c=this.channelOptions,u=Pp(n);if(u)throw u;if(this.channelOptions=Ds((o=this.client._Crypto)!=null?o:null,this.logger,n),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(n,c))return this.attachImpl(),new Promise((f,m)=>{this._allChannelChanges.once(["attached","update","detached","failed"],function(_){switch(this.event){case"update":case"attached":f();break;default:m(_.reason)}})})}_shouldReattachToSetOptions(n,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(n?.params){let c=Xa(n.params),u=Xa(o.params);if(Object.keys(c).length!==Object.keys(u).length||!Qn(u,c))return!0}return!!(n?.modes&&(!o.modes||!Qo(n.modes,o.modes)))}async publish(...n){let o=n[0],c=n[1],u,f;if(typeof o=="string"||o===null||o===void 0)u=[$e.fromValues({name:o,data:c})],f=n[2];else if(kt(o))u=[$e.fromValues(o)],f=n[1];else if(Array.isArray(o))u=$e.fromValuesArray(o),f=n[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);let m=this.client.options.maxMessageSize,_=await La(u,this.channelOptions),A=qa(_);if(A>m)throw new x(`Maximum size of messages that can be published at once exceeded (was ${A} bytes; limit is ${m} bytes)`,40009,400);this.throwIfUnpublishableState(),d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+_.length);let I=we({action:z.MESSAGE,channel:this.name,messages:_,params:f?Kn(f):void 0});return await this.sendMessage(I)||{serials:[]}}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(n){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.onEvent()","received message");let o=this.subscriptions;for(let c=0;c<n.length;c++){let u=n[c];o.emit(u.name,u)}}async attach(){return this.state==="attached"?null:new Promise((n,o)=>{this._attach(!1,null,(c,u)=>c?o(c):n(u))})}_attach(n,o,c){c||(c=f=>{f&&d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+f.toString())});let u=this.connectionManager;if(!u.activeState()){c(u.getError());return}(this.state!=="attaching"||n)&&this.requestState("attaching",o),this.once(function(f){switch(this.event){case"attached":c?.(null,f);break;case"detached":case"suspended":case"failed":c?.(f.reason||u.getError()||new x("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":c?.(new x("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let n=we({action:z.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&n.encodeModesToFlags(zo(this.channelOptions.modes)),this._attachResume&&n.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(n.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(n).catch(Qa)}async detach(){let n=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new x("Unable to detach; channel state = failed",90001,400);default:if(n.state.state!=="connected"){this.notifyState("detached");return}this.requestState("detaching");case"detaching":return new Promise((o,c)=>{this.once(function(u){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":c(u.reason||n.getError()||new x("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":c(new x("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let n=we({action:z.DETACH,channel:this.name});this.sendMessage(n).catch(Qa)}async subscribe(...n){let[o,c]=Co.processListenerArgs(n);if(this.state==="failed")throw x.fromValues(this.invalidStateError());return o&&typeof o=="object"&&!Array.isArray(o)?this.client._FilteredSubscriptions.subscribeFilter(this,o,c):this.subscriptions.on(o,c),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...n){var o;let[c,u]=Co.processListenerArgs(n);if(typeof c=="object"&&!u||(o=this.filteredSubscriptions)!=null&&o.has(u)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,c,u).forEach(f=>this.subscriptions.off(f));return}this.subscriptions.off(c,u)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Ee("Unable to sync to channel; not attached",4e4);default:}let n=this.connectionManager;if(!n.activeState())throw n.getError();let o=we({action:z.SYNC,channel:this.name});this.syncChannelSerial&&(o.channelSerial=this.syncChannelSerial),n.send(o)}async sendMessage(n){return new Promise((o,c)=>{this.connectionManager.send(n,this.client.options.queueMessages,(u,f)=>{u?c(u):o(f)})})}async sendPresence(n){let o=we({action:z.PRESENCE,channel:this.name,presence:n});await this.sendMessage(o)}async sendState(n){let o=we({action:z.OBJECT,channel:this.name,state:n});await this.sendMessage(o)}async processMessage(n){(n.action===z.ATTACHED||n.action===z.MESSAGE||n.action===z.PRESENCE||n.action===z.OBJECT||n.action===z.ANNOTATION)&&this.setChannelSerial(n.channelSerial);let o,c=!1;switch(n.action){case z.ATTACHED:{this.properties.attachSerial=n.channelSerial,this._mode=n.getMode(),this.params=n.params||{};let u=n.decodeModesFromFlags();this.modes=u&&Vo(u)||void 0;let f=n.hasFlag("RESUMED"),m=n.hasFlag("HAS_PRESENCE"),_=n.hasFlag("HAS_BACKLOG"),A=n.hasFlag("HAS_OBJECTS");if(this.state==="attached"){f||(this._presence&&this._presence.onAttached(m),this._object&&this._object.onAttached(A));let I=new lr(this.state,this.state,f,_,n.error);this._allChannelChanges.emit("update",I),(!f||this.channelOptions.updateOnAttached)&&this.emit("update",I)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",n.error,f,m,_,A);break}case z.DETACHED:{let u=n.error?x.fromValues(n.error):new x("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",u):this.state==="attaching"?this.notifyState("suspended",u):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",u);break}case z.SYNC:if(c=!0,o=this.syncChannelSerial=n.channelSerial,!n.presence)break;case z.PRESENCE:{if(!n.presence)break;$s(n);let u=this.channelOptions;if(this._presence){let f=await Promise.all(n.presence.map(m=>m.decode(u,this.logger)));this._presence.setPresence(f,c,o)}break}case z.OBJECT:case z.OBJECT_SYNC:{if(!this._object||!n.state)return;$s(n);let u=this.client.connection.connectionManager.getActiveTransportFormat(),f=n.state.map(m=>m.decode(this.client,u));n.action===z.OBJECT?this._object.handleObjectMessages(f):this._object.handleObjectSyncMessages(f,n.channelSerial);break}case z.MESSAGE:{if(this.state!=="attached"){d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+n.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}$s(n);let u=n.messages,f=u[0],m=u[u.length-1];if(f.extras&&f.extras.delta&&f.extras.delta.from!==this._lastPayload.messageId){let A='Delta message decode failure - previous message not available for message "'+n.id+'" on this channel "'+this.name+'".';d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel.processMessage()",A),this._startDecodeFailureRecovery(new x(A,40018,400));break}let _=[];for(let A=0;A<u.length;A++){let{decoded:I,err:q}=await u[A].decodeWithErr(this._decodingContext,this.logger);if(_[A]=I,q)switch(q.code){case 40018:this._startDecodeFailureRecovery(q);return;case 40019:case 40021:this.notifyState("failed",q);return;default:}}this._lastPayload.messageId=m.id,this._lastPayload.protocolMessageChannelSerial=n.channelSerial,this.onEvent(_);break}case z.ANNOTATION:{$s(n);let u=this.channelOptions;if(this._annotations){let f=await Promise.all((n.annotations||[]).map(m=>m.decode(u,this.logger)));this._annotations._processIncoming(f)}break}case z.ERROR:{let u=n.error;u&&u.code==80016?this.checkPendingState():this.notifyState("failed",x.fromValues(u));break}default:d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+n.action+")")}}_startDecodeFailureRecovery(n){this._lastPayload.decodeFailureRecoveryInProgress||(d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,n,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(n,o,c,u,f,m){if(d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+n),this.clearStateTimer(),["detached","suspended","failed"].includes(n)&&(this.properties.channelSerial=null),n===this.state)return;this._presence&&this._presence.actOnChannelState(n,u,o),this._object&&this._object.actOnChannelState(n,m),n==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);let _=new lr(this.state,n,c,f,o),A='Channel state for channel "'+this.name+'"',I=n+(o?"; reason: "+o:"");n==="failed"?d.logAction(this.logger,d.LOG_ERROR,A,I):d.logAction(this.logger,d.LOG_MAJOR,A,I),n!=="attaching"&&n!=="suspended"&&(this.retryCount=0),n==="attached"&&this.onAttached(),n==="attached"?this._attachResume=!0:(n==="detaching"||n==="failed")&&(this._attachResume=!1),this.state=n,this._allChannelChanges.emit(n,_),this.emit(n,_)}requestState(n,o){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+n),this.notifyState(n,o),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break;default:break}}timeoutPendingState(){switch(this.state){case"attaching":{let n=new x("Channel attach timed out",90007,408);this.notifyState("suspended",n);break}case"detaching":{let n=new x("Channel detach timed out",90007,408);this.notifyState("attached",n);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){let n=this.stateTimer;n&&(clearTimeout(n),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let n=Yn(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},n)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){let n=this.state;return n==="initialized"||n==="detached"||n==="failed"?null:new x("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+n,90001,400)}setChannelSerial(n){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+n+"; previous = "+this.properties.channelSerial),n&&(this.properties.channelSerial=n)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(n){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,n)}async updateMessage(n,o,c){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(n,"message.update",o,c)}async deleteMessage(n,o,c){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(n,"message.delete",o,c)}async appendMessage(n,o,c){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(n,"message.append",o,c)}async sendUpdate(n,o,c,u){var f,m;if(!n.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();let A=await $e.fromValues(S(E({},n),{action:o,version:c})).encode(this.channelOptions),I=we({action:z.MESSAGE,channel:this.name,messages:[A],params:u?Kn(u):void 0}),q=await this.sendMessage(I);return{versionSerial:(m=(f=q?.serials)==null?void 0:f[0])!=null?m:null}}async getMessageVersions(n,o){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,n,o)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;case"failed":default:throw x.fromValues(this.invalidStateError())}}};function Xa(r){let n=r||{},{agent:o}=n;return N(n,["agent"])}var os=Ip,Mp=class{constructor(r){this.channel=r,this.logger=r.logger,this.subscriptions=new he(this.logger)}async publish(r,n){let o=this.channel.name,c=Ja(r,n),u=await c.encode();this.channel.throwIfUnpublishableState(),d.logAction(this.logger,d.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+o+", sending annotation with messageSerial = "+c.messageSerial+", type = "+c.type);let f=we({action:z.ANNOTATION,channel:o,annotations:[u]});await this.channel.sendMessage(f)}async delete(r,n){n.action="annotation.delete",await this.publish(r,n)}async subscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());if(this.subscriptions.on(o,c),this.channel.channelOptions.attachOnSubscribe!==!1&&await u.attach(),(this.channel.state==="attached"&&this.channel._mode&ve.ANNOTATION_SUBSCRIBE)===0)throw new x("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1];this.subscriptions.off(o,c)}_processIncoming(r){for(let n of r)this.subscriptions.emit(n.type||"",n)}async get(r,n){return Gs.prototype.get.call(this,r,n)}},ur=Mp,mt=class Gn extends vp{constructor(n){var o,c;if(!Gn._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Rest",d.defaultLogger,S(E({},$a),{Crypto:(o=Gn.Crypto)!=null?o:void 0,MsgPack:(c=Gn._MsgPack)!=null?c:void 0,Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(n){this._Crypto=n}};mt._Crypto=null,mt.Message=Ha,mt.PresenceMessage=Ga,mt.Annotation=za,mt._MsgPack=null,mt._Http=tr;var Za=mt,xp=class extends he{constructor(r){super(r),this.messages=[]}count(){return this.messages.length}push(r){this.messages.push(r)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(r){this.messages.push.apply(this.messages,r)}prepend(r){this.messages.unshift.apply(this.messages,r)}completeMessages(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"MessageQueue.completeMessages()",r=="all"?"(all)":"serial = "+r.serial+"; count = "+r.count),n=n||null;let c=this.messages;if(c.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let u=[];if(r==="all")u=c.splice(0);else{let f=c[0];if(f){let m=f.message.msgSerial,_=r.serial+r.count;_>m&&(u=c.splice(0,_-m))}}for(let f=0;f<u.length;f++){let m=u[f],_=o?.[f];m.callback(n,_)}c.length==0&&this.emit("idle")}completeAllMessages(r){this.completeMessages("all",r)}resetSendAttempted(){for(let r of this.messages)r.sendAttempted=!1}clear(){d.logAction(this.logger,d.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},ec=xp,tc=class{constructor(r,n){this.message=r,this.callback=n,this.merged=!1;let o=r.action;this.sendAttempted=!1,this.ackRequired=typeof o=="number"&&[z.MESSAGE,z.PRESENCE,z.ANNOTATION,z.OBJECT].includes(o)}},Np=class extends he{constructor(r){super(r.logger),this.transport=r,this.messageQueue=new ec(this.logger),r.on("ack",(n,o,c)=>{this.onAck(n,o,c)}),r.on("nack",(n,o,c)=>{this.onNack(n,o,c)})}onAck(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"Protocol.onAck()","serial = "+r+"; count = "+n),this.messageQueue.completeMessages({serial:r,count:n},null,o)}onNack(r,n,o){d.logAction(this.logger,d.LOG_ERROR,"Protocol.onNack()","serial = "+r+"; count = "+n+"; err = "+ee(o)),o||(o=new x("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:r,count:n},o)}onceIdle(r){let n=this.messageQueue;if(n.count()===0){r();return}n.once("idle",r)}send(r){r.ackRequired&&this.messageQueue.push(r),this.logger.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(this.logger,d.LOG_MICRO,"Protocol.send()","sending msg; "+ar(r.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),r.sendAttempted=!0,this.transport.send(r.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let r=this.transport;this.onceIdle(function(){r.disconnect()})}},Lp=Np,jp=class{constructor(r,n,o,c){this.previous=r,this.current=n,o&&(this.retryIn=o),c&&(this.reason=c)}},Ws=jp,at={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},qp={disconnected:()=>x.fromValues({statusCode:400,code:at.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:at.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:at.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:at.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:at.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:at.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:at.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function Up(r){return!r.statusCode||!r.code||r.statusCode>=500?!0:Object.values(at).includes(r.code)}var yt=qp,Dp=we({action:z.CLOSE}),Bp=we({action:z.DISCONNECT}),$p=class extends he{constructor(r,n,o,c){super(r.logger),c&&(o.format=void 0,o.heartbeats=!0),this.connectionManager=r,this.auth=n,this.params=o,this.timeouts=o.options.timeouts,this.format=o.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",yt.closed())}disconnect(r){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",r||yt.disconnected())}fail(r){this.isConnected&&this.requestDisconnect(),this.finish("failed",r||yt.failed())}finish(r,n){var o;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((o=this.idleTimer)!=null?o:void 0),this.idleTimer=null,this.emit(r,n),this.dispose())}onProtocolMessage(r){switch(this.logger.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+ar(r,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),r.action){case z.HEARTBEAT:d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",r.id);break;case z.CONNECTED:this.onConnect(r),this.emit("connected",r.error,r.connectionId,r.connectionDetails,r);break;case z.CLOSED:this.onClose(r);break;case z.DISCONNECTED:this.onDisconnect(r);break;case z.ACK:this.emit("ack",r.msgSerial,r.count,r.res);break;case z.NACK:this.emit("nack",r.msgSerial,r.count,r.error);break;case z.SYNC:this.connectionManager.onChannelMessage(r,this);break;case z.ACTIVATE:break;case z.AUTH:Oe(this.auth.authorize(),n=>{n&&d.logAction(this.logger,d.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+ee(n))});break;case z.ERROR:if(d.logAction(this.logger,d.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+L.Config.inspect(r.error)+(r.channel?", channel: "+r.channel:"")),r.channel===void 0){this.onFatalError(r);break}this.connectionManager.onChannelMessage(r,this);break;default:this.connectionManager.onChannelMessage(r,this)}}onConnect(r){if(this.isConnected=!0,!r.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");let n=r.connectionDetails.maxIdleInterval;n&&(this.maxIdleInterval=n+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onDisconnect()","err = "+ee(n)),this.finish("disconnected",n)}onFatalError(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onFatalError()","err = "+ee(n)),this.finish("failed",n)}onClose(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onClose()","err = "+ee(n)),this.finish("closed",n)}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestClose()",""),this.send(Dp)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(Bp)}ping(r){let n={action:z.HEARTBEAT};r&&(n.id=r),this.send(we(n))}dispose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(r){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},r))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;let r=Date.now()-this.lastActivity,n=this.maxIdleInterval-r;if(n<=0){let o="No activity seen from realtime in "+r+"ms; assuming connection has dropped";d.logAction(this.logger,d.LOG_ERROR,"Transport.onIdleTimerExpire()",o),this.disconnect(new x(o,80003,408))}else this.setIdleTimer(n+100)}static tryConnect(r,n,o,c,u){let f=new r(n,o,c),m,_=function(I){clearTimeout(m),u({event:this.event,error:I})},A=n.options.timeouts.realtimeRequestTimeout;return m=setTimeout(()=>{f.off(["preconnect","disconnected","failed"]),f.dispose(),_.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},A),f.on(["failed","disconnected"],_),f.on("preconnect",function(){d.logAction(n.logger,d.LOG_MINOR,"Transport.tryConnect()","viable transport "+f),clearTimeout(m),f.off(["failed","disconnected"],_),u(null,f)}),f.connect(),f}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}},Mt=$p,ge;(r=>{r.WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling"})(ge||(ge={}));var Hp=typeof global<"u"?global:typeof window<"u"?window:self,hr=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.localSupported)},as=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.sessionSupported)},sc=function(){},dr="ably-transport-preference";function fr(r){try{return JSON.parse(r)}catch{return null}}var Gp=class{constructor(r,n,o,c){this.options=r,this.host=n,this.mode=o,this.connectionKey=c,this.format=r.useBinaryProtocol?"msgpack":"json"}getConnectParams(r){let n=r?es(r):{},o=this.options;switch(this.mode){case"resume":n.resume=this.connectionKey;break;case"recover":{let c=fr(o.recover);c&&(n.recover=c.connectionKey);break}default:}return o.clientId!==void 0&&(n.clientId=o.clientId),o.echoMessages===!1&&(n.echo="false"),this.format!==void 0&&(n.format=this.format),this.stream!==void 0&&(n.stream=this.stream),this.heartbeats!==void 0&&(n.heartbeats=this.heartbeats),n.v=K.protocolVersion,n.agent=Xn(this.options),o.transportParams!==void 0&&J(n,o.transportParams),n}toString(){let r="[mode="+this.mode;return this.host&&(r+=",host="+this.host),this.connectionKey&&(r+=",connectionKey="+this.connectionKey),this.format&&(r+=",format="+this.format),r+="]",r}},Fp=class Pd extends he{constructor(n,o){super(n.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=n,this.initTransports(),this.options=o;let c=o.timeouts,u=c.webSocketConnectTimeout+c.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:u,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:c.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:c.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:c.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new ec(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=c.connectionStateTtl,this.maxIdleInterval=null,this.transports=No(o.transports||K.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ge.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ge.XhrPolling)?this.baseTransport=ge.XhrPolling:this.transports.includes(ge.Comet)&&(this.baseTransport=ge.Comet),this.domains=K.getHosts(o),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,d.logAction(this.logger,d.LOG_MINOR,"Realtime.ConnectionManager()","started"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(o.transports||K.defaultTransports)+"]"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){let m="no requested transports available";throw d.logAction(this.logger,d.LOG_ERROR,"realtime.ConnectionManager()",m),new Error(m)}let f=L.Config.addEventListener;f&&(as()&&typeof o.recover=="function"&&f("beforeunload",this.persistConnection.bind(this)),o.closeOnUnload===!0&&f("beforeunload",()=>{d.logAction(this.logger,d.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),f("online",()=>{var m;this.state==this.states.disconnected||this.state==this.states.suspended?(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((m=this.pendingTransport)==null||m.off(),this.disconnectAllTransports(),this.startConnect())}),f("offline",()=>{this.state==this.states.connected&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(n){let o={supportedTransports:{}};return this.initTransports(n,o),o.supportedTransports}static initTransports(n,o){let c=E(E({},L.Transports.bundledImplementations),n);[ge.WebSocket,...L.Transports.order].forEach(u=>{let f=c[u];f&&f.isAvailable()&&(o.supportedTransports[u]=f)})}initTransports(){Pd.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(n,o){return new Gp(this.options,n,o,this.connectionKey)}getTransportParams(n){(c=>{if(this.connectionKey){c("resume");return}if(typeof this.options.recover=="string"){c("recover");return}let u=this.options.recover,f=this.getSessionRecoverData(),m=this.sessionRecoveryName();if(f&&typeof u=="function"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+m+")"),u(f,_=>{_?(this.options.recover=f.recoveryKey,c("recover")):c("clean")});return}c("clean")})(c=>{let u=this.createTransportParams(null,c);if(c==="recover"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let f=fr(this.options.recover);f&&(this.msgSerial=f.msgSerial)}else d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+u.toString());n(u)})}tryATransport(n,o,c){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+o),this.proposedTransport=Mt.tryConnect(this.supportedTransports[o],this,this.realtime.auth,n,(u,f)=>{let m=this.state;if(m==this.states.closing||m==this.states.closed||m==this.states.failed){f&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+m.state+" while we were attempting the transport; closing "+f),f.close()),c(!0);return}if(u){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+u.event+", err: "+u.error.toString()),We.isTokenErr(u.error)&&!(this.errorReason&&We.isTokenErr(this.errorReason))?(this.errorReason=u.error,Oe(this.realtime.auth._forceNewToken(null,null),_=>{if(_){this.actOnErrorFromAuthorize(_);return}this.tryATransport(n,o,c)})):u.event==="failed"?(this.notifyState({state:"failed",error:u.error}),c(!0)):u.event==="disconnected"&&(Up(u.error)?c(!1):(this.notifyState({state:this.states.connecting.failState,error:u.error}),c(!0)));return}d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+o+"; setting pending"),this.setTransportPending(f,n),c(null,f)})}setTransportPending(n,o){let c=o.mode;d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+n+"; mode = "+c),this.pendingTransport=n,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),n.once("connected",(f,m,_)=>{this.activateTransport(f,n,m,_),c==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let u=this;n.on(["disconnected","closed","failed"],function(f){u.deactivateTransport(n,this.event,f)}),this.emit("transport.pending",n)}activateTransport(n,o,c,u){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+o),n&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+n),c&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+c),u&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(u)),this.persistTransportPreference(o);let f=this.state,m=this.states.connected.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+f.state),f.state==this.states.closing.state||f.state==this.states.closed.state||f.state==this.states.failed.state)return d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),o.disconnect(),!1;if(delete this.pendingTransport,!o.isConnected)return d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+o+" since it appears to no longer be connected"),!1;let _=this.activeProtocol;this.activeProtocol=new Lp(o),this.host=o.params.host;let A=u.connectionKey;if(A&&this.connectionKey!=A&&this.setConnection(c,u,!!n),this.onConnectionDetailsUpdate(u,o),L.Config.nextTick(()=>{o.on("connected",(I,q,j)=>{this.onConnectionDetailsUpdate(j,o),this.emit("update",new Ws(m,m,null,I))})}),f.state===this.states.connected.state?n&&(this.errorReason=this.realtime.connection.errorReason=n,this.emit("update",new Ws(m,m,null,n))):(this.notifyState({state:"connected",error:n}),this.errorReason=this.realtime.connection.errorReason=n||null),this.emit("transport.active",o),_)if(_.messageQueue.count()>0&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+_.transport.shortName+", new one is "+o.shortName+") finishing with "+_.messageQueue.count()+" messages still pending"),_.transport===o){let I="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+o.shortName+"; stack = "+new Error().stack;d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()",I)}else _.finish();return!0}deactivateTransport(n,o,c){let u=this.activeProtocol,f=u&&u.getTransport()===n,m=n===this.pendingTransport,_=this.noTransportsScheduledForActivation();if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+n),d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+o+(f?"; was active":m?"; was pending":"")+(_?"":"; another transport is scheduled for activation")),c&&c.message&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+c.message),f&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(u.getPendingMessages()),u.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",n),f&&_||f&&o==="failed"||o==="closed"||u===null&&m){if(o==="disconnected"&&c&&c.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:o,error:c,retryImmediately:!0});return}let A=o==="failed"&&We.isTokenErr(c)?"disconnected":o;this.notifyState({state:A,error:c});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(n,o,c){let u=this.connectionId;(u&&u!==n||!u&&c)&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==n&&d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=n,this.realtime.connection.key=this.connectionKey=o.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;let n=Date.now()-this.lastActivity;n>this.connectionStateTtl+this.maxIdleInterval&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+n+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(as()){let n=this.createRecoveryKey();n&&this.setSessionRecoverData({recoveryKey:n,disconnectedAt:Date.now(),location:Hp.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var n;return(n=this.activeProtocol)==null?void 0:n.getTransport().format}getError(){if(this.errorReason){let n=Ee.fromValues(this.errorReason);return n.cause=this.errorReason,n}return this.getStateError()}getStateError(){var n,o;return(o=(n=yt)[this.state.state])==null?void 0:o.call(n)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(n){let o="Connection state",c=n.current+(n.reason?"; reason: "+n.reason:"");n.current==="failed"?d.logAction(this.logger,d.LOG_ERROR,o,c):d.logAction(this.logger,d.LOG_MAJOR,o,c),d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+n.current+"; reason = "+(n.reason&&n.reason.message));let u=this.state=this.states[n.current];n.reason&&(this.errorReason=n.reason,this.realtime.connection.errorReason=n.reason),(u.terminal||u.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",n)}startTransitionTimer(n){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+n.state),this.transitionTimer&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager "+n.state+" timer expired","requesting new state: "+n.failState),this.notifyState({state:n.failState}))},n.retryDelay)}cancelTransitionTimer(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(n){n!=="disconnected"&&n!=="suspended"&&n!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(n){this.retryTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},n)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&Oe(this.realtime.http.checkConnectivity(),(n,o)=>{n||!o?(d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new x("Unable to connect (network unreachable)",80003,404)})):d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(n){this.webSocketGiveUpTimer=setTimeout(()=>{var o,c;this.wsCheckResult||(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(o=this.proposedTransport)==null||o.dispose(),(c=this.pendingTransport)==null||c.dispose(),this.connectBase(n,++this.connectCounter)):d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(n){var o,c;let u=n.state,f=u==="disconnected"&&(this.state===this.states.connected||n.retryImmediately||this.state===this.states.connecting&&n.error&&We.isTokenErr(n.error)&&!(this.errorReason&&We.isTokenErr(this.errorReason)));if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+u+(f?"; will retry connection immediately":"")),u==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(n.state),(u==="suspended"||u==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;let m=this.states[n.state],_=m.retryDelay;m.state==="disconnected"&&(this.disconnectedRetryCount++,_=Yn(m.retryDelay,this.disconnectedRetryCount));let A=new Ws(this.state.state,m.state,_,n.error||((c=(o=yt)[m.state])==null?void 0:c.call(o)));if(f){let I=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},q=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;q&&q<1e3?(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+q+"ms ago, waiting another "+(1e3-q)+"ms before trying again"),setTimeout(I,1e3-q)):L.Config.nextTick(I)}else(u==="disconnected"||u==="suspended")&&this.startRetryTimer(_);(u==="disconnected"&&!f||u==="suspended"||m.terminal)&&L.Config.nextTick(()=>{this.disconnectAllTransports()}),u=="connected"&&!this.activeProtocol&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(A),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(u,A.reason),this.failQueuedMessages(A.reason))}requestState(n){var o,c;let u=n.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+u+"; current state: "+this.state.state),u==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(u),u=="connecting"&&this.state.state=="connected")||u=="closing"&&this.state.state=="closed")return;let f=this.states[u],m=new Ws(this.state.state,f.state,null,n.error||((c=(o=yt)[f.state])==null?void 0:c.call(o)));this.enactStateChange(m),u=="connecting"&&L.Config.nextTick(()=>{this.startConnect()}),u=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}let n=this.realtime.auth,o=++this.connectCounter,c=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(u=>{if(u.mode==="recover"&&u.options.recover){let f=fr(u.options.recover);f&&this.realtime.channels.recoverChannels(f.channelSerials)}o===this.connectCounter&&this.connectImpl(u,o)})};if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),n.method==="basic")c();else{let u=f=>{o===this.connectCounter&&(f?this.actOnErrorFromAuthorize(f):c())};this.errorReason&&We.isTokenErr(this.errorReason)?Oe(n._forceNewToken(null,null),u):Oe(n._ensureValidAuthCredentials(!1),u)}}connectImpl(n,o){let c=this.state.state;if(c!==this.states.connecting.state){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+c);return}let u=this.getTransportPreference();u&&u===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(n,++this.connectCounter))}).catch(sc),u&&u===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(n,o):this.connectWs(n,o)}connectWs(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(n),this.tryTransportWithFallbacks("web_socket",n,!0,o,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,n,!1,o,()=>!0):this.notifyState({state:"disconnected",error:new x("No transports left to try",8e4,404)})}tryTransportWithFallbacks(n,o,c,u,f){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",n);let m=j=>{this.notifyState({state:this.states.connecting.failState,error:j})},_=this.domains.slice(),A=(j,G)=>{if(u===this.connectCounter){if(!f()){G&&G.dispose();return}!G&&!j&&q()}},I=_.shift();if(!I){m(new x("Unable to connect (no available host)",80003,404));return}o.host=I;let q=()=>{if(!_.length){m(new x("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){m(new Ee("Internal error: Http.checkConnectivity not set",null,500));return}Oe(this.realtime.http.checkConnectivity(),(j,G)=>{if(u===this.connectCounter&&f()){if(j){m(j);return}if(!G){m(new x("Unable to connect (network unreachable)",80003,404));return}o.host=zn(_),this.tryATransport(o,n,A)}})};if(this.forceFallbackHost&&_.length){this.forceFallbackHost=!1,q();return}this.tryATransport(o,n,A)}closeImpl(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(n,o){var c;switch(this.state.state){case"connected":{d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");let u=(c=this.activeProtocol)==null?void 0:c.getTransport();u&&u.onAuthUpdated&&u.onAuthUpdated(n);let f=we({action:z.AUTH,auth:{accessToken:n.token}});this.send(f);let m=()=>{this.off(_),o(null,n)},_=A=>{A.current==="failed"&&(this.off(m),this.off(_),o(A.reason||this.getStateError()))};this.once("connectiondetails",m),this.on("connectionstate",_);break}case"connecting":d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let u=f=>{switch(f.current){case"connected":this.off(u),o(null,n);break;case"failed":case"closed":case"suspended":this.off(u),o(f.reason||this.getStateError());break;default:break}};this.on("connectionstate",u),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(n,o,c){c=c||sc;let u=this.state;if(u.sendEvents){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new tc(n,c));return}if(!(o&&u.queueEvents)){let m="rejecting event, queueEvent was "+o+", state was "+u.state;d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()",m),c(this.errorReason||new x(m,9e4,400));return}this.logger.shouldLog(d.LOG_MICRO)&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+ar(n,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(n,c)}sendImpl(n){let o=n.message;n.ackRequired&&!n.sendAttempted&&(o.msgSerial=this.msgSerial++);try{this.activeProtocol.send(n)}catch(c){d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+c.stack)}}queue(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new tc(n,o))}sendQueuedMessages(){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let n;for(;n=this.queuedMessages.shift();)this.sendImpl(n)}queuePendingMessages(n){n&&n.length&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+n.length+" pending messages"),this.queuedMessages.prepend(n))}failQueuedMessages(n){let o=this.queuedMessages.count();o>0&&(d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+o+" queued messages, err = "+ee(n)),this.queuedMessages.completeAllMessages(n))}onChannelMessage(n,o){this.pendingChannelMessagesState.queue.push({message:n,transport:o}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let n=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(n.message).catch(o=>{d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",o)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(n){await this.realtime.channels.processChannelMessage(n)}async ping(){var n;if(this.state.state!=="connected")throw new x("Unable to ping service; not connected",4e4,400);let o=(n=this.activeProtocol)==null?void 0:n.getTransport();if(!o)throw this.getStateError();d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.ping()","transport = "+o);let c=Date.now(),u=Go();return Xo(new Promise(f=>{let m=_=>{_===u&&(o.off("heartbeat",m),f(Date.now()-c))};o.on("heartbeat",m),o.ping(u)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(n){this.activeProtocol.getTransport().fail(n)}getTransportPreference(){var n,o;return this.transportPreference||hr()&&((o=(n=L.WebStorage)==null?void 0:n.get)==null?void 0:o.call(n,dr))}persistTransportPreference(n){var o,c;this.transportPreference=n.shortName,hr()&&((c=(o=L.WebStorage)==null?void 0:o.set)==null||c.call(o,dr,n.shortName))}unpersistTransportPreference(){var n,o;this.transportPreference=null,hr()&&((o=(n=L.WebStorage)==null?void 0:n.remove)==null||o.call(n,dr))}actOnErrorFromAuthorize(n){if(n.code===40171)this.notifyState({state:"failed",error:n});else if(n.code===40102)this.notifyState({state:"failed",error:n});else if(n.statusCode===ns.Forbidden){let o="Client configured authentication provider returned 403; failing the connection";d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",o),this.notifyState({state:"failed",error:new x(o,80019,403,n)})}else{let o="Client configured authentication provider request failed";d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",o),this.notifyState({state:this.state.failState,error:new x(o,80019,401,n)})}}onConnectionDetailsUpdate(n,o){if(!n)return;this.connectionDetails=n,n.maxMessageSize&&(this.options.maxMessageSize=n.maxMessageSize);let c=n.clientId;if(c){let f=this.realtime.auth._uncheckedSetClientId(c);if(f){d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",f.message),o.fail(f);return}}let u=n.connectionStateTtl;u&&(this.connectionStateTtl=u),this.maxIdleInterval=n.maxIdleInterval,this.emit("connectiondetails",n)}checkWsConnectivity(){let n=this.options.wsConnectivityCheckUrl||K.wsConnectivityCheckUrl,o=new L.Config.WebSocket(n);return new Promise((c,u)=>{let f=!1;o.onopen=()=>{f||(f=!0,c(),o.close())},o.onclose=o.onerror=()=>{f||(f=!0,u())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var n,o;return as()&&((o=(n=L.WebStorage)==null?void 0:n.getSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}setSessionRecoverData(n){var o,c;return as()&&((c=(o=L.WebStorage)==null?void 0:o.setSession)==null?void 0:c.call(o,this.sessionRecoveryName(),n))}clearSessionRecoverData(){var n,o;return as()&&((o=(n=L.WebStorage)==null?void 0:n.removeSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}},nc=Fp,Wp=class extends he{constructor(r,n){super(r.logger),this.whenState=o=>he.prototype.whenState.call(this,o,this.state),this.ably=r,this.connectionManager=new nc(r,n),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",o=>{let c=this.state=o.current;L.Config.nextTick(()=>{this.emit(c,o)})}),this.connectionManager.on("update",o=>{L.Config.nextTick(()=>{this.emit("update",o)})})}connect(){d.logAction(this.logger,d.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return d.logAction(this.logger,d.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){d.logAction(this.logger,d.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},Vp=Wp,rc=class Id extends Ea{constructor(n){var o,c,u,f;if(super(K.objectifyOptions(n,!1,"BaseRealtime",d.defaultLogger)),d.logAction(this.logger,d.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new x(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=Id.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(c=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?c:null,this._liveObjectsPlugin=(f=(u=this.options.plugins)==null?void 0:u.LiveObjects)!=null?f:null,this.connection=new Vp(this,this.options),this._channels=new Kp(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(n){let o={};return n?.WebSocketTransport&&(o[ge.WebSocket]=n.WebSocketTransport),n?.XHRPolling&&(o[ge.XhrPolling]=n.XHRPolling),o}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){d.logAction(this.logger,d.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){d.logAction(this.logger,d.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};rc.EventEmitter=he;var zp=rc,Kp=class extends he{constructor(r){super(r.logger),this.realtime=r,this.all=Object.create(null),r.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let r={};for(let n of js(this.all,!0)){let o=this.all[n];o.properties.channelSerial&&(r[n]=o.properties.channelSerial)}return r}recoverChannels(r){for(let n of js(r,!0)){let o=this.get(n);o.properties.channelSerial=r[n]}}async processChannelMessage(r){let n=r.channel;if(n===void 0){d.logAction(this.logger,d.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+r.action);return}let o=this.all[n];if(!o){d.logAction(this.logger,d.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n);return}await o.processMessage(r)}onTransportActive(){for(let r in this.all){let n=this.all[r];n.state==="attaching"||n.state==="detaching"?n.checkPendingState():n.state==="suspended"?n._attach(!1,null):n.state==="attached"&&n.requestState("attaching")}}propogateConnectionInterruption(r,n){let o={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},c=["attaching","attached","detaching","suspended"],u=o[r];for(let f in this.all){let m=this.all[f];c.includes(m.state)&&m.notifyState(u,n)}}get(r,n){r=String(r);let o=this.all[r];if(!o)o=this.all[r]=new os(this.realtime,r,n);else if(n){if(o._shouldReattachToSetOptions(n,o.channelOptions))throw new x("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);o.setOptions(n)}return o}getDerived(r,n,o){if(n.filter){let c=Us(n.filter),u=Yo(r);r=`[filter=${c}${u.qualifierParam}]${u.channelName}`}return this.get(r,o)}release(r){r=String(r);let n=this.all[r];if(!n)return;let o=n.getReleaseErr();if(o)throw o;delete this.all[r]}},Jp=zp;function Yp(r,n){if(r.isSynthesized()||n.isSynthesized())return r.timestamp>=n.timestamp;let o=r.parseId(),c=n.parseId();return o.msgSerial===c.msgSerial?o.index>c.index:o.msgSerial>c.msgSerial}var pr=class extends he{constructor(r,n,o=Yp){super(r.logger),this.presence=r,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=n,this.newerThan=o}get(r){return this.map[r]}getClient(r){let n=this.map,o=[];for(let c in n){let u=n[c];u.clientId==r&&u.action!="absent"&&o.push(u)}return o}list(r){let n=this.map,o=r&&r.clientId,c=r&&r.connectionId,u=[];for(let f in n){let m=n[f];m.action!=="absent"&&(o&&o!=m.clientId||c&&c!=m.connectionId||u.push(m))}return u}put(r){(r.action==="enter"||r.action==="update")&&(r=Ve.fromValues(r),r.action="present");let n=this.map,o=this.memberKey(r);this.residualMembers&&delete this.residualMembers[o];let c=n[o];return c&&!this.newerThan(r,c)?!1:(n[o]=r,!0)}values(){let r=this.map,n=[];for(let o in r){let c=r[o];c.action!="absent"&&n.push(c)}return n}remove(r){let n=this.map,o=this.memberKey(r),c=n[o];return c&&!this.newerThan(r,c)?!1:(this.syncInProgress?(r=Ve.fromValues(r),r.action="absent",n[o]=r):delete n[o],!!c)}startSync(){let r=this.map,n=this.syncInProgress;d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+n),this.syncInProgress||(this.residualMembers=es(r),this.setInProgress(!0))}endSync(){let r=this.map,n=this.syncInProgress;if(d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+n),n){for(let o in r)r[o].action==="absent"&&delete r[o];this.presence._synthesizeLeaves(Uo(this.residualMembers));for(let o in this.residualMembers)delete r[o];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){let r=this.syncInProgress;d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),r&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(r){d.logAction(this.logger,d.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+r),this.syncInProgress=r,this.presence.syncComplete=!r}};function Qp(r){return r.channel.client.auth.clientId}function gr(r){let n=r.channel.client,o=n.auth.clientId;return(!o||o==="*")&&n.connection.state==="connected"}var Xp=class extends he{constructor(r){super(r.logger),this.channel=r,this.syncComplete=!1,this.members=new pr(this,n=>n.clientId+":"+n.connectionId),this._myMembers=new pr(this,n=>n.clientId),this.subscriptions=new he(this.logger),this.pendingPresence=[]}async enter(r){if(gr(this))throw new x("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"enter")}async update(r){if(gr(this))throw new x("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"update")}async enterClient(r,n){return this._enterOrUpdateClient(void 0,r,n,"enter")}async updateClient(r,n){return this._enterOrUpdateClient(void 0,r,n,"update")}async _enterOrUpdateClient(r,n,o,c){let u=this.channel;if(!u.connectionManager.activeState())throw u.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence."+c+"Client()","channel = "+u.name+", id = "+r+", client = "+(n||"(implicit) "+Qp(this)));let f=Ve.fromData(o);f.action=c,r&&(f.id=r),n&&(f.clientId=n);let m=await f.encode(u.channelOptions);switch(u.state){case"attached":return u.sendPresence([m]);case"initialized":case"detached":u.attach();case"attaching":return new Promise((_,A)=>{this.pendingPresence.push({presence:m,callback:I=>I?A(I):_()})});default:{let _=new Ee("Unable to "+c+" presence channel while in "+u.state+" state",90001);throw _.code=90001,_}}}async leave(r){if(gr(this))throw new x("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,r)}async leaveClient(r,n){let o=this.channel;if(!o.connectionManager.activeState())throw o.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+r);let c=Ve.fromData(n);c.action="leave",r&&(c.clientId=r);let u=await c.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([u]);case"attaching":return new Promise((f,m)=>{this.pendingPresence.push({presence:u,callback:_=>_?m(_):f()})});case"initialized":case"failed":throw new Ee("Unable to leave presence channel (incompatible state)",90001);default:throw o.invalidStateError()}}async get(r){let n=!r||("waitForSync"in r?r.waitForSync:!0);function o(u){return r?u.list(r):u.values()}if(this.channel.state==="suspended"){if(n)throw x.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return o(this.members)}await this.channel.ensureAttached();let c=this.members;return n&&await c.waitSync(),o(this.members)}async history(r){d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let n=this.channel.client.rest.presenceMixin;if(r&&r.untilAttach)if(this.channel.state==="attached")delete r.untilAttach,r.from_serial=this.channel.properties.attachSerial;else throw new x("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return n.history(this,r)}setPresence(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+r.length+" participants; syncChannelSerial = "+o);let c,u,f=this.members,m=this._myMembers,_=[],A=this.channel.connectionManager.connectionId;n&&(this.members.startSync(),o&&(u=o.match(/^[\w-]+:(.*)$/))&&(c=u[1]));for(let I of r)switch(I.action){case"leave":f.remove(I)&&_.push(I),I.connectionId===A&&!I.isSynthesized()&&m.remove(I);break;case"enter":case"present":case"update":f.put(I)&&_.push(I),I.connectionId===A&&m.put(I);break}n&&!c&&(f.endSync(),this.channel.syncChannelSerial=null);for(let I=0;I<_.length;I++){let q=_[I];this.subscriptions.emit(q.action,q)}}onAttached(r){d.logAction(this.logger,d.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+r),r?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let n=this.pendingPresence,o=n.length;if(o){this.pendingPresence=[];let c=[],u=ca.create(this.logger);d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.onAttached","sending "+o+" queued presence messages");for(let f=0;f<o;f++){let m=n[f];c.push(m.presence),u.push(m.callback)}this.channel.sendPresence(c).then(()=>u()).catch(f=>u(f))}}actOnChannelState(r,n,o){switch(r){case"attached":this.onAttached(n);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(o);break}}failPendingPresence(r){if(this.pendingPresence.length){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+ee(r));for(let n=0;n<this.pendingPresence.length;n++)try{this.pendingPresence[n].callback(r)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let r=this._myMembers,n=this.channel.connectionManager.connectionId;for(let o in r.map){let c=r.map[o];d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+c.clientId+'" into the presence set');let u=c.connectionId===n?c.id:void 0;this._enterOrUpdateClient(u,c.clientId,c.data,"enter").catch(f=>{let m=new x("Presence auto re-enter failed",91004,400,f);d.logAction(this.logger,d.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+ee(f));let _=new lr(this.channel.state,this.channel.state,!0,!1,m);this.channel.emit("update",_)})}}_synthesizeLeaves(r){let n=this.subscriptions;r.forEach(function(o){let c=Ve.fromValues({action:"leave",connectionId:o.connectionId,clientId:o.clientId,data:o.data,encoding:o.encoding,timestamp:Date.now()});n.emit("leave",c)})}async subscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());this.subscriptions.on(o,c),u.channelOptions.attachOnSubscribe!==!1&&await u.attach()}unsubscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1];this.subscriptions.off(o,c)}},Zp=Xp,eg=ge.WebSocket;function tg(r){return!!r.on}var sg=class extends Mt{constructor(r,n,o){super(r,n,o),this.shortName=eg,o.heartbeats=L.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!L.Config.WebSocket}createWebSocket(r,n){return this.uri=r+ts(n),new L.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","starting"),Mt.prototype.connect.call(this);let r=this,n=this.params,o=n.options,u=(o.tls?"wss://":"ws://")+this.wsHost+":"+K.getPort(o)+"/";d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","uri: "+u),Oe(this.auth.getAuthParams(),function(f,m){if(r.isDisposed)return;let _="";for(let I in m)_+=" "+I+": "+m[I]+";";if(d.logAction(r.logger,d.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+_+" err: "+f),f){r.disconnect(f);return}let A=n.getConnectParams(m);try{let I=r.wsConnection=r.createWebSocket(u,A);I.binaryType=L.Config.binaryType,I.onopen=function(){r.onWsOpen()},I.onclose=function(q){r.onWsClose(q)},I.onmessage=function(q){r.onWsData(q.data)},I.onerror=function(q){r.onWsError(q)},tg(I)&&I.on("ping",function(){r.onActivity()})}catch(I){d.logAction(r.logger,d.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(I.stack||I.message)),r.disconnect(I)}})}send(r){let n=this.wsConnection;if(!n){d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{n.send(kp(r,this.connectionManager.realtime._MsgPack,this.params.format))}catch(o){let c="Exception from ws connection when trying to send: "+ee(o);d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.send()",c),this.finish("disconnected",new x(c,5e4,500))}}onWsData(r){d.logAction(this.logger,d.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+r.length+"; type = "+typeof r);try{this.onProtocolMessage(Sp(r,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(n){d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+n.stack)}}onWsOpen(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(r){let n,o;if(typeof r=="object"?(o=r.code,n=r.wasClean||o===1e3):(o=r,n=o==1e3),delete this.wsConnection,n){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let c=new x("Websocket closed",80003,400);this.finish("disconnected",c)}else{let c="Unclean disconnection of WebSocket ; code = "+o,u=new x(c,80003,400);d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()",c),this.finish("disconnected",u)}this.emit("disposed")}onWsError(r){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+r.message),L.Config.nextTick(()=>{this.disconnect(Error(r.message))})}dispose(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let r=this.wsConnection;r&&(r.onmessage=function(){},delete this.wsConnection,L.Config.nextTick(()=>{if(d.logAction(this.logger,d.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!r)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");r.close()}))}},ic=sg,ng=class{static subscribeFilter(r,n,o){let c=u=>{var f,m,_,A,I,q;let j={name:u.name,refTimeserial:(m=(f=u.extras)==null?void 0:f.ref)==null?void 0:m.timeserial,refType:(A=(_=u.extras)==null?void 0:_.ref)==null?void 0:A.type,isRef:!!((q=(I=u.extras)==null?void 0:I.ref)!=null&&q.timeserial),clientId:u.clientId};Object.entries(n).find(([G,w])=>w!==void 0?j[G]!==w:!1)||o(u)};this.addFilteredSubscription(r,n,o,c),r.subscriptions.on(c)}static addFilteredSubscription(r,n,o,c){var u;if(r.filteredSubscriptions||(r.filteredSubscriptions=new Map),r.filteredSubscriptions.has(o)){let f=r.filteredSubscriptions.get(o);f.set(n,((u=f?.get(n))==null?void 0:u.concat(c))||[c])}else r.filteredSubscriptions.set(o,new Map([[n,[c]]]))}static getAndDeleteFilteredSubscriptions(r,n,o){if(!r.filteredSubscriptions)return[];if(!o&&n)return Array.from(r.filteredSubscriptions.entries()).map(([f,m])=>{var _;let A=m.get(n);return m.delete(n),m.size===0&&((_=r.filteredSubscriptions)==null||_.delete(f)),A}).reduce((f,m)=>m?f.concat(...m):f,[]);if(!o||!r.filteredSubscriptions.has(o))return[];let c=r.filteredSubscriptions.get(o);if(!n){let f=Array.from(c.values()).reduce((m,_)=>m.concat(..._),[]);return r.filteredSubscriptions.delete(o),f}let u=c.get(n);return c.delete(n),u||[]}},Ae=class Eo extends Jp{constructor(n){var o;let c=Eo._MsgPack;if(!c)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Realtime",d.defaultLogger,S(E({},$a),{Crypto:(o=Eo.Crypto)!=null?o:void 0,MsgPack:c,RealtimePresence:{RealtimePresence:Zp,PresenceMessage:Ve,WirePresenceMessage:rs},Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs},WebSocketTransport:ic,MessageInteractions:ng})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(n){this._Crypto=n}};Ae.Utils=Zt,Ae.ConnectionManager=nc,Ae.ProtocolMessage=Ap,Ae._Crypto=null,Ae.Message=Ha,Ae.PresenceMessage=Ga,Ae.Annotation=za,Ae._MsgPack=null,Ae._Http=tr,Ae._PresenceMap=pr,Ae._MessageEncoding=Bs;var oc=Ae,ac=Z(D("crypto")),rg=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}base64Decode(r){return Buffer.from(r,"base64")}base64Encode(r){return this.toBuffer(r).toString("base64")}base64UrlEncode(r){return this.toBuffer(r).toString("base64url")}areBuffersEqual(r,n){return!r||!n?!1:this.toBuffer(r).compare(this.toBuffer(n))==0}byteLength(r){return r.byteLength}hexDecode(r){return Buffer.from(r,"hex")}hexEncode(r){return this.toBuffer(r).toString("hex")}isBuffer(r){return Buffer.isBuffer(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)}toArrayBuffer(r){let n=this.toBuffer(r);return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}toBuffer(r){return Buffer.isBuffer(r)?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength)}arrayBufferViewToBuffer(r){return this.toBuffer(r)}utf8Decode(r){if(!this.isBuffer(r))throw new Error("Expected input of utf8Decode to be a buffer, arraybuffer, or view");return this.toBuffer(r).toString("utf8")}utf8Encode(r){return Buffer.from(r,"utf8")}concat(r){return Buffer.concat(r.map(n=>this.toBuffer(n)))}sha256(r){let n=this.toBuffer(r);return ac.default.createHash("SHA256").update(n).digest()}hmacSha256(r,n){let o=this.toBuffer(r),c=this.toBuffer(n);return ac.default.createHmac("SHA256",c).update(o).digest()}},cc=new rg,mr=Z(D("crypto")),ig=Z(D("util")),og=function(r){var n="aes",o=256,c="cbc",u=16;async function f(U){return ig.default.promisify(mr.default.randomBytes)(U)}function m(U){return U+u&-u}function _(U){if(U.algorithm==="aes"&&U.mode==="cbc"){if(U.keyLength===128||U.keyLength===256)return;throw new Error("Unsupported key length "+U.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function A(U){return U.replace("_","/").replace("-","+")}function I(U,H){var V=Buffer.alloc(U);return V.fill(H),V}for(var q=[I(16,16)],j=1;j<=16;j++)q.push(I(j,j));class G{constructor(H,V,F,X){this.algorithm=H,this.keyLength=V,this.mode=F,this.key=X,this.iv=null}}function w(U){return!!(U.algorithm&&U.key&&U.keyLength&&U.mode)}class R{static getDefaultParams(H){var V;if(!H.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof H.key=="string"?V=r.base64Decode(A(H.key)):H.key instanceof ArrayBuffer?V=Buffer.from(H.key):V=H.key;var F=H.algorithm||n,X=V.length*8,Ce=H.mode||c,_e=new G(F,X,Ce,V);if(H.keyLength&&H.keyLength!==_e.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+H.keyLength+" was specified, but the key actually has length "+_e.keyLength);return _(_e),_e}static async generateRandomKey(H){try{return f((H||o)/8)}catch(V){throw new x("Failed to generate random key: "+V.message,500,5e4,V)}}static getCipher(H,V){var F,X=w(H)?H:this.getDefaultParams(H);return{cipherParams:X,cipher:new P(X,(F=H.iv)!=null?F:null,V)}}}R.CipherParams=G;class P{constructor(H,V,F){this.logger=F,this.encryptCipher=null,this.algorithm=H.algorithm+"-"+String(H.keyLength)+"-"+H.mode,this.key=H.key,this.iv=V}async encrypt(H){d.logAction(this.logger,d.LOG_MICRO,"CBCCipher.encrypt()","");let V=await this.getIv();this.encryptCipher||(this.encryptCipher=mr.default.createCipheriv(this.algorithm,this.key,V));var F=r.toBuffer(H),X=F.length,Ce=m(X),_e=this.encryptCipher.update(Buffer.concat([F,q[Ce-X]])),ze=Buffer.concat([V,_e]);return ze}async decrypt(H){var V=mr.default.createDecipheriv(this.algorithm,this.key,H.slice(0,u)),F=V.update(H.slice(u)),X=V.final();return X&&X.length&&(F=Buffer.concat([F,X])),F}async getIv(){if(this.iv){var H=this.iv;return this.iv=null,H}var V=await f(u);return this.encryptCipher?this.encryptCipher.update(V):V}}return R},lc=Z(Hn()),ag=Z(D("http")),cg=Z(D("https")),uc=[],cs,lg=(cs=class{constructor(r){this.agent=null,this.supportsAuthHeaders=!0,this.supportsLinkHeaders=!0,this.checkConnectivity=async()=>{var n,o,c,u,f;if((n=this.client)!=null&&n.options.disableConnectivityCheck)return!0;let m=((o=this.client)==null?void 0:o.options.connectivityCheckUrl)||K.connectivityCheckUrl,_=(u=(c=this.client)==null?void 0:c.options.connectivityCheckParams)!=null?u:null,A=!((f=this.client)!=null&&f.options.connectivityCheckUrl),{error:I,statusCode:q,body:j}=await this.doUri(ce.Get,m,null,null,_);return!I&&!A?Af(q):!I&&j?.toString().trim()==="yes"},this.client=r??null}async doUri(r,n,o,c,u){var f;let m=this.client&&this.client.options.restAgentOptions||K.restAgentOptions,_={headers:o||void 0,responseType:"buffer"};if(!this.agent){let A=(f=uc.find(I=>Qn(m,I.options)))==null?void 0:f.agents;A?this.agent=A:(this.agent={http:new ag.default.Agent(m),https:new cg.default.Agent(m)},uc.push({options:m,agents:this.agent}))}c&&(_.body=c),u&&(_.searchParams=u),_.agent=this.agent,_.url=n,_.timeout={request:(this.client&&this.client.options.timeouts||K.TIMEOUTS).httpRequestTimeout},_.retry={limit:0};try{let A=await lc.default[r](_);return this._handler(null,A,A.body)}catch(A){return A instanceof lc.default.HTTPError?this._handler(null,A.response,A.response.body):this._handler(A)}}shouldFallback(r){let{code:n,statusCode:o}=r;return n==="ENETUNREACH"||n==="EHOSTUNREACH"||n==="EHOSTDOWN"||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||n==="ENOTFOUND"||n==="ECONNRESET"||n==="ECONNREFUSED"||o>=500&&o<=504}_handler(r,n,o){var c;if(r)return{error:r};let u=n.statusCode,f=n.headers;if(u>=300){switch(f["content-type"]){case"application/json":o=JSON.parse(o);break;case"application/x-msgpack":if(!((c=this.client)!=null&&c._MsgPack))return{error:ss("MsgPack")};o=this.client._MsgPack.decode(o);break}return{error:o.error?x.fromValues(o.error):new x(f["x-ably-errormessage"]||"Error response received from server: "+u+" body was: "+L.Config.inspect(o),Number(f["x-ably-errorcode"]),u),body:o,headers:f,unpacked:!0,statusCode:u}}return{error:null,body:o,headers:f,unpacked:!1,statusCode:u}}},cs.methods=[ce.Get,ce.Delete,ce.Post,ce.Put,ce.Patch],cs.methodsWithoutBody=[ce.Get,ce.Delete],cs.methodsWithBody=[ce.Post,ce.Put,ce.Patch],cs),ug=lg,hg=Z(D("crypto")),dg=Z(dn()),yr=Z(D("util")),fg={agent:"nodejs/"+process.versions.node,logTimestamps:!0,userAgent:null,binaryType:"nodebuffer",WebSocket:dg.default,useProtocolHeartbeats:!1,supportsBinary:!0,preferBinary:!0,nextTick:process.nextTick,inspect:yr.default.inspect,stringByteSize:Buffer.byteLength,inherits:yr.default.inherits,addEventListener:null,getRandomArrayBuffer:async function(r){return yr.default.promisify(hg.default.randomBytes)(r)}},pg=fg,hc=(r=>(r[r.REQ_SEND=0]="REQ_SEND",r[r.REQ_RECV=1]="REQ_RECV",r[r.REQ_RECV_POLL=2]="REQ_RECV_POLL",r[r.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",r))(hc||{}),ct=hc;function gg(r){let n=[80015,80017,80030];return r.code?We.isTokenErr(r)?!1:n.includes(r.code)?!0:r.code>=4e4&&r.code<5e4:!1}function _r(r){return gg(r)?[we({action:z.ERROR,error:r})]:[we({action:z.DISCONNECTED,error:r})]}var mg=class extends Mt{constructor(r,n,o){super(r,n,o,!0),this.onAuthUpdated=c=>{this.authParams={access_token:c.token}},this.stream="stream"in o?o.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","starting"),Mt.prototype.connect.call(this);let r=this.params,n=r.options,o=r.host||n.primaryDomain,c=K.getPort(n),u=n.tls?"https://":"http://";this.baseUri=u+o+":"+c+"/comet/";let f=this.baseUri+"connect";d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","uri: "+f),Oe(this.auth.getAuthParams(),(m,_)=>{if(m){this.disconnect(m);return}if(this.isDisposed)return;this.authParams=_;let A=this.params.getConnectParams(_);"stream"in A&&(this.stream=A.stream),d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","connectParams:"+ts(A));let I=!1,q=this.recvRequest=this.createRequest(f,null,A,null,this.stream?ct.REQ_RECV_STREAM:ct.REQ_RECV);q.on("data",j=>{this.recvRequest&&(I||(I=!0,this.emit("preconnect")),this.onData(j))}),q.on("complete",j=>{if(this.recvRequest||(j=j||new x("Request cancelled",80003,400)),this.recvRequest=null,!I&&!j&&(I=!0,this.emit("preconnect")),this.onActivity(),j){j.code?this.onData(_r(j)):this.disconnect(j);return}L.Config.nextTick(()=>{this.recv()})}),q.exec()})}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(r){let n=r?this.closeUri:this.disconnectUri;if(n){let o=this.createRequest(n,null,this.authParams,null,ct.REQ_SEND);o.on("complete",c=>{c&&(d.logAction(this.logger,d.LOG_ERROR,"CometTransport.request"+(r?"Close()":"Disconnect()"),"request returned err = "+ee(c)),this.finish("disconnected",c))}),o.exec()}}dispose(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(d.logAction(this.logger,d.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",yt.disconnected()),L.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(r){var n;if(this.isDisposed)return;let o=(n=r.connectionDetails)==null?void 0:n.connectionKey;Mt.prototype.onConnect.call(this,r);let c=this.baseUri+o;d.logAction(this.logger,d.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+c),this.sendUri=c+"/send",this.recvUri=c+"/recv",this.closeUri=c+"/close",this.disconnectUri=c+"/disconnect"}send(r){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(r);return}let n=this.pendingItems||[];n.push(r),this.pendingItems=null,this.sendItems(n)}sendAnyPending(){let r=this.pendingItems;r&&(this.pendingItems=null,this.sendItems(r))}sendItems(r){let n=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(r),ct.REQ_SEND);n.on("complete",(o,c)=>{if(o&&d.logAction(this.logger,d.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+ee(o)),this.sendRequest=null,o){o.code?this.onData(_r(o)):this.disconnect(o);return}c&&this.onData(c),this.pendingItems&&L.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),n.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let r=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?ct.REQ_RECV_STREAM:ct.REQ_RECV_POLL);r.on("data",n=>{this.onData(n)}),r.on("complete",n=>{if(this.recvRequest=null,this.onActivity(),n){n.code?this.onData(_r(n)):this.disconnect(n);return}L.Config.nextTick(()=>{this.recv()})}),r.exec()}onData(r){try{let n=this.decodeResponse(r);if(n&&n.length)for(let o=0;o<n.length;o++)this.onProtocolMessage(or(n[o],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(n){d.logAction(this.logger,d.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+n.stack)}}encodeRequest(r){return JSON.stringify(r)}decodeResponse(r){return typeof r=="string"?JSON.parse(r):r}},dc=mg,fc=Z(D("http")),pc=Z(D("https")),yg=Z(D("url")),_g=Z(D("util")),bg=function(){},vg=ge.Comet,wg=class extends dc{constructor(r,n,o){super(r,n,o),this.httpAgent=null,this.httpsAgent=null,this.pendingRequests=0,this.shortName=vg}static isAvailable(){return!0}toString(){return"NodeCometTransport; uri="+this.baseUri+"; isConnected="+this.isConnected+"; format="+this.format+"; stream="+this.stream}getAgent(r){var n=r?"httpsAgent":"httpAgent",o=this[n];return o||(o=this[n]=new(r?pc.default:fc.default).Agent({keepAlive:!0})),o}dispose(){var r=this;this.onceNoPending(function(){r.httpAgent&&r.httpAgent.destroy(),r.httpsAgent&&r.httpsAgent.destroy()}),dc.prototype.dispose.call(this)}request(r,n,o,c,u){var f=this.createRequest(r,n,o,c);return f.once("complete",u),f.exec(),f}createRequest(r,n,o,c,u){return new Cg(r,n,o,c,u,this.format,this.timeouts,this)}addPending(){++this.pendingRequests}removePending(){--this.pendingRequests<=0&&this.emit("nopending")}onceNoPending(r){if(this.pendingRequests==0){r();return}this.once("nopending",r)}},Cg=class extends he{constructor(r,n,o,c,u,f,m,_){super(_.logger),typeof r=="string"&&(r=yg.default.parse(r));var A=r.protocol=="https:";this.client=A?pc.default:fc.default,this.requestMode=u,this.timeouts=m,this.transport=_,this.requestComplete=!1,this.req=this.res=null;var I="GET",q=f=="msgpack"?"application/x-msgpack":"application/json";n=n?J({},n):{},n.accept=q,c&&(I="POST",Buffer.isBuffer(c)||(typeof c=="object"&&(c=JSON.stringify(c)),c=Buffer.from(c)),this.body=c,n["Content-Length"]=c.length,n["Content-Type"]=q);var j=this.requestOptions={hostname:r.hostname,port:r.port,path:r.path+ts(o),method:I,headers:n};_&&(j.agent=_.getAgent(A))}exec(){var r=this.requestMode==ct.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,n=this,o=this.timer=setTimeout(function(){n.abort()},r),c=this.req=this.client.request(this.requestOptions);c.on("error",this.onReqError=function(u){u=new Ee("Request error: "+u.message,null,400),clearTimeout(o),n.timer=null,n.complete(u)}),c.on("response",function(u){clearTimeout(o),n.timer=null;var f=u.statusCode;if(f==ns.NoContent){u.resume(),n.complete();return}u.on("error",n.onResError=function(m){m=new Ee("Response error: "+m.message,null,400),n.complete(m)}),n.res=u,n.requestMode==ct.REQ_RECV_STREAM&&f<400?n.readStream():n.readFully()}),this.transport&&this.transport.addPending(),c.end(this.body)}readStream(){var r=this.res,n=this;this.chunks=[],this.streamComplete=!1;function o(c){try{c=JSON.parse(c)}catch(f){var u="Malformed response body from server: "+f.message;d.logAction(n.logger,d.LOG_ERROR,"NodeCometTransport.Request.readStream()",u),n.complete(new Ee(u,null,400));return}n.emit("data",c)}r.on("data",this.ondata=function(c){var u=String(c).split(`
|
|
45
|
-
`),f=n.chunks;u.length>1&&f.length>0&&(f.push(u.shift()),n.chunks=[],o(f.join("")));var m=u.pop();m.length&&n.chunks.push(m),u.map(o)}),r.on("end",function(){n.streamComplete=!0,process.nextTick(function(){n.complete()})})}readFully(){var r=this.res,n=[],o=this;r.on("data",function(c){n.push(c)}),r.on("end",function(){process.nextTick(function(){var c=Buffer.concat(n),u=r.statusCode;try{c=JSON.parse(String(c))}catch(_){var f="Malformed response body from server: "+_.message;d.logAction(o.logger,d.LOG_ERROR,"NodeCometTransport.Request.readFully()",f),o.complete(new Ee(f,null,400));return}if(u<400||Array.isArray(c)){o.complete(null,c);return}var m=c.error&&x.fromValues(c.error);m||(m=new Ee("Error response received from server: "+u+", body was: "+_g.default.inspect(c),null,u)),o.complete(m)})})}complete(r,n){this.requestComplete||(this.requestComplete=!0,n&&this.emit("data",n),this.emit("complete",r,n),r&&this.ondata&&!this.streamComplete&&this.ondata&&this.res&&this.res.removeListener("data",this.ondata),this.transport&&this.transport.removePending())}abort(){d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","");var r=this.timer;r&&(clearTimeout(r),this.timer=null);var n=this.req;n&&(d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","aborting request"),n.removeListener("error",this.onReqError),n.on("error",bg),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},Eg=wg,Og={order:[ge.Comet],bundledImplementations:{[ge.WebSocket]:ic,[ge.Comet]:Eg}},kg={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ge.WebSocket],restAgentOptions:{maxSockets:40,keepAlive:!0}},Sg=kg,Tg=sf(),gc=og(cc);L.Crypto=gc,L.BufferUtils=cc,L.Http=ug,L.Config=pg,L.Transports=Og,L.WebStorage=null;for(let r of[Za,oc])r.Crypto=gc,r._MsgPack=Tg;if(d.initLogHandlers(),L.Defaults=Sf(Sg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:x,Rest:Za,Realtime:oc,msgpack:null,makeProtocolMessageFromDeserialized:Tp},typeof i.exports=="object"&&typeof t=="object"){var Ag=(r,n,o,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of Object.getOwnPropertyNames(n))!Object.prototype.hasOwnProperty.call(r,u)&&u!==o&&Object.defineProperty(r,u,{get:()=>n[u],enumerable:!(c=Object.getOwnPropertyDescriptor(n,u))||c.enumerable});return r};i.exports=Ag(i.exports,t)}return i.exports})});var Pc=br(Rc(),1),{program:us,createCommand:Ew,createArgument:Ow,createOption:kw,CommanderError:Sw,InvalidArgumentError:Tw,InvalidOptionArgumentError:Aw,Command:Rw,Argument:Pw,Option:Iw,Help:Mw}=Pc.default;var zd=br(qc(),1);import{resolve as Vd}from"path";import{existsSync as pw}from"fs";function fm(s){let e=s.apiKey||process.env.SEGO_API_KEY,t=s.apiUrl||process.env.SEGO_API_URL||"https://sego.pm",i=s.pollIntervalMs||(process.env.AUTO_TASK_POLL_INTERVAL_MS?parseInt(process.env.AUTO_TASK_POLL_INTERVAL_MS,10):3e4),a=s.timeoutMs||(process.env.AUTO_TASK_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_TIMEOUT_MS,10):6e5),l=s.clientRequestTimeoutMs||(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS,10):3e5);if(!e)throw new Error("API key is required. Set SEGO_API_KEY environment variable or use --api-key flag.");let h=s.projectId||process.env.SEGO_PROJECT_ID,p=s.sseEnabled??process.env.AUTO_TASK_SSE_ENABLED!=="false",g=s.workingDirectory||process.env.SEGO_WORKING_DIR,y=s.useAgentSdk??process.env.USE_CLI_MODE!=="true",C=s.streamProgress??process.env.STREAM_PROGRESS!=="false",v=s.conversationOnly??process.env.CONVERSATION_ONLY==="true",O=s.autoCommit??process.env.AUTO_COMMIT==="true",k=s.autoPush??process.env.AUTO_PUSH==="true";return{apiKey:e,apiUrl:t,pollIntervalMs:i,timeoutMs:a,dryRun:s.dryRun??!1,projectId:h,sseEnabled:p,clientRequestTimeoutMs:l,workingDirectory:g,useAgentSdk:y,streamProgress:C,conversationOnly:v,autoCommit:O,autoPush:k}}function Uc(s){let e={apiKey:s.apiKey?"cli":process.env.SEGO_API_KEY?"env":"default",apiUrl:s.apiUrl?"cli":process.env.SEGO_API_URL?"env":"default",pollIntervalMs:s.pollIntervalMs?"cli":process.env.AUTO_TASK_POLL_INTERVAL_MS?"env":"default",timeoutMs:s.timeoutMs?"cli":process.env.AUTO_TASK_TIMEOUT_MS?"env":"default",dryRun:s.dryRun!==void 0?"cli":"default",projectId:s.projectId?"cli":process.env.SEGO_PROJECT_ID?"env":"default",sseEnabled:s.sseEnabled!==void 0?"cli":process.env.AUTO_TASK_SSE_ENABLED?"env":"default",clientRequestTimeoutMs:s.clientRequestTimeoutMs?"cli":process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?"env":"default",workingDirectory:s.workingDirectory?"cli":process.env.SEGO_WORKING_DIR?"env":"default",useAgentSdk:s.useAgentSdk!==void 0?"cli":process.env.USE_CLI_MODE?"env":"default",streamProgress:s.streamProgress!==void 0?"cli":process.env.STREAM_PROGRESS?"env":"default",conversationOnly:s.conversationOnly!==void 0?"cli":process.env.CONVERSATION_ONLY?"env":"default",autoCommit:s.autoCommit!==void 0?"cli":process.env.AUTO_COMMIT?"env":"default",autoPush:s.autoPush!==void 0?"cli":process.env.AUTO_PUSH?"env":"default"};return{config:fm(s),sources:e}}function ke(s){switch(s){case"cli":return"[cli]";case"env":return"[env]";case"default":return"[default]"}}var Js=class{baseUrl;apiKey;projectId;constructor(e,t,i){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i}async request(e,t={}){let i=`${this.baseUrl}${e}`,a=await fetch(i,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(!a.ok){let l=await a.text(),h;try{let p=JSON.parse(l);h=p.error||p.message||l}catch{h=l}throw new Error(`API error (${a.status}): ${h}`)}return a.json()}async getEligibleTask(){let e=this.projectId?`/api/mcp/tasks/auto-task/eligible?projectId=${this.projectId}`:"/api/mcp/tasks/auto-task/eligible";return(await this.request(e)).task}async startTask(e){return this.request("/api/mcp/tasks/auto-task/start",{method:"POST",body:JSON.stringify({taskId:e})})}async completeTask(e,t,i){return this.request("/api/mcp/tasks/auto-task/complete",{method:"POST",body:JSON.stringify({runId:e,status:t,comment:i?.comment,errorMessage:i?.errorMessage})})}async sendAlert(e,t,i){return this.request("/api/notifications/auto-task-alert",{method:"POST",body:JSON.stringify({runId:e,alertType:t,errorDetails:i})})}async validateAuth(){try{return await this.request("/api/mcp/auth/validate",{method:"POST"}),!0}catch{return!1}}getClientRequestMonitorUrl(){if(!this.projectId)throw new Error("Project ID is required for client request monitoring");return`${this.baseUrl}/api/projects/${this.projectId}/client-requests/monitor`}getApiKey(){return this.apiKey}getProjectId(){return this.projectId}async submitAnalysis(e,t,i,a){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:i,processingTimeMs:a})})}async reportAnalysisFailure(e,t,i){return this.request(`/api/client-requests/${e}/analysis`,{method:"PUT",body:JSON.stringify({monitorId:t,error:i})})}async getClientRequest(e){try{let i=(await this.request(`/api/client-requests/${e}`)).request,a=i.project.brief;return{id:i.id,projectId:i.projectId,description:i.description,channel:i.channel,createdById:i.createdById,projectContext:{projectName:i.project.name,projectDescription:i.project.description,techStack:a?.techStack?.split(",").map(l=>l.trim()),existingFeatures:i.project.tasks?.map(l=>l.title),knowledgeBase:i.project.knowledgeBase||void 0}}}catch(t){return console.error(`[ApiClient] Failed to fetch client request ${e}:`,t),null}}async claimTask(e,t){if(!this.projectId)throw new Error("Project ID is required for claiming tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/claim`,{method:"POST",body:JSON.stringify({monitorId:t})})}async completeBacklogTask(e,t,i){if(!this.projectId)throw new Error("Project ID is required for completing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/complete`,{method:"POST",body:JSON.stringify({monitorId:t,result:i})})}async failBacklogTask(e,t,i,a=!0){if(!this.projectId)throw new Error("Project ID is required for failing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/fail`,{method:"POST",body:JSON.stringify({monitorId:t,error:i,returnToBacklog:a})})}formatEventPayload(e){return{type:e.type,timestamp:e.timestamp,message:e.message,emoji:e.emoji,data:e.data}}async sendAgentProgress(e,t,i){return this.request(`/api/client-requests/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}async sendTaskAgentProgress(e,t,i){if(!this.projectId)throw new Error("Project ID is required for task progress events");return this.request(`/api/projects/${this.projectId}/tasks/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}};import{spawn as Ys}from"child_process";import{existsSync as Dc,writeFileSync as Bc,unlinkSync as $c}from"fs";import{homedir as pm,tmpdir as Hc}from"os";import{join as qr}from"path";function Qs(){let s=[qr(pm(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(Dc(e))return e;return"claude"}var me=null;function gm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.project.name}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,"","## Description",s.description,""];return s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.project.knowledgeBase&&(e.push("## Project Context"),e.push(s.project.knowledgeBase),e.push("")),e.push("---"),e.push(""),e.push('Please work on this task. When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
46
|
-
`)}async function Gc(s,e){let t=
|
|
47
|
-
`)}function
|
|
43
|
+
`+D+`
|
|
44
|
+
`;return y.mac=y.mac||Mf(F,f),d.logAction(this.logger,d.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),y}async getAuthParams(){if(this.method=="basic")return{key:this.key};{let r=await this._ensureValidAuthCredentials(!1);if(!r)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:r.token}}}async getAuthHeaders(){if(this.method=="basic")return{authorization:"Basic "+this.basicKey};{let r=await this._ensureValidAuthCredentials(!1);if(!r)throw new Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+Us(r.token)}}}_saveBasicOptions(r){this.method="basic",this.key=r.key,this.basicKey=Us(r.key),this.authOptions=r||{},"clientId"in r&&this._userSetClientId(r.clientId)}_saveTokenOptions(r,n){this.method="token",r&&(this.tokenParams=r),n&&(n.token&&(n.tokenDetails=typeof n.token=="string"?{token:n.token}:n.token),n.tokenDetails&&(this.tokenDetails=n.tokenDetails),"clientId"in n&&this._userSetClientId(n.clientId),this.authOptions=n)}async _ensureValidAuthCredentials(r){let n=this.tokenDetails;if(n){if(this._tokenClientIdMismatch(n.clientId))throw new x("Mismatch between clientId in token ("+n.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!n.expires||n.expires>=this.client.getTimestampUsingOffset())return d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+n.expires),n;d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let o=(this.waitingForTokenRequest||(this.waitingForTokenRequest=ca.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!r)return o;let c=this.currentTokenRequestId=jf(),u,f=null;try{u=await this.requestToken(this.tokenParams,this.authOptions)}catch(_){f=_}if(this.currentTokenRequestId>c)return d.logAction(this.logger,d.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),o;this.currentTokenRequestId=null;let y=this.waitingForTokenRequest;return this.waitingForTokenRequest=null,f?(y?.rejectAll(f),o):(y?.resolveAll(this.tokenDetails=u),o)}_userSetClientId(r){if(typeof r=="string"||r===null){if(r==="*")throw new x('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{let n=this._uncheckedSetClientId(r);if(n)throw n}}else throw new x("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(r){if(this._tokenClientIdMismatch(r)){let n="Unexpected clientId mismatch: client has "+this.clientId+", requested "+r,o=new x(n,40102,401);return d.logAction(this.logger,d.LOG_ERROR,"Auth._uncheckedSetClientId()",n),o}else return this.clientId=this.tokenParams.clientId=r,null}_tokenClientIdMismatch(r){return!!(this.clientId&&this.clientId!=="*"&&r&&r!=="*"&&this.clientId!==r)}static isTokenErr(r){return r.code&&r.code>=40140&&r.code<40150}revokeTokens(r,n){return this.client.rest.revokeTokens(r,n)}async _getTimestamp(r){return this.client.getTimestamp(r||!!this.authOptions.queryTime)}},We=Df;function er(r){let n=[];if(r)for(let o in r)n.push(o+"="+r[o]);return n.join("&")}function St(r,n){return r+(n?"?":"")+er(n)}function Uf(r,n,o,c,u){r.error?d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received Error; "+St(o,c)+"; Error: "+ee(r.error)):d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received; "+St(o,c)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+r.body))}function qf(r,n,o,c,u){u.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(u,d.LOG_MICRO,"Http."+r+"()","Sending; "+St(n,c)+"; Body"+(L.BufferUtils.isBuffer(o)?" (Base64): "+L.BufferUtils.base64Encode(o):": "+o))}var tr=class{constructor(r){this.client=r,this.platformHttp=new L.Http(r),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var r,n;return(n=(r=this.client)==null?void 0:r.logger)!=null?n:d.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(r){let n=r.connection,o=n&&n.connectionManager.host;return o?[o].concat(J.getFallbackHosts(r.options)):J.getHosts(r.options)}async do(r,n,o,c,u){try{let f=this.client;if(!f)return{error:new x("http.do called without client",5e4,500)};let y=typeof n=="function"?n:function(j){return f.baseUri(j)+n},_=f._currentFallback;if(_)if(_.validUntil>Date.now()){let j=await this.doUri(r,y(_.host),o,c,u);return j.error&&this.platformHttp.shouldFallback(j.error)?(f._currentFallback=null,this.do(r,n,o,c,u)):j}else f._currentFallback=null;let T=this._getHosts(f);if(T.length===1)return this.doUri(r,y(T[0]),o,c,u);let I=null,D=async(j,F)=>{let w=j.shift();I=I??new Date;let R=await this.doUri(r,y(w),o,c,u);return R.error&&this.platformHttp.shouldFallback(R.error)&&j.length?Date.now()-I.getTime()>f.options.timeouts.httpMaxRetryDuration?{error:new x(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${f.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:D(j,!0):(F&&(f._currentFallback={host:w,validUntil:Date.now()+f.options.timeouts.fallbackRetryTimeout}),R)};return D(T)}catch(f){return{error:new x(`Unexpected error in Http.do: ${ee(f)}`,500,5e4)}}}async doUri(r,n,o,c,u){try{qf(r,n,c,u,this.logger);let f=await this.platformHttp.doUri(r,n,o,c,u);return this.logger.shouldLog(d.LOG_MICRO)&&Uf(f,r,n,u,this.logger),f}catch(f){return{error:new x(`Unexpected error in Http.doUri: ${ee(f)}`,500,5e4)}}}};function Bf(r,n,o,c){try{o.apply(n,c)}catch(u){d.logAction(r,d.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+u+"; stack = "+(u&&u.stack))}}function sr(r,n,o){let c,u,f;for(let y=0;y<r.length;y++)if(c=r[y],o&&(c=c[o]),Array.isArray(c)){for(;(u=c.indexOf(n))!==-1;)c.splice(u,1);o&&c.length===0&&delete r[y][o]}else if(Ot(c))for(f in c)Object.prototype.hasOwnProperty.call(c,f)&&Array.isArray(c[f])&&sr([c],n,f)}var $f=class{constructor(r){this.logger=r,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...r){if(r.length===1){let n=r[0];if(typeof n=="function")this.any.push(n);else throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r))}if(r.length===2){let[n,o]=r;if(typeof o!="function")throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r));if(Fe(n))this.any.push(o);else if(Array.isArray(n))n.forEach(c=>{this.on(c,o)});else{if(typeof n!="string")throw new Error("EventListener.on(): Invalid arguments: "+L.Config.inspect(r));(this.events[n]||(this.events[n]=[])).push(o)}}}off(...r){if(r.length==0||Fe(r[0])&&Fe(r[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[n,o]=r,c=null,u=null;if(r.length===1||!o)typeof n=="function"?c=n:u=n;else{if(typeof o!="function")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));[u,c]=[n,o]}if(c&&Fe(u)){sr([this.any,this.events,this.anyOnce,this.eventsOnce],c);return}if(Array.isArray(u)){u.forEach(f=>{this.off(f,c)});return}if(typeof u!="string")throw new Error("EventEmitter.off(): invalid arguments:"+L.Config.inspect(r));c?sr([this.events,this.eventsOnce],c,u):(delete this.events[u],delete this.eventsOnce[u])}listeners(r){if(r){let n=this.events[r]||[];return this.eventsOnce[r]&&Array.prototype.push.apply(n,this.eventsOnce[r]),n.length?n:null}return this.any.length?this.any:null}emit(r,...n){let o={event:r},c=[];this.anyOnce.length&&(Array.prototype.push.apply(c,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(c,this.any);let u=this.eventsOnce[r];u&&(Array.prototype.push.apply(c,u),delete this.eventsOnce[r]);let f=this.events[r];f&&Array.prototype.push.apply(c,f),c.forEach(y=>{Bf(this.logger,o,y,n)})}once(...r){let n=r.length;if(n===0||n===1&&typeof r[0]!="function"){let u=r[0];return new Promise(f=>{this.once(u,f)})}let[o,c]=r;if(r.length===1&&typeof o=="function")this.anyOnce.push(o);else if(Fe(o)){if(typeof c!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));this.anyOnce.push(c)}else if(Array.isArray(o)){let u=this,f=function(){let y=Array.prototype.slice.call(arguments);if(o.forEach(function(_){u.off(_,f)}),typeof c!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));c.apply(this,y)};o.forEach(function(y){u.on(y,f)})}else{if(typeof o!="string")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));let u=this.eventsOnce[o]||(this.eventsOnce[o]=[]);if(c){if(typeof c!="function")throw new Error("EventEmitter.once(): Invalid arguments:"+L.Config.inspect(r));u.push(c)}}}async whenState(r,n){if(typeof r!="string"||typeof n!="string")throw new Error("whenState requires a valid state String argument");return r===n?null:this.once(r)}},he=$f,z={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},ga=[];Object.keys(z).forEach(function(r){ga[z[r]]=r});var ve={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:1<<17,SUBSCRIBE:1<<18,PRESENCE_SUBSCRIBE:1<<19,ANNOTATION_PUBLISH:1<<21,ANNOTATION_SUBSCRIBE:1<<22,OBJECT_SUBSCRIBE:1<<24,OBJECT_PUBLISH:1<<25},Hf=Object.keys(ve);ve.MODE_ALL=ve.PRESENCE|ve.PUBLISH|ve.SUBSCRIBE|ve.PRESENCE_SUBSCRIBE|ve.ANNOTATION_PUBLISH|ve.ANNOTATION_SUBSCRIBE|ve.OBJECT_SUBSCRIBE|ve.OBJECT_PUBLISH;var ma=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Gf(r){return!r||!r.channelOptions?{channelOptions:r,plugins:{},baseEncodedPreviousPayload:void 0}:r}function ya(r,n,o){if(o&&o.cipher){r||pe("Crypto");let c=r.getCipher(o.cipher,n);return{cipher:c.cipherParams,channelCipher:c.cipher}}return o??{}}async function Ff(r,n){let{data:o,encoding:c}=await _a(r.data,r.encoding,n);return r.data=o,r.encoding=c,r}async function _a(r,n,o){let c=o.channelCipher,u=r,f=n?n+"/":"";L.BufferUtils.isBuffer(u)||(u=L.BufferUtils.utf8Encode(String(u)),f=f+"utf-8/");let y=await c.encrypt(u);return f=f+"cipher+"+c.algorithm,{data:y,encoding:f}}async function nr(r,n){let{data:o,encoding:c}=ba(r.data,r.encoding);return r.data=o,r.encoding=c,n!=null&&n.cipher?Ff(r,n):r}function ba(r,n){if(typeof r=="string"||L.BufferUtils.isBuffer(r)||r===null||r===void 0)return{data:r,encoding:n};if(Ot(r)||Array.isArray(r))return{data:JSON.stringify(r),encoding:n?n+"/json":"json"};throw new x("Data type is unsupported",40013,400)}async function rr(r,n){let{data:o,encoding:c,error:u}=await va(r.data,r.encoding,n);if(r.data=o,r.encoding=c,u)throw u}async function va(r,n,o){let c=Gf(o),u=r,f=r,y=n,_;if(n){let T=n.split("/"),I,D=T.length,j="";try{for(;(I=D)>0;){let F=T[--D].match(/([-\w]+)(\+([\w-]+))?/);if(!F)break;switch(j=F[1],j){case"base64":f=L.BufferUtils.base64Decode(String(f)),I==T.length&&(u=f);continue;case"utf-8":f=L.BufferUtils.utf8Decode(f);continue;case"json":f=JSON.parse(f);continue;case"cipher":if(c.channelOptions!=null&&c.channelOptions.cipher&&c.channelOptions.channelCipher){let w=F[3],R=c.channelOptions.channelCipher;if(w!=R.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");f=await R.decrypt(f);continue}else throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!c.plugins||!c.plugins.vcdiff)throw new x("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new x("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let w=c.baseEncodedPreviousPayload;typeof w=="string"&&(w=L.BufferUtils.utf8Encode(w));let R=L.BufferUtils.toBuffer(w);f=L.BufferUtils.toBuffer(f),f=L.BufferUtils.arrayBufferViewToBuffer(c.plugins.vcdiff.decode(f,R)),u=f}catch(w){throw new x("Vcdiff delta decode failed with "+w,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(F){let w=F;_=new x(`Error processing the ${j} encoding, decoder returned \u2018${w.message}\u2019`,w.code||40013,400)}finally{y=I<=0?null:T.slice(0,I).join("/")}}return _?{error:_,data:f,encoding:y}:(c.baseEncodedPreviousPayload=u,{data:f,encoding:y})}function ir(...r){let n=r.length>0?"json":"msgpack",{data:o,encoding:c}=wa(this.data,this.encoding,n);return Object.assign({},this,{encoding:c,data:o})}function wa(r,n,o){return!r||!L.BufferUtils.isBuffer(r)?{data:r,encoding:n}:o==="msgpack"?{data:L.BufferUtils.toBuffer(r),encoding:n}:{data:L.BufferUtils.base64Encode(r),encoding:n?n+"/base64":"base64"}}var Bs={encryptData:_a,encodeData:ba,encodeDataForWire:wa,decodeData:va};function $s(r){let{id:n,connectionId:o,timestamp:c}=r,u;switch(r.action){case z.MESSAGE:{u=r.messages;break}case z.PRESENCE:case z.SYNC:u=r.presence;break;case z.ANNOTATION:u=r.annotations;break;case z.OBJECT:case z.OBJECT_SYNC:u=r.state;break;default:throw new x("Unexpected action "+r.action,4e4,400)}for(let f=0;f<u.length;f++){let y=u[f];y.connectionId||(y.connectionId=o),y.timestamp||(y.timestamp=c),n&&!y.id&&(y.id=n+":"+f)}}function Tt(r,n){let o="["+n;for(let c in r)c==="data"?typeof r.data=="string"?o+="; data="+r.data:L.BufferUtils.isBuffer(r.data)?o+="; data (buffer)="+L.BufferUtils.base64Encode(r.data):typeof r.data<"u"&&(o+="; data (json)="+JSON.stringify(r.data)):c&&(c==="extras"||c==="operation")?o+="; "+c+"="+JSON.stringify(r[c]):c==="version"?o+="; version="+JSON.stringify(r[c]):c==="annotations"?o+="; annotations="+JSON.stringify(r[c]):r[c]!==void 0&&(o+="; "+c+"="+r[c]);return o+="]",o}var At=class{},Ca=class{constructor(r){this.Platform=L,this.ErrorInfo=x,this.Logger=d,this.Defaults=J,this.Utils=Zt,this.EventEmitter=he,this.MessageEncoding=Bs;var n,o,c,u,f,y,_,T,I,D;this._additionalHTTPRequestImplementations=(n=r.plugins)!=null?n:null,this.logger=new d,this.logger.setLog(r.logLevel,r.logHandler),d.logAction(this.logger,d.LOG_MICRO,"BaseClient()","initialized with clientOptions "+L.Config.inspect(r)),this._MsgPack=(c=(o=r.plugins)==null?void 0:o.MsgPack)!=null?c:null;let j=this.options=J.normaliseOptions(r,this._MsgPack,this.logger);if(j.key){let F=j.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!F){let w="invalid key parameter";throw d.logAction(this.logger,d.LOG_ERROR,"BaseClient()",w),new x(w,40400,404)}j.keyName=F[1],j.keySecret=F[2]}if("clientId"in j)if(typeof j.clientId=="string"||j.clientId===null){if(j.clientId==="*")throw new x('Can\u2019t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}else throw new x("clientId must be either a string or null",40012,400);d.logAction(this.logger,d.LOG_MINOR,"BaseClient()","started; version = "+J.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new tr(this),this.auth=new We(this,j),this._rest=(u=r.plugins)!=null&&u.Rest?new r.plugins.Rest(this):null,this._Crypto=(y=(f=r.plugins)==null?void 0:f.Crypto)!=null?y:null,this.__FilteredSubscriptions=(T=(_=r.plugins)==null?void 0:_.MessageInteractions)!=null?T:null,this._Annotations=(D=(I=r.plugins)==null?void 0:I.Annotations)!=null?D:null}get rest(){return this._rest||pe("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||pe("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var r;return(!((r=this.options.plugins)!=null&&r.Push)||!this.push.LocalDevice)&&pe("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(r){return J.getHttpScheme(this.options)+r+":"+J.getPort(this.options,!1)}async stats(r){return this.rest.stats(r)}async time(r){return this.rest.time(r)}async request(r,n,o,c,u,f){return this.rest.request(r,n,o,c,u,f)}batchPublish(r){return this.rest.batchPublish(r)}batchPresence(r){return this.rest.batchPresence(r)}setLog(r){this.logger.setLog(r.level,r.handler)}async getTimestamp(r){return!this.isTimeOffsetSet()&&r?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return this.serverTimeOffset!==null}};Ca.Platform=L;var Ea=Ca,Wf=class Qt{toJSON(){var n,o,c;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:(n=this.push)==null?void 0:n.recipient,state:(o=this.push)==null?void 0:o.state,error:(c=this.push)==null?void 0:c.error}}}toString(){var n,o,c,u;let f="[DeviceDetails";return this.id&&(f+="; id="+this.id),this.platform&&(f+="; platform="+this.platform),this.formFactor&&(f+="; formFactor="+this.formFactor),this.clientId&&(f+="; clientId="+this.clientId),this.metadata&&(f+="; metadata="+this.metadata),this.deviceIdentityToken&&(f+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(n=this.push)!=null&&n.recipient&&(f+="; push.recipient="+JSON.stringify(this.push.recipient)),(o=this.push)!=null&&o.state&&(f+="; push.state="+this.push.state),(c=this.push)!=null&&c.error&&(f+="; push.error="+JSON.stringify(this.push.error)),(u=this.push)!=null&&u.metadata&&(f+="; push.metadata="+this.push.metadata),f+="]",f}static toRequestBody(n,o,c){return je(n,o,c)}static fromResponseBody(n,o,c){return c&&(n=ue(n,o,c)),Array.isArray(n)?Qt.fromValuesArray(n):Qt.fromValues(n)}static fromValues(n){return n.error=n.error&&x.fromValues(n.error),Object.assign(new Qt,n)}static fromLocalDevice(n){return Object.assign(new Qt,n)}static fromValuesArray(n){let o=n.length,c=new Array(o);for(let u=0;u<o;u++)c[u]=Qt.fromValues(n[u]);return c}},Rt=Wf;async function ka(r,n,o,c){if(r.http.supportsAuthHeaders){let u=await r.auth.getAuthHeaders();return c(Y(u,n),o)}else{let u=await r.auth.getAuthParams();return c(n,Y(u,o))}}function Vf(r,n,o){if(r.err&&!r.body)return{err:r.err};if(r.statusCode===ns.NoContent)return O(E({},r),{body:[],unpacked:!0});let c=r.body;if(!r.unpacked)try{c=ue(c,n,o)}catch(_){return Jn(_)?{err:_}:{err:new Ee(ee(_),null)}}if(!c)return{err:new Ee("unenvelope(): Response body is missing",null)};let{statusCode:u,response:f,headers:y}=c;if(u===void 0)return O(E({},r),{body:c,unpacked:!0});if(u<200||u>=300){let _=f&&f.error||r.err;return _||(_=new Error("Error in unenveloping "+c),_.statusCode=u),{err:_,body:f,headers:y,unpacked:!0,statusCode:u}}return{err:r.err,body:f,headers:y,unpacked:!0,statusCode:u}}function zf(r,n,o,c,u){r.err?d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received Error; "+St(o,c)+"; Error: "+ee(r.err)):d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received; "+St(o,c)+"; Headers: "+er(r.headers)+"; StatusCode: "+r.statusCode+"; Body: "+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+L.Config.inspect(r.body)))}var Kf=class Xt{static async get(n,o,c,u,f,y){return Xt.do(ce.Get,n,o,null,c,u,f,y??!1)}static async delete(n,o,c,u,f,y){return Xt.do(ce.Delete,n,o,null,c,u,f,y)}static async post(n,o,c,u,f,y,_){return Xt.do(ce.Post,n,o,c,u,f,y,_)}static async patch(n,o,c,u,f,y,_){return Xt.do(ce.Patch,n,o,c,u,f,y,_)}static async put(n,o,c,u,f,y,_){return Xt.do(ce.Put,n,o,c,u,f,y,_)}static async do(n,o,c,u,f,y,_,T){_&&((y=y||{}).envelope=_);let I=o.logger;async function D(F,w){var R;if(I.shouldLog(d.LOG_MICRO)){let U=u;if(((R=F["content-type"])==null?void 0:R.indexOf("msgpack"))>0)try{o._MsgPack||pe("MsgPack"),U=o._MsgPack.decode(u)}catch(G){d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending MsgPack Decoding Error: "+ee(G))}d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending; "+St(c,w)+"; Body: "+U)}let P=await o.http.do(n,c,F,u,w);return P.error&&We.isTokenErr(P.error)?(await o.auth.authorize(null,null),ka(o,F,w,D)):{err:P.error,body:P.body,headers:P.headers,unpacked:P.unpacked,statusCode:P.statusCode}}let j=await ka(o,f,y,D);if(_&&(j=Vf(j,o._MsgPack,_)),I.shouldLog(d.LOG_MICRO)&&zf(j,n,c,y,I),T){if(j.err)throw j.err;{let F=E({},j);return delete F.err,F}}return j}},ie=Kf;function Jf(r){let n=r.match(/^\.\/(\w+)\?(.*)$/);return n&&n[2]&&Ds(n[2])}function Yf(r){typeof r=="string"&&(r=r.split(","));let n={};for(let o=0;o<r.length;o++){let c=r[o].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(c){let u=Jf(c[1]);u&&(n[c[2]]=u)}}return n}function Qf(r,n,o){return!(o&&(n||typeof r.code=="number"))}var Xf=class{constructor(r,n,o,c,u,f){this.client=r,this.path=n,this.headers=o,this.envelope=c??null,this.bodyHandler=u,this.useHttpPaginatedResponse=f||!1}get logger(){return this.client.logger}async get(r){let n=await ie.get(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async delete(r){let n=await ie.delete(this.client,this.path,this.headers,r,this.envelope,!1);return this.handlePage(n)}async post(r,n){let o=await ie.post(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async put(r,n){let o=await ie.put(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async patch(r,n){let o=await ie.patch(this.client,this.path,n,this.headers,r,this.envelope,!1);return this.handlePage(o)}async handlePage(r){if(r.err&&Qf(r.err,r.body,this.useHttpPaginatedResponse))throw d.logAction(this.logger,d.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+ee(r.err)),r.err;let n,o,c;try{n=r.statusCode==ns.NoContent?[]:await this.bodyHandler(r.body,r.headers||{},r.unpacked)}catch(u){throw r.err||u}return r.headers&&(o=r.headers.Link||r.headers.link)&&(c=Yf(o)),this.useHttpPaginatedResponse?new Zf(this,n,r.headers||{},r.statusCode,c,r.err):new Oa(this,n,c)}},Oa=class{constructor(r,n,o){this.resource=r,this.items=n,this._relParams=o}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new x("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new x("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return this._relParams!=null&&"first"in this._relParams}hasCurrent(){return this._relParams!=null&&"current"in this._relParams}hasNext(){return this._relParams!=null&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(r){let n=this.resource,o=await ie.get(n.client,n.path,n.headers,r,n.envelope,!1);return n.handlePage(o)}},Zf=class extends Oa{constructor(r,n,o,c,u,f){super(r,n,u),this.statusCode=c,this.success=c<300&&c>=200,this.headers=o,this.errorCode=f&&f.code,this.errorMessage=f&&f.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},Ue=Xf,Sa=class Ms{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let n="[PushChannelSubscription";return this.channel&&(n+="; channel="+this.channel),this.deviceId&&(n+="; deviceId="+this.deviceId),this.clientId&&(n+="; clientId="+this.clientId),n+="]",n}static fromResponseBody(n,o,c){return c&&(n=ue(n,o,c)),Array.isArray(n)?Ms.fromValuesArray(n):Ms.fromValues(n)}static fromValues(n){return Object.assign(new Ms,n)}static fromValuesArray(n){let o=n.length,c=new Array(o);for(let u=0;u<o;u++)c[u]=Ms.fromValues(n[u]);return c}};Sa.toRequestBody=je;var ep=Sa,Hs=ep,tp=class{constructor(r){var n;this.client=r,this.admin=new sp(r),L.Config.push&&((n=r.options.plugins)!=null&&n.Push)&&(this.stateMachine=new r.options.plugins.Push.ActivationStateMachine(r),this.LocalDevice=r.options.plugins.Push.localDeviceFactory(Rt))}async activate(r,n){await new Promise((o,c)=>{var u;if(!((u=this.client.options.plugins)!=null&&u.Push)){c(ss("Push"));return}if(!this.stateMachine){c(new x("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){c(new x("Activation already in progress",4e4,400));return}this.stateMachine.activatedCallback=f=>{if(f){c(f);return}o()},this.stateMachine.updateFailedCallback=n,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,r))})}async deactivate(r){await new Promise((n,o)=>{var c;if(!((c=this.client.options.plugins)!=null&&c.Push)){o(ss("Push"));return}if(!this.stateMachine){o(new x("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){o(new x("Deactivation already in progress",4e4,400));return}this.stateMachine.deactivatedCallback=u=>{if(u){o(u);return}n()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,r))})}},sp=class{constructor(r){this.client=r,this.deviceRegistrations=new np(r),this.channelSubscriptions=new rp(r)}async publish(r,n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=J.defaultPostHeaders(o.options),f={},y=Y({recipient:r},n);Y(u,o.options.headers),o.options.pushFullWait&&Y(f,{fullWait:"true"});let _=je(y,o._MsgPack,c);await ie.post(o,"/push/publish",_,u,f,null,!0)}},np=class{constructor(r){this.client=r}async save(r){let n=this.client,o=Rt.fromValues(r),c=n.options.useBinaryProtocol?"msgpack":"json",u=J.defaultPostHeaders(n.options),f={};Y(u,n.options.headers),n.options.pushFullWait&&Y(f,{fullWait:"true"});let y=je(o,n._MsgPack,c),_=await ie.put(n,"/push/deviceRegistrations/"+encodeURIComponent(r.id),y,u,f,null,!0);return Rt.fromResponseBody(_.body,n._MsgPack,_.unpacked?void 0:c)}async get(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=J.defaultGetHeaders(n.options),u=r.id||r;if(typeof u!="string"||!u.length)throw new x("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);Y(c,n.options.headers);let f=await ie.get(n,"/push/deviceRegistrations/"+encodeURIComponent(u),c,{},null,!0);return Rt.fromResponseBody(f.body,n._MsgPack,f.unpacked?void 0:o)}async list(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:o,u=J.defaultGetHeaders(n.options);return Y(u,n.options.headers),new Ue(n,"/push/deviceRegistrations",u,c,async function(f,y,_){return Rt.fromResponseBody(f,n._MsgPack,_?void 0:o)}).get(r)}async remove(r){let n=this.client,o=J.defaultGetHeaders(n.options),c={},u=r.id||r;if(typeof u!="string"||!u.length)throw new x("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);Y(o,n.options.headers),n.options.pushFullWait&&Y(c,{fullWait:"true"}),await ie.delete(n,"/push/deviceRegistrations/"+encodeURIComponent(u),o,c,null,!0)}async removeWhere(r){let n=this.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=J.defaultGetHeaders(n.options,{format:o});Y(c,n.options.headers),n.options.pushFullWait&&Y(r,{fullWait:"true"}),await ie.delete(n,"/push/deviceRegistrations",c,r,null,!0)}},rp=class Rd{constructor(n){this.remove=Rd.prototype.removeWhere,this.client=n}async save(n){let o=this.client,c=Hs.fromValues(n),u=o.options.useBinaryProtocol?"msgpack":"json",f=J.defaultPostHeaders(o.options),y={};Y(f,o.options.headers),o.options.pushFullWait&&Y(y,{fullWait:"true"});let _=je(c,o._MsgPack,u),T=await ie.post(o,"/push/channelSubscriptions",_,f,y,null,!0);return Hs.fromResponseBody(T.body,o._MsgPack,T.unpacked?void 0:u)}async list(n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:c,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),new Ue(o,"/push/channelSubscriptions",f,u,async function(y,_,T){return Hs.fromResponseBody(y,o._MsgPack,T?void 0:c)}).get(n)}async removeWhere(n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=J.defaultGetHeaders(o.options,{format:c});Y(u,o.options.headers),o.options.pushFullWait&&Y(n,{fullWait:"true"}),await ie.delete(o,"/push/channelSubscriptions",u,n,null,!0)}async listChannels(n){let o=this.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=this.client.http.supportsLinkHeaders?void 0:c,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),o.options.pushFullWait&&Y(n,{fullWait:"true"}),new Ue(o,"/push/channels",f,u,async function(y,_,T){let I=!T&&c?ue(y,o._MsgPack,c):y;for(let D=0;D<I.length;D++)I[D]=String(I[D]);return I}).get(n)}},ip=tp,Ta=["absent","present","enter","leave","update"];async function Aa(r,n,o,c){let u=ya(n,r,c??null);return rs.fromValues(o).decode(u,r)}async function op(r,n,o,c){return Promise.all(o.map(function(u){return Aa(r,n,u,c)}))}async function ap(r,n){return rs.fromValues(r).decode(n.channelOptions,n.logger)}async function Ra(r,n){return Promise.all(r.map(function(o){return ap(o,n)}))}var Pa=class xs extends At{isSynthesized(){return!this.id||!this.connectionId?!0:this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw new Error("parseId(): Presence message does not contain an id");let n=this.id.split(":");return{connectionId:n[0],msgSerial:parseInt(n[1],10),index:parseInt(n[2],10)}}async encode(n){let o=Object.assign(new rs,this,{action:Ta.indexOf(this.action||"present")});return nr(o,n)}static fromValues(n){return Object.assign(new xs,n)}static fromValuesArray(n){return n.map(o=>xs.fromValues(o))}static fromData(n){return n instanceof xs?n:xs.fromValues({data:n})}toString(){return Tt(this,"PresenceMessage")}},rs=class yo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new yo,n)}static fromValuesArray(n){return n.map(o=>yo.fromValues(o))}async decode(n,o){let c=Object.assign(new Pa,O(E({},this),{action:Ta[this.action]}));try{await rr(c,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WirePresenceMessage.decode()",ee(u))}return c}toString(){return Tt(this,"WirePresenceMessage")}},Ve=Pa,cp=class{constructor(r){this.channel=r}get logger(){return this.channel.logger}async get(r){d.logAction(this.logger,d.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);let n=this.channel.client,o=n.options.useBinaryProtocol?"msgpack":"json",c=this.channel.client.http.supportsLinkHeaders?void 0:o,u=J.defaultGetHeaders(n.options);return Y(u,n.options.headers),new Ue(n,this.channel.client.rest.presenceMixin.basePath(this),u,c,async(f,y,_)=>{let T=_?f:ue(f,n._MsgPack,o);return Ra(T,this.channel)}).get(r)}async history(r){return d.logAction(this.logger,d.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,r)}},lp=cp,Ia=["message.create","message.update","message.delete","meta","message.summary","message.append"];function up(r){return Ia[r||0]||"unknown"}function hp(r){let n=0;return r.name&&(n+=r.name.length),r.clientId&&(n+=r.clientId.length),r.extras&&(n+=JSON.stringify(r.extras).length),r.data&&(n+=Ho(r.data)),n}async function Ma(r,n,o,c){let u=ya(n,r,c??null);return is.fromValues(o).decode(u,r)}async function dp(r,n,o,c){return Promise.all(o.map(function(u){return Ma(r,n,u,c)}))}async function xa(r,n){return is.fromValues(r).decode(n.channelOptions,n.logger)}async function Na(r,n){return Promise.all(r.map(function(o){return xa(o,n)}))}async function La(r,n){return Promise.all(r.map(o=>o.encode(n)))}var ja=je;function Da(r){let n,o=0;for(let c=0;c<r.length;c++)n=r[c],o+=n.size||(n.size=hp(n));return o}var Ua=class _o extends At{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(let[n,o]of Object.entries(this.annotations.summary))if(n.endsWith(":distinct.v1")||n.endsWith(":unique.v1")||n.endsWith(":multiple.v1"))for(let[,c]of Object.entries(o))c.clipped||(c.clipped=!1);else n.endsWith(":flag.v1")&&(o.clipped||(o.clipped=!1))}async encode(n){let o=Object.assign(new is,this,{action:Ia.indexOf(this.action||"message.create")});return nr(o,n)}static fromValues(n){return Object.assign(new _o,n)}static fromValuesArray(n){return n.map(o=>_o.fromValues(o))}toString(){return Tt(this,"Message")}},is=class bo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new bo,n)}static fromValuesArray(n){return n.map(o=>bo.fromValues(o))}async decodeWithErr(n,o){let c=Object.assign(new Ua,O(E({},this),{action:up(this.action)})),u;try{await rr(c,n)}catch(f){d.logAction(o,d.LOG_ERROR,"WireMessage.decode()",ee(f)),u=f}return c.expandFields(),{decoded:c,err:u}}async decode(n,o){let{decoded:c}=await this.decodeWithErr(n,o);return c}toString(){return Tt(this,"WireMessage")}},$e=Ua,fp=9;function pp(r){return r.every(function(n){return!n.id})}var gp=class{constructor(r,n,o){this._annotations=null;var c,u;d.logAction(r.logger,d.LOG_MINOR,"RestChannel()","started; name = "+n),this.name=n,this.client=r,this.presence=new lp(this),this.channelOptions=qs((c=r._Crypto)!=null?c:null,this.logger,o),(u=r.options.plugins)!=null&&u.Push&&(this._push=new r.options.plugins.Push.PushChannel(this)),r._Annotations&&(this._annotations=new r._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||pe("Annotations"),this._annotations}get push(){return this._push||pe("Push"),this._push}get logger(){return this.client.logger}setOptions(r){var n;this.channelOptions=qs((n=this.client._Crypto)!=null?n:null,this.logger,r)}async history(r){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,r)}async publish(...r){let n=r[0],o=r[1],c,u;if(typeof n=="string"||n===null)c=[$e.fromValues({name:n,data:o})],u=r[2];else if(Ot(n))c=[$e.fromValues(n)],u=r[1];else if(Array.isArray(n))c=$e.fromValuesArray(n),u=r[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);u||(u={});let f=this.client,y=f.options,_=y.useBinaryProtocol?"msgpack":"json",T=f.options.idempotentRestPublishing,I=J.defaultPostHeaders(f.options);if(Y(I,y.headers),T&&pp(c)){let w=await Fo(fp);c.forEach(function(R,P){R.id=w+":"+P.toString()})}let D=await La(c,this.channelOptions),j=Da(D),F=y.maxMessageSize;if(j>F)throw new x(`Maximum size of messages that can be published at once exceeded (was ${j} bytes; limit is ${F} bytes)`,40009,400);return this._publish(ja(D,f._MsgPack,_),I,u)}async _publish(r,n,o){let c=this.client,u=c.options.useBinaryProtocol?"msgpack":"json",{body:f,unpacked:y}=await ie.post(c,c.rest.channelMixin.basePath(this)+"/messages",r,n,o,null,!0),_=(y?f:ue(f,c._MsgPack,u))||{};return delete _.channel,delete _.messageId,_}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(r){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,r)}async updateMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",r,n,o)}async deleteMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",r,n,o)}async appendMessage(r,n,o){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",r,n,o)}async getMessageVersions(r,n){return d.logAction(this.logger,d.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,r,n)}},mp=gp,yp=class Pd{constructor(n){this.entries=n&&n.entries||void 0,this.schema=n&&n.schema||void 0,this.appId=n&&n.appId||void 0,this.inProgress=n&&n.inProgress||void 0,this.unit=n&&n.unit||void 0,this.intervalId=n&&n.intervalId||void 0}static fromValues(n){return new Pd(n)}},_p=yp,qa=class{static basePath(r){return"/channels/"+encodeURIComponent(r.name)}static history(r,n){let o=r.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=r.client.http.supportsLinkHeaders?void 0:c,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),new Ue(o,this.basePath(r)+"/messages",f,u,async function(y,_,T){let I=T?y:ue(y,o._MsgPack,c);return Na(I,r)}).get(n)}static async status(r){let n=r.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultPostHeaders(r.client.options);return(await ie.get(r.client,this.basePath(r),o,{},n,!0)).body}static async getMessage(r,n){let o=typeof n=="string"?n:n.serial;if(!o)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let c=r.client,u=c.options.useBinaryProtocol?"msgpack":"json",f=J.defaultGetHeaders(c.options);Y(f,c.options.headers);let{body:y,unpacked:_}=await ie.get(c,this.basePath(r)+"/messages/"+encodeURIComponent(o),f,{},null,!0),T=_?y:ue(y,c._MsgPack,u);return xa(T,r)}static async updateDeleteMessage(r,n,o,c,u){if(!o.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let f=r.client,y=f.options.useBinaryProtocol?"msgpack":"json",_=J.defaultPostHeaders(f.options);Y(_,f.options.headers);let T=$e.fromValues(o);T.action=n,T.version=c;let I=await T.encode(r.channelOptions),D=ja(I,f._MsgPack,y),j=ie.patch,{body:F,unpacked:w}=await j(f,this.basePath(r)+"/messages/"+encodeURIComponent(o.serial),D,_,u||{},null,!0);return(w?F:ue(F,f._MsgPack,y))||{versionSerial:null}}static getMessageVersions(r,n,o){let c=typeof n=="string"?n:n.serial;if(!c)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let u=r.client,f=u.options.useBinaryProtocol?"msgpack":"json",y=r.client.http.supportsLinkHeaders?void 0:f,_=J.defaultGetHeaders(u.options);return Y(_,u.options.headers),new Ue(u,this.basePath(r)+"/messages/"+encodeURIComponent(c)+"/versions",_,y,async(T,I,D)=>{let j=D?T:ue(T,u._MsgPack,f);return Na(j,r)}).get(o||{})}},bp=class{static basePath(r){return qa.basePath(r.channel)+"/presence"}static async history(r,n){let o=r.channel.client,c=o.options.useBinaryProtocol?"msgpack":"json",u=r.channel.client.http.supportsLinkHeaders?void 0:c,f=J.defaultGetHeaders(o.options);return Y(f,o.options.headers),new Ue(o,this.basePath(r)+"/history",f,u,async(y,_,T)=>{let I=T?y:ue(y,o._MsgPack,c);return Ra(I,r.channel)}).get(n)}},Ba=class{constructor(r){this.channelMixin=qa,this.presenceMixin=bp,this.Resource=ie,this.PaginatedResource=Ue,this.DeviceDetails=Rt,this.PushChannelSubscription=Hs,this.client=r,this.channels=new vp(this.client),this.push=new ip(this.client)}async stats(r){let n=J.defaultGetHeaders(this.client.options),o=this.client.options.useBinaryProtocol?"msgpack":"json",c=this.client.http.supportsLinkHeaders?void 0:o;return Y(n,this.client.options.headers),new Ue(this.client,"/stats",n,c,async(u,f,y)=>{let _=y?u:ue(u,this.client._MsgPack,o);for(let T=0;T<_.length;T++)_[T]=_p.fromValues(_[T]);return _}).get(r)}async time(r){let n=J.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&Y(n,this.client.options.headers);let o=_=>this.client.baseUri(_)+"/time",{error:c,body:u,unpacked:f}=await this.client.http.do(ce.Get,o,n,null,r);if(c)throw c;f||(u=JSON.parse(u));let y=u[0];if(!y)throw new x("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=y-Date.now(),y}async request(r,n,o,c,u,f){var y;let[_,T,I]=this.client.options.useBinaryProtocol?(this.client._MsgPack||pe("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],D=this.client.http.supportsLinkHeaders?void 0:I;c=c||{};let j=r.toLowerCase(),F=j=="get"?J.defaultGetHeaders(this.client.options,{format:I,protocolVersion:o}):J.defaultPostHeaders(this.client.options,{format:I,protocolVersion:o});typeof u!="string"&&(u=(y=_(u))!=null?y:null),Y(F,this.client.options.headers),f&&Y(F,f);let w=new Ue(this.client,n,F,D,async function(R,P,U){return Mo(U?R:T(R))},!0);if(!L.Http.methods.includes(j))throw new x("Unsupported method "+j,40500,405);return L.Http.methodsWithBody.includes(j)?w[j](c,u):w[j](c)}async batchPublish(r){let n,o;Array.isArray(r)?(n=r,o=!1):(n=[r],o=!0);let c=this.client.options.useBinaryProtocol?"msgpack":"json",u=J.defaultPostHeaders(this.client.options);this.client.options.headers&&Y(u,this.client.options.headers);let f=je(n,this.client._MsgPack,c),y=await ie.post(this.client,"/messages",f,u,{},null,!0),_=y.unpacked?y.body:ue(y.body,this.client._MsgPack,c);return o?_[0]:_}async batchPresence(r){let n=this.client.options.useBinaryProtocol?"msgpack":"json",o=J.defaultGetHeaders(this.client.options);this.client.options.headers&&Y(o,this.client.options.headers);let c=r.join(","),u=await ie.get(this.client,"/presence",o,{channels:c},null,!0);return u.unpacked?u.body:ue(u.body,this.client._MsgPack,n)}async revokeTokens(r,n){if(pa(this.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);let o=this.client.options.keyName,c=n??{},u=E({targets:r.map(I=>`${I.type}:${I.value}`)},c),f=this.client.options.useBinaryProtocol?"msgpack":"json",y=J.defaultPostHeaders(this.client.options);this.client.options.headers&&Y(y,this.client.options.headers);let _=je(u,this.client._MsgPack,f),T=await ie.post(this.client,`/keys/${o}/revokeTokens`,_,y,{},null,!0);return T.unpacked?T.body:ue(T.body,this.client._MsgPack,f)}},vp=class{constructor(r){this.client=r,this.all=Object.create(null)}get(r,n){r=String(r);let o=this.all[r];return o?n&&o.setOptions(n):this.all[r]=o=new mp(this.client,r,n),o}release(r){delete this.all[String(r)]}},wp=class extends Ea{constructor(r){super(J.objectifyOptions(r,!1,"BaseRest",d.defaultLogger,{Rest:Ba}))}},$a={Rest:Ba},Ha=class extends $e{static async fromEncoded(r,n){return Ma(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return dp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return $e.fromValues(r)}},Ga=class extends Ve{static async fromEncoded(r,n){return Aa(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return op(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Ve.fromValues(r)}},Fa=["annotation.create","annotation.delete"];async function Wa(r,n,o){return Pt.fromValues(n).decode(o||{},r)}async function Cp(r,n,o){return Promise.all(n.map(function(c){return Wa(r,c,o)}))}async function Ep(r,n){return Pt.fromValues(r).decode(n.channelOptions,n.logger)}async function kp(r,n){return Promise.all(r.map(function(o){return Ep(o,n)}))}var Va=class vo extends At{async encode(){let n=Object.assign(new Pt,this,{action:Fa.indexOf(this.action||"annotation.create")});return nr(n,{})}static fromValues(n){return Object.assign(new vo,n)}static fromValuesArray(n){return n.map(o=>vo.fromValues(o))}toString(){return Tt(this,"Annotation")}},Pt=class wo extends At{toJSON(...n){return ir.call(this,...n)}static fromValues(n){return Object.assign(new wo,n)}static fromValuesArray(n){return n.map(o=>wo.fromValues(o))}async decode(n,o){let c=Object.assign(new Va,O(E({},this),{action:Fa[this.action]}));try{await rr(c,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WireAnnotation.decode()",ee(u))}return c}toString(){return Tt(this,"WireAnnotation")}},It=Va,za=class extends It{static async fromEncoded(r,n){return Wa(d.defaultLogger,r,n)}static async fromEncodedArray(r,n){return Cp(d.defaultLogger,r,n)}static fromValues(r){return It.fromValues(r)}};function Ka(r){let n;switch(typeof r){case"string":n=r;break;case"object":n=r.serial;break}if(!n||typeof n!="string")throw new x("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return n}function Ja(r,n){let o=Ka(r);if(!n||typeof n!="object")throw new x("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let c=It.fromValues(n);return c.messageSerial=o,c.action||(c.action="annotation.create"),c}function Ya(r,n){return r.client.rest.channelMixin.basePath(r)+"/messages/"+encodeURIComponent(n)+"/annotations"}var Op=class{constructor(r){this.channel=r}async publish(r,n){let o=Ja(r,n),c=await o.encode(),u=this.channel.client,f=u.options,y=f.useBinaryProtocol?"msgpack":"json",_=J.defaultPostHeaders(u.options),T={};Y(_,u.options.headers);let I=je([c],u._MsgPack,y);await ie.post(u,Ya(this.channel,o.messageSerial),I,_,T,null,!0)}async delete(r,n){return n.action="annotation.delete",this.publish(r,n)}async get(r,n){let o=this.channel.client,c=Ka(r),u=o.options.useBinaryProtocol?"msgpack":"json",f=o.http.supportsLinkHeaders?void 0:u,y=J.defaultGetHeaders(o.options);return Y(y,o.options.headers),new Ue(o,Ya(this.channel,c),y,f,async(_,T,I)=>{let D=I?_:ue(_,o._MsgPack,u);return kp(D,this.channel)}).get(n)}},Gs=Op,Sp=je;function Fs(r){let n=[];if(r)for(let o=0;o<r.length;o++)n.push(r[o].toString());return"[ "+n.join(", ")+" ]"}function Tp(r,n,o,c,u,f){let y=ue(r,n,f);return or(y,o,c,u)}function or(r,n,o,c){let u;r.error&&(u=x.fromValues(r.error));let f;r.messages&&(f=is.fromValuesArray(r.messages));let y;n&&r.presence&&(y=n.WirePresenceMessage.fromValuesArray(r.presence));let _;o&&r.annotations&&(_=o.WireAnnotation.fromValuesArray(r.annotations));let T;return c&&r.state&&(T=c.WireObjectMessage.fromValuesArray(r.state,Zt,Bs)),Object.assign(new cr,O(E({},r),{presence:y,messages:f,annotations:_,state:T,error:u}))}function Ap(r){return n=>{var o;return or(n,{PresenceMessage:Ve,WirePresenceMessage:rs},{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs},(o=r?.LiveObjectsPlugin)!=null?o:null)}}function we(r){return Object.assign(new cr,r)}function ar(r,n,o,c){let u="[ProtocolMessage";r.action!==void 0&&(u+="; action="+ga[r.action]||r.action);let f=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"],y;for(let _=0;_<f.length;_++)y=f[_],r[y]!==void 0&&(u+="; "+y+"="+r[y]);if(r.messages&&(u+="; messages="+Fs(is.fromValuesArray(r.messages))),r.presence&&n&&(u+="; presence="+Fs(n.WirePresenceMessage.fromValuesArray(r.presence))),r.annotations&&o&&(u+="; annotations="+Fs(o.WireAnnotation.fromValuesArray(r.annotations))),r.state&&c&&(u+="; state="+Fs(c.WireObjectMessage.fromValuesArray(r.state,Zt,Bs))),r.error&&(u+="; error="+x.fromValues(r.error).toString()),r.auth&&r.auth.accessToken&&(u+="; token="+r.auth.accessToken),r.flags&&(u+="; flags="+Hf.filter(r.hasFlag).join(",")),r.params){let _="";qo(r.params,function(T){_.length>0&&(_+="; "),_+=T+"="+r.params[T]}),_.length>0&&(u+="; params=["+_+"]")}return u+="]",u}var cr=class{constructor(){this.hasFlag=r=>(this.flags&ve[r])>0}setFlag(r){return this.flags=this.flags|ve[r]}getMode(){return(this.flags||0)&ve.MODE_ALL}encodeModesToFlags(r){r.forEach(n=>this.setFlag(n))}decodeModesFromFlags(){let r=[];return ma.forEach(n=>{this.hasFlag(n)&&r.push(n)}),r.length>0?r:void 0}},Rp=cr,Pp=class{constructor(r,n,o,c,u){this.previous=r,this.current=n,n==="attached"&&(this.resumed=o,this.hasBacklog=c),u&&(this.reason=u)}},lr=Pp,Qa=function(){};function Ip(r){if(r&&"params"in r&&!Ot(r.params))return new x("options.params must be an object",4e4,400);if(r&&"modes"in r){if(!Array.isArray(r.modes))return new x("options.modes must be an array",4e4,400);for(let n=0;n<r.modes.length;n++){let o=r.modes[n];if(!o||typeof o!="string"||!ma.includes(String.prototype.toUpperCase.call(o)))return new x("Invalid channel mode: "+o,4e4,400)}}}var Mp=class Co extends he{constructor(n,o,c){var u,f,y;super(n.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(_){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let T=this.client.rest.channelMixin;if(_&&_.untilAttach){if(this.state!=="attached")throw new x("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new x("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete _.untilAttach,_.from_serial=this.properties.attachSerial}return T.history(this,_)},this.whenState=_=>he.prototype.whenState.call(this,_,this.state),d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel()","started; name = "+o),this.name=o,this.channelOptions=qs((u=n._Crypto)!=null?u:null,this.logger,c),this.client=n,this._presence=n._RealtimePresence?new n._RealtimePresence.RealtimePresence(this):null,n._Annotations&&(this._annotations=new n._Annotations.RealtimeAnnotations(this)),this.connectionManager=n.connection.connectionManager,this.state="initialized",this.subscriptions=new he(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(c),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:n.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new he(this.logger),(f=n.options.plugins)!=null&&f.Push&&(this._push=new n.options.plugins.Push.PushChannel(this)),(y=n.options.plugins)!=null&&y.LiveObjects&&(this._object=new n.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||pe("RealtimePresence"),this._presence}get annotations(){return this._annotations||pe("Annotations"),this._annotations}get push(){return this._push||pe("Push"),this._push}get object(){return this._object||pe("LiveObjects"),this._object}invalidStateError(){return new x("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(n){return n=Array.prototype.slice.call(n),typeof n[0]=="function"&&n.unshift(null),n}async setOptions(n){var o;let c=this.channelOptions,u=Ip(n);if(u)throw u;if(this.channelOptions=qs((o=this.client._Crypto)!=null?o:null,this.logger,n),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(n,c))return this.attachImpl(),new Promise((f,y)=>{this._allChannelChanges.once(["attached","update","detached","failed"],function(_){switch(this.event){case"update":case"attached":f();break;default:y(_.reason)}})})}_shouldReattachToSetOptions(n,o){if(!(this.state==="attached"||this.state==="attaching"))return!1;if(n?.params){let c=Xa(n.params),u=Xa(o.params);if(Object.keys(c).length!==Object.keys(u).length||!Qn(u,c))return!0}return!!(n?.modes&&(!o.modes||!Qo(n.modes,o.modes)))}async publish(...n){let o=n[0],c=n[1],u,f;if(typeof o=="string"||o===null||o===void 0)u=[$e.fromValues({name:o,data:c})],f=n[2];else if(Ot(o))u=[$e.fromValues(o)],f=n[1];else if(Array.isArray(o))u=$e.fromValuesArray(o),f=n[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);let y=this.client.options.maxMessageSize,_=await La(u,this.channelOptions),T=Da(_);if(T>y)throw new x(`Maximum size of messages that can be published at once exceeded (was ${T} bytes; limit is ${y} bytes)`,40009,400);this.throwIfUnpublishableState(),d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+_.length);let I=we({action:z.MESSAGE,channel:this.name,messages:_,params:f?Kn(f):void 0});return await this.sendMessage(I)||{serials:[]}}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(this.state==="failed"||this.state==="suspended")throw this.invalidStateError()}onEvent(n){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.onEvent()","received message");let o=this.subscriptions;for(let c=0;c<n.length;c++){let u=n[c];o.emit(u.name,u)}}async attach(){return this.state==="attached"?null:new Promise((n,o)=>{this._attach(!1,null,(c,u)=>c?o(c):n(u))})}_attach(n,o,c){c||(c=f=>{f&&d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+f.toString())});let u=this.connectionManager;if(!u.activeState()){c(u.getError());return}(this.state!=="attaching"||n)&&this.requestState("attaching",o),this.once(function(f){switch(this.event){case"attached":c?.(null,f);break;case"detached":case"suspended":case"failed":c?.(f.reason||u.getError()||new x("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":c?.(new x("Attach request superseded by a subsequent detach request",9e4,409));break}})}attachImpl(){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let n=we({action:z.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&n.encodeModesToFlags(zo(this.channelOptions.modes)),this._attachResume&&n.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(n.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(n).catch(Qa)}async detach(){let n=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new x("Unable to detach; channel state = failed",90001,400);default:if(n.state.state!=="connected"){this.notifyState("detached");return}this.requestState("detaching");case"detaching":return new Promise((o,c)=>{this.once(function(u){switch(this.event){case"detached":o();break;case"attached":case"suspended":case"failed":c(u.reason||n.getError()||new x("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":c(new x("Detach request superseded by a subsequent attach request",9e4,409));break}})})}}detachImpl(){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let n=we({action:z.DETACH,channel:this.name});this.sendMessage(n).catch(Qa)}async subscribe(...n){let[o,c]=Co.processListenerArgs(n);if(this.state==="failed")throw x.fromValues(this.invalidStateError());return o&&typeof o=="object"&&!Array.isArray(o)?this.client._FilteredSubscriptions.subscribeFilter(this,o,c):this.subscriptions.on(o,c),this.channelOptions.attachOnSubscribe!==!1?this.attach():null}unsubscribe(...n){var o;let[c,u]=Co.processListenerArgs(n);if(typeof c=="object"&&!u||(o=this.filteredSubscriptions)!=null&&o.has(u)){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,c,u).forEach(f=>this.subscriptions.off(f));return}this.subscriptions.off(c,u)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new Ee("Unable to sync to channel; not attached",4e4);default:}let n=this.connectionManager;if(!n.activeState())throw n.getError();let o=we({action:z.SYNC,channel:this.name});this.syncChannelSerial&&(o.channelSerial=this.syncChannelSerial),n.send(o)}async sendMessage(n){return new Promise((o,c)=>{this.connectionManager.send(n,this.client.options.queueMessages,(u,f)=>{u?c(u):o(f)})})}async sendPresence(n){let o=we({action:z.PRESENCE,channel:this.name,presence:n});await this.sendMessage(o)}async sendState(n){let o=we({action:z.OBJECT,channel:this.name,state:n});await this.sendMessage(o)}async processMessage(n){(n.action===z.ATTACHED||n.action===z.MESSAGE||n.action===z.PRESENCE||n.action===z.OBJECT||n.action===z.ANNOTATION)&&this.setChannelSerial(n.channelSerial);let o,c=!1;switch(n.action){case z.ATTACHED:{this.properties.attachSerial=n.channelSerial,this._mode=n.getMode(),this.params=n.params||{};let u=n.decodeModesFromFlags();this.modes=u&&Vo(u)||void 0;let f=n.hasFlag("RESUMED"),y=n.hasFlag("HAS_PRESENCE"),_=n.hasFlag("HAS_BACKLOG"),T=n.hasFlag("HAS_OBJECTS");if(this.state==="attached"){f||(this._presence&&this._presence.onAttached(y),this._object&&this._object.onAttached(T));let I=new lr(this.state,this.state,f,_,n.error);this._allChannelChanges.emit("update",I),(!f||this.channelOptions.updateOnAttached)&&this.emit("update",I)}else this.state==="detaching"?this.checkPendingState():this.notifyState("attached",n.error,f,y,_,T);break}case z.DETACHED:{let u=n.error?x.fromValues(n.error):new x("Channel detached",90001,404);this.state==="detaching"?this.notifyState("detached",u):this.state==="attaching"?this.notifyState("suspended",u):(this.state==="attached"||this.state==="suspended")&&this.requestState("attaching",u);break}case z.SYNC:if(c=!0,o=this.syncChannelSerial=n.channelSerial,!n.presence)break;case z.PRESENCE:{if(!n.presence)break;$s(n);let u=this.channelOptions;if(this._presence){let f=await Promise.all(n.presence.map(y=>y.decode(u,this.logger)));this._presence.setPresence(f,c,o)}break}case z.OBJECT:case z.OBJECT_SYNC:{if(!this._object||!n.state)return;$s(n);let u=this.client.connection.connectionManager.getActiveTransportFormat(),f=n.state.map(y=>y.decode(this.client,u));n.action===z.OBJECT?this._object.handleObjectMessages(f):this._object.handleObjectSyncMessages(f,n.channelSerial);break}case z.MESSAGE:{if(this.state!=="attached"){d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+n.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}$s(n);let u=n.messages,f=u[0],y=u[u.length-1];if(f.extras&&f.extras.delta&&f.extras.delta.from!==this._lastPayload.messageId){let T='Delta message decode failure - previous message not available for message "'+n.id+'" on this channel "'+this.name+'".';d.logAction(this.logger,d.LOG_ERROR,"RealtimeChannel.processMessage()",T),this._startDecodeFailureRecovery(new x(T,40018,400));break}let _=[];for(let T=0;T<u.length;T++){let{decoded:I,err:D}=await u[T].decodeWithErr(this._decodingContext,this.logger);if(_[T]=I,D)switch(D.code){case 40018:this._startDecodeFailureRecovery(D);return;case 40019:case 40021:this.notifyState("failed",D);return;default:}}this._lastPayload.messageId=y.id,this._lastPayload.protocolMessageChannelSerial=n.channelSerial,this.onEvent(_);break}case z.ANNOTATION:{$s(n);let u=this.channelOptions;if(this._annotations){let f=await Promise.all((n.annotations||[]).map(y=>y.decode(u,this.logger)));this._annotations._processIncoming(f)}break}case z.ERROR:{let u=n.error;u&&u.code==80016?this.checkPendingState():this.notifyState("failed",x.fromValues(u));break}default:d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+n.action+")")}}_startDecodeFailureRecovery(n){this._lastPayload.decodeFailureRecoveryInProgress||(d.logAction(this.logger,d.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,n,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(n,o,c,u,f,y){if(d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+n),this.clearStateTimer(),["detached","suspended","failed"].includes(n)&&(this.properties.channelSerial=null),n===this.state)return;this._presence&&this._presence.actOnChannelState(n,u,o),this._object&&this._object.actOnChannelState(n,y),n==="suspended"&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),o&&(this.errorReason=o);let _=new lr(this.state,n,c,f,o),T='Channel state for channel "'+this.name+'"',I=n+(o?"; reason: "+o:"");n==="failed"?d.logAction(this.logger,d.LOG_ERROR,T,I):d.logAction(this.logger,d.LOG_MAJOR,T,I),n!=="attaching"&&n!=="suspended"&&(this.retryCount=0),n==="attached"&&this.onAttached(),n==="attached"?this._attachResume=!0:(n==="detaching"||n==="failed")&&(this._attachResume=!1),this.state=n,this._allChannelChanges.emit(n,_),this.emit(n,_)}requestState(n,o){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+n),this.notifyState(n,o),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync();break;default:break}}timeoutPendingState(){switch(this.state){case"attaching":{let n=new x("Channel attach timed out",90007,408);this.notifyState("suspended",n);break}case"detaching":{let n=new x("Channel detach timed out",90007,408);this.notifyState("attached",n);break}default:this.checkPendingState();break}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){let n=this.stateTimer;n&&(clearTimeout(n),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let n=Yn(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{this.state==="suspended"&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},n)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){let n=this.state;return n==="initialized"||n==="detached"||n==="failed"?null:new x("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+n,90001,400)}setChannelSerial(n){d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+n+"; previous = "+this.properties.channelSerial),n&&(this.properties.channelSerial=n)}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(n){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,n)}async updateMessage(n,o,c){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(n,"message.update",o,c)}async deleteMessage(n,o,c){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(n,"message.delete",o,c)}async appendMessage(n,o,c){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(n,"message.append",o,c)}async sendUpdate(n,o,c,u){var f,y;if(!n.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();let T=await $e.fromValues(O(E({},n),{action:o,version:c})).encode(this.channelOptions),I=we({action:z.MESSAGE,channel:this.name,messages:[T],params:u?Kn(u):void 0}),D=await this.sendMessage(I);return{versionSerial:(y=(f=D?.serials)==null?void 0:f[0])!=null?y:null}}async getMessageVersions(n,o){return d.logAction(this.logger,d.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,n,o)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;case"failed":default:throw x.fromValues(this.invalidStateError())}}};function Xa(r){let n=r||{},{agent:o}=n;return N(n,["agent"])}var os=Mp,xp=class{constructor(r){this.channel=r,this.logger=r.logger,this.subscriptions=new he(this.logger)}async publish(r,n){let o=this.channel.name,c=Ja(r,n),u=await c.encode();this.channel.throwIfUnpublishableState(),d.logAction(this.logger,d.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+o+", sending annotation with messageSerial = "+c.messageSerial+", type = "+c.type);let f=we({action:z.ANNOTATION,channel:o,annotations:[u]});await this.channel.sendMessage(f)}async delete(r,n){n.action="annotation.delete",await this.publish(r,n)}async subscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());if(this.subscriptions.on(o,c),this.channel.channelOptions.attachOnSubscribe!==!1&&await u.attach(),(this.channel.state==="attached"&&this.channel._mode&ve.ANNOTATION_SUBSCRIBE)===0)throw new x("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1];this.subscriptions.off(o,c)}_processIncoming(r){for(let n of r)this.subscriptions.emit(n.type||"",n)}async get(r,n){return Gs.prototype.get.call(this,r,n)}},ur=xp,mt=class Gn extends wp{constructor(n){var o,c;if(!Gn._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(J.objectifyOptions(n,!0,"Rest",d.defaultLogger,O(E({},$a),{Crypto:(o=Gn.Crypto)!=null?o:void 0,MsgPack:(c=Gn._MsgPack)!=null?c:void 0,Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs}})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(n){this._Crypto=n}};mt._Crypto=null,mt.Message=Ha,mt.PresenceMessage=Ga,mt.Annotation=za,mt._MsgPack=null,mt._Http=tr;var Za=mt,Np=class extends he{constructor(r){super(r),this.messages=[]}count(){return this.messages.length}push(r){this.messages.push(r)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(r){this.messages.push.apply(this.messages,r)}prepend(r){this.messages.unshift.apply(this.messages,r)}completeMessages(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"MessageQueue.completeMessages()",r=="all"?"(all)":"serial = "+r.serial+"; count = "+r.count),n=n||null;let c=this.messages;if(c.length===0)throw new Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let u=[];if(r==="all")u=c.splice(0);else{let f=c[0];if(f){let y=f.message.msgSerial,_=r.serial+r.count;_>y&&(u=c.splice(0,_-y))}}for(let f=0;f<u.length;f++){let y=u[f],_=o?.[f];y.callback(n,_)}c.length==0&&this.emit("idle")}completeAllMessages(r){this.completeMessages("all",r)}resetSendAttempted(){for(let r of this.messages)r.sendAttempted=!1}clear(){d.logAction(this.logger,d.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},ec=Np,tc=class{constructor(r,n){this.message=r,this.callback=n,this.merged=!1;let o=r.action;this.sendAttempted=!1,this.ackRequired=typeof o=="number"&&[z.MESSAGE,z.PRESENCE,z.ANNOTATION,z.OBJECT].includes(o)}},Lp=class extends he{constructor(r){super(r.logger),this.transport=r,this.messageQueue=new ec(this.logger),r.on("ack",(n,o,c)=>{this.onAck(n,o,c)}),r.on("nack",(n,o,c)=>{this.onNack(n,o,c)})}onAck(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"Protocol.onAck()","serial = "+r+"; count = "+n),this.messageQueue.completeMessages({serial:r,count:n},null,o)}onNack(r,n,o){d.logAction(this.logger,d.LOG_ERROR,"Protocol.onNack()","serial = "+r+"; count = "+n+"; err = "+ee(o)),o||(o=new x("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:r,count:n},o)}onceIdle(r){let n=this.messageQueue;if(n.count()===0){r();return}n.once("idle",r)}send(r){r.ackRequired&&this.messageQueue.push(r),this.logger.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(this.logger,d.LOG_MICRO,"Protocol.send()","sending msg; "+ar(r.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),r.sendAttempted=!0,this.transport.send(r.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let r=this.transport;this.onceIdle(function(){r.disconnect()})}},jp=Lp,Dp=class{constructor(r,n,o,c){this.previous=r,this.current=n,o&&(this.retryIn=o),c&&(this.reason=c)}},Ws=Dp,at={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Up={disconnected:()=>x.fromValues({statusCode:400,code:at.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:at.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:at.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:at.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:at.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:at.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:at.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function qp(r){return!r.statusCode||!r.code||r.statusCode>=500?!0:Object.values(at).includes(r.code)}var yt=Up,Bp=we({action:z.CLOSE}),$p=we({action:z.DISCONNECT}),Hp=class extends he{constructor(r,n,o,c){super(r.logger),c&&(o.format=void 0,o.heartbeats=!0),this.connectionManager=r,this.auth=n,this.params=o,this.timeouts=o.options.timeouts,this.format=o.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",yt.closed())}disconnect(r){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",r||yt.disconnected())}fail(r){this.isConnected&&this.requestDisconnect(),this.finish("failed",r||yt.failed())}finish(r,n){var o;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout((o=this.idleTimer)!=null?o:void 0),this.idleTimer=null,this.emit(r,n),this.dispose())}onProtocolMessage(r){switch(this.logger.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+ar(r,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),r.action){case z.HEARTBEAT:d.logActionNoStrip(this.logger,d.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",r.id);break;case z.CONNECTED:this.onConnect(r),this.emit("connected",r.error,r.connectionId,r.connectionDetails,r);break;case z.CLOSED:this.onClose(r);break;case z.DISCONNECTED:this.onDisconnect(r);break;case z.ACK:this.emit("ack",r.msgSerial,r.count,r.res);break;case z.NACK:this.emit("nack",r.msgSerial,r.count,r.error);break;case z.SYNC:this.connectionManager.onChannelMessage(r,this);break;case z.ACTIVATE:break;case z.AUTH:ke(this.auth.authorize(),n=>{n&&d.logAction(this.logger,d.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+ee(n))});break;case z.ERROR:if(d.logAction(this.logger,d.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+L.Config.inspect(r.error)+(r.channel?", channel: "+r.channel:"")),r.channel===void 0){this.onFatalError(r);break}this.connectionManager.onChannelMessage(r,this);break;default:this.connectionManager.onChannelMessage(r,this)}}onConnect(r){if(this.isConnected=!0,!r.connectionDetails)throw new Error("Transport.onConnect(): Connect message recieved without connectionDetails");let n=r.connectionDetails.maxIdleInterval;n&&(this.maxIdleInterval=n+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onDisconnect()","err = "+ee(n)),this.finish("disconnected",n)}onFatalError(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onFatalError()","err = "+ee(n)),this.finish("failed",n)}onClose(r){let n=r&&r.error;d.logAction(this.logger,d.LOG_MINOR,"Transport.onClose()","err = "+ee(n)),this.finish("closed",n)}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestClose()",""),this.send(Bp)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestDisconnect()",""),this.send($p)}ping(r){let n={action:z.HEARTBEAT};r&&(n.id=r),this.send(we(n))}dispose(){d.logAction(this.logger,d.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(r){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},r))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw new Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;let r=Date.now()-this.lastActivity,n=this.maxIdleInterval-r;if(n<=0){let o="No activity seen from realtime in "+r+"ms; assuming connection has dropped";d.logAction(this.logger,d.LOG_ERROR,"Transport.onIdleTimerExpire()",o),this.disconnect(new x(o,80003,408))}else this.setIdleTimer(n+100)}static tryConnect(r,n,o,c,u){let f=new r(n,o,c),y,_=function(I){clearTimeout(y),u({event:this.event,error:I})},T=n.options.timeouts.realtimeRequestTimeout;return y=setTimeout(()=>{f.off(["preconnect","disconnected","failed"]),f.dispose(),_.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},T),f.on(["failed","disconnected"],_),f.on("preconnect",function(){d.logAction(n.logger,d.LOG_MINOR,"Transport.tryConnect()","viable transport "+f),clearTimeout(y),f.off(["failed","disconnected"],_),u(null,f)}),f.connect(),f}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}},Mt=Hp,ge;(r=>{r.WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling"})(ge||(ge={}));var Gp=typeof global<"u"?global:typeof window<"u"?window:self,hr=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.localSupported)},as=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.sessionSupported)},sc=function(){},dr="ably-transport-preference";function fr(r){try{return JSON.parse(r)}catch{return null}}var Fp=class{constructor(r,n,o,c){this.options=r,this.host=n,this.mode=o,this.connectionKey=c,this.format=r.useBinaryProtocol?"msgpack":"json"}getConnectParams(r){let n=r?es(r):{},o=this.options;switch(this.mode){case"resume":n.resume=this.connectionKey;break;case"recover":{let c=fr(o.recover);c&&(n.recover=c.connectionKey);break}default:}return o.clientId!==void 0&&(n.clientId=o.clientId),o.echoMessages===!1&&(n.echo="false"),this.format!==void 0&&(n.format=this.format),this.stream!==void 0&&(n.stream=this.stream),this.heartbeats!==void 0&&(n.heartbeats=this.heartbeats),n.v=J.protocolVersion,n.agent=Xn(this.options),o.transportParams!==void 0&&Y(n,o.transportParams),n}toString(){let r="[mode="+this.mode;return this.host&&(r+=",host="+this.host),this.connectionKey&&(r+=",connectionKey="+this.connectionKey),this.format&&(r+=",format="+this.format),r+="]",r}},Wp=class Id extends he{constructor(n,o){super(n.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=n,this.initTransports(),this.options=o;let c=o.timeouts,u=c.webSocketConnectTimeout+c.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:u,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:c.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:c.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:c.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new ec(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=c.connectionStateTtl,this.maxIdleInterval=null,this.transports=No(o.transports||J.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(ge.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(ge.XhrPolling)?this.baseTransport=ge.XhrPolling:this.transports.includes(ge.Comet)&&(this.baseTransport=ge.Comet),this.domains=J.getHosts(o),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,d.logAction(this.logger,d.LOG_MINOR,"Realtime.ConnectionManager()","started"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(o.transports||J.defaultTransports)+"]"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),d.logAction(this.logger,d.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){let y="no requested transports available";throw d.logAction(this.logger,d.LOG_ERROR,"realtime.ConnectionManager()",y),new Error(y)}let f=L.Config.addEventListener;f&&(as()&&typeof o.recover=="function"&&f("beforeunload",this.persistConnection.bind(this)),o.closeOnUnload===!0&&f("beforeunload",()=>{d.logAction(this.logger,d.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),f("online",()=>{var y;this.state==this.states.disconnected||this.state==this.states.suspended?(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&((y=this.pendingTransport)==null||y.off(),this.disconnectAllTransports(),this.startConnect())}),f("offline",()=>{this.state==this.states.connected&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(n){let o={supportedTransports:{}};return this.initTransports(n,o),o.supportedTransports}static initTransports(n,o){let c=E(E({},L.Transports.bundledImplementations),n);[ge.WebSocket,...L.Transports.order].forEach(u=>{let f=c[u];f&&f.isAvailable()&&(o.supportedTransports[u]=f)})}initTransports(){Id.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(n,o){return new Fp(this.options,n,o,this.connectionKey)}getTransportParams(n){(c=>{if(this.connectionKey){c("resume");return}if(typeof this.options.recover=="string"){c("recover");return}let u=this.options.recover,f=this.getSessionRecoverData(),y=this.sessionRecoveryName();if(f&&typeof u=="function"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+y+")"),u(f,_=>{_?(this.options.recover=f.recoveryKey,c("recover")):c("clean")});return}c("clean")})(c=>{let u=this.createTransportParams(null,c);if(c==="recover"){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let f=fr(this.options.recover);f&&(this.msgSerial=f.msgSerial)}else d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+u.toString());n(u)})}tryATransport(n,o,c){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+o),this.proposedTransport=Mt.tryConnect(this.supportedTransports[o],this,this.realtime.auth,n,(u,f)=>{let y=this.state;if(y==this.states.closing||y==this.states.closed||y==this.states.failed){f&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+y.state+" while we were attempting the transport; closing "+f),f.close()),c(!0);return}if(u){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+o+" "+u.event+", err: "+u.error.toString()),We.isTokenErr(u.error)&&!(this.errorReason&&We.isTokenErr(this.errorReason))?(this.errorReason=u.error,ke(this.realtime.auth._forceNewToken(null,null),_=>{if(_){this.actOnErrorFromAuthorize(_);return}this.tryATransport(n,o,c)})):u.event==="failed"?(this.notifyState({state:"failed",error:u.error}),c(!0)):u.event==="disconnected"&&(qp(u.error)?c(!1):(this.notifyState({state:this.states.connecting.failState,error:u.error}),c(!0)));return}d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+o+"; setting pending"),this.setTransportPending(f,n),c(null,f)})}setTransportPending(n,o){let c=o.mode;d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+n+"; mode = "+c),this.pendingTransport=n,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),n.once("connected",(f,y,_)=>{this.activateTransport(f,n,y,_),c==="recover"&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let u=this;n.on(["disconnected","closed","failed"],function(f){u.deactivateTransport(n,this.event,f)}),this.emit("transport.pending",n)}activateTransport(n,o,c,u){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+o),n&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+n),c&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+c),u&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(u)),this.persistTransportPreference(o);let f=this.state,y=this.states.connected.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+f.state),f.state==this.states.closing.state||f.state==this.states.closed.state||f.state==this.states.failed.state)return d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),o.disconnect(),!1;if(delete this.pendingTransport,!o.isConnected)return d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+o+" since it appears to no longer be connected"),!1;let _=this.activeProtocol;this.activeProtocol=new jp(o),this.host=o.params.host;let T=u.connectionKey;if(T&&this.connectionKey!=T&&this.setConnection(c,u,!!n),this.onConnectionDetailsUpdate(u,o),L.Config.nextTick(()=>{o.on("connected",(I,D,j)=>{this.onConnectionDetailsUpdate(j,o),this.emit("update",new Ws(y,y,null,I))})}),f.state===this.states.connected.state?n&&(this.errorReason=this.realtime.connection.errorReason=n,this.emit("update",new Ws(y,y,null,n))):(this.notifyState({state:"connected",error:n}),this.errorReason=this.realtime.connection.errorReason=n||null),this.emit("transport.active",o),_)if(_.messageQueue.count()>0&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+_.transport.shortName+", new one is "+o.shortName+") finishing with "+_.messageQueue.count()+" messages still pending"),_.transport===o){let I="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+o.shortName+"; stack = "+new Error().stack;d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.activateTransport()",I)}else _.finish();return!0}deactivateTransport(n,o,c){let u=this.activeProtocol,f=u&&u.getTransport()===n,y=n===this.pendingTransport,_=this.noTransportsScheduledForActivation();if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+n),d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+o+(f?"; was active":y?"; was pending":"")+(_?"":"; another transport is scheduled for activation")),c&&c.message&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+c.message),f&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(u.getPendingMessages()),u.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",n),f&&_||f&&o==="failed"||o==="closed"||u===null&&y){if(o==="disconnected"&&c&&c.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:o,error:c,retryImmediately:!0});return}let T=o==="failed"&&We.isTokenErr(c)?"disconnected":o;this.notifyState({state:T,error:c});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(n,o,c){let u=this.connectionId;(u&&u!==n||!u&&c)&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==n&&d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=n,this.realtime.connection.key=this.connectionKey=o.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;let n=Date.now()-this.lastActivity;n>this.connectionStateTtl+this.maxIdleInterval&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+n+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(as()){let n=this.createRecoveryKey();n&&this.setSessionRecoverData({recoveryKey:n,disconnectedAt:Date.now(),location:Gp.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var n;return(n=this.activeProtocol)==null?void 0:n.getTransport().format}getError(){if(this.errorReason){let n=Ee.fromValues(this.errorReason);return n.cause=this.errorReason,n}return this.getStateError()}getStateError(){var n,o;return(o=(n=yt)[this.state.state])==null?void 0:o.call(n)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(n){let o="Connection state",c=n.current+(n.reason?"; reason: "+n.reason:"");n.current==="failed"?d.logAction(this.logger,d.LOG_ERROR,o,c):d.logAction(this.logger,d.LOG_MAJOR,o,c),d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+n.current+"; reason = "+(n.reason&&n.reason.message));let u=this.state=this.states[n.current];n.reason&&(this.errorReason=n.reason,this.realtime.connection.errorReason=n.reason),(u.terminal||u.state==="suspended")&&this.clearConnection(),this.emit("connectionstate",n)}startTransitionTimer(n){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+n.state),this.transitionTimer&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager "+n.state+" timer expired","requesting new state: "+n.failState),this.notifyState({state:n.failState}))},n.retryDelay)}cancelTransitionTimer(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(n){n!=="disconnected"&&n!=="suspended"&&n!=="connecting"&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(n){this.retryTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},n)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&ke(this.realtime.http.checkConnectivity(),(n,o)=>{n||!o?(d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new x("Unable to connect (network unreachable)",80003,404)})):d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(n){this.webSocketGiveUpTimer=setTimeout(()=>{var o,c;this.wsCheckResult||(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,(o=this.proposedTransport)==null||o.dispose(),(c=this.pendingTransport)==null||c.dispose(),this.connectBase(n,++this.connectCounter)):d.logAction(this.logger,d.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(n){var o,c;let u=n.state,f=u==="disconnected"&&(this.state===this.states.connected||n.retryImmediately||this.state===this.states.connecting&&n.error&&We.isTokenErr(n.error)&&!(this.errorReason&&We.isTokenErr(this.errorReason)));if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+u+(f?"; will retry connection immediately":"")),u==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(n.state),(u==="suspended"||u==="connected")&&(this.disconnectedRetryCount=0),this.state.terminal))return;let y=this.states[n.state],_=y.retryDelay;y.state==="disconnected"&&(this.disconnectedRetryCount++,_=Yn(y.retryDelay,this.disconnectedRetryCount));let T=new Ws(this.state.state,y.state,_,n.error||((c=(o=yt)[y.state])==null?void 0:c.call(o)));if(f){let I=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},D=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;D&&D<1e3?(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+D+"ms ago, waiting another "+(1e3-D)+"ms before trying again"),setTimeout(I,1e3-D)):L.Config.nextTick(I)}else(u==="disconnected"||u==="suspended")&&this.startRetryTimer(_);(u==="disconnected"&&!f||u==="suspended"||y.terminal)&&L.Config.nextTick(()=>{this.disconnectAllTransports()}),u=="connected"&&!this.activeProtocol&&d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(T),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(u,T.reason),this.failQueuedMessages(T.reason))}requestState(n){var o,c;let u=n.state;if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+u+"; current state: "+this.state.state),u==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(u),u=="connecting"&&this.state.state=="connected")||u=="closing"&&this.state.state=="closed")return;let f=this.states[u],y=new Ws(this.state.state,f.state,null,n.error||((c=(o=yt)[f.state])==null?void 0:c.call(o)));this.enactStateChange(y),u=="connecting"&&L.Config.nextTick(()=>{this.startConnect()}),u=="closing"&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}let n=this.realtime.auth,o=++this.connectCounter,c=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(u=>{if(u.mode==="recover"&&u.options.recover){let f=fr(u.options.recover);f&&this.realtime.channels.recoverChannels(f.channelSerials)}o===this.connectCounter&&this.connectImpl(u,o)})};if(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),n.method==="basic")c();else{let u=f=>{o===this.connectCounter&&(f?this.actOnErrorFromAuthorize(f):c())};this.errorReason&&We.isTokenErr(this.errorReason)?ke(n._forceNewToken(null,null),u):ke(n._ensureValidAuthCredentials(!1),u)}}connectImpl(n,o){let c=this.state.state;if(c!==this.states.connecting.state){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+c);return}let u=this.getTransportPreference();u&&u===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(n,++this.connectCounter))}).catch(sc),u&&u===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(n,o):this.connectWs(n,o)}connectWs(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(n),this.tryTransportWithFallbacks("web_socket",n,!0,o,()=>this.wsCheckResult!==!1&&!this.abandonedWebSocket)}connectBase(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,n,!1,o,()=>!0):this.notifyState({state:"disconnected",error:new x("No transports left to try",8e4,404)})}tryTransportWithFallbacks(n,o,c,u,f){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",n);let y=j=>{this.notifyState({state:this.states.connecting.failState,error:j})},_=this.domains.slice(),T=(j,F)=>{if(u===this.connectCounter){if(!f()){F&&F.dispose();return}!F&&!j&&D()}},I=_.shift();if(!I){y(new x("Unable to connect (no available host)",80003,404));return}o.host=I;let D=()=>{if(!_.length){y(new x("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){y(new Ee("Internal error: Http.checkConnectivity not set",null,500));return}ke(this.realtime.http.checkConnectivity(),(j,F)=>{if(u===this.connectCounter&&f()){if(j){y(j);return}if(!F){y(new x("Unable to connect (network unreachable)",80003,404));return}o.host=zn(_),this.tryATransport(o,n,T)}})};if(this.forceFallbackHost&&_.length){this.forceFallbackHost=!1,D();return}this.tryATransport(o,n,T)}closeImpl(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(n,o){var c;switch(this.state.state){case"connected":{d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");let u=(c=this.activeProtocol)==null?void 0:c.getTransport();u&&u.onAuthUpdated&&u.onAuthUpdated(n);let f=we({action:z.AUTH,auth:{accessToken:n.token}});this.send(f);let y=()=>{this.off(_),o(null,n)},_=T=>{T.current==="failed"&&(this.off(y),this.off(_),o(T.reason||this.getStateError()))};this.once("connectiondetails",y),this.on("connectionstate",_);break}case"connecting":d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let u=f=>{switch(f.current){case"connected":this.off(u),o(null,n);break;case"failed":case"closed":case"suspended":this.off(u),o(f.reason||this.getStateError());break;default:break}};this.on("connectionstate",u),this.state.state==="connecting"?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(n,o,c){c=c||sc;let u=this.state;if(u.sendEvents){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new tc(n,c));return}if(!(o&&u.queueEvents)){let y="rejecting event, queueEvent was "+o+", state was "+u.state;d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()",y),c(this.errorReason||new x(y,9e4,400));return}this.logger.shouldLog(d.LOG_MICRO)&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+ar(n,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),this.queue(n,c)}sendImpl(n){let o=n.message;n.ackRequired&&!n.sendAttempted&&(o.msgSerial=this.msgSerial++);try{this.activeProtocol.send(n)}catch(c){d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+c.stack)}}queue(n,o){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new tc(n,o))}sendQueuedMessages(){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");let n;for(;n=this.queuedMessages.shift();)this.sendImpl(n)}queuePendingMessages(n){n&&n.length&&(d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+n.length+" pending messages"),this.queuedMessages.prepend(n))}failQueuedMessages(n){let o=this.queuedMessages.count();o>0&&(d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+o+" queued messages, err = "+ee(n)),this.queuedMessages.completeAllMessages(n))}onChannelMessage(n,o){this.pendingChannelMessagesState.queue.push({message:n,transport:o}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let n=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(n.message).catch(o=>{d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",o)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(n){await this.realtime.channels.processChannelMessage(n)}async ping(){var n;if(this.state.state!=="connected")throw new x("Unable to ping service; not connected",4e4,400);let o=(n=this.activeProtocol)==null?void 0:n.getTransport();if(!o)throw this.getStateError();d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.ping()","transport = "+o);let c=Date.now(),u=Go();return Xo(new Promise(f=>{let y=_=>{_===u&&(o.off("heartbeat",y),f(Date.now()-c))};o.on("heartbeat",y),o.ping(u)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(n){this.activeProtocol.getTransport().fail(n)}getTransportPreference(){var n,o;return this.transportPreference||hr()&&((o=(n=L.WebStorage)==null?void 0:n.get)==null?void 0:o.call(n,dr))}persistTransportPreference(n){var o,c;this.transportPreference=n.shortName,hr()&&((c=(o=L.WebStorage)==null?void 0:o.set)==null||c.call(o,dr,n.shortName))}unpersistTransportPreference(){var n,o;this.transportPreference=null,hr()&&((o=(n=L.WebStorage)==null?void 0:n.remove)==null||o.call(n,dr))}actOnErrorFromAuthorize(n){if(n.code===40171)this.notifyState({state:"failed",error:n});else if(n.code===40102)this.notifyState({state:"failed",error:n});else if(n.statusCode===ns.Forbidden){let o="Client configured authentication provider returned 403; failing the connection";d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",o),this.notifyState({state:"failed",error:new x(o,80019,403,n)})}else{let o="Client configured authentication provider request failed";d.logAction(this.logger,d.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",o),this.notifyState({state:this.state.failState,error:new x(o,80019,401,n)})}}onConnectionDetailsUpdate(n,o){if(!n)return;this.connectionDetails=n,n.maxMessageSize&&(this.options.maxMessageSize=n.maxMessageSize);let c=n.clientId;if(c){let f=this.realtime.auth._uncheckedSetClientId(c);if(f){d.logAction(this.logger,d.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",f.message),o.fail(f);return}}let u=n.connectionStateTtl;u&&(this.connectionStateTtl=u),this.maxIdleInterval=n.maxIdleInterval,this.emit("connectiondetails",n)}checkWsConnectivity(){let n=this.options.wsConnectivityCheckUrl||J.wsConnectivityCheckUrl,o=new L.Config.WebSocket(n);return new Promise((c,u)=>{let f=!1;o.onopen=()=>{f||(f=!0,c(),o.close())},o.onclose=o.onerror=()=>{f||(f=!0,u())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var n,o;return as()&&((o=(n=L.WebStorage)==null?void 0:n.getSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}setSessionRecoverData(n){var o,c;return as()&&((c=(o=L.WebStorage)==null?void 0:o.setSession)==null?void 0:c.call(o,this.sessionRecoveryName(),n))}clearSessionRecoverData(){var n,o;return as()&&((o=(n=L.WebStorage)==null?void 0:n.removeSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}},nc=Wp,Vp=class extends he{constructor(r,n){super(r.logger),this.whenState=o=>he.prototype.whenState.call(this,o,this.state),this.ably=r,this.connectionManager=new nc(r,n),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",o=>{let c=this.state=o.current;L.Config.nextTick(()=>{this.emit(c,o)})}),this.connectionManager.on("update",o=>{L.Config.nextTick(()=>{this.emit("update",o)})})}connect(){d.logAction(this.logger,d.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return d.logAction(this.logger,d.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){d.logAction(this.logger,d.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},zp=Vp,rc=class Md extends Ea{constructor(n){var o,c,u,f;if(super(J.objectifyOptions(n,!1,"BaseRealtime",d.defaultLogger)),d.logAction(this.logger,d.LOG_MINOR,"Realtime()",""),typeof EdgeRuntime=="string")throw new x(`Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === 'string')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.`,4e4,400);this._additionalTransportImplementations=Md.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=(c=(o=this.options.plugins)==null?void 0:o.RealtimePresence)!=null?c:null,this._liveObjectsPlugin=(f=(u=this.options.plugins)==null?void 0:u.LiveObjects)!=null?f:null,this.connection=new zp(this,this.options),this._channels=new Jp(this),this.options.autoConnect!==!1&&this.connect()}static transportImplementationsFromPlugins(n){let o={};return n?.WebSocketTransport&&(o[ge.WebSocket]=n.WebSocketTransport),n?.XHRPolling&&(o[ge.XhrPolling]=n.XHRPolling),o}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){d.logAction(this.logger,d.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){d.logAction(this.logger,d.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};rc.EventEmitter=he;var Kp=rc,Jp=class extends he{constructor(r){super(r.logger),this.realtime=r,this.all=Object.create(null),r.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let r={};for(let n of js(this.all,!0)){let o=this.all[n];o.properties.channelSerial&&(r[n]=o.properties.channelSerial)}return r}recoverChannels(r){for(let n of js(r,!0)){let o=this.get(n);o.properties.channelSerial=r[n]}}async processChannelMessage(r){let n=r.channel;if(n===void 0){d.logAction(this.logger,d.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+r.action);return}let o=this.all[n];if(!o){d.logAction(this.logger,d.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+n);return}await o.processMessage(r)}onTransportActive(){for(let r in this.all){let n=this.all[r];n.state==="attaching"||n.state==="detaching"?n.checkPendingState():n.state==="suspended"?n._attach(!1,null):n.state==="attached"&&n.requestState("attaching")}}propogateConnectionInterruption(r,n){let o={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"},c=["attaching","attached","detaching","suspended"],u=o[r];for(let f in this.all){let y=this.all[f];c.includes(y.state)&&y.notifyState(u,n)}}get(r,n){r=String(r);let o=this.all[r];if(!o)o=this.all[r]=new os(this.realtime,r,n);else if(n){if(o._shouldReattachToSetOptions(n,o.channelOptions))throw new x("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);o.setOptions(n)}return o}getDerived(r,n,o){if(n.filter){let c=Us(n.filter),u=Yo(r);r=`[filter=${c}${u.qualifierParam}]${u.channelName}`}return this.get(r,o)}release(r){r=String(r);let n=this.all[r];if(!n)return;let o=n.getReleaseErr();if(o)throw o;delete this.all[r]}},Yp=Kp;function Qp(r,n){if(r.isSynthesized()||n.isSynthesized())return r.timestamp>=n.timestamp;let o=r.parseId(),c=n.parseId();return o.msgSerial===c.msgSerial?o.index>c.index:o.msgSerial>c.msgSerial}var pr=class extends he{constructor(r,n,o=Qp){super(r.logger),this.presence=r,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=n,this.newerThan=o}get(r){return this.map[r]}getClient(r){let n=this.map,o=[];for(let c in n){let u=n[c];u.clientId==r&&u.action!="absent"&&o.push(u)}return o}list(r){let n=this.map,o=r&&r.clientId,c=r&&r.connectionId,u=[];for(let f in n){let y=n[f];y.action!=="absent"&&(o&&o!=y.clientId||c&&c!=y.connectionId||u.push(y))}return u}put(r){(r.action==="enter"||r.action==="update")&&(r=Ve.fromValues(r),r.action="present");let n=this.map,o=this.memberKey(r);this.residualMembers&&delete this.residualMembers[o];let c=n[o];return c&&!this.newerThan(r,c)?!1:(n[o]=r,!0)}values(){let r=this.map,n=[];for(let o in r){let c=r[o];c.action!="absent"&&n.push(c)}return n}remove(r){let n=this.map,o=this.memberKey(r),c=n[o];return c&&!this.newerThan(r,c)?!1:(this.syncInProgress?(r=Ve.fromValues(r),r.action="absent",n[o]=r):delete n[o],!!c)}startSync(){let r=this.map,n=this.syncInProgress;d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+n),this.syncInProgress||(this.residualMembers=es(r),this.setInProgress(!0))}endSync(){let r=this.map,n=this.syncInProgress;if(d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+n),n){for(let o in r)r[o].action==="absent"&&delete r[o];this.presence._synthesizeLeaves(Uo(this.residualMembers));for(let o in this.residualMembers)delete r[o];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){let r=this.syncInProgress;d.logAction(this.logger,d.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+r),r&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(r){d.logAction(this.logger,d.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+r),this.syncInProgress=r,this.presence.syncComplete=!r}};function Xp(r){return r.channel.client.auth.clientId}function gr(r){let n=r.channel.client,o=n.auth.clientId;return(!o||o==="*")&&n.connection.state==="connected"}var Zp=class extends he{constructor(r){super(r.logger),this.channel=r,this.syncComplete=!1,this.members=new pr(this,n=>n.clientId+":"+n.connectionId),this._myMembers=new pr(this,n=>n.clientId),this.subscriptions=new he(this.logger),this.pendingPresence=[]}async enter(r){if(gr(this))throw new x("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"enter")}async update(r){if(gr(this))throw new x("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"update")}async enterClient(r,n){return this._enterOrUpdateClient(void 0,r,n,"enter")}async updateClient(r,n){return this._enterOrUpdateClient(void 0,r,n,"update")}async _enterOrUpdateClient(r,n,o,c){let u=this.channel;if(!u.connectionManager.activeState())throw u.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence."+c+"Client()","channel = "+u.name+", id = "+r+", client = "+(n||"(implicit) "+Xp(this)));let f=Ve.fromData(o);f.action=c,r&&(f.id=r),n&&(f.clientId=n);let y=await f.encode(u.channelOptions);switch(u.state){case"attached":return u.sendPresence([y]);case"initialized":case"detached":u.attach();case"attaching":return new Promise((_,T)=>{this.pendingPresence.push({presence:y,callback:I=>I?T(I):_()})});default:{let _=new Ee("Unable to "+c+" presence channel while in "+u.state+" state",90001);throw _.code=90001,_}}}async leave(r){if(gr(this))throw new x("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,r)}async leaveClient(r,n){let o=this.channel;if(!o.connectionManager.activeState())throw o.connectionManager.getError();d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+r);let c=Ve.fromData(n);c.action="leave",r&&(c.clientId=r);let u=await c.encode(o.channelOptions);switch(o.state){case"attached":return o.sendPresence([u]);case"attaching":return new Promise((f,y)=>{this.pendingPresence.push({presence:u,callback:_=>_?y(_):f()})});case"initialized":case"failed":throw new Ee("Unable to leave presence channel (incompatible state)",90001);default:throw o.invalidStateError()}}async get(r){let n=!r||("waitForSync"in r?r.waitForSync:!0);function o(u){return r?u.list(r):u.values()}if(this.channel.state==="suspended"){if(n)throw x.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return o(this.members)}await this.channel.ensureAttached();let c=this.members;return n&&await c.waitSync(),o(this.members)}async history(r){d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let n=this.channel.client.rest.presenceMixin;if(r&&r.untilAttach)if(this.channel.state==="attached")delete r.untilAttach,r.from_serial=this.channel.properties.attachSerial;else throw new x("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return n.history(this,r)}setPresence(r,n,o){d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+r.length+" participants; syncChannelSerial = "+o);let c,u,f=this.members,y=this._myMembers,_=[],T=this.channel.connectionManager.connectionId;n&&(this.members.startSync(),o&&(u=o.match(/^[\w-]+:(.*)$/))&&(c=u[1]));for(let I of r)switch(I.action){case"leave":f.remove(I)&&_.push(I),I.connectionId===T&&!I.isSynthesized()&&y.remove(I);break;case"enter":case"present":case"update":f.put(I)&&_.push(I),I.connectionId===T&&y.put(I);break}n&&!c&&(f.endSync(),this.channel.syncChannelSerial=null);for(let I=0;I<_.length;I++){let D=_[I];this.subscriptions.emit(D.action,D)}}onAttached(r){d.logAction(this.logger,d.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+r),r?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let n=this.pendingPresence,o=n.length;if(o){this.pendingPresence=[];let c=[],u=ca.create(this.logger);d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence.onAttached","sending "+o+" queued presence messages");for(let f=0;f<o;f++){let y=n[f];c.push(y.presence),u.push(y.callback)}this.channel.sendPresence(c).then(()=>u()).catch(f=>u(f))}}actOnChannelState(r,n,o){switch(r){case"attached":this.onAttached(n);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(o);break}}failPendingPresence(r){if(this.pendingPresence.length){d.logAction(this.logger,d.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+ee(r));for(let n=0;n<this.pendingPresence.length;n++)try{this.pendingPresence[n].callback(r)}catch{}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let r=this._myMembers,n=this.channel.connectionManager.connectionId;for(let o in r.map){let c=r.map[o];d.logAction(this.logger,d.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+c.clientId+'" into the presence set');let u=c.connectionId===n?c.id:void 0;this._enterOrUpdateClient(u,c.clientId,c.data,"enter").catch(f=>{let y=new x("Presence auto re-enter failed",91004,400,f);d.logAction(this.logger,d.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+ee(f));let _=new lr(this.channel.state,this.channel.state,!0,!1,y);this.channel.emit("update",_)})}}_synthesizeLeaves(r){let n=this.subscriptions;r.forEach(function(o){let c=Ve.fromValues({action:"leave",connectionId:o.connectionId,clientId:o.clientId,data:o.data,encoding:o.encoding,timestamp:Date.now()});n.emit("leave",c)})}async subscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1],u=this.channel;if(u.state==="failed")throw x.fromValues(u.invalidStateError());this.subscriptions.on(o,c),u.channelOptions.attachOnSubscribe!==!1&&await u.attach()}unsubscribe(...r){let n=os.processListenerArgs(r),o=n[0],c=n[1];this.subscriptions.off(o,c)}},eg=Zp,tg=ge.WebSocket;function sg(r){return!!r.on}var ng=class extends Mt{constructor(r,n,o){super(r,n,o),this.shortName=tg,o.heartbeats=L.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!L.Config.WebSocket}createWebSocket(r,n){return this.uri=r+ts(n),new L.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","starting"),Mt.prototype.connect.call(this);let r=this,n=this.params,o=n.options,u=(o.tls?"wss://":"ws://")+this.wsHost+":"+J.getPort(o)+"/";d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","uri: "+u),ke(this.auth.getAuthParams(),function(f,y){if(r.isDisposed)return;let _="";for(let I in y)_+=" "+I+": "+y[I]+";";if(d.logAction(r.logger,d.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+_+" err: "+f),f){r.disconnect(f);return}let T=n.getConnectParams(y);try{let I=r.wsConnection=r.createWebSocket(u,T);I.binaryType=L.Config.binaryType,I.onopen=function(){r.onWsOpen()},I.onclose=function(D){r.onWsClose(D)},I.onmessage=function(D){r.onWsData(D.data)},I.onerror=function(D){r.onWsError(D)},sg(I)&&I.on("ping",function(){r.onActivity()})}catch(I){d.logAction(r.logger,d.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(I.stack||I.message)),r.disconnect(I)}})}send(r){let n=this.wsConnection;if(!n){d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{n.send(Sp(r,this.connectionManager.realtime._MsgPack,this.params.format))}catch(o){let c="Exception from ws connection when trying to send: "+ee(o);d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.send()",c),this.finish("disconnected",new x(c,5e4,500))}}onWsData(r){d.logAction(this.logger,d.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+r.length+"; type = "+typeof r);try{this.onProtocolMessage(Tp(r,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin,this.format))}catch(n){d.logAction(this.logger,d.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+n.stack)}}onWsOpen(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(r){let n,o;if(typeof r=="object"?(o=r.code,n=r.wasClean||o===1e3):(o=r,n=o==1e3),delete this.wsConnection,n){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let c=new x("Websocket closed",80003,400);this.finish("disconnected",c)}else{let c="Unclean disconnection of WebSocket ; code = "+o,u=new x(c,80003,400);d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onWsClose()",c),this.finish("disconnected",u)}this.emit("disposed")}onWsError(r){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+r.message),L.Config.nextTick(()=>{this.disconnect(Error(r.message))})}dispose(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let r=this.wsConnection;r&&(r.onmessage=function(){},delete this.wsConnection,L.Config.nextTick(()=>{if(d.logAction(this.logger,d.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!r)throw new Error("WebSocketTransport.dispose(): wsConnection is not defined");r.close()}))}},ic=ng,rg=class{static subscribeFilter(r,n,o){let c=u=>{var f,y,_,T,I,D;let j={name:u.name,refTimeserial:(y=(f=u.extras)==null?void 0:f.ref)==null?void 0:y.timeserial,refType:(T=(_=u.extras)==null?void 0:_.ref)==null?void 0:T.type,isRef:!!((D=(I=u.extras)==null?void 0:I.ref)!=null&&D.timeserial),clientId:u.clientId};Object.entries(n).find(([F,w])=>w!==void 0?j[F]!==w:!1)||o(u)};this.addFilteredSubscription(r,n,o,c),r.subscriptions.on(c)}static addFilteredSubscription(r,n,o,c){var u;if(r.filteredSubscriptions||(r.filteredSubscriptions=new Map),r.filteredSubscriptions.has(o)){let f=r.filteredSubscriptions.get(o);f.set(n,((u=f?.get(n))==null?void 0:u.concat(c))||[c])}else r.filteredSubscriptions.set(o,new Map([[n,[c]]]))}static getAndDeleteFilteredSubscriptions(r,n,o){if(!r.filteredSubscriptions)return[];if(!o&&n)return Array.from(r.filteredSubscriptions.entries()).map(([f,y])=>{var _;let T=y.get(n);return y.delete(n),y.size===0&&((_=r.filteredSubscriptions)==null||_.delete(f)),T}).reduce((f,y)=>y?f.concat(...y):f,[]);if(!o||!r.filteredSubscriptions.has(o))return[];let c=r.filteredSubscriptions.get(o);if(!n){let f=Array.from(c.values()).reduce((y,_)=>y.concat(..._),[]);return r.filteredSubscriptions.delete(o),f}let u=c.get(n);return c.delete(n),u||[]}},Ae=class Eo extends Yp{constructor(n){var o;let c=Eo._MsgPack;if(!c)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(J.objectifyOptions(n,!0,"Realtime",d.defaultLogger,O(E({},$a),{Crypto:(o=Eo.Crypto)!=null?o:void 0,MsgPack:c,RealtimePresence:{RealtimePresence:eg,PresenceMessage:Ve,WirePresenceMessage:rs},Annotations:{Annotation:It,WireAnnotation:Pt,RealtimeAnnotations:ur,RestAnnotations:Gs},WebSocketTransport:ic,MessageInteractions:rg})))}static get Crypto(){if(this._Crypto===null)throw new Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(n){this._Crypto=n}};Ae.Utils=Zt,Ae.ConnectionManager=nc,Ae.ProtocolMessage=Rp,Ae._Crypto=null,Ae.Message=Ha,Ae.PresenceMessage=Ga,Ae.Annotation=za,Ae._MsgPack=null,Ae._Http=tr,Ae._PresenceMap=pr,Ae._MessageEncoding=Bs;var oc=Ae,ac=Z(q("crypto")),ig=class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}base64Decode(r){return Buffer.from(r,"base64")}base64Encode(r){return this.toBuffer(r).toString("base64")}base64UrlEncode(r){return this.toBuffer(r).toString("base64url")}areBuffersEqual(r,n){return!r||!n?!1:this.toBuffer(r).compare(this.toBuffer(n))==0}byteLength(r){return r.byteLength}hexDecode(r){return Buffer.from(r,"hex")}hexEncode(r){return this.toBuffer(r).toString("hex")}isBuffer(r){return Buffer.isBuffer(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)}toArrayBuffer(r){let n=this.toBuffer(r);return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}toBuffer(r){return Buffer.isBuffer(r)?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength)}arrayBufferViewToBuffer(r){return this.toBuffer(r)}utf8Decode(r){if(!this.isBuffer(r))throw new Error("Expected input of utf8Decode to be a buffer, arraybuffer, or view");return this.toBuffer(r).toString("utf8")}utf8Encode(r){return Buffer.from(r,"utf8")}concat(r){return Buffer.concat(r.map(n=>this.toBuffer(n)))}sha256(r){let n=this.toBuffer(r);return ac.default.createHash("SHA256").update(n).digest()}hmacSha256(r,n){let o=this.toBuffer(r),c=this.toBuffer(n);return ac.default.createHmac("SHA256",c).update(o).digest()}},cc=new ig,mr=Z(q("crypto")),og=Z(q("util")),ag=function(r){var n="aes",o=256,c="cbc",u=16;async function f(U){return og.default.promisify(mr.default.randomBytes)(U)}function y(U){return U+u&-u}function _(U){if(U.algorithm==="aes"&&U.mode==="cbc"){if(U.keyLength===128||U.keyLength===256)return;throw new Error("Unsupported key length "+U.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function T(U){return U.replace("_","/").replace("-","+")}function I(U,G){var V=Buffer.alloc(U);return V.fill(G),V}for(var D=[I(16,16)],j=1;j<=16;j++)D.push(I(j,j));class F{constructor(G,V,W,X){this.algorithm=G,this.keyLength=V,this.mode=W,this.key=X,this.iv=null}}function w(U){return!!(U.algorithm&&U.key&&U.keyLength&&U.mode)}class R{static getDefaultParams(G){var V;if(!G.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof G.key=="string"?V=r.base64Decode(T(G.key)):G.key instanceof ArrayBuffer?V=Buffer.from(G.key):V=G.key;var W=G.algorithm||n,X=V.length*8,Ce=G.mode||c,_e=new F(W,X,Ce,V);if(G.keyLength&&G.keyLength!==_e.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+G.keyLength+" was specified, but the key actually has length "+_e.keyLength);return _(_e),_e}static async generateRandomKey(G){try{return f((G||o)/8)}catch(V){throw new x("Failed to generate random key: "+V.message,500,5e4,V)}}static getCipher(G,V){var W,X=w(G)?G:this.getDefaultParams(G);return{cipherParams:X,cipher:new P(X,(W=G.iv)!=null?W:null,V)}}}R.CipherParams=F;class P{constructor(G,V,W){this.logger=W,this.encryptCipher=null,this.algorithm=G.algorithm+"-"+String(G.keyLength)+"-"+G.mode,this.key=G.key,this.iv=V}async encrypt(G){d.logAction(this.logger,d.LOG_MICRO,"CBCCipher.encrypt()","");let V=await this.getIv();this.encryptCipher||(this.encryptCipher=mr.default.createCipheriv(this.algorithm,this.key,V));var W=r.toBuffer(G),X=W.length,Ce=y(X),_e=this.encryptCipher.update(Buffer.concat([W,D[Ce-X]])),ze=Buffer.concat([V,_e]);return ze}async decrypt(G){var V=mr.default.createDecipheriv(this.algorithm,this.key,G.slice(0,u)),W=V.update(G.slice(u)),X=V.final();return X&&X.length&&(W=Buffer.concat([W,X])),W}async getIv(){if(this.iv){var G=this.iv;return this.iv=null,G}var V=await f(u);return this.encryptCipher?this.encryptCipher.update(V):V}}return R},lc=Z(Hn()),cg=Z(q("http")),lg=Z(q("https")),uc=[],cs,ug=(cs=class{constructor(r){this.agent=null,this.supportsAuthHeaders=!0,this.supportsLinkHeaders=!0,this.checkConnectivity=async()=>{var n,o,c,u,f;if((n=this.client)!=null&&n.options.disableConnectivityCheck)return!0;let y=((o=this.client)==null?void 0:o.options.connectivityCheckUrl)||J.connectivityCheckUrl,_=(u=(c=this.client)==null?void 0:c.options.connectivityCheckParams)!=null?u:null,T=!((f=this.client)!=null&&f.options.connectivityCheckUrl),{error:I,statusCode:D,body:j}=await this.doUri(ce.Get,y,null,null,_);return!I&&!T?Rf(D):!I&&j?.toString().trim()==="yes"},this.client=r??null}async doUri(r,n,o,c,u){var f;let y=this.client&&this.client.options.restAgentOptions||J.restAgentOptions,_={headers:o||void 0,responseType:"buffer"};if(!this.agent){let T=(f=uc.find(I=>Qn(y,I.options)))==null?void 0:f.agents;T?this.agent=T:(this.agent={http:new cg.default.Agent(y),https:new lg.default.Agent(y)},uc.push({options:y,agents:this.agent}))}c&&(_.body=c),u&&(_.searchParams=u),_.agent=this.agent,_.url=n,_.timeout={request:(this.client&&this.client.options.timeouts||J.TIMEOUTS).httpRequestTimeout},_.retry={limit:0};try{let T=await lc.default[r](_);return this._handler(null,T,T.body)}catch(T){return T instanceof lc.default.HTTPError?this._handler(null,T.response,T.response.body):this._handler(T)}}shouldFallback(r){let{code:n,statusCode:o}=r;return n==="ENETUNREACH"||n==="EHOSTUNREACH"||n==="EHOSTDOWN"||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||n==="ENOTFOUND"||n==="ECONNRESET"||n==="ECONNREFUSED"||o>=500&&o<=504}_handler(r,n,o){var c;if(r)return{error:r};let u=n.statusCode,f=n.headers;if(u>=300){switch(f["content-type"]){case"application/json":o=JSON.parse(o);break;case"application/x-msgpack":if(!((c=this.client)!=null&&c._MsgPack))return{error:ss("MsgPack")};o=this.client._MsgPack.decode(o);break}return{error:o.error?x.fromValues(o.error):new x(f["x-ably-errormessage"]||"Error response received from server: "+u+" body was: "+L.Config.inspect(o),Number(f["x-ably-errorcode"]),u),body:o,headers:f,unpacked:!0,statusCode:u}}return{error:null,body:o,headers:f,unpacked:!1,statusCode:u}}},cs.methods=[ce.Get,ce.Delete,ce.Post,ce.Put,ce.Patch],cs.methodsWithoutBody=[ce.Get,ce.Delete],cs.methodsWithBody=[ce.Post,ce.Put,ce.Patch],cs),hg=ug,dg=Z(q("crypto")),fg=Z(dn()),yr=Z(q("util")),pg={agent:"nodejs/"+process.versions.node,logTimestamps:!0,userAgent:null,binaryType:"nodebuffer",WebSocket:fg.default,useProtocolHeartbeats:!1,supportsBinary:!0,preferBinary:!0,nextTick:process.nextTick,inspect:yr.default.inspect,stringByteSize:Buffer.byteLength,inherits:yr.default.inherits,addEventListener:null,getRandomArrayBuffer:async function(r){return yr.default.promisify(dg.default.randomBytes)(r)}},gg=pg,hc=(r=>(r[r.REQ_SEND=0]="REQ_SEND",r[r.REQ_RECV=1]="REQ_RECV",r[r.REQ_RECV_POLL=2]="REQ_RECV_POLL",r[r.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",r))(hc||{}),ct=hc;function mg(r){let n=[80015,80017,80030];return r.code?We.isTokenErr(r)?!1:n.includes(r.code)?!0:r.code>=4e4&&r.code<5e4:!1}function _r(r){return mg(r)?[we({action:z.ERROR,error:r})]:[we({action:z.DISCONNECTED,error:r})]}var yg=class extends Mt{constructor(r,n,o){super(r,n,o,!0),this.onAuthUpdated=c=>{this.authParams={access_token:c.token}},this.stream="stream"in o?o.stream:!0,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","starting"),Mt.prototype.connect.call(this);let r=this.params,n=r.options,o=r.host||n.primaryDomain,c=J.getPort(n),u=n.tls?"https://":"http://";this.baseUri=u+o+":"+c+"/comet/";let f=this.baseUri+"connect";d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","uri: "+f),ke(this.auth.getAuthParams(),(y,_)=>{if(y){this.disconnect(y);return}if(this.isDisposed)return;this.authParams=_;let T=this.params.getConnectParams(_);"stream"in T&&(this.stream=T.stream),d.logAction(this.logger,d.LOG_MINOR,"CometTransport.connect()","connectParams:"+ts(T));let I=!1,D=this.recvRequest=this.createRequest(f,null,T,null,this.stream?ct.REQ_RECV_STREAM:ct.REQ_RECV);D.on("data",j=>{this.recvRequest&&(I||(I=!0,this.emit("preconnect")),this.onData(j))}),D.on("complete",j=>{if(this.recvRequest||(j=j||new x("Request cancelled",80003,400)),this.recvRequest=null,!I&&!j&&(I=!0,this.emit("preconnect")),this.onActivity(),j){j.code?this.onData(_r(j)):this.disconnect(j);return}L.Config.nextTick(()=>{this.recv()})}),D.exec()})}requestClose(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(r){let n=r?this.closeUri:this.disconnectUri;if(n){let o=this.createRequest(n,null,this.authParams,null,ct.REQ_SEND);o.on("complete",c=>{c&&(d.logAction(this.logger,d.LOG_ERROR,"CometTransport.request"+(r?"Close()":"Disconnect()"),"request returned err = "+ee(c)),this.finish("disconnected",c))}),o.exec()}}dispose(){d.logAction(this.logger,d.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(d.logAction(this.logger,d.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",yt.disconnected()),L.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(r){var n;if(this.isDisposed)return;let o=(n=r.connectionDetails)==null?void 0:n.connectionKey;Mt.prototype.onConnect.call(this,r);let c=this.baseUri+o;d.logAction(this.logger,d.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+c),this.sendUri=c+"/send",this.recvUri=c+"/recv",this.closeUri=c+"/close",this.disconnectUri=c+"/disconnect"}send(r){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(r);return}let n=this.pendingItems||[];n.push(r),this.pendingItems=null,this.sendItems(n)}sendAnyPending(){let r=this.pendingItems;r&&(this.pendingItems=null,this.sendItems(r))}sendItems(r){let n=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(r),ct.REQ_SEND);n.on("complete",(o,c)=>{if(o&&d.logAction(this.logger,d.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+ee(o)),this.sendRequest=null,o){o.code?this.onData(_r(o)):this.disconnect(o);return}c&&this.onData(c),this.pendingItems&&L.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),n.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let r=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?ct.REQ_RECV_STREAM:ct.REQ_RECV_POLL);r.on("data",n=>{this.onData(n)}),r.on("complete",n=>{if(this.recvRequest=null,this.onActivity(),n){n.code?this.onData(_r(n)):this.disconnect(n);return}L.Config.nextTick(()=>{this.recv()})}),r.exec()}onData(r){try{let n=this.decodeResponse(r);if(n&&n.length)for(let o=0;o<n.length;o++)this.onProtocolMessage(or(n[o],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(n){d.logAction(this.logger,d.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+n.stack)}}encodeRequest(r){return JSON.stringify(r)}decodeResponse(r){return typeof r=="string"?JSON.parse(r):r}},dc=yg,fc=Z(q("http")),pc=Z(q("https")),_g=Z(q("url")),bg=Z(q("util")),vg=function(){},wg=ge.Comet,Cg=class extends dc{constructor(r,n,o){super(r,n,o),this.httpAgent=null,this.httpsAgent=null,this.pendingRequests=0,this.shortName=wg}static isAvailable(){return!0}toString(){return"NodeCometTransport; uri="+this.baseUri+"; isConnected="+this.isConnected+"; format="+this.format+"; stream="+this.stream}getAgent(r){var n=r?"httpsAgent":"httpAgent",o=this[n];return o||(o=this[n]=new(r?pc.default:fc.default).Agent({keepAlive:!0})),o}dispose(){var r=this;this.onceNoPending(function(){r.httpAgent&&r.httpAgent.destroy(),r.httpsAgent&&r.httpsAgent.destroy()}),dc.prototype.dispose.call(this)}request(r,n,o,c,u){var f=this.createRequest(r,n,o,c);return f.once("complete",u),f.exec(),f}createRequest(r,n,o,c,u){return new Eg(r,n,o,c,u,this.format,this.timeouts,this)}addPending(){++this.pendingRequests}removePending(){--this.pendingRequests<=0&&this.emit("nopending")}onceNoPending(r){if(this.pendingRequests==0){r();return}this.once("nopending",r)}},Eg=class extends he{constructor(r,n,o,c,u,f,y,_){super(_.logger),typeof r=="string"&&(r=_g.default.parse(r));var T=r.protocol=="https:";this.client=T?pc.default:fc.default,this.requestMode=u,this.timeouts=y,this.transport=_,this.requestComplete=!1,this.req=this.res=null;var I="GET",D=f=="msgpack"?"application/x-msgpack":"application/json";n=n?Y({},n):{},n.accept=D,c&&(I="POST",Buffer.isBuffer(c)||(typeof c=="object"&&(c=JSON.stringify(c)),c=Buffer.from(c)),this.body=c,n["Content-Length"]=c.length,n["Content-Type"]=D);var j=this.requestOptions={hostname:r.hostname,port:r.port,path:r.path+ts(o),method:I,headers:n};_&&(j.agent=_.getAgent(T))}exec(){var r=this.requestMode==ct.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,n=this,o=this.timer=setTimeout(function(){n.abort()},r),c=this.req=this.client.request(this.requestOptions);c.on("error",this.onReqError=function(u){u=new Ee("Request error: "+u.message,null,400),clearTimeout(o),n.timer=null,n.complete(u)}),c.on("response",function(u){clearTimeout(o),n.timer=null;var f=u.statusCode;if(f==ns.NoContent){u.resume(),n.complete();return}u.on("error",n.onResError=function(y){y=new Ee("Response error: "+y.message,null,400),n.complete(y)}),n.res=u,n.requestMode==ct.REQ_RECV_STREAM&&f<400?n.readStream():n.readFully()}),this.transport&&this.transport.addPending(),c.end(this.body)}readStream(){var r=this.res,n=this;this.chunks=[],this.streamComplete=!1;function o(c){try{c=JSON.parse(c)}catch(f){var u="Malformed response body from server: "+f.message;d.logAction(n.logger,d.LOG_ERROR,"NodeCometTransport.Request.readStream()",u),n.complete(new Ee(u,null,400));return}n.emit("data",c)}r.on("data",this.ondata=function(c){var u=String(c).split(`
|
|
45
|
+
`),f=n.chunks;u.length>1&&f.length>0&&(f.push(u.shift()),n.chunks=[],o(f.join("")));var y=u.pop();y.length&&n.chunks.push(y),u.map(o)}),r.on("end",function(){n.streamComplete=!0,process.nextTick(function(){n.complete()})})}readFully(){var r=this.res,n=[],o=this;r.on("data",function(c){n.push(c)}),r.on("end",function(){process.nextTick(function(){var c=Buffer.concat(n),u=r.statusCode;try{c=JSON.parse(String(c))}catch(_){var f="Malformed response body from server: "+_.message;d.logAction(o.logger,d.LOG_ERROR,"NodeCometTransport.Request.readFully()",f),o.complete(new Ee(f,null,400));return}if(u<400||Array.isArray(c)){o.complete(null,c);return}var y=c.error&&x.fromValues(c.error);y||(y=new Ee("Error response received from server: "+u+", body was: "+bg.default.inspect(c),null,u)),o.complete(y)})})}complete(r,n){this.requestComplete||(this.requestComplete=!0,n&&this.emit("data",n),this.emit("complete",r,n),r&&this.ondata&&!this.streamComplete&&this.ondata&&this.res&&this.res.removeListener("data",this.ondata),this.transport&&this.transport.removePending())}abort(){d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","");var r=this.timer;r&&(clearTimeout(r),this.timer=null);var n=this.req;n&&(d.logAction(this.logger,d.LOG_MINOR,"NodeCometTransport.Request.abort()","aborting request"),n.removeListener("error",this.onReqError),n.on("error",vg),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},kg=Cg,Og={order:[ge.Comet],bundledImplementations:{[ge.WebSocket]:ic,[ge.Comet]:kg}},Sg={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[ge.WebSocket],restAgentOptions:{maxSockets:40,keepAlive:!0}},Tg=Sg,Ag=nf(),gc=ag(cc);L.Crypto=gc,L.BufferUtils=cc,L.Http=hg,L.Config=gg,L.Transports=Og,L.WebStorage=null;for(let r of[Za,oc])r.Crypto=gc,r._MsgPack=Ag;if(d.initLogHandlers(),L.Defaults=Tf(Tg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:x,Rest:Za,Realtime:oc,msgpack:null,makeProtocolMessageFromDeserialized:Ap},typeof i.exports=="object"&&typeof t=="object"){var Rg=(r,n,o,c)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of Object.getOwnPropertyNames(n))!Object.prototype.hasOwnProperty.call(r,u)&&u!==o&&Object.defineProperty(r,u,{get:()=>n[u],enumerable:!(c=Object.getOwnPropertyDescriptor(n,u))||c.enumerable});return r};i.exports=Rg(i.exports,t)}return i.exports})});var Pc=br(Rc(),1),{program:us,createCommand:Aw,createArgument:Rw,createOption:Pw,CommanderError:Iw,InvalidArgumentError:Mw,InvalidOptionArgumentError:xw,Command:Nw,Argument:Lw,Option:jw,Help:Dw}=Pc.default;var Kd=br(Dc(),1);import{resolve as zd}from"path";import{existsSync as bw}from"fs";function pm(s){let e=s.apiKey||process.env.SEGO_API_KEY,t=s.apiUrl||process.env.SEGO_API_URL||"https://sego.pm",i=s.pollIntervalMs||(process.env.AUTO_TASK_POLL_INTERVAL_MS?parseInt(process.env.AUTO_TASK_POLL_INTERVAL_MS,10):3e4),a=s.timeoutMs||(process.env.AUTO_TASK_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_TIMEOUT_MS,10):6e5),l=s.clientRequestTimeoutMs||(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS,10):3e5);if(!e)throw new Error("API key is required. Set SEGO_API_KEY environment variable or use --api-key flag.");let h=s.projectId||process.env.SEGO_PROJECT_ID,p=s.sseEnabled??process.env.AUTO_TASK_SSE_ENABLED!=="false",g=s.workingDirectory||process.env.SEGO_WORKING_DIR,m=s.useAgentSdk??process.env.USE_CLI_MODE!=="true",v=s.streamProgress??process.env.STREAM_PROGRESS!=="false",C=s.conversationOnly??process.env.CONVERSATION_ONLY==="true",k=s.autoCommit??process.env.AUTO_COMMIT==="true",S=s.autoPush??process.env.AUTO_PUSH==="true";return{apiKey:e,apiUrl:t,pollIntervalMs:i,timeoutMs:a,dryRun:s.dryRun??!1,projectId:h,sseEnabled:p,clientRequestTimeoutMs:l,workingDirectory:g,useAgentSdk:m,streamProgress:v,conversationOnly:C,autoCommit:k,autoPush:S}}function Uc(s){let e={apiKey:s.apiKey?"cli":process.env.SEGO_API_KEY?"env":"default",apiUrl:s.apiUrl?"cli":process.env.SEGO_API_URL?"env":"default",pollIntervalMs:s.pollIntervalMs?"cli":process.env.AUTO_TASK_POLL_INTERVAL_MS?"env":"default",timeoutMs:s.timeoutMs?"cli":process.env.AUTO_TASK_TIMEOUT_MS?"env":"default",dryRun:s.dryRun!==void 0?"cli":"default",projectId:s.projectId?"cli":process.env.SEGO_PROJECT_ID?"env":"default",sseEnabled:s.sseEnabled!==void 0?"cli":process.env.AUTO_TASK_SSE_ENABLED?"env":"default",clientRequestTimeoutMs:s.clientRequestTimeoutMs?"cli":process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?"env":"default",workingDirectory:s.workingDirectory?"cli":process.env.SEGO_WORKING_DIR?"env":"default",useAgentSdk:s.useAgentSdk!==void 0?"cli":process.env.USE_CLI_MODE?"env":"default",streamProgress:s.streamProgress!==void 0?"cli":process.env.STREAM_PROGRESS?"env":"default",conversationOnly:s.conversationOnly!==void 0?"cli":process.env.CONVERSATION_ONLY?"env":"default",autoCommit:s.autoCommit!==void 0?"cli":process.env.AUTO_COMMIT?"env":"default",autoPush:s.autoPush!==void 0?"cli":process.env.AUTO_PUSH?"env":"default"};return{config:pm(s),sources:e}}function Oe(s){switch(s){case"cli":return"[cli]";case"env":return"[env]";case"default":return"[default]"}}var Js=class{baseUrl;apiKey;projectId;constructor(e,t,i){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i}async request(e,t={}){let i=`${this.baseUrl}${e}`,a=await fetch(i,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(!a.ok){let l=await a.text(),h;try{let p=JSON.parse(l);h=p.error||p.message||l}catch{h=l}throw new Error(`API error (${a.status}): ${h}`)}return a.json()}async getEligibleTask(){let e=this.projectId?`/api/mcp/tasks/auto-task/eligible?projectId=${this.projectId}`:"/api/mcp/tasks/auto-task/eligible";return(await this.request(e)).task}async startTask(e){return this.request("/api/mcp/tasks/auto-task/start",{method:"POST",body:JSON.stringify({taskId:e})})}async completeTask(e,t,i){return this.request("/api/mcp/tasks/auto-task/complete",{method:"POST",body:JSON.stringify({runId:e,status:t,comment:i?.comment,errorMessage:i?.errorMessage})})}async sendAlert(e,t,i){return this.request("/api/notifications/auto-task-alert",{method:"POST",body:JSON.stringify({runId:e,alertType:t,errorDetails:i})})}async validateAuth(){try{return await this.request("/api/mcp/auth/validate",{method:"POST"}),!0}catch{return!1}}getClientRequestMonitorUrl(){if(!this.projectId)throw new Error("Project ID is required for client request monitoring");return`${this.baseUrl}/api/projects/${this.projectId}/client-requests/monitor`}getApiKey(){return this.apiKey}getProjectId(){return this.projectId}async submitAnalysis(e,t,i,a){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:i,processingTimeMs:a})})}async reportAnalysisFailure(e,t,i){return this.request(`/api/client-requests/${e}/analysis`,{method:"PUT",body:JSON.stringify({monitorId:t,error:i})})}async getClientRequest(e){try{let i=(await this.request(`/api/client-requests/${e}`)).request,a=i.project.brief;return{id:i.id,projectId:i.projectId,description:i.description,channel:i.channel,createdById:i.createdById,projectContext:{projectName:i.project.name,projectDescription:i.project.description,techStack:a?.techStack?.split(",").map(l=>l.trim()),existingFeatures:i.project.tasks?.map(l=>l.title),knowledgeBase:i.project.knowledgeBase||void 0}}}catch(t){return console.error(`[ApiClient] Failed to fetch client request ${e}:`,t),null}}async claimTask(e,t){if(!this.projectId)throw new Error("Project ID is required for claiming tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/claim`,{method:"POST",body:JSON.stringify({monitorId:t})})}async completeBacklogTask(e,t,i){if(!this.projectId)throw new Error("Project ID is required for completing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/complete`,{method:"POST",body:JSON.stringify({monitorId:t,result:i})})}async failBacklogTask(e,t,i,a=!0){if(!this.projectId)throw new Error("Project ID is required for failing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/fail`,{method:"POST",body:JSON.stringify({monitorId:t,error:i,returnToBacklog:a})})}formatEventPayload(e){return{type:e.type,timestamp:e.timestamp,message:e.message,emoji:e.emoji,data:e.data}}async sendAgentProgress(e,t,i){return this.request(`/api/client-requests/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}async sendTaskAgentProgress(e,t,i){if(!this.projectId)throw new Error("Project ID is required for task progress events");return this.request(`/api/projects/${this.projectId}/tasks/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(i)})})}};import{spawn as Ys}from"child_process";import{existsSync as qc,writeFileSync as Bc,unlinkSync as $c}from"fs";import{homedir as gm,tmpdir as Hc}from"os";import{join as Dr}from"path";function Qs(){let s=[Dr(gm(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(qc(e))return e;return"claude"}var me=null;function mm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.project.name}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,"","## Description",s.description,""];return s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.project.knowledgeBase&&(e.push("## Project Context"),e.push(s.project.knowledgeBase),e.push("")),e.push("---"),e.push(""),e.push('Please work on this task. When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
46
|
+
`)}async function Gc(s,e){let t=mm(s);return me||(me=Qs()),new Promise(i=>{let a="",l="",h=!1,p=!1,g=Ys(me,["--print","--dangerously-skip-permissions","--mcp-config",'{"mcpServers":{}}'],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()}});g.stdin?.write(t),g.stdin?.end();let m=setTimeout(()=>{h=!0,p=!0,g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},5e3)},e);g.stdout?.on("data",v=>{a+=v.toString()}),g.stderr?.on("data",v=>{l+=v.toString()}),g.on("close",v=>{if(clearTimeout(m),h){i({success:!1,output:a,error:"Process timed out",timedOut:!0});return}let C=a.includes("TASK_COMPLETE")&&!a.includes("TASK_BLOCKED");if(v!==0&&!p){i({success:!1,output:a,error:l||`Process exited with code ${v}`,timedOut:!1});return}let k=a.match(/TASK_BLOCKED:\s*(.+)/i);if(k){i({success:!1,output:a,error:`Task blocked: ${k[1]}`,timedOut:!1});return}i({success:C,output:a,error:C?void 0:"Task did not complete successfully",timedOut:!1})}),g.on("error",v=>{clearTimeout(m),i({success:!1,output:a,error:`Failed to spawn claude: ${v.message}`,timedOut:!1})})})}async function Fc(){return me=Qs(),me&&me!=="claude"&&qc(me)?(console.log(`Found Claude CLI at: ${me}`),!0):new Promise(s=>{let e=Ys(me,["--version"],{stdio:["pipe","pipe","pipe"]});e.on("close",t=>{s(t===0)}),e.on("error",()=>{s(!1)}),setTimeout(()=>{e.kill(),s(!1)},5e3)})}function ym(s){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",s.description,"","## Project Context","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&e.push(`**Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),s.projectContext.existingFeatures&&s.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),s.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
|
|
47
|
+
`)}function _m(s){let e=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=s.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function Wc(s,e,t={}){let i=ym(s),a=t.verbose??!0;return a&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",i.length,"characters")),me||(me=Qs()),new Promise(l=>{let h="",p="",g=!1,m=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let v=Dr(Hc(),`claude-prompt-${Date.now()}.txt`);Bc(v,i,"utf-8");let C=`cat "${v}" | ${me} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Working directory:",process.cwd()),console.log("[Claude] Temp file:",v),console.log("[Claude] Running via shell..."));let k=Ys("sh",["-c",C],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()},cwd:process.cwd()});a&&console.log("[Claude] Shell process started with PID:",k.pid),k.stdin?.end();let S=()=>{try{$c(v),a&&console.log("[Claude] Temp file cleaned up")}catch{}},A=setTimeout(()=>{g=!0,m=!0,console.log("[Claude] Timeout reached, killing process..."),k.kill("SIGTERM"),setTimeout(()=>{k.killed||k.kill("SIGKILL")},5e3)},e);k.stdout?.on("data",E=>{let O=E.toString();h+=O,a&&process.stdout.write(O)}),k.stderr?.on("data",E=>{let O=E.toString();p+=O,a&&process.stderr.write(`[Claude stderr] ${O}`)}),k.on("close",(E,O)=>{clearTimeout(A),S(),a&&(console.log(""),console.log(`[Claude] Process exited with code ${E}, signal ${O}`),console.log(`[Claude] Output length: ${h.length} characters`),console.log(`[Claude] Error output length: ${p.length} characters`),p&&console.log(`[Claude] Stderr: ${p.substring(0,500)}`));let N=_m(h);if(N&&N.summary&&Array.isArray(N.suggestedTasks)){a&&g&&console.log("[Claude] Timeout was triggered but we got valid output - treating as success"),l({success:!0,analysis:N,output:h,timedOut:!1});return}if(g){l({success:!1,output:h,error:"Process timed out without producing valid output",timedOut:!0});return}if(E!==0&&!m){l({success:!1,output:h,error:p||`Process exited with code ${E}`,timedOut:!1});return}if(!N){l({success:!1,output:h,error:"Failed to parse analysis JSON from output",timedOut:!1});return}if(!N.summary||!Array.isArray(N.suggestedTasks)){l({success:!1,output:h,error:"Invalid analysis structure - missing required fields",timedOut:!1});return}l({success:!0,analysis:N,output:h,timedOut:!1})}),k.on("error",E=>{clearTimeout(A),console.error("[Claude] Spawn error:",E),l({success:!1,output:h,error:`Failed to spawn claude: ${E.message}`,timedOut:!1})}),k.on("spawn",()=>{a&&console.log("[Claude] Process spawned successfully")})})}function bm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.projectContext.projectName}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,`**Estimated Hours:** ${s.estimatedHours||"N/A"}`,"","## Description",s.description||"No description provided.",""];if(s.acceptanceCriteria&&s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.projectContext.projectDescription&&(e.push("## Project Description"),e.push(s.projectContext.projectDescription),e.push("")),s.projectContext.knowledgeBase){e.push("## Project Knowledge Base");let t=s.projectContext.knowledgeBase;t.length>1e4?e.push(t.substring(0,1e4)+`
|
|
48
48
|
|
|
49
49
|
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
50
|
-
`)}async function Vc(s,e,t={}){let i=
|
|
51
|
-
`)}function zc(s){let e=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=s.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function Kc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=
|
|
50
|
+
`)}async function Vc(s,e,t={}){let i=bm(s),a=t.verbose??!0,l=t.workingDirectory||process.cwd();return a&&(console.log("[Claude] Starting backlog task processing..."),console.log("[Claude] Prompt length:",i.length,"characters"),console.log("[Claude] Working directory:",l)),me||(me=Qs()),a&&console.log("[Claude] Claude path:",me),new Promise(h=>{let p="",g="",m=!1,v=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let C=Dr(Hc(),`claude-task-${Date.now()}.txt`);Bc(C,i,"utf-8");let k=`cat "${C}" | ${me} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Temp file:",C),console.log("[Claude] Running via shell..."));let S=Ys("sh",["-c",k],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:l},cwd:l});a&&console.log("[Claude] Shell process started with PID:",S.pid);let A=0,E=setInterval(()=>{if(a&&!m){let K=Math.floor((Date.now()-O)/1e3);p.length===A&&console.log(`[Claude] Still running... ${K}s elapsed, ${p.length} bytes output, waiting for response...`),A=p.length}},3e4),O=Date.now();S.stdin?.end();let N=()=>{try{$c(C),a&&console.log("[Claude] Temp file cleaned up")}catch{}},H=setTimeout(()=>{m=!0,v=!0,clearInterval(E),console.log("[Claude] Timeout reached, killing process..."),console.log(`[Claude] Output collected: ${p.length} characters`),p.length>0&&console.log(`[Claude] Last 500 chars of output: ${p.slice(-500)}`),g.length>0&&console.log(`[Claude] Stderr: ${g.substring(0,500)}`),S.kill("SIGTERM"),setTimeout(()=>{S.killed||S.kill("SIGKILL")},5e3)},e);S.stdout?.on("data",K=>{let se=K.toString();p+=se,a&&process.stdout.write(se)}),S.stderr?.on("data",K=>{let se=K.toString();g+=se,a&&process.stderr.write(`[Claude stderr] ${se}`)}),S.on("close",(K,se)=>{clearTimeout(H),clearInterval(E),N(),a&&(console.log(""),console.log(`[Claude] Process exited with code ${K}, signal ${se}`),console.log(`[Claude] Output length: ${p.length} characters`),g&&console.log(`[Claude] Stderr: ${g.substring(0,1e3)}`));let Z=p.includes("TASK_COMPLETE"),Te=p.match(/TASK_BLOCKED:\s*(.+)/);if(m&&!Z){h({success:!1,output:p,error:"Process timed out",timedOut:!0});return}if(Te){h({success:!1,output:p,error:`Task blocked: ${Te[1]}`,timedOut:!1});return}if(K!==0&&!v){h({success:!1,output:p,error:g||`Process exited with code ${K}`,timedOut:!1});return}h({success:!0,output:p,timedOut:!1})}),S.on("error",K=>{clearTimeout(H),clearInterval(E),N(),console.error("[Claude] Spawn error:",K),h({success:!1,output:p,error:`Failed to spawn claude: ${K.message}`,timedOut:!1})}),S.on("spawn",()=>{a&&console.log("[Claude] Process spawned successfully")})})}import{query as Ur}from"@anthropic-ai/claude-agent-sdk";function vm(s,e){let t=e;switch(s){case"Read":return{emoji:"\u{1F4D6}",message:`Reading file: ${t?.file_path||"unknown"}`};case"Write":return{emoji:"\u270F\uFE0F",message:`Writing file: ${t?.file_path||"unknown"}`};case"Edit":return{emoji:"\u{1F4DD}",message:`Editing file: ${t?.file_path||"unknown"}`};case"Glob":return{emoji:"\u{1F50D}",message:`Searching for files: ${t?.pattern||"unknown pattern"}`};case"Grep":return{emoji:"\u{1F50E}",message:`Searching code: ${t?.pattern||"unknown pattern"}`};case"Bash":return{emoji:"\u{1F4BB}",message:`Running command: ${String(t?.command||"").substring(0,80)}${String(t?.command||"").length>80?"...":""}`};case"WebSearch":return{emoji:"\u{1F310}",message:`Web search: ${t?.query||"unknown query"}`};case"WebFetch":return{emoji:"\u{1F310}",message:`Fetching URL: ${t?.url||"unknown"}`};case"Task":return{emoji:"\u{1F916}",message:`Running sub-agent: ${t?.description||"task"}`};case"TodoWrite":return{emoji:"\u{1F4CB}",message:"Updating task list"};default:return{emoji:"\u{1F527}",message:`Using tool: ${s}`}}}function qr(s){let e={type:s.type,timestamp:s.timestamp};switch(s.type){case"tool_start":{let t=s.data,{message:i,emoji:a}=vm(t.tool,t.input);return{...e,emoji:a,message:i,data:{toolUseId:t.toolUseId,tool:t.tool}}}case"tool_end":{let t=s.data;return{...e,emoji:t.isError?"\u274C":"\u2705",message:t.isError?"Tool failed":"Tool completed",data:{toolUseId:t.toolUseId}}}case"thinking":{let t=s.data,i=t.text.substring(0,150);return{...e,emoji:"\u{1F4AD}",message:`${i}${t.text.length>150?"...":""}`}}case"assistant_message":{let t=s.data,i=t.text.substring(0,200);return{...e,emoji:"\u{1F4AC}",message:`${i}${t.text.length>200?"...":""}`,data:{text:t.text,uuid:t.uuid}}}case"result":{let t=s.data;return{...e,emoji:t.success?"\u{1F389}":"\u26A0\uFE0F",message:t.success?"Analysis complete":"Analysis completed with issues",data:t}}case"error":{let t=s.data;return{...e,emoji:"\u2757",message:`Error: ${t.error}`,data:t}}case"session_start":return{...e,emoji:"\u{1F680}",message:"Starting analysis..."};case"processing":{let t=s.data;return{...e,emoji:"\u23F3",message:t.message||`Processing... (${Math.round((t.elapsedMs||0)/1e3)}s)`,data:t}}default:return{...e,emoji:"\u2139\uFE0F",message:`Event: ${s.type}`,data:s.data}}}function wm(s){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",s.description,"","## Project Context","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&e.push(`**Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),s.projectContext.existingFeatures&&s.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),s.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
|
|
51
|
+
`)}function zc(s){let e=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=s.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function Kc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=wm(s),g=Date.now(),m="",v=!1;i&&(console.log("[Agent] Starting analysis with Claude Agent SDK..."),console.log("[Agent] Prompt length:",p.length,"characters"),console.log("[Agent] Working directory:",h),console.log("[Agent] Model: claude-opus-4-5-20250929"));let C=new AbortController,k=setTimeout(()=>{v=!0,C.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(A,E)=>{l&&l({type:A,timestamp:Date.now(),data:E})};S("session_start",{prompt:p.substring(0,200),cwd:h});try{let A=Ur({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits"}});for await(let E of A)switch(E.type){case"assistant":if(E.message.content){for(let N of E.message.content)if(N.type==="text")m+=N.text,i&&process.stdout.write(N.text),S("assistant_message",{text:N.text,uuid:E.uuid});else if(N.type==="thinking"){let H=N;i&&console.log(`[Agent] Thinking: ${H.thinking.substring(0,100)}...`),S("thinking",{text:H.thinking,uuid:E.uuid})}else if(N.type==="tool_use"||"name"in N){let H=N;i&&console.log(`[Agent] Tool: ${H.name}`),S("tool_start",{tool:H.name,toolUseId:H.id,input:H.input})}}break;case"user":if(E.message.content){for(let N of E.message.content)if(typeof N=="object"&&N!==null&&"type"in N&&N.type==="tool_result"){let H=N;S("tool_end",{toolUseId:H.tool_use_id,isError:H.is_error||!1,hasContent:!!H.content})}}break;case"result":i&&(console.log(""),console.log(`[Agent] Completed in ${E.duration_ms}ms`),console.log(`[Agent] Cost: $${E.total_cost_usd?.toFixed(4)||"N/A"}`)),clearTimeout(k);let O=zc(m);if(O&&O.summary&&Array.isArray(O.suggestedTasks))return S("result",{success:!0,analysis:O,costUsd:E.total_cost_usd,usage:E.usage}),{success:!0,analysis:O,output:m,timedOut:!1,totalCostUsd:E.total_cost_usd,usage:E.usage?{inputTokens:E.usage.input_tokens,outputTokens:E.usage.output_tokens}:void 0};if(E.subtype!=="success"){let N="result"in E?E.result:E.subtype;return S("error",{error:E.subtype,result:N}),{success:!1,output:m,error:`Agent error: ${E.subtype} - ${N}`,timedOut:!1,totalCostUsd:E.total_cost_usd}}return{success:!1,output:m,error:"Failed to parse analysis JSON from output",timedOut:!1,totalCostUsd:E.total_cost_usd}}return clearTimeout(k),{success:!1,output:m,error:"Query stream ended without result",timedOut:v}}catch(A){clearTimeout(k);let E=A instanceof Error?A.message:String(A);i&&console.error("[Agent] Error:",E),S("error",{error:E});let O=zc(m);return O&&O.summary&&Array.isArray(O.suggestedTasks)?(i&&console.log("[Agent] Got valid output despite error - treating as success"),{success:!0,analysis:O,output:m,timedOut:!1}):{success:!1,output:m,error:v?"Process timed out":E,timedOut:v}}}function Cm(s){let e=[`# Task: ${s.title}`,"",`**Project:** ${s.projectContext.projectName}`,`**Priority:** ${s.priority}`,`**Type:** ${s.type}`,`**Estimated Hours:** ${s.estimatedHours||"N/A"}`,"","## Description",s.description||"No description provided.",""];if(s.acceptanceCriteria&&s.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((t,i)=>{e.push(`${i+1}. ${t}`)}),e.push("")),s.technicalNotes&&(e.push("## Technical Notes"),e.push(s.technicalNotes),e.push("")),s.projectContext.projectDescription&&(e.push("## Project Description"),e.push(s.projectContext.projectDescription),e.push("")),s.projectContext.knowledgeBase){e.push("## Project Knowledge Base");let t=s.projectContext.knowledgeBase;t.length>1e4?e.push(t.substring(0,1e4)+`
|
|
52
52
|
|
|
53
53
|
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
54
|
-
`)}async function Jc(s,e={}){let{timeoutMs:t=6e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=
|
|
55
|
-
`)}function Om(s){let
|
|
56
|
-
`).
|
|
54
|
+
`)}async function Jc(s,e={}){let{timeoutMs:t=6e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=Cm(s),g=Date.now(),m="",v=!1;i&&(console.log("[Agent] Starting backlog task with Claude Agent SDK..."),console.log("[Agent] Task:",s.title),console.log("[Agent] Working directory:",h),console.log("[Agent] Model: claude-opus-4-5-20250929"));let C=new AbortController,k=setTimeout(()=>{v=!0,C.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(A,E)=>{l&&l({type:A,timestamp:Date.now(),data:E})};S("session_start",{task:s.title,cwd:h});try{let A=Ur({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","Write"],permissionMode:"acceptEdits"}});for await(let E of A)switch(E.type){case"assistant":if(E.message.content){for(let H of E.message.content)if(H.type==="text")m+=H.text,i&&process.stdout.write(H.text);else if("name"in H){let K=H;i&&console.log(`[Agent] Tool: ${K.name}`),S("tool_start",{tool:K.name,toolUseId:K.id,input:K.input})}}break;case"result":clearTimeout(k),i&&(console.log(""),console.log(`[Agent] Completed in ${E.duration_ms}ms`),console.log(`[Agent] Cost: $${E.total_cost_usd?.toFixed(4)||"N/A"}`));let O=m.includes("TASK_COMPLETE"),N=m.match(/TASK_BLOCKED:\s*(.+)/);return N?{success:!1,output:m,error:`Task blocked: ${N[1]}`,timedOut:!1,totalCostUsd:E.total_cost_usd}:{success:O||E.subtype==="success",output:m,timedOut:!1,totalCostUsd:E.total_cost_usd}}return clearTimeout(k),{success:!1,output:m,error:"Query stream ended without result",timedOut:v}}catch(A){clearTimeout(k);let E=A instanceof Error?A.message:String(A);return i&&console.error("[Agent] Error:",E),S("error",{error:E}),{success:!1,output:m,error:v?"Process timed out":E,timedOut:v}}}async function Yc(){try{return!0}catch{return!1}}function Qc(s){return s.includes("[CONVERSATIONAL SESSION]")}function Xc(s){return s.includes("MODE: PLANNING")?"planning":s.includes("MODE: BUILD")||s.includes("MODE: WORK")?"work":s.includes("[MODE: PLANNING")?"planning":"work"}function Em(s){let t=s.replace("[CONVERSATIONAL SESSION]","").trim().split(/\n---\nUser follow-up:\n/);if(t.length===1){let l=t[0].replace(/^User message:\s*/i,"").trim();return{initialMessage:l,followUps:[],latestMessage:l,isFollowUp:!1}}let i=t[0].replace(/^User message:\s*/i,"").trim(),a=t.slice(1).map(l=>l.trim());return{initialMessage:i,followUps:a,latestMessage:a[a.length-1],isFollowUp:!0}}function km(s,e){let t=["# PLANNING MODE - Exploration & Discovery","","You are a thoughtful collaborator helping a user explore and refine their ideas. Your role is to ask questions, discuss trade-offs, and help clarify requirements.","","## CRITICAL RULES FOR PLANNING MODE","","**DO NOT generate any tasks.** This is a strict requirement.","- Never output <task>JSON</task> blocks","- Never suggest specific task titles or estimates","- Focus entirely on understanding and exploration","","**Your goals in planning mode:**","1. Ask clarifying questions to understand the user's goals","2. Discuss trade-offs and alternatives","3. Help the user think through their idea thoroughly","4. Explore the codebase to understand context (but don't propose changes)","","---","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&t.push(`**Project Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((i,a)=>{t.push(`${a+1}. ${i}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message"),t.push(""),t.push(e.latestMessage)):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage)),t.push(""),t.push("---"),t.push(""),t.push("## Mode Switch Suggestion"),t.push(""),t.push("When you believe the requirements are clear enough to create actionable tasks, suggest switching to Build mode by outputting:"),t.push(""),t.push("<suggest_build_mode>"),t.push("Your reasoning for why the requirements are now clear enough"),t.push("</suggest_build_mode>"),t.push(""),t.push("Only suggest this when:"),t.push("- You have a good understanding of what the user wants to accomplish"),t.push("- Key technical decisions have been discussed"),t.push("- The scope is reasonably defined"),t.push(""),t.push("Remember: In planning mode, your job is to explore and clarify, NOT to generate tasks."),t.join(`
|
|
55
|
+
`)}function Om(s,e){let t=["# BUILD MODE - Task Creation","","You are helping create actionable development tasks. Your goal is to generate well-structured tasks based on the user's requirements.","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&t.push(`**Project Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push("This is an ongoing conversation. Here is what was discussed:"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((i,a)=>{t.push(`${a+1}. ${i}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message (respond to this)"),t.push(""),t.push(e.latestMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("This is a FOLLOW-UP message. DO NOT start over or re-introduce yourself."),t.push("Simply respond directly to their latest message, building on the context of the conversation."),t.push(""),t.push("If you already explored the codebase in a previous turn, you do NOT need to explore it again unless the user asks about something new."),t.push(""),t.push("**Refinement mode:** If the user is providing feedback on suggested tasks, immediately update or regenerate the tasks with their input.")):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("You have access to the full codebase, so explore it to understand the project structure."),t.push(""),t.push("**Your goal is to generate actionable tasks within this first exchange.** Don't spend time asking qualifying questions - use the codebase and project context to make informed assumptions. Briefly explore relevant files if needed, then propose concrete tasks."),t.push(""),t.push("The client should feel like their work is being shaped into actionable items immediately, not that they're entering an interview process.")),t.push(""),t.push("## Task Generation"),t.push(""),t.push("**IMPORTANT: Prioritize generating tasks quickly.** Clients want to feel like work is starting immediately."),t.push(""),t.push("- Generate initial task suggestions within your FIRST response whenever possible"),t.push("- Make reasonable assumptions based on the project context and codebase - don't ask questions you can answer yourself"),t.push("- If something is unclear, make a sensible default assumption, note it in the task, and let the client refine it"),t.push("- Only ask 1-2 critical questions if absolutely essential - prefer to suggest tasks with noted assumptions"),t.push("- Tasks can always be refined through follow-up conversation - the goal is momentum, not perfection"),t.push(""),t.push("When you identify work that should become a task, output it in this format:"),t.push("<task>"),t.push("{"),t.push(' "title": "Task title",'),t.push(' "description": "What needs to be done",'),t.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),t.push(' "estimatedHours": 4,'),t.push(' "priority": "MEDIUM",'),t.push(' "type": "FEATURE",'),t.push(' "technicalNotes": "Implementation notes (include any assumptions made)",'),t.push(' "aiConfidence": 0.85'),t.push("}"),t.push("</task>"),t.push(""),t.push('Include an "assumptions" section in technicalNotes if you made decisions the client might want to change.'),t.push(`After suggesting tasks, invite the client to refine: "These tasks are ready for review. Let me know if you'd like to adjust scope, estimates, or approach."`),t.push(""),t.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),t.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),t.join(`
|
|
56
|
+
`)}function Sm(s,e="work"){let t=Em(s.description);return e==="planning"?km(s,t):Om(s,t)}var Tm=["LOW","MEDIUM","HIGH","URGENT"],Am=["FEATURE","BUG","ENHANCEMENT","DOCUMENTATION","DESIGN","TECHNICAL_DEBT"];function Rm(s){let e=[],t=s.includes("<task>")&&s.includes("</task>");if(console.log(`[Agent] parseTasksFromOutput: hasTaskTags=${t}, outputLength=${s.length}`),!t)return console.log("[Agent] No <task> tags found in output"),e;let i=/<task>([\s\S]*?)<\/task>/g,a,l=0;for(;(a=i.exec(s))!==null;){l++;let h=a[1].trim();console.log(`[Agent] Found task block #${l}, parsing JSON...`);try{let p=h.replace(/^```json\s*/i,"").replace(/^```\s*/i,"").replace(/\s*```$/i,"").trim(),g=p.match(/\{[\s\S]*\}/);g&&(p=g[0]);let m=JSON.parse(p);if(!m.title||typeof m.title!="string"){console.warn(`[Agent] Task #${l} missing or invalid title, skipping`);continue}let v=Tm.includes(m.priority?.toUpperCase?.())?m.priority.toUpperCase():"MEDIUM",C=Am.includes(m.type?.toUpperCase?.())?m.type.toUpperCase():"FEATURE",k=Array.isArray(m.acceptanceCriteria)?m.acceptanceCriteria.filter(E=>typeof E=="string").map(E=>E.trim()):[],S=Math.max(0,Number(m.estimatedHours)||4),A=Math.min(1,Math.max(0,Number(m.aiConfidence||m.confidence)||.8));console.log(`[Agent] Parsed task #${l}: "${m.title}" (${v}, ${C}, ${S}h)`),e.push({title:String(m.title).trim(),description:String(m.description||"").trim(),acceptanceCriteria:k,estimatedHours:S,priority:v,type:C,technicalNotes:m.technicalNotes?String(m.technicalNotes).trim():void 0,aiConfidence:A})}catch(p){console.error(`[Agent] Failed to parse task #${l} JSON:`,p instanceof Error?p.message:p),console.error("[Agent] Raw task content (first 500 chars):",h.substring(0,500))}}return console.log(`[Agent] parseTasksFromOutput: returning ${e.length} valid tasks (found ${l} total blocks)`),e}async function Zc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:l,mode:h="work"}=e,p=a||process.cwd(),g=Sm(s,h),m="",v=!1;i&&(console.log("[Agent] Starting conversational session..."),console.log("[Agent] Mode:",h),console.log("[Agent] Working directory:",p));let C=new AbortController,k=setTimeout(()=>{v=!0,C.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(E,O)=>{l&&l({type:E,timestamp:Date.now(),data:O})};S("session_start",{cwd:p,mode:h});let A=h==="planning"?["Read","Glob","Grep","WebSearch","WebFetch"]:["Read","Edit","Glob","Grep","Bash","WebSearch"];try{let E=Ur({prompt:g,options:{allowedTools:A,permissionMode:"acceptEdits"}});for await(let O of E)switch(O.type){case"assistant":if(O.message.content){for(let H of O.message.content)if(H.type==="text")m+=H.text,i&&process.stdout.write(H.text),S("assistant_message",{text:H.text,uuid:O.uuid});else if(H.type==="thinking"){let K=H;i&&console.log(`[Agent] Thinking: ${K.thinking.substring(0,100)}...`),S("thinking",{text:K.thinking,uuid:O.uuid})}else if(H.type==="tool_use"||"name"in H){let K=H;i&&console.log(`[Agent] Tool: ${K.name}`),S("tool_start",{tool:K.name,toolUseId:K.id,input:K.input})}}break;case"user":if(O.message.content){for(let H of O.message.content)if(typeof H=="object"&&H!==null&&"type"in H&&H.type==="tool_result"){let K=H;S("tool_end",{toolUseId:K.tool_use_id,isError:K.is_error||!1,hasContent:!!K.content})}}break;case"result":clearTimeout(k),i&&(console.log(""),console.log(`[Agent] Completed in ${O.duration_ms}ms`),console.log(`[Agent] Cost: $${O.total_cost_usd?.toFixed(4)||"N/A"}`));let N=Rm(m);return i&&N.length>0&&console.log(`[Agent] Found ${N.length} task(s) in output`),S("result",{success:!0,output:m,tasks:N,costUsd:O.total_cost_usd}),{success:!0,output:m,tasks:N,timedOut:!1,totalCostUsd:O.total_cost_usd}}return clearTimeout(k),{success:!1,output:m,tasks:[],error:"Query stream ended without result",timedOut:v}}catch(E){clearTimeout(k);let O=E instanceof Error?E.message:String(E);return i&&console.error("[Agent] Error:",O),S("error",{error:O}),{success:!1,output:m,tasks:[],error:v?"Process timed out":O,timedOut:v}}}var Nd=br(xd(),1),Fn=class s{baseUrl;apiKey;projectId;monitorId;ably=null;channel=null;isRunning=!1;isStopping=!1;heartbeatInterval=null;static HEARTBEAT_INTERVAL_MS=3e4;onNewWorkHandler=null;onConnectedHandler=null;onErrorHandler=null;onDisconnectedHandler=null;constructor(e,t,i,a){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=i,this.monitorId=a}async start(){if(this.isRunning){console.log("[AblyWorkClient] Already running");return}console.log(`[AblyWorkClient] Starting Ably client for project ${this.projectId}`),this.isRunning=!0,this.isStopping=!1;try{this.ably=new Nd.default.Realtime({authCallback:(e,t)=>{this.fetchToken().then(i=>t(null,i)).catch(i=>t(i,null))},disconnectedRetryTimeout:1e3,suspendedRetryTimeout:5e3}),this.ably.connection.on("connected",()=>{console.log("[AblyWorkClient] Connected to Ably"),this.onConnectedHandler&&this.onConnectedHandler({projectId:this.projectId,projectName:"",monitorId:this.monitorId,timestamp:new Date().toISOString()})}),this.ably.connection.on("disconnected",()=>{console.log("[AblyWorkClient] Disconnected from Ably (will auto-reconnect)")}),this.ably.connection.on("suspended",()=>{console.log("[AblyWorkClient] Connection suspended"),this.onDisconnectedHandler&&this.onDisconnectedHandler()}),this.ably.connection.on("failed",e=>{console.error("[AblyWorkClient] Connection failed:",e.reason),this.onErrorHandler&&this.onErrorHandler(new Error(`Ably connection failed: ${e.reason?.message||"Unknown error"}`))}),this.channel=this.ably.channels.get(`project:${this.projectId}:work`),this.channel.subscribe("new_request",e=>{let t=e.data;console.log("[AblyWorkClient] Received work notification:",t),this.onNewWorkHandler&&!this.isStopping&&Promise.resolve(this.onNewWorkHandler(t)).catch(i=>{console.error("[AblyWorkClient] Error in new work handler:",i)})}),console.log(`[AblyWorkClient] Subscribed to project:${this.projectId}:work channel`),await this.waitForConnection(),this.startHeartbeat()}catch(e){throw console.error("[AblyWorkClient] Failed to start:",e),this.isRunning=!1,this.onErrorHandler&&this.onErrorHandler(e instanceof Error?e:new Error(String(e))),e}}async fetchToken(){let e=`${this.baseUrl}/api/ably/token`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({projectId:this.projectId,monitorId:this.monitorId})});if(!t.ok){let a=await t.text();throw new Error(`Failed to get Ably token (${t.status}): ${a}`)}let{tokenRequest:i}=await t.json();return console.log("[AblyWorkClient] Got scoped Ably token (registered as active)"),i}startHeartbeat(){this.stopHeartbeat(),this.sendHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.sendHeartbeat()},s.HEARTBEAT_INTERVAL_MS),console.log(`[AblyWorkClient] Started heartbeat (every ${s.HEARTBEAT_INTERVAL_MS/1e3}s)`)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}async sendHeartbeat(){if(!(!this.isRunning||this.isStopping))try{let e=`${this.baseUrl}/api/projects/${this.projectId}/monitor/heartbeat`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({monitorId:this.monitorId})});t.ok||console.error(`[AblyWorkClient] Heartbeat failed (${t.status})`)}catch(e){this.isRunning&&!this.isStopping&&console.error("[AblyWorkClient] Heartbeat error:",e)}}waitForConnection(e=1e4){return new Promise((t,i)=>{if(!this.ably){i(new Error("Ably client not initialized"));return}if(this.ably.connection.state==="connected"){t();return}let a=setTimeout(()=>{i(new Error("Connection timeout"))},e),l=h=>{h.current==="connected"?(clearTimeout(a),this.ably?.connection.off(l),t()):h.current==="failed"&&(clearTimeout(a),this.ably?.connection.off(l),i(new Error(`Connection failed: ${h.reason?.message||"Unknown error"}`)))};this.ably.connection.on(l)})}stop(){console.log("[AblyWorkClient] Stopping..."),this.isStopping=!0,this.isRunning=!1,this.stopHeartbeat(),this.channel&&(this.channel.unsubscribe(),this.channel=null),this.ably&&(this.ably.close(),this.ably=null),this.onDisconnectedHandler&&this.onDisconnectedHandler()}isConnected(){return this.isRunning&&!this.isStopping&&this.ably?.connection.state==="connected"}onNewWork(e){this.onNewWorkHandler=e}onConnected(e){this.onConnectedHandler=e}onError(e){this.onErrorHandler=e}onDisconnected(e){this.onDisconnectedHandler=e}};import{exec as Xv}from"child_process";import{promisify as Zv}from"util";var ew=Zv(Xv);async function it(s,e){try{return await ew(s,{cwd:e,maxBuffer:10485760})}catch(t){let i=t;if(i.stdout!==void 0||i.stderr!==void 0)return{stdout:i.stdout||"",stderr:i.stderr||""};throw t}}async function tw(s){try{return await it("git rev-parse --is-inside-work-tree",s),!0}catch{return!1}}async function Oo(s){let{stdout:e}=await it("git status --porcelain",s),t=[],i=[],a=[],l=e.trim().split(`
|
|
57
|
+
`).filter(Boolean);for(let h of l){let p=h[0],g=h[1],m=h.substring(3).trim();p!==" "&&p!=="?"&&t.push(m),g!==" "&&g!=="?"&&i.push(m),p==="?"&&g==="?"&&a.push(m)}return{hasChanges:t.length>0||i.length>0||a.length>0,staged:t,unstaged:i,untracked:a}}async function sw(s){let{stdout:e}=await it("git rev-parse --abbrev-ref HEAD",s);return e.trim()}async function nw(s){let{stdout:e}=await it("git rev-parse --short HEAD",s);return e.trim()}async function rw(s){await it("git add .",s)}async function iw(s,e,t){try{if(!(await Oo(s)).hasChanges)return{success:!1,filesCommitted:[],error:"No changes to commit"};await rw(s);let l=(await Oo(s)).staged,h=e;t&&(h=`${e}
|
|
57
58
|
|
|
58
|
-
Task-ID: ${t}`);let p=h.replace(/'/g,"'\\''");return await it(`git commit -m '${p}'`,s),{success:!0,commitHash:await
|
|
59
|
+
Task-ID: ${t}`);let p=h.replace(/'/g,"'\\''");return await it(`git commit -m '${p}'`,s),{success:!0,commitHash:await nw(s),filesCommitted:l}}catch(i){return{success:!1,filesCommitted:[],error:i instanceof Error?i.message:"Unknown error during commit"}}}async function ow(s){try{let e=await sw(s);try{await it("git rev-parse --abbrev-ref --symbolic-full-name @{u}",s)}catch{return console.log(`[Git] No upstream configured, setting upstream to origin/${e}`),await it(`git push -u origin ${e}`,s),{success:!0,branch:e,remote:"origin"}}return await it("git push",s),{success:!0,branch:e,remote:"origin"}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error during push"}}}async function So(s,e){let t={committed:!1,pushed:!1,commitHash:void 0,filesCommitted:[],error:void 0};if(!e.autoCommit)return t;if(!await tw(s))return t.error="Not a git repository",t;let a=await Oo(s);if(!a.hasChanges)return console.log("[Git] No changes to commit"),t;console.log(`[Git] Found ${a.unstaged.length+a.untracked.length} files with changes`);let l=`feat: ${e.taskTitle}
|
|
59
60
|
|
|
60
|
-
Automatically committed by Sego Auto-Task Monitor`;console.log("[Git] Committing changes...");let h=await ew(s,l,e.taskId);if(!h.success)return t.error=h.error,t;if(t.committed=!0,t.commitHash=h.commitHash,t.filesCommitted=h.filesCommitted,console.log(`[Git] Committed ${h.filesCommitted.length} files (${h.commitHash})`),e.autoPush){console.log("[Git] Pushing to remote...");let p=await tw(s);p.success?(t.pushed=!0,console.log(`[Git] Pushed to ${p.remote}/${p.branch}`)):(console.error(`[Git] Push failed: ${p.error}`),t.error=`Commit succeeded but push failed: ${p.error}`)}return t}import{randomBytes as sw}from"crypto";var Wn=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;ablyClient=null;monitorId;backlogTaskQueue=[];constructor(e){this.config=e,this.client=new Js(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${sw(8).toString("hex")}`}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] Real-time (Ably) enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),console.log(`[Monitor] Use Agent SDK: ${this.config.useAgentSdk}`),console.log(`[Monitor] Stream progress: ${this.config.streamProgress}`),console.log(`[Monitor] Conversation only: ${this.config.conversationOnly}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.config.sseEnabled&&this.config.projectId?await this.startAbly():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] Real-time disabled - project ID required for client request monitoring"),this.config.conversationOnly?console.log("[Monitor] Conversation-only mode - skipping auto-task polling"):await this.poll()}async startAbly(){try{console.log(`[Monitor] Connecting to Ably for project: ${this.config.projectId}`),this.ablyClient=new Fn(this.config.apiUrl,this.config.apiKey,this.config.projectId,this.monitorId),this.ablyClient.onConnected(e=>{console.log(`[Monitor] Ably connected to project: ${e.projectId}`),console.log(`[Monitor] Monitor ID: ${e.monitorId}`),console.log("[Monitor] Ready to receive work notifications")}),this.ablyClient.onNewWork(async e=>{console.log(`[Monitor] Received work notification: ${e.type} for ${e.requestId}`);try{let t=await this.client.getClientRequest(e.requestId);if(!t){console.error(`[Monitor] Client request ${e.requestId} not found`);return}let i={id:t.id,projectId:t.projectId,description:t.description,channel:t.channel,createdById:t.createdById,projectContext:t.projectContext||{projectName:"Unknown Project"}};await this.processClientRequest(i)}catch(t){console.error(`[Monitor] Error fetching client request ${e.requestId}:`,t)}}),this.ablyClient.onError(e=>{console.error("[Monitor] Ably error:",e.message)}),this.ablyClient.onDisconnected(()=>{console.log("[Monitor] Ably disconnected")}),await this.ablyClient.start()}catch(e){throw console.error("[Monitor] Failed to start Ably:",e),e}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}let t=Qc(e.description);if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Mode: ${t?"Conversational":"Analysis"}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log(`[Monitor] SDK Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}if(this.config.conversationOnly&&!t){console.log("[Monitor] Conversation-only mode - skipping non-conversational request analysis");return}this.isProcessingClientRequest=!0;let i=Date.now(),a=Date.now(),l="session_start",h=null;this.config.streamProgress&&(h=setInterval(async()=>{let p=Date.now()-a,g=Date.now()-i;if(p>5e3)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"processing",timestamp:Date.now(),message:l==="tool_end"?`Analyzing results... (${Math.round(g/1e3)}s)`:`Processing... (${Math.round(g/1e3)}s)`,emoji:"\u23F3",data:{elapsedMs:g,lastEventType:l,timeSinceLastEventMs:p}})}catch{}},5e3));try{console.log(`[Monitor] Running Claude for ${t?"conversation":"analysis"}...`),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let p=this.config.streamProgress?async v=>{a=Date.now(),l=v.type;let O=Dr(v);console.log(`[Monitor] ${O.emoji} ${O.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,O)}catch(k){console.error("[Monitor] Failed to send progress event:",k)}}:void 0;if(t&&this.config.useAgentSdk){let v=await Xc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p});console.log("-".repeat(60));let O=Date.now()-i;if(v.totalCostUsd&&console.log(`[Monitor] Agent cost: $${v.totalCostUsd.toFixed(4)}`),v.timedOut){console.log("[Monitor] Claude timed out for conversation");try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:"Conversation timed out",emoji:"\u23F1\uFE0F",data:{error:"timeout",message:"The agent took too long to respond"}})}catch(k){console.error("[Monitor] Failed to send timeout event:",k)}return}if(!v.success){console.log(`[Monitor] Conversation error: ${v.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:v.error||"Unknown error",emoji:"\u274C",data:{error:v.error}})}catch(k){console.error("[Monitor] Failed to send error event:",k)}return}if(console.log(`[Monitor] Conversation completed (${O}ms)`),console.log(`[Monitor] Result has ${v.tasks?.length||0} tasks`),v.tasks&&v.tasks.length>0){console.log(`[Monitor] Sending ${v.tasks.length} suggested task(s) to frontend`);for(let k of v.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${k.title}`,emoji:"\u{1F4CB}",data:{task:k}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${k.title}`)}catch(T){console.error("[Monitor] Failed to send task_suggested event:",T)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${v.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:v.tasks?.length||0,processingTimeMs:O}}),console.log("[Monitor] \u2705 Sent result event")}catch(k){console.error("[Monitor] Failed to send result event:",k)}return}let g;this.config.useAgentSdk?(g=await Kc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p}),g.totalCostUsd&&console.log(`[Monitor] Agent cost: $${g.totalCostUsd.toFixed(4)}`)):g=await Wc(e,this.config.clientRequestTimeoutMs,{verbose:!0}),console.log("-".repeat(60));let y=Date.now()-i;if(g.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!g.success||!g.analysis){console.log(`[Monitor] Claude analysis failed: ${g.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,g.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let C=await this.client.submitAnalysis(e.id,this.monitorId,g.analysis,y);console.log(`[Monitor] Analysis submitted successfully - ${C.tasksCount} tasks suggested (${y}ms)`)}catch(p){console.error("[Monitor] Error processing client request:",p);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,p instanceof Error?p.message:"Unknown error")}catch(g){console.error("[Monitor] Failed to report analysis failure:",g)}}finally{h&&clearInterval(h),this.isProcessingClientRequest=!1}}async handleTaskAvailable(e){if(console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.config.conversationOnly){console.log("[Monitor] Conversation-only mode - skipping task processing");return}this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log(`[Monitor] Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now();try{console.log("[Monitor] Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let i;this.config.useAgentSdk?(i=await Jc(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async p=>{let g=Dr(p);console.log(`[Monitor] ${g.emoji} ${g.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,g)}catch(y){console.error("[Monitor] Failed to send progress event:",y)}}:void 0}),i.totalCostUsd&&console.log(`[Monitor] Agent cost: $${i.totalCostUsd.toFixed(4)}`)):i=await Vc(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let a=Date.now()-t;if(i.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!i.success){console.log(`[Monitor] Claude failed: ${i.error}`),await this.client.failBacklogTask(e.id,this.monitorId,i.error||"Unknown error",!0);return}let l,h=[];if(this.config.autoCommit){console.log("[Monitor] Running auto-commit...");let p=this.config.workingDirectory||process.cwd(),g=await So(p,{taskId:e.id,taskTitle:e.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush});g.committed?(l=g.commitHash,h=g.filesCommitted,console.log(`[Monitor] Auto-commit successful: ${l} (${h.length} files)`),g.pushed?console.log("[Monitor] Auto-push successful"):this.config.autoPush&&g.error&&console.warn(`[Monitor] Auto-push failed: ${g.error}`)):g.error&&g.error!=="No changes to commit"?console.warn(`[Monitor] Auto-commit failed: ${g.error}`):console.log("[Monitor] No changes to commit")}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:i.output?.substring(0,1e3)||"Task completed by auto-monitor",filesChanged:h.length>0?h:void 0,commitHash:l}),console.log(`[Monitor] Task ${e.id} completed successfully (${a}ms)`)}catch(i){console.error("[Monitor] Error processing backlog task:",i);try{await this.client.failBacklogTask(e.id,this.monitorId,i instanceof Error?i.message:"Unknown error",!0)}catch(a){console.error("[Monitor] Failed to report task failure:",a)}}finally{this.isProcessingBacklogTask=!1,this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.ablyClient&&(this.ablyClient.stop(),this.ablyClient=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let i=await Gc(e,this.config.timeoutMs);if(i.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",i.output,"Task processing timed out");return}if(!i.success){console.log(`[Monitor] Claude failed: ${i.error}`),await this.handleFailure(t.runId,e,"FAILED",i.output,i.error);return}console.log("[Monitor] Claude completed successfully"),await this.handleSuccess(t.runId,e,i.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,i){let a="";if(this.config.autoCommit){console.log("[Monitor] Running auto-commit...");let p=this.config.workingDirectory||process.cwd(),g=await So(p,{taskId:t.id,taskTitle:t.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush});g.committed?(a=`
|
|
61
|
+
Automatically committed by Sego Auto-Task Monitor`;console.log("[Git] Committing changes...");let h=await iw(s,l,e.taskId);if(!h.success)return t.error=h.error,t;if(t.committed=!0,t.commitHash=h.commitHash,t.filesCommitted=h.filesCommitted,console.log(`[Git] Committed ${h.filesCommitted.length} files (${h.commitHash})`),e.autoPush){console.log("[Git] Pushing to remote...");let p=await ow(s);p.success?(t.pushed=!0,console.log(`[Git] Pushed to ${p.remote}/${p.branch}`)):(console.error(`[Git] Push failed: ${p.error}`),t.error=`Commit succeeded but push failed: ${p.error}`)}return t}import{randomBytes as aw}from"crypto";var Wn=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;ablyClient=null;monitorId;backlogTaskQueue=[];constructor(e){this.config=e,this.client=new Js(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${aw(8).toString("hex")}`}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] Real-time (Ably) enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),console.log(`[Monitor] Use Agent SDK: ${this.config.useAgentSdk}`),console.log(`[Monitor] Stream progress: ${this.config.streamProgress}`),console.log(`[Monitor] Conversation only: ${this.config.conversationOnly}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.config.sseEnabled&&this.config.projectId?await this.startAbly():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] Real-time disabled - project ID required for client request monitoring"),this.config.conversationOnly?console.log("[Monitor] Conversation-only mode - skipping auto-task polling"):await this.poll()}async startAbly(){try{console.log(`[Monitor] Connecting to Ably for project: ${this.config.projectId}`),this.ablyClient=new Fn(this.config.apiUrl,this.config.apiKey,this.config.projectId,this.monitorId),this.ablyClient.onConnected(e=>{console.log(`[Monitor] Ably connected to project: ${e.projectId}`),console.log(`[Monitor] Monitor ID: ${e.monitorId}`),console.log("[Monitor] Ready to receive work notifications")}),this.ablyClient.onNewWork(async e=>{console.log(`[Monitor] Received work notification: ${e.type} for ${e.requestId}`);try{let t=await this.client.getClientRequest(e.requestId);if(!t){console.error(`[Monitor] Client request ${e.requestId} not found`);return}let i={id:t.id,projectId:t.projectId,description:t.description,channel:t.channel,createdById:t.createdById,projectContext:t.projectContext||{projectName:"Unknown Project"}};await this.processClientRequest(i)}catch(t){console.error(`[Monitor] Error fetching client request ${e.requestId}:`,t)}}),this.ablyClient.onError(e=>{console.error("[Monitor] Ably error:",e.message)}),this.ablyClient.onDisconnected(()=>{console.log("[Monitor] Ably disconnected")}),await this.ablyClient.start()}catch(e){throw console.error("[Monitor] Failed to start Ably:",e),e}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}let t=Qc(e.description);if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Mode: ${t?"Conversational":"Analysis"}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log(`[Monitor] SDK Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}if(this.config.conversationOnly&&!t){console.log("[Monitor] Conversation-only mode - skipping non-conversational request analysis");return}this.isProcessingClientRequest=!0;let i=Date.now(),a=Date.now(),l="session_start",h=null;this.config.streamProgress&&(h=setInterval(async()=>{let p=Date.now()-a,g=Date.now()-i;if(p>5e3)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"processing",timestamp:Date.now(),message:l==="tool_end"?`Analyzing results... (${Math.round(g/1e3)}s)`:`Processing... (${Math.round(g/1e3)}s)`,emoji:"\u23F3",data:{elapsedMs:g,lastEventType:l,timeSinceLastEventMs:p}})}catch{}},5e3));try{console.log(`[Monitor] Running Claude for ${t?"conversation":"analysis"}...`),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let p=this.config.streamProgress?async C=>{a=Date.now(),l=C.type;let k=qr(C);console.log(`[Monitor] ${k.emoji} ${k.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,k)}catch(S){console.error("[Monitor] Failed to send progress event:",S)}}:void 0;if(t&&this.config.useAgentSdk){let C=Xc(e.description);console.log(`[Monitor] Conversation mode: ${C}`);let k=await Zc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p,mode:C});console.log("-".repeat(60));let S=Date.now()-i;if(k.totalCostUsd&&console.log(`[Monitor] Agent cost: $${k.totalCostUsd.toFixed(4)}`),k.timedOut){console.log("[Monitor] Claude timed out for conversation");try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:"Conversation timed out",emoji:"\u23F1\uFE0F",data:{error:"timeout",message:"The agent took too long to respond"}})}catch(A){console.error("[Monitor] Failed to send timeout event:",A)}return}if(!k.success){console.log(`[Monitor] Conversation error: ${k.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:k.error||"Unknown error",emoji:"\u274C",data:{error:k.error}})}catch(A){console.error("[Monitor] Failed to send error event:",A)}return}if(console.log(`[Monitor] Conversation completed (${S}ms)`),console.log(`[Monitor] Result has ${k.tasks?.length||0} tasks`),k.tasks&&k.tasks.length>0){console.log(`[Monitor] Sending ${k.tasks.length} suggested task(s) to frontend`);for(let A of k.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${A.title}`,emoji:"\u{1F4CB}",data:{task:A}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${A.title}`)}catch(E){console.error("[Monitor] Failed to send task_suggested event:",E)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${k.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:k.tasks?.length||0,processingTimeMs:S}}),console.log("[Monitor] \u2705 Sent result event")}catch(A){console.error("[Monitor] Failed to send result event:",A)}return}let g;this.config.useAgentSdk?(g=await Kc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p}),g.totalCostUsd&&console.log(`[Monitor] Agent cost: $${g.totalCostUsd.toFixed(4)}`)):g=await Wc(e,this.config.clientRequestTimeoutMs,{verbose:!0}),console.log("-".repeat(60));let m=Date.now()-i;if(g.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!g.success||!g.analysis){console.log(`[Monitor] Claude analysis failed: ${g.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,g.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let v=await this.client.submitAnalysis(e.id,this.monitorId,g.analysis,m);console.log(`[Monitor] Analysis submitted successfully - ${v.tasksCount} tasks suggested (${m}ms)`)}catch(p){console.error("[Monitor] Error processing client request:",p);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,p instanceof Error?p.message:"Unknown error")}catch(g){console.error("[Monitor] Failed to report analysis failure:",g)}}finally{h&&clearInterval(h),this.isProcessingClientRequest=!1}}async handleTaskAvailable(e){if(console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.config.conversationOnly){console.log("[Monitor] Conversation-only mode - skipping task processing");return}this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log(`[Monitor] Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now();try{console.log("[Monitor] Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let i;this.config.useAgentSdk?(i=await Jc(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async p=>{let g=qr(p);console.log(`[Monitor] ${g.emoji} ${g.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,g)}catch(m){console.error("[Monitor] Failed to send progress event:",m)}}:void 0}),i.totalCostUsd&&console.log(`[Monitor] Agent cost: $${i.totalCostUsd.toFixed(4)}`)):i=await Vc(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let a=Date.now()-t;if(i.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!i.success){console.log(`[Monitor] Claude failed: ${i.error}`),await this.client.failBacklogTask(e.id,this.monitorId,i.error||"Unknown error",!0);return}let l,h=[];if(this.config.autoCommit){console.log("[Monitor] Running auto-commit...");let p=this.config.workingDirectory||process.cwd(),g=await So(p,{taskId:e.id,taskTitle:e.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush});g.committed?(l=g.commitHash,h=g.filesCommitted,console.log(`[Monitor] Auto-commit successful: ${l} (${h.length} files)`),g.pushed?console.log("[Monitor] Auto-push successful"):this.config.autoPush&&g.error&&console.warn(`[Monitor] Auto-push failed: ${g.error}`)):g.error&&g.error!=="No changes to commit"?console.warn(`[Monitor] Auto-commit failed: ${g.error}`):console.log("[Monitor] No changes to commit")}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:i.output?.substring(0,1e3)||"Task completed by auto-monitor",filesChanged:h.length>0?h:void 0,commitHash:l}),console.log(`[Monitor] Task ${e.id} completed successfully (${a}ms)`)}catch(i){console.error("[Monitor] Error processing backlog task:",i);try{await this.client.failBacklogTask(e.id,this.monitorId,i instanceof Error?i.message:"Unknown error",!0)}catch(a){console.error("[Monitor] Failed to report task failure:",a)}}finally{this.isProcessingBacklogTask=!1,this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.ablyClient&&(this.ablyClient.stop(),this.ablyClient=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let i=await Gc(e,this.config.timeoutMs);if(i.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",i.output,"Task processing timed out");return}if(!i.success){console.log(`[Monitor] Claude failed: ${i.error}`),await this.handleFailure(t.runId,e,"FAILED",i.output,i.error);return}console.log("[Monitor] Claude completed successfully"),await this.handleSuccess(t.runId,e,i.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,i){let a="";if(this.config.autoCommit){console.log("[Monitor] Running auto-commit...");let p=this.config.workingDirectory||process.cwd(),g=await So(p,{taskId:t.id,taskTitle:t.title,autoCommit:this.config.autoCommit,autoPush:this.config.autoPush});g.committed?(a=`
|
|
61
62
|
|
|
62
63
|
### Git
|
|
63
64
|
- Commit: \`${g.commitHash}\`
|
|
@@ -73,7 +74,7 @@ Automatically committed by Sego Auto-Task Monitor`;console.log("[Git] Committing
|
|
|
73
74
|
${h}${a}`}),console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,i,a,l){let p=a.length>3e3?`${a.substring(0,3e3)}...
|
|
74
75
|
|
|
75
76
|
[Output truncated]`:a,g=[`## Auto-Task ${i==="TIMEOUT"?"Timed Out":"Failed"}`,"",l?`**Error:** ${l}`:"","","### Output","```",p,"```"].filter(Boolean).join(`
|
|
76
|
-
`);await this.client.completeTask(e,i,{comment:g,errorMessage:l}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let
|
|
77
|
+
`);await this.client.completeTask(e,i,{comment:g,errorMessage:l}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let m=await this.client.sendAlert(e,i,l);console.log(`[Monitor] Alert sent to ${m.emailsSent} recipients`)}catch(m){console.error("[Monitor] Failed to send alert:",m)}}};import{createInterface as cw}from"readline";import{writeFileSync as Ld,existsSync as lw}from"fs";import{resolve as jd}from"path";function uw(){let s=cw({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{s.question(e,i=>{t(i.trim())})}),close:()=>s.close()}}async function Dd(s,e){try{return(await fetch(`${s}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function Ud(s){let e=`# Sego Auto-Task Monitor Configuration
|
|
77
78
|
# Generated by sego-auto-task init
|
|
78
79
|
|
|
79
80
|
# Required: Your Sego PM API key
|
|
@@ -84,10 +85,10 @@ SEGO_API_URL=${s.apiUrl}
|
|
|
84
85
|
`;return s.projectId&&(e+=`
|
|
85
86
|
# Filter to specific project
|
|
86
87
|
SEGO_PROJECT_ID=${s.projectId}
|
|
87
|
-
`),e}async function
|
|
88
|
-
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${a}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!");let p={apiKey:i,apiUrl:a,projectId:l||void 0},g=
|
|
89
|
-
Error: API key is required.`),process.exit(1)),console.log(""),console.log("Step 2: API URL");let l=await t.ask("Enter API URL (press Enter for https://sego.pm): ")||"https://sego.pm";console.log(""),console.log("Validating API key..."),await
|
|
90
|
-
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${l}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let p=await t.ask("Enter Project ID (press Enter to skip): "),g={apiKey:i,apiUrl:l,projectId:p||void 0};console.log(""),console.log("Step 4: Save Configuration");let
|
|
88
|
+
`),e}async function Bd(s={}){let e=s.yes||!1;if(console.log(""),console.log("=".repeat(50)),console.log(" Sego Auto-Task Monitor Setup Wizard"),console.log("=".repeat(50)),console.log(""),e){console.log("Running in non-interactive mode (--yes flag)"),console.log("");let i=process.env.SEGO_API_KEY,a=process.env.SEGO_API_URL||"https://sego.pm",l=process.env.SEGO_PROJECT_ID;i||(console.error("Error: SEGO_API_KEY environment variable is required in non-interactive mode."),console.error(""),console.error("Usage:"),console.error(" SEGO_API_KEY=your_key sego-auto-task init --yes"),console.error(""),console.error("Or run without --yes for interactive setup."),process.exit(1)),console.log("Validating API key..."),await Dd(a,i)||(console.error(`
|
|
89
|
+
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${a}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!");let p={apiKey:i,apiUrl:a,projectId:l||void 0},g=jd(process.cwd(),".env"),m=Ud(p);Ld(g,m),qd(g);return}let t=uw();try{console.log("Step 1: API Key"),console.log("Get your API key from: https://sego.pm/developer/api-keys"),console.log("");let i=await t.ask("Enter your Sego PM API key: ");i||(console.error(`
|
|
90
|
+
Error: API key is required.`),process.exit(1)),console.log(""),console.log("Step 2: API URL");let l=await t.ask("Enter API URL (press Enter for https://sego.pm): ")||"https://sego.pm";console.log(""),console.log("Validating API key..."),await Dd(l,i)||(console.error(`
|
|
91
|
+
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${l}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let p=await t.ask("Enter Project ID (press Enter to skip): "),g={apiKey:i,apiUrl:l,projectId:p||void 0};console.log(""),console.log("Step 4: Save Configuration");let m=jd(process.cwd(),".env");if(lw(m)&&(console.log(`Warning: .env file already exists at ${m}`),(await t.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${g.apiKey}"`),console.log(`export SEGO_API_URL="${g.apiUrl}"`),g.projectId&&console.log(`export SEGO_PROJECT_ID="${g.projectId}"`),console.log(""),t.close();return}let C=Ud(g);Ld(m,C),qd(m)}finally{t.close()}}function qd(s){console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${s}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}import{existsSync as Hd,mkdirSync as hw,readFileSync as dw,writeFileSync as fw}from"fs";import{homedir as pw}from"os";import{join as Gd}from"path";var Fd="@segosolutions/auto-task",To=Gd(pw(),".sego-auto-task"),Ao=Gd(To,"version-check.json"),gw=24*60*60*1e3;function $d(s,e){let t=s.replace(/^v/,"").split(".").map(Number),i=e.replace(/^v/,"").split(".").map(Number);for(let a=0;a<Math.max(t.length,i.length);a++){let l=t[a]||0,h=i[a]||0;if(l<h)return-1;if(l>h)return 1}return 0}function mw(){try{if(!Hd(Ao))return null;let s=JSON.parse(dw(Ao,"utf-8"));return Date.now()-s.checkedAt<gw?s:null}catch{return null}}function yw(s){try{Hd(To)||hw(To,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};fw(Ao,JSON.stringify(e,null,2))}catch{}}async function _w(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(Fd)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function Wd(s){let e=mw();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:$d(s,e.latestVersion)<0};let t=await _w();return t&&yw(t),{currentVersion:s,latestVersion:t,updateAvailable:t?$d(s,t)<0:!1}}function Vd(s){!s.updateAvailable||!s.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${s.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${s.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${Fd}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var Jd="1.5.0",Ro=null;us.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
|
|
91
92
|
|
|
92
93
|
Runs in hybrid mode:
|
|
93
94
|
- SSE: Listens for client request events and processes them with local Claude
|
|
@@ -95,8 +96,8 @@ Runs in hybrid mode:
|
|
|
95
96
|
|
|
96
97
|
Environment variables are loaded from .env in the working directory.
|
|
97
98
|
|
|
98
|
-
Use "sego-auto-task init" to run the interactive setup wizard.`).version(
|
|
99
|
-
Received shutdown signal`),
|
|
99
|
+
Use "sego-auto-task init" to run the interactive setup wizard.`).version(Jd);us.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async s=>{await Bd({yes:s.yes})});us.option("--api-key <key>","Sego PM API key (or set SEGO_API_KEY env)").option("--api-url <url>","Sego PM API URL (default: https://sego.pm)").option("--project-id <id>","Only process tasks for this project (or set SEGO_PROJECT_ID env). Required for SSE mode.").option("--poll <seconds>","Poll interval in seconds (default: 30)","30").option("--timeout <minutes>","Task timeout in minutes (default: 10)","10").option("--client-request-timeout <minutes>","Client request analysis timeout in minutes (default: 2)","2").option("--no-sse","Disable SSE mode for client request processing").option("--dry-run","Poll but do not process tasks",!1).option("--working-dir <path>","Working directory for Claude and .env loading (or set SEGO_WORKING_DIR env)").option("--no-update-check","Disable update check on startup").option("--use-cli-mode","Use CLI subprocess instead of Agent SDK (legacy mode)").option("--no-stream-progress","Disable streaming agent progress events to the web app").option("--auto-commit","Automatically commit changes after task completion").option("--auto-push","Automatically push commits to remote (requires --auto-commit)").option("--conversation-only","Only handle conversational sessions, skip automatic task processing").action(async s=>{try{s.updateCheck!==!1&&(Ro=Wd(Jd).then(Vd).catch(()=>{}));let e=s.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=zd(e),i=zd(t,".env");bw(i)?(console.log(`Loading environment from: ${i}`),Kd.default.config({path:i})):console.log(`No .env file found in: ${t}`);let a=s.useCliMode||process.env.USE_CLI_MODE==="true";a?(console.log("Checking for Claude CLI (legacy mode)..."),await Fc()||(console.error("Error: Claude CLI is not available. Please install Claude Code first."),console.error(" npm install -g @anthropic-ai/claude-code"),process.exit(1)),console.log("Claude CLI is available")):(console.log("Checking for Claude Agent SDK..."),await Yc()||(console.error("Error: Claude Agent SDK is not available."),process.exit(1)),console.log("Claude Agent SDK is available"));let{config:l,sources:h}=Uc({apiKey:s.apiKey,apiUrl:s.apiUrl,projectId:s.projectId,pollIntervalMs:parseInt(s.poll,10)*1e3,timeoutMs:parseInt(s.timeout,10)*60*1e3,clientRequestTimeoutMs:parseInt(s.clientRequestTimeout,10)*60*1e3,sseEnabled:s.sse!==!1?void 0:!1,dryRun:s.dryRun?!0:void 0,workingDirectory:t,useAgentSdk:a?!1:void 0,streamProgress:s.streamProgress===!1?!1:void 0,conversationOnly:s.conversationOnly?!0:void 0,autoCommit:s.autoCommit?!0:void 0,autoPush:s.autoPush?!0:void 0}),g=l.apiUrl.includes("sego.pm")||l.apiUrl.includes("vercel")?"PRODUCTION":"DEVELOPMENT";console.log(""),console.log("=".repeat(70)),console.log("Sego Auto-Task Monitor - Configuration"),console.log("=".repeat(70)),console.log(`Environment: ${g}`),console.log(`API URL: ${l.apiUrl} ${Oe(h.apiUrl)}`),console.log(`SSE Mode: ${l.sseEnabled?"enabled":"disabled"} ${Oe(h.sseEnabled)}`),console.log(`Project Filter: ${l.projectId||"all projects"} ${Oe(h.projectId)}`),console.log(`Poll Interval: ${l.pollIntervalMs/1e3}s ${Oe(h.pollIntervalMs)}`),console.log(`Task Timeout: ${l.timeoutMs/6e4}min ${Oe(h.timeoutMs)}`),console.log(`Dry Run: ${l.dryRun?"yes":"no"} ${Oe(h.dryRun)}`),console.log(`Working Dir: ${l.workingDirectory} ${Oe(h.workingDirectory)}`),console.log(`Execution Mode: ${l.useAgentSdk?"Agent SDK":"CLI subprocess (legacy)"} ${Oe(h.useAgentSdk)}`),console.log(`Stream Progress: ${l.streamProgress?"yes":"no"} ${Oe(h.streamProgress)}`),console.log(`Conv. Only: ${l.conversationOnly?"yes":"no"} ${Oe(h.conversationOnly)}`),console.log(`Auto-Commit: ${l.autoCommit?"yes":"no"} ${Oe(h.autoCommit)}`),console.log(`Auto-Push: ${l.autoPush?"yes":"no"} ${Oe(h.autoPush)}`),console.log("-".repeat(70)),console.log("Sources: [cli] = command line, [env] = environment variable, [default]"),console.log("=".repeat(70)),console.log(""),Ro&&await Ro;let m=new Wn(l),v=()=>{console.log(`
|
|
100
|
+
Received shutdown signal`),m.stop(),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v),await m.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});us.parse();
|
|
100
101
|
/*! Bundled license information:
|
|
101
102
|
|
|
102
103
|
ably/build/ably-node.js:
|