@segosolutions/auto-task 1.2.0 → 1.3.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.cjs +0 -0
- package/dist/index.mjs +95 -0
- package/package.json +11 -11
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "module";
|
|
3
|
+
const require = createRequire(import.meta.url);
|
|
4
|
+
var Og=Object.create;var fc=Object.defineProperty;var Sg=Object.getOwnPropertyDescriptor;var Tg=Object.getOwnPropertyNames;var Ag=Object.getPrototypeOf,Rg=Object.prototype.hasOwnProperty;var U=(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 H=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Pg=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Tg(e))!Rg.call(s,a)&&a!==t&&fc(s,a,{get:()=>e[a],enumerable:!(i=Sg(e,a))||i.enumerable});return s};var yr=(s,e,t)=>(t=s!=null?Og(Ag(s)):{},Pg(e||!s||!s.__esModule?fc(t,"default",{value:s,enumerable:!0}):t,s));var as=H(br=>{var Fs=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}},_r=class extends Fs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};br.CommanderError=Fs;br.InvalidArgumentError=_r});var Ws=H(wr=>{var{InvalidArgumentError:Ig}=as(),vr=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 Ig(`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 xg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}wr.Argument=vr;wr.humanReadableArgName=xg});var Er=H(pc=>{var{humanReadableArgName:Mg}=Ws(),Cr=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=>Mg(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(T,E){if(E){let O=`${T.padEnd(i+h)}${E}`;return t.wrap(O,a-l,i+h)}return T}function g(T){return T.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(l))}let y=[`Usage: ${t.commandUsage(e)}`,""],C=t.commandDescription(e);C.length>0&&(y=y.concat([t.wrap(C,a,0),""]));let v=t.visibleArguments(e).map(T=>p(t.argumentTerm(T),t.argumentDescription(T)));v.length>0&&(y=y.concat(["Arguments:",g(v),""]));let k=t.visibleOptions(e).map(T=>p(t.optionTerm(T),t.optionDescription(T)));if(k.length>0&&(y=y.concat(["Options:",g(k),""])),this.showGlobalOptions){let T=t.visibleGlobalOptions(e).map(E=>p(t.optionTerm(E),t.optionDescription(E)));T.length>0&&(y=y.concat(["Global Options:",g(T),""]))}let S=t.visibleCommands(e).map(T=>p(t.subcommandTerm(T),t.subcommandDescription(T)));return S.length>0&&(y=y.concat(["Commands:",g(S),""])),y.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),y=e.slice(i).replace(`\r
|
|
7
|
+
`,`
|
|
8
|
+
`),C=" ".repeat(i),k="\\s\u200B",S=new RegExp(`
|
|
9
|
+
|.{1,${p-1}}([${k}]|$)|[^${k}]+?([${k}]|$)`,"g"),T=y.match(S)||[];return g+T.map((E,O)=>E===`
|
|
10
|
+
`?"":(O>0?C:"")+E.trimEnd()).join(`
|
|
11
|
+
`)}};pc.Help=Cr});var Tr=H(Sr=>{var{InvalidArgumentError:Ng}=as(),kr=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=jg(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 Ng(`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 Lg(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Or=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 Lg(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function jg(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}}Sr.Option=kr;Sr.DualOptions=Or});var mc=H(gc=>{function qg(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 Dg(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=qg(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
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
13
|
+
(Did you mean ${i[0]}?)`:""}gc.suggestSimilar=Dg});var wc=H(vc=>{var Ug=U("node:events").EventEmitter,Ar=U("node:child_process"),ze=U("node:path"),Rr=U("node:fs"),oe=U("node:process"),{Argument:Bg,humanReadableArgName:Hg}=Ws(),{CommanderError:Pr}=as(),{Help:$g}=Er(),{Option:yc,DualOptions:Gg}=Tr(),{suggestSimilar:_c}=mc(),Ir=class s extends Ug{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 $g,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 Bg(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
|
+
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 Pr(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 yc(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 yc)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,y)=>{let C=p.exec(g);return C?C[0]:y},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(C,v){let k=ze.resolve(C,v);if(Rr.existsSync(k))return k;if(a.includes(ze.extname(v)))return;let S=a.find(T=>Rr.existsSync(`${k}${T}`));if(S)return`${k}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let h=e._executableFile||`${this._name}-${e._name}`,p=this._executableDir||"";if(this._scriptPath){let C;try{C=Rr.realpathSync(this._scriptPath)}catch{C=this._scriptPath}p=ze.resolve(ze.dirname(C),p)}if(p){let C=l(p,h);if(!C&&!e._executableFile&&this._scriptPath){let v=ze.basename(this._scriptPath,ze.extname(this._scriptPath));v!==this._name&&(C=l(p,`${v}-${e._name}`))}h=C||h}i=a.includes(ze.extname(h));let g;oe.platform!=="win32"?i?(t.unshift(h),t=bc(oe.execArgv).concat(t),g=Ar.spawn(oe.argv[0],t,{stdio:"inherit"})):g=Ar.spawn(h,t,{stdio:"inherit"}):(t.unshift(h),t=bc(oe.execArgv).concat(t),g=Ar.spawn(oe.execPath,t,{stdio:"inherit"})),g.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(v=>{oe.on(v,()=>{g.killed===!1&&g.exitCode===null&&g.kill(v)})});let y=this._exitCallback;g.on("close",C=>{C=C??1,y?y(new Pr(C,"commander.executeSubCommandAsync","(close)")):oe.exit(C)}),g.on("error",C=>{if(C.code==="ENOENT"){let v=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
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
18
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
19
|
+
- ${v}`;throw new Error(k)}else if(C.code==="EACCES")throw new Error(`'${h}' not executable`);if(!y)oe.exit(1);else{let v=new Pr(1,"commander.executeSubCommandAsync","(error)");v.nestedError=C,y(v)}}),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 y=this._findOption(g);if(y){if(y.required){let C=l.shift();C===void 0&&this.optionMissingArgument(y),this.emit(`option:${y.name()}`,C)}else if(y.optional){let C=null;l.length>0&&!h(l[0])&&(C=l.shift()),this.emit(`option:${y.name()}`,C)}else this.emit(`option:${y.name()}`);p=y.variadic?y:null;continue}}if(g.length>2&&g[0]==="-"&&g[1]!=="-"){let y=this._findOption(`-${g[1]}`);if(y){y.required||y.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${y.name()}`,g.slice(2)):(this.emit(`option:${y.name()}`),l.unshift(`-${g.slice(2)}`));continue}}if(/^--[^=]+=/.test(g)){let y=g.indexOf("="),C=this._findOption(g.slice(0,y));if(C&&(C.required||C.optional)){this.emit(`option:${C.name()}`,g.slice(y+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
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
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 Gg(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),y=this.options.find(v=>v.negate&&p===v.attributeName()),C=this.options.find(v=>!v.negate&&p===v.attributeName());return y&&(y.presetArg===void 0&&g===!1||y.presetArg!==void 0&&g===y.presetArg)?y:C||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=_c(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=_c(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=>Hg(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=ze.basename(e,ze.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
|
+
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 bc(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})}vc.Command=Ir});var Oc=H(Ae=>{var{Argument:Cc}=Ws(),{Command:xr}=wc(),{CommanderError:Fg,InvalidArgumentError:Ec}=as(),{Help:Wg}=Er(),{Option:kc}=Tr();Ae.program=new xr;Ae.createCommand=s=>new xr(s);Ae.createOption=(s,e)=>new kc(s,e);Ae.createArgument=(s,e)=>new Cc(s,e);Ae.Command=xr;Ae.Option=kc;Ae.Argument=Cc;Ae.Help=Wg;Ae.CommanderError=Fg;Ae.InvalidArgumentError=Ec;Ae.InvalidOptionArgumentError=Ec});var Tc=H((vw,Vg)=>{Vg.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 Mc=H((ww,Ke)=>{var Mr=U("fs"),Vs=U("path"),zg=U("os"),Kg=U("crypto"),Jg=Tc(),Nr=Jg.version,Ac=["\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 Yg(){return Ac[Math.floor(Math.random()*Ac.length)]}function It(s){return typeof s=="string"?!["false","0","no","off",""].includes(s.toLowerCase()):!!s}function Qg(){return process.stdout.isTTY}function Xg(s){return Qg()?`\x1B[2m${s}\x1B[0m`:s}var Zg=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function em(s){let e={},t=s.toString();t=t.replace(/\r\n?/mg,`
|
|
26
|
+
`);let i;for(;(i=Zg.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 tm(s){s=s||{};let e=xc(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=Ic(s).split(","),a=i.length,l;for(let h=0;h<a;h++)try{let p=i[h].trim(),g=nm(t,p);l=le.decrypt(g.ciphertext,g.key);break}catch(p){if(h+1>=a)throw p}return le.parse(l)}function sm(s){console.error(`[dotenv@${Nr}][WARN] ${s}`)}function ls(s){console.log(`[dotenv@${Nr}][DEBUG] ${s}`)}function Pc(s){console.log(`[dotenv@${Nr}] ${s}`)}function Ic(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 nm(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 xc(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)Mr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=Vs.resolve(process.cwd(),".env.vault");return Mr.existsSync(e)?e:null}function Rc(s){return s[0]==="~"?Vs.join(zg.homedir(),s.slice(1)):s}function rm(s){let e=It(process.env.DOTENV_CONFIG_DEBUG||s&&s.debug),t=It(process.env.DOTENV_CONFIG_QUIET||s&&s.quiet);(e||!t)&&Pc("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 im(s){let e=Vs.resolve(process.cwd(),".env"),t="utf8",i=process.env;s&&s.processEnv!=null&&(i=s.processEnv);let a=It(i.DOTENV_CONFIG_DEBUG||s&&s.debug),l=It(i.DOTENV_CONFIG_QUIET||s&&s.quiet);s&&s.encoding?t=s.encoding:a&&ls("No encoding is specified. UTF-8 is used by default");let h=[e];if(s&&s.path)if(!Array.isArray(s.path))h=[Rc(s.path)];else{h=[];for(let C of s.path)h.push(Rc(C))}let p,g={};for(let C of h)try{let v=le.parse(Mr.readFileSync(C,{encoding:t}));le.populate(g,v,s)}catch(v){a&&ls(`Failed to load ${C} ${v.message}`),p=v}let y=le.populate(i,g,s);if(a=It(i.DOTENV_CONFIG_DEBUG||a),l=It(i.DOTENV_CONFIG_QUIET||l),a||!l){let C=Object.keys(y).length,v=[];for(let k of h)try{let S=Vs.relative(process.cwd(),k);v.push(S)}catch(S){a&&ls(`Failed to load ${k} ${S.message}`),p=S}Pc(`injecting env (${C}) from ${v.join(",")} ${Xg(`-- tip: ${Yg()}`)}`)}return p?{parsed:g,error:p}:{parsed:g}}function om(s){if(Ic(s).length===0)return le.configDotenv(s);let e=xc(s);return e?le._configVault(s):(sm(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),le.configDotenv(s))}function am(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=Kg.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 cm(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&&ls(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:im,_configVault:rm,_parseVault:tm,config:om,decrypt:am,parse:em,populate:cm};Ke.exports.configDotenv=le.configDotenv;Ke.exports._configVault=le._configVault;Ke.exports._parseVault=le._parseVault;Ke.exports.config=le.config;Ke.exports.decrypt=le.decrypt;Ke.exports.parse=le.parse;Ke.exports.populate=le.populate;Ke.exports=le});var Je=H((xw,Qc)=>{"use strict";var Jc=["nodebuffer","arraybuffer","fragments"],Yc=typeof Blob<"u";Yc&&Jc.push("blob");Qc.exports={BINARY_TYPES:Jc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Yc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var us=H((Mw,Ys)=>{"use strict";var{EMPTY_BUFFER:vm}=Je(),Dr=Buffer[Symbol.species];function wm(s,e){if(s.length===0)return vm;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 Dr(t.buffer,t.byteOffset,i):t}function Xc(s,e,t,i,a){for(let l=0;l<a;l++)t[i+l]=s[l]^e[l&3]}function Zc(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}function Cm(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}function Ur(s){if(Ur.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Dr(s):ArrayBuffer.isView(s)?e=new Dr(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ur.readOnly=!1),e}Ys.exports={concat:wm,mask:Xc,toArrayBuffer:Cm,toBuffer:Ur,unmask:Zc};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=U("bufferutil");Ys.exports.mask=function(e,t,i,a,l){l<48?Xc(e,t,i,a,l):s.mask(e,t,i,a,l)},Ys.exports.unmask=function(e,t){e.length<32?Zc(e,t):s.unmask(e,t)}}catch{}});var sl=H((Nw,tl)=>{"use strict";var el=Symbol("kDone"),Br=Symbol("kRun"),Hr=class{constructor(e){this[el]=()=>{this.pending--,this[Br]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Br]()}[Br](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[el])}}};tl.exports=Hr});var ds=H((Lw,ol)=>{"use strict";var hs=U("zlib"),nl=us(),Em=sl(),{kStatusCode:rl}=Je(),km=Buffer[Symbol.species],Om=Buffer.from([0,0,255,255]),Xs=Symbol("permessage-deflate"),Ye=Symbol("total-length"),xt=Symbol("callback"),at=Symbol("buffers"),Mt=Symbol("error"),Qs,$r=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,!Qs){let a=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Qs=new Em(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[xt];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){Qs.add(a=>{this._decompress(e,t,(l,h)=>{a(),i(l,h)})})}compress(e,t,i){Qs.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"?hs.Z_DEFAULT_WINDOWBITS:this.params[l];this._inflate=hs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:h}),this._inflate[Xs]=this,this._inflate[Ye]=0,this._inflate[at]=[],this._inflate.on("error",Tm),this._inflate.on("data",il)}this._inflate[xt]=i,this._inflate.write(e),t&&this._inflate.write(Om),this._inflate.flush(()=>{let l=this._inflate[Mt];if(l){this._inflate.close(),this._inflate=null,i(l);return}let h=nl.concat(this._inflate[at],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[at]=[],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"?hs.Z_DEFAULT_WINDOWBITS:this.params[l];this._deflate=hs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:h}),this._deflate[Ye]=0,this._deflate[at]=[],this._deflate.on("data",Sm)}this._deflate[xt]=i,this._deflate.write(e),this._deflate.flush(hs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let l=nl.concat(this._deflate[at],this._deflate[Ye]);t&&(l=new km(l.buffer,l.byteOffset,l.length-4)),this._deflate[xt]=null,this._deflate[Ye]=0,this._deflate[at]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,l)})}};ol.exports=$r;function Sm(s){this[at].push(s),this[Ye]+=s.length}function il(s){if(this[Ye]+=s.length,this[Xs]._maxPayload<1||this[Ye]<=this[Xs]._maxPayload){this[at].push(s);return}this[Mt]=new RangeError("Max payload size exceeded"),this[Mt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Mt][rl]=1009,this.removeListener("data",il),this.reset()}function Tm(s){if(this[Xs]._inflate=null,this[Mt]){this[xt](this[Mt]);return}s[rl]=1007,this[xt](s)}});var Nt=H((jw,Zs)=>{"use strict";var{isUtf8:al}=U("buffer"),{hasBlob:Am}=Je(),Rm=[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 Pm(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}function Gr(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 Im(s){return Am&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}Zs.exports={isBlob:Im,isValidStatusCode:Pm,isValidUTF8:Gr,tokenChars:Rm};if(al)Zs.exports.isValidUTF8=function(s){return s.length<24?Gr(s):al(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=U("utf-8-validate");Zs.exports.isValidUTF8=function(e){return e.length<32?Gr(e):s(e)}}catch{}});var Kr=H((qw,pl)=>{"use strict";var{Writable:xm}=U("stream"),cl=ds(),{BINARY_TYPES:Mm,EMPTY_BUFFER:ll,kStatusCode:Nm,kWebSocket:Lm}=Je(),{concat:Fr,toArrayBuffer:jm,unmask:qm}=us(),{isValidStatusCode:Dm,isValidUTF8:ul}=Nt(),en=Buffer[Symbol.species],Re=0,hl=1,dl=2,fl=3,Wr=4,Vr=5,tn=6,zr=class extends xm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Mm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Lm]=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=Re}_write(e,t,i){if(this._opcode===8&&this._state==Re)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 en(i.buffer,i.byteOffset+e,i.length-e),new en(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 en(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 Re:this.getInfo(e);break;case hl:this.getPayloadLength16(e);break;case dl:this.getPayloadLength64(e);break;case fl:this.getMask();break;case Wr:this.getData(e);break;case Vr:case tn: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[cl.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=hl:this._payloadLength===127?this._state=dl: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=fl:this._state=Wr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Wr}getData(e){let t=ll;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]&&qm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Vr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[cl.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===Re&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Re;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=Fr(i,t):this._binaryType==="arraybuffer"?a=jm(Fr(i,t)):this._binaryType==="blob"?a=new Blob(i):a=i,this._allowSynchronousEvents?(this.emit("message",a,!0),this._state=Re):(this._state=tn,setImmediate(()=>{this.emit("message",a,!0),this._state=Re,this.startLoop(e)}))}else{let a=Fr(i,t);if(!this._skipUTF8Validation&&!ul(a)){let l=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(l);return}this._state===Vr||this._allowSynchronousEvents?(this.emit("message",a,!1),this._state=Re):(this._state=tn,setImmediate(()=>{this.emit("message",a,!1),this._state=Re,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ll),this.end();else{let i=e.readUInt16BE(0);if(!Dm(i)){let l=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(l);return}let a=new en(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ul(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=Re;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Re):(this._state=tn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Re,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[Nm]=a,h}};pl.exports=zr});var Qr=H((Uw,yl)=>{"use strict";var{Duplex:Dw}=U("stream"),{randomFillSync:Um}=U("crypto"),gl=ds(),{EMPTY_BUFFER:Bm,kWebSocket:Hm,NOOP:$m}=Je(),{isBlob:Lt,isValidStatusCode:Gm}=Nt(),{mask:ml,toBuffer:mt}=us(),Pe=Symbol("kByteLength"),Fm=Buffer.alloc(4),sn=8*1024,yt,jt=sn,De=0,Wm=1,Vm=2,Jr=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=$m,this[Hm]=void 0}static frame(e,t){let i,a=!1,l=2,h=!1;t.mask&&(i=t.maskBuffer||Fm,t.generateMask?t.generateMask(i):(jt===sn&&(yt===void 0&&(yt=Buffer.alloc(sn)),Um(yt,0,sn),jt=0),i[0]=yt[jt++],i[1]=yt[jt++],i[2]=yt[jt++],i[3]=yt[jt++]),h=(i[0]|i[1]|i[2]|i[3])===0,l=6);let p;typeof e=="string"?(!t.mask||h)&&t[Pe]!==void 0?p=t[Pe]:(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?(ml(e,i,y,l,p),[y]):(ml(e,i,e,0,p),[y,e])):[y,e]}close(e,t,i,a){let l;if(e===void 0)l=Bm;else{if(typeof e!="number"||!Gm(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={[Pe]: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):Lt(e)?(a=e.size,l=!1):(e=mt(e),a=e.length,l=mt.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Pe]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:l,rsv1:!1};Lt(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):Lt(e)?(a=e.size,l=!1):(e=mt(e),a=e.length,l=mt.readOnly),a>125)throw new RangeError("The data size must not be greater than 125 bytes");let h={[Pe]:a,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:l,rsv1:!1};Lt(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[gl.extensionName],l=t.binary?2:1,h=t.compress,p,g;typeof e=="string"?(p=Buffer.byteLength(e),g=!1):Lt(e)?(p=e.size,g=!1):(e=mt(e),p=e.length,g=mt.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={[Pe]:p,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:l,readOnly:g,rsv1:h};Lt(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[Pe],this._state=Vm,e.arrayBuffer().then(l=>{if(this._socket.destroyed){let p=new Error("The socket was closed while the blob was being read");process.nextTick(Yr,this,p,a);return}this._bufferedBytes-=i[Pe];let h=mt(l);t?this.dispatch(h,t,i,a):(this._state=De,this.sendFrame(s.frame(h,i),a),this.dequeue())}).catch(l=>{process.nextTick(zm,this,l,a)})}dispatch(e,t,i,a){if(!t){this.sendFrame(s.frame(e,i),a);return}let l=this._extensions[gl.extensionName];this._bufferedBytes+=i[Pe],this._state=Wm,l.compress(e,i.fin,(h,p)=>{if(this._socket.destroyed){let g=new Error("The socket was closed while data was being compressed");Yr(this,g,a);return}this._bufferedBytes-=i[Pe],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][Pe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Pe],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)}};yl.exports=Jr;function Yr(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 zm(s,e,t){Yr(s,e,t),s.onerror(e)}});var Sl=H((Bw,Ol)=>{"use strict";var{kForOnEventAttribute:fs,kListener:Xr}=Je(),_l=Symbol("kCode"),bl=Symbol("kData"),vl=Symbol("kError"),wl=Symbol("kMessage"),Cl=Symbol("kReason"),qt=Symbol("kTarget"),El=Symbol("kType"),kl=Symbol("kWasClean"),Qe=class{constructor(e){this[qt]=null,this[El]=e}get target(){return this[qt]}get type(){return this[El]}};Object.defineProperty(Qe.prototype,"target",{enumerable:!0});Object.defineProperty(Qe.prototype,"type",{enumerable:!0});var _t=class extends Qe{constructor(e,t={}){super(e),this[_l]=t.code===void 0?0:t.code,this[Cl]=t.reason===void 0?"":t.reason,this[kl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[_l]}get reason(){return this[Cl]}get wasClean(){return this[kl]}};Object.defineProperty(_t.prototype,"code",{enumerable:!0});Object.defineProperty(_t.prototype,"reason",{enumerable:!0});Object.defineProperty(_t.prototype,"wasClean",{enumerable:!0});var Dt=class extends Qe{constructor(e,t={}){super(e),this[vl]=t.error===void 0?null:t.error,this[wl]=t.message===void 0?"":t.message}get error(){return this[vl]}get message(){return this[wl]}};Object.defineProperty(Dt.prototype,"error",{enumerable:!0});Object.defineProperty(Dt.prototype,"message",{enumerable:!0});var ps=class extends Qe{constructor(e,t={}){super(e),this[bl]=t.data===void 0?null:t.data}get data(){return this[bl]}};Object.defineProperty(ps.prototype,"data",{enumerable:!0});var Km={addEventListener(s,e,t={}){for(let a of this.listeners(s))if(!t[fs]&&a[Xr]===e&&!a[fs])return;let i;if(s==="message")i=function(l,h){let p=new ps("message",{data:h?l:l.toString()});p[qt]=this,nn(e,this,p)};else if(s==="close")i=function(l,h){let p=new _t("close",{code:l,reason:h.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});p[qt]=this,nn(e,this,p)};else if(s==="error")i=function(l){let h=new Dt("error",{error:l,message:l.message});h[qt]=this,nn(e,this,h)};else if(s==="open")i=function(){let l=new Qe("open");l[qt]=this,nn(e,this,l)};else return;i[fs]=!!t[fs],i[Xr]=e,t.once?this.once(s,i):this.on(s,i)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[Xr]===e&&!t[fs]){this.removeListener(s,t);break}}};Ol.exports={CloseEvent:_t,ErrorEvent:Dt,Event:Qe,EventTarget:Km,MessageEvent:ps};function nn(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}});var Zr=H((Hw,Tl)=>{"use strict";var{tokenChars:gs}=Nt();function He(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}function Jm(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&&gs[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 S=s.slice(g,C);y===44?(He(e,S,t),t=Object.create(null)):h=S,g=C=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);else if(p===void 0)if(C===-1&&gs[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(gs[y]!==1)throw new SyntaxError(`Unexpected character at index ${v}`);g===-1?g=v:i||(i=!0),a=!1}else if(l)if(gs[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&&gs[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 S=s.slice(g,C);i&&(S=S.replace(/\\/g,""),i=!1),He(t,p,S),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 k=s.slice(g,C);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 Ym(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(", ")}Tl.exports={format:Ym,parse:Jm}});var cn=H((Fw,Ul)=>{"use strict";var Qm=U("events"),Xm=U("https"),Zm=U("http"),Pl=U("net"),ey=U("tls"),{randomBytes:ty,createHash:sy}=U("crypto"),{Duplex:$w,Readable:Gw}=U("stream"),{URL:ei}=U("url"),ct=ds(),ny=Kr(),ry=Qr(),{isBlob:iy}=Nt(),{BINARY_TYPES:Al,CLOSE_TIMEOUT:oy,EMPTY_BUFFER:rn,GUID:ay,kForOnEventAttribute:ti,kListener:cy,kStatusCode:ly,kWebSocket:de,NOOP:Il}=Je(),{EventTarget:{addEventListener:uy,removeEventListener:hy}}=Sl(),{format:dy,parse:fy}=Zr(),{toBuffer:py}=us(),xl=Symbol("kAborted"),si=[8,13],Xe=["CONNECTING","OPEN","CLOSING","CLOSED"],gy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,re=class s extends Qm{constructor(e,t,i){super(),this._binaryType=Al[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=rn,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]),Ml(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Al.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 ny({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),l=new ry(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",_y),a.on("drain",by),a.on("error",vy),a.on("message",wy),a.on("ping",Cy),a.on("pong",Ey),l.onerror=ky,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",jl),e.on("data",an),e.on("end",ql),e.on("error",Dl),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[ct.extensionName]&&this._extensions[ct.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){Oe(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())}),Ll(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){ni(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||rn,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){ni(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||rn,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){ni(this,e,i);return}let a={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ct.extensionName]||(a.compress=!1),this._sender.send(e||rn,a,i)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Oe(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:Xe.indexOf("CONNECTING")});Object.defineProperty(re.prototype,"CONNECTING",{enumerable:!0,value:Xe.indexOf("CONNECTING")});Object.defineProperty(re,"OPEN",{enumerable:!0,value:Xe.indexOf("OPEN")});Object.defineProperty(re.prototype,"OPEN",{enumerable:!0,value:Xe.indexOf("OPEN")});Object.defineProperty(re,"CLOSING",{enumerable:!0,value:Xe.indexOf("CLOSING")});Object.defineProperty(re.prototype,"CLOSING",{enumerable:!0,value:Xe.indexOf("CLOSING")});Object.defineProperty(re,"CLOSED",{enumerable:!0,value:Xe.indexOf("CLOSED")});Object.defineProperty(re.prototype,"CLOSED",{enumerable:!0,value:Xe.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[ti])return e[cy];return null},set(e){for(let t of this.listeners(s))if(t[ti]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[ti]:!0})}})});re.prototype.addEventListener=uy;re.prototype.removeEventListener=hy;Ul.exports=re;function Ml(s,e,t,i){let a={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:oy,protocolVersion:si[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,!si.includes(a.protocolVersion))throw new RangeError(`Unsupported protocol version: ${a.protocolVersion} (supported versions: ${si.join(", ")})`);let l;if(e instanceof ei)l=e;else try{l=new ei(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;on(s,E);return}let y=h?443:80,C=ty(16).toString("base64"),v=h?Xm.request:Zm.request,k=new Set,S;if(a.createConnection=a.createConnection||(h?yy:my),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&&(S=new ct(a.perMessageDeflate!==!0?a.perMessageDeflate:{},!1,a.maxPayload),a.headers["Sec-WebSocket-Extensions"]=dy({[ct.extensionName]:S.offer()})),t.length){for(let E of t){if(typeof E!="string"||!gy.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 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[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")),T=s._req=v(a),s._redirects&&s.emit("redirect",s.url,T)}else T=s._req=v(a);a.timeout&&T.on("timeout",()=>{Oe(s,T,"Opening handshake has timed out")}),T.on("error",E=>{T===null||T[xl]||(T=s._req=null,on(s,E))}),T.on("response",E=>{let O=E.headers.location,N=E.statusCode;if(O&&a.followRedirects&&N>=300&&N<400){if(++s._redirects>a.maxRedirects){Oe(s,T,"Maximum redirects exceeded");return}T.abort();let W;try{W=new ei(O,e)}catch{let se=new SyntaxError(`Invalid URL: ${O}`);on(s,se);return}Ml(s,W,t,i)}else s.emit("unexpected-response",T,E)||Oe(s,T,`Unexpected server response: ${E.statusCode}`)}),T.on("upgrade",(E,O,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"){Oe(s,O,"Invalid Upgrade header");return}let Y=sy("sha1").update(C+ay).digest("base64");if(E.headers["sec-websocket-accept"]!==Y){Oe(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){Oe(s,O,Z);return}se&&(s._protocol=se);let Se=E.headers["sec-websocket-extensions"];if(Se!==void 0){if(!S){Oe(s,O,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Ne;try{Ne=fy(Se)}catch{Oe(s,O,"Invalid Sec-WebSocket-Extensions header");return}let rt=Object.keys(Ne);if(rt.length!==1||rt[0]!==ct.extensionName){Oe(s,O,"Server indicated an extension that was not requested");return}try{S.accept(Ne[ct.extensionName])}catch{Oe(s,O,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ct.extensionName]=S}s.setSocket(O,N,{allowSynchronousEvents:a.allowSynchronousEvents,generateMask:a.generateMask,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation})}),a.finishRequest?a.finishRequest(T,s):T.end()}function on(s,e){s._readyState=re.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}function my(s){return s.path=s.socketPath,Pl.connect(s)}function yy(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Pl.isIP(s.host)?"":s.host),ey.connect(s)}function Oe(s,e,t){s._readyState=re.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Oe),e.setHeader?(e[xl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(on,s,i)):(e.destroy(i),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}function ni(s,e,t){if(e){let i=iy(e)?e.size:py(e).length;s._socket?s._sender._bufferedBytes+=i:s._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${s.readyState} (${Xe[s.readyState]})`);process.nextTick(t,i)}}function _y(s,e){let t=this[de];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[de]!==void 0&&(t._socket.removeListener("data",an),process.nextTick(Nl,t._socket),s===1005?t.close():t.close(s,e))}function by(){let s=this[de];s.isPaused||s._socket.resume()}function vy(s){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",an),process.nextTick(Nl,e._socket),e.close(s[ly])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}function Rl(){this[de].emitClose()}function wy(s,e){this[de].emit("message",s,e)}function Cy(s){let e=this[de];e._autoPong&&e.pong(s,!this._isServer,Il),e.emit("ping",s)}function Ey(s){this[de].emit("pong",s)}function Nl(s){s.resume()}function ky(s){let e=this[de];e.readyState!==re.CLOSED&&(e.readyState===re.OPEN&&(e._readyState=re.CLOSING,Ll(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}function Ll(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}function jl(){let s=this[de];if(this.removeListener("close",jl),this.removeListener("data",an),this.removeListener("end",ql),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",Rl),s._receiver.on("finish",Rl))}function an(s){this[de]._receiver.write(s)||this.pause()}function ql(){let s=this[de];s._readyState=re.CLOSING,s._receiver.end(),this.end()}function Dl(){let s=this[de];this.removeListener("error",Dl),this.on("error",Il),s&&(s._readyState=re.CLOSING,this.destroy())}});var Gl=H((Vw,$l)=>{"use strict";var Ww=cn(),{Duplex:Oy}=U("stream");function Bl(s){s.emit("close")}function Sy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Hl(s){this.removeListener("error",Hl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}function Ty(s,e){let t=!0,i=new Oy({...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(Bl,i);return}let h=!1;s.once("error",function(g){h=!0,l(g)}),s.once("close",function(){h||l(a),process.nextTick(Bl,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",Sy),i.on("error",Hl),i}$l.exports=Ty});var Wl=H((zw,Fl)=>{"use strict";var{tokenChars:Ay}=Nt();function Ry(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&&Ay[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}Fl.exports={parse:Ry}});var Xl=H((Jw,Ql)=>{"use strict";var Py=U("events"),ln=U("http"),{Duplex:Kw}=U("stream"),{createHash:Iy}=U("crypto"),Vl=Zr(),bt=ds(),xy=Wl(),My=cn(),{CLOSE_TIMEOUT:Ny,GUID:Ly,kWebSocket:jy}=Je(),qy=/^[+/0-9A-Za-z]{22}==$/,zl=0,Kl=1,Yl=2,ri=class extends Py{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Ny,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:My,...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=ln.createServer((i,a)=>{let l=ln.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=Dy(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=zl}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===Yl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ms,this);return}if(e&&this.once("close",e),this._state!==Kl)if(this._state=Kl,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(ms,this):process.nextTick(ms,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ms(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",Jl);let l=e.headers["sec-websocket-key"],h=e.headers.upgrade,p=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vt(this,e,t,405,"Invalid HTTP method");return}if(h===void 0||h.toLowerCase()!=="websocket"){vt(this,e,t,400,"Invalid Upgrade header");return}if(l===void 0||!qy.test(l)){vt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(p!==13&&p!==8){vt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ys(t,400);return}let g=e.headers["sec-websocket-protocol"],y=new Set;if(g!==void 0)try{y=xy.parse(g)}catch{vt(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 k=new bt(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let S=Vl.parse(C);S[bt.extensionName]&&(k.accept(S[bt.extensionName]),v[bt.extensionName]=k)}catch{vt(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,T,E,O)=>{if(!S)return ys(t,T||401,E,O);this.completeUpgrade(v,l,y,e,t,i,a)});return}if(!this.options.verifyClient(k))return ys(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[jy])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>zl)return ys(l,503);let y=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Iy("sha1").update(t+Ly).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[bt.extensionName]){let v=e[bt.extensionName].params,k=Vl.format({[bt.extensionName]:[v]});y.push(`Sec-WebSocket-Extensions: ${k}`),C._extensions=e}this.emit("headers",y,a),l.write(y.concat(`\r
|
|
28
|
+
`).join(`\r
|
|
29
|
+
`)),l.removeListener("error",Jl),C.setSocket(l,h,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(C),C.on("close",()=>{this.clients.delete(C),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ms,this)})),p(C,a)}};Ql.exports=ri;function Dy(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 ms(s){s._state=Yl,s.emit("close")}function Jl(){this.destroy()}function ys(s,e,t,i){t=t||ln.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} ${ln.STATUS_CODES[e]}\r
|
|
30
|
+
`+Object.keys(i).map(a=>`${a}: ${i[a]}`).join(`\r
|
|
31
|
+
`)+`\r
|
|
32
|
+
\r
|
|
33
|
+
`+t)}function vt(s,e,t,i,a,l){if(s.listenerCount("wsClientError")){let h=new Error(a);Error.captureStackTrace(h,vt),s.emit("wsClientError",h,t,e)}else ys(t,i,a,l)}});var un=H((Yw,Zl)=>{"use strict";var Ze=cn();Ze.createWebSocketStream=Gl();Ze.Server=Xl();Ze.Receiver=Kr();Ze.Sender=Qr();Ze.WebSocket=Ze;Ze.WebSocketServer=Ze.Server;Zl.exports=Ze});var tt=H((et,hn)=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});var eu=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Uy(s){return eu.includes(s)}var By=["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",...eu];function Hy(s){return By.includes(s)}var $y=["null","undefined","string","number","bigint","boolean","symbol"];function Gy(s){return $y.includes(s)}function Ut(s){return e=>typeof e===s}var{toString:tu}=Object.prototype,_s=s=>{let e=tu.call(s).slice(8,-1);if(/HTML\w+Element/.test(e)&&b.domElement(s))return"HTMLElement";if(Hy(e))return e},te=s=>e=>_s(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=_s(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=Ut("undefined");b.string=Ut("string");var Fy=Ut("number");b.number=s=>Fy(s)&&!b.nan(s);b.bigint=Ut("bigint");b.function_=Ut("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=Ut("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 Wy=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)||Wy(s);b.generatorFunction=te("GeneratorFunction");b.asyncGeneratorFunction=s=>_s(s)==="AsyncGeneratorFunction";b.asyncFunction=s=>_s(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)||Gy(typeof s);b.integer=s=>Number.isInteger(s);b.safeInteger=s=>Number.isSafeInteger(s);b.plainObject=s=>{if(tu.call(s)!=="[object Object]")return!1;let e=Object.getPrototypeOf(s);return e===null||e===Object.getPrototypeOf({})};b.typedArray=s=>Uy(_s(s));var Vy=s=>b.safeInteger(s)&&s>=0;b.arrayLike=s=>!b.nullOrUndefined(s)&&!b.function_(s)&&Vy(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 zy=1,Ky=["innerHTML","ownerDocument","style","attributes","nodeValue"];b.domElement=s=>b.object(s)&&s.nodeType===zy&&b.string(s.nodeName)&&!b.plainObject(s)&&Ky.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 su=s=>e=>b.integer(e)&&Math.abs(e%2)===s;b.evenInteger=su(0);b.oddInteger=su(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 Jy=s=>b.string(s)&&!/\S/.test(s);b.emptyStringOrWhitespace=s=>b.emptyString(s)||Jy(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 nu=(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=>nu(Array.prototype.some,i,e));b.all=(s,...e)=>nu(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}.`)}};et.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(et.assert,{class:{value:et.assert.class_},function:{value:et.assert.function_},null:{value:et.assert.null_}});et.default=b;hn.exports=b;hn.exports.default=b;hn.exports.assert=et.assert});var ru=H((Qw,ii)=>{"use strict";var dn=class extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}},fn=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 dn(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(fn.prototype,Promise.prototype);ii.exports=fn;ii.exports.CancelError=dn});var iu=H((ai,ci)=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});function Yy(s){return s.encrypted}var oi=(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(),Yy(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)};ai.default=oi;ci.exports=oi;ci.exports.default=oi});var ou=H((ui,hi)=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});var Qy=iu(),Xy=U("util"),Zy=Number(process.versions.node.split(".")[0]),li=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||Zy>=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,Xy.types.isProxy(p))return;let g=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};p.prependOnceListener("lookup",g),Qy.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};ui.default=li;hi.exports=li;hi.exports.default=li});var fu=H((Xw,pi)=>{"use strict";var{V4MAPPED:e_,ADDRCONFIG:t_,ALL:du,promises:{Resolver:au},lookup:s_}=U("dns"),{promisify:di}=U("util"),n_=U("os"),Bt=Symbol("cacheableLookupCreateConnection"),fi=Symbol("cacheableLookupInstance"),cu=Symbol("expires"),r_=typeof du=="number",lu=s=>{if(!(s&&typeof s.createConnection=="function"))throw new Error("Expected an Agent instance as the first argument")},i_=s=>{for(let e of s)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},uu=()=>{let s=!1,e=!1;for(let t of Object.values(n_.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}},o_=s=>Symbol.iterator in s,hu={ttl:!0},a_={all:!0},pn=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:i=3600,errorTtl:a=.15,resolver:l=new au,lookup:h=s_}={}){if(this.maxTtl=t,this.errorTtl=a,this._cache=e,this._resolver=l,this._dnsLookup=di(h),this._resolver instanceof au?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=di(this._resolver.resolve4.bind(this._resolver)),this._resolve6=di(this._resolver.resolve6.bind(this._resolver))),this._iface=uu(),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&e_&&(r_&&t.hints&du||a.length===0)?i_(i):i=a}else t.family===4&&(i=i.filter(a=>a.family===4));if(t.hints&t_){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,hu),this._resolve6(e,hu)].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[cu]=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}}o_(this._cache)&&this._tick(i)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,a_);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[cu];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(lu(e),Bt in e)throw new Error("CacheableLookup has been already installed");e[Bt]=e.createConnection,e[fi]=this,e.createConnection=(t,i)=>("lookup"in t||(t.lookup=this.lookup),e[Bt](t,i))}uninstall(e){if(lu(e),e[Bt]){if(e[fi]!==this)throw new Error("The agent is not owned by this CacheableLookup instance");e.createConnection=e[Bt],delete e[Bt],delete e[fi]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=uu(),(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()}};pi.exports=pn;pi.exports.default=pn});var mu=H((Zw,gu)=>{"use strict";var c_="text/plain",l_="us-ascii",pu=(s,e)=>e.some(t=>t instanceof RegExp?t.test(s):t===s),u_=(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[k,S=""]=v.split("=").map(T=>T.trim());return k==="charset"&&(S=S.toLowerCase(),S===l_)?"":`${k}${S?`=${S}`:""}`}).filter(Boolean)];return p&&C.push("base64"),(C.length!==0||g&&g!==c_)&&C.unshift(g),`data:${C.join(";")},${p?a.trim():a}${l?`#${l}`:""}`},h_=(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 u_(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];pu(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()])pu(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};gu.exports=h_});var bu=H((eC,_u)=>{_u.exports=yu;function yu(s,e){if(s&&e)return yu(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 mi=H((tC,gi)=>{var vu=bu();gi.exports=vu(gn);gi.exports.strict=vu(wu);gn.proto=gn(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return gn(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return wu(this)},configurable:!0})});function gn(s){var e=function(){return e.called?e.value:(e.called=!0,e.value=s.apply(this,arguments))};return e.called=!1,e}function wu(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 ku=H((sC,Eu)=>{var d_=mi(),f_=function(){},p_=global.Bare?queueMicrotask:process.nextTick.bind(process),g_=function(s){return s.setHeader&&typeof s.abort=="function"},m_=function(s){return s.stdio&&Array.isArray(s.stdio)&&s.stdio.length===3},Cu=function(s,e,t){if(typeof e=="function")return Cu(s,null,e);e||(e={}),t=d_(t||f_);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(O){t.call(s,O?new Error("exited with error code: "+O):null)},k=function(O){t.call(s,O)},S=function(){p_(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 g_(s)?(s.on("complete",y),s.on("abort",S),s.req?E():s.on("request",E)):h&&!i&&(s.on("end",g),s.on("close",g)),m_(s)&&s.on("exit",v),s.on("end",C),s.on("finish",y),e.error!==!1&&s.on("error",k),s.on("close",S),function(){p=!0,s.removeListener("complete",y),s.removeListener("abort",S),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",k),s.removeListener("close",S)}};Eu.exports=Cu});var Tu=H((nC,Su)=>{var y_=mi(),__=ku(),mn;try{mn=U("fs")}catch{}var bs=function(){},b_=typeof process>"u"?!1:/^v?\.0/.test(process.version),yn=function(s){return typeof s=="function"},v_=function(s){return!b_||!mn?!1:(s instanceof(mn.ReadStream||bs)||s instanceof(mn.WriteStream||bs))&&yn(s.close)},w_=function(s){return s.setHeader&&yn(s.abort)},C_=function(s,e,t,i){i=y_(i);var a=!1;s.on("close",function(){a=!0}),__(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,v_(s))return s.close(bs);if(w_(s))return s.abort();if(yn(s.destroy))return s.destroy();i(h||new Error("stream was destroyed"))}}},Ou=function(s){s()},E_=function(s,e){return s.pipe(e)},k_=function(){var s=Array.prototype.slice.call(arguments),e=yn(s[s.length-1]||bs)&&s.pop()||bs;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 C_(a,h,p,function(g){t||(t=g),g&&i.forEach(Ou),!h&&(i.forEach(Ou),e(t))})});return s.reduce(E_)};Su.exports=k_});var Ru=H((rC,Au)=>{"use strict";var{PassThrough:O_}=U("stream");Au.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 O_({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 Pu=H((iC,Ht)=>{"use strict";var{constants:S_}=U("buffer"),T_=Tu(),A_=Ru(),_n=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function bn(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()<=S_.MAX_LENGTH&&(p.bufferedData=i.getBufferedValue()),l(p)};i=T_(s,A_(e),p=>{if(p){h(p);return}a()}),i.on("data",()=>{i.getBufferedLength()>t&&h(new _n)})}),i.getBufferedValue()}Ht.exports=bn;Ht.exports.default=bn;Ht.exports.buffer=(s,e)=>bn(s,{...e,encoding:"buffer"});Ht.exports.array=(s,e)=>bn(s,{...e,array:!0});Ht.exports.MaxBufferError=_n});var xu=H((aC,Iu)=>{"use strict";var R_=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),P_=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),I_=new Set([500,502,503,504]),x_={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},M_={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function st(s){let e=parseInt(s,10);return isFinite(e)?e:0}function N_(s){return s?I_.has(s.status):!0}function yi(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 L_(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(", ")}Iu.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=yi(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=yi(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":L_(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())&&P_.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||R_.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=yi(e.headers["cache-control"]);return t["no-cache"]||/no-cache/.test(e.headers.pragma)?this._evaluateRequestMissResult(e):t["max-age"]&&this.age()>st(t["max-age"])?this._evaluateRequestMissResult(e):t["min-fresh"]&&this.maxAge()-this.age()<st(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)x_[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 st(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 st(this._rescc["s-maxage"])}if(this._rescc["max-age"])return st(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+st(this._rescc["stale-if-error"]),i=e+st(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()+st(this._rescc["stale-if-error"])>this.age()}useStaleWhileRevalidate(){let e=st(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()&&N_(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&&!M_[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 vn=H((cC,Mu)=>{"use strict";Mu.exports=s=>{let e={};for(let[t,i]of Object.entries(s))e[t.toLowerCase()]=i;return e}});var Lu=H((lC,Nu)=>{"use strict";var j_=U("stream").Readable,q_=vn(),_i=class extends j_{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=q_(t),this.body=i,this.url=a}_read(){this.push(this.body),this.push(null)}};Nu.exports=_i});var qu=H((uC,ju)=>{"use strict";var D_=["destroy","setTimeout","socket","headers","trailers","rawHeaders","statusCode","httpVersion","httpVersionMinor","httpVersionMajor","rawTrailers","statusMessage"];ju.exports=(s,e)=>{let t=new Set(Object.keys(s).concat(D_));for(let i of t)i in e||(e[i]=typeof s[i]=="function"?s[i].bind(s):s[i])}});var Uu=H((hC,Du)=>{"use strict";var U_=U("stream").PassThrough,B_=qu(),H_=s=>{if(!(s&&s.pipe))throw new TypeError("Parameter `response` must be a response stream.");let e=new U_;return B_(s,e),s.pipe(e)};Du.exports=H_});var Bu=H(bi=>{bi.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)};bi.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 Fu=H((fC,Gu)=>{"use strict";var $_=U("events"),Hu=Bu(),G_=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(U(e[t]))(s)}return new Map},$u=["sqlite","postgres","mysql","mongo","redis","tiered"],vi=class extends $_{constructor(e,{emitErrors:t=!0,...i}={}){if(super(),this.opts={namespace:"keyv",serialize:Hu.stringify,deserialize:Hu.parse,...typeof e=="string"?{uri:e}:e,...i},!this.opts.store){let l={...this.opts};this.opts.store=G_(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 $u.includes(this.opts.store.opts.dialect)||$u.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()}};Gu.exports=vi});var zu=H((gC,Vu)=>{"use strict";var F_=U("events"),wn=U("url"),W_=mu(),V_=Pu(),wi=xu(),Wu=Lu(),z_=vn(),K_=Uu(),J_=Fu(),vs=class s{constructor(e,t){if(typeof e!="function")throw new TypeError("Parameter `request` must be a function");return this.cache=new J_({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=Ci(wn.parse(t)),t={};else if(t instanceof wn.URL)a=Ci(wn.parse(t.toString())),t={};else{let[v,...k]=(t.path||"").split("?"),S=k.length>0?`?${k.join("?")}`:"";a=Ci({...t,pathname:v,search:S})}t={headers:{},method:"GET",cache:!0,strictTtl:!1,automaticFailover:!1,...t,...Y_(a)},t.headers=z_(t.headers);let l=new F_,h=W_(wn.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),p=`${t.method}:${h}`,g=!1,y=!1,C=v=>{y=!0;let k=!1,S,T=new Promise(O=>{S=()=>{k||(k=!0,O())}}),E=O=>{if(g&&!v.forceRefresh){O.status=O.statusCode;let W=wi.fromObject(g.cachePolicy).revalidatedPolicy(v,O);if(!W.modified){let Y=W.policy.responseHeaders();O=new Wu(g.statusCode,Y,g.body,g.url),O.cachePolicy=W.policy,O.fromCache=!0}}O.fromCache||(O.cachePolicy=new wi(v,O,v),O.fromCache=!1);let N;v.cache&&O.cachePolicy.storable()?(N=K_(O),(async()=>{try{let W=V_.buffer(O);if(await Promise.race([T,new Promise(Se=>O.once("end",Se))]),k)return;let Y=await W,se={cachePolicy:O.cachePolicy.toObject(),url:O.url,statusCode:O.fromCache?g.statusCode:O.statusCode,body:Y},Z=v.strictTtl?O.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||O),typeof i=="function"&&i(N||O)};try{let O=e(v,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 v=async S=>{await Promise.resolve();let T=S.cache?await this.cache.get(p):void 0;if(typeof T>"u")return C(S);let E=wi.fromObject(T.cachePolicy);if(E.satisfiesWithoutRevalidation(S)&&!S.forceRefresh){let O=E.responseHeaders(),N=new Wu(T.statusCode,O,T.body,T.url);N.cachePolicy=E,N.fromCache=!0,l.emit("response",N),typeof i=="function"&&i(N)}else g=T,S.headers=E.revalidationHeaders(S),C(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 v(t)}catch(S){t.automaticFailover&&!y&&C(t),l.emit("error",new s.CacheError(S))}})(),l}}};function Y_(s){let e={...s};return e.path=`${s.pathname||"/"}${s.search||""}`,delete e.pathname,delete e.search,e}function Ci(s){return{protocol:s.protocol,auth:s.auth,hostname:s.hostname||s.host||"localhost",port:s.port,pathname:s.pathname,search:s.search}}vs.RequestError=class extends Error{constructor(s){super(s.message),this.name="RequestError",Object.assign(this,s)}};vs.CacheError=class extends Error{constructor(s){super(s.message),this.name="CacheError",Object.assign(this,s)}};Vu.exports=vs});var Ju=H((_C,Ku)=>{"use strict";var Q_=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];Ku.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(Q_)),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 Qu=H((bC,Yu)=>{"use strict";var{Transform:X_,PassThrough:Z_}=U("stream"),Ei=U("zlib"),eb=Ju();Yu.exports=s=>{let e=(s.headers["content-encoding"]||"").toLowerCase();if(!["gzip","deflate","br"].includes(e))return s;let t=e==="br";if(t&&typeof Ei.createBrotliDecompress!="function")return s.destroy(new Error("Brotli is not supported on Node.js < 12")),s;let i=!0,a=new X_({transform(p,g,y){i=!1,y(null,p)},flush(p){p()}}),l=new Z_({autoDestroy:!1,destroy(p,g){s.destroy(),g(p)}}),h=t?Ei.createBrotliDecompress():Ei.createUnzip();return h.once("error",p=>{if(i&&!s.readable){l.end();return}l.destroy(p)}),eb(s,l),s.pipe(a).pipe(h).pipe(l),l}});var Oi=H((vC,Xu)=>{"use strict";var ki=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)}};Xu.exports=ki});var Ti=H((wC,sh)=>{"use strict";var tb=U("events"),sb=U("tls"),nb=U("http2"),rb=Oi(),be=Symbol("currentStreamsCount"),Zu=Symbol("request"),Ie=Symbol("cachedOriginSet"),$t=Symbol("gracefullyClosing"),ib=["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"],ob=(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},ab=(s,e)=>s.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,Si=(s,e)=>{for(let t of s)t[Ie].length<e[Ie].length&&t[Ie].every(i=>e[Ie].includes(i))&&t[be]+e[be]<=e.remoteSettings.maxConcurrentStreams&&th(t)},cb=(s,e)=>{for(let t of s)e[Ie].length<t[Ie].length&&e[Ie].every(i=>t[Ie].includes(i))&&e[be]+t[be]<=t.remoteSettings.maxConcurrentStreams&&th(e)},eh=({agent:s,isFree:e})=>{let t={};for(let i in s.sessions){let l=s.sessions[i].filter(h=>{let p=h[wt.kCurrentStreamsCount]<h.remoteSettings.maxConcurrentStreams;return e?p:!p});l.length!==0&&(t[i]=l)}return t},th=s=>{s[$t]=!0,s[be]===0&&s.close()},wt=class s extends tb{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 rb({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 ib)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,k=-1,S;for(let T of C){let E=T.remoteSettings.maxConcurrentStreams;if(E<v)break;if(T[Ie].includes(p)){let O=T[be];if(O>=E||T[$t]||T.destroyed)continue;S||(v=E),O>k&&(S=T,k=O)}}if(S){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(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]===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 k=nb.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(C),...t});k[be]=0,k[$t]=!1;let S=()=>k[be]<k.remoteSettings.maxConcurrentStreams,T=!0;k.socket.once("session",O=>{this.tlsSessionCache.set(C,O)}),k.once("error",O=>{for(let{reject:N}of i)N(O);this.tlsSessionCache.delete(C)}),k.setTimeout(this.timeout,()=>{k.destroy()}),k.once("close",()=>{if(v){T&&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[Ie])if(O in this.queue[h]){let{listeners:N}=this.queue[h][O];for(;N.length!==0&&S();)N.shift().resolve(k);let W=this.queue[h];if(W[O].listeners.length===0&&(delete W[O],Object.keys(W).length===0)){delete this.queue[h];break}if(!S())break}}};k.on("origin",()=>{k[Ie]=k.originSet,S()&&(E(),Si(this.sessions[h],k))}),k.once("remoteSettings",()=>{if(k.ref(),k.unref(),this._sessionsCount++,y.destroyed){let O=new Error("Agent has been destroyed");for(let N of i)N.reject(O);k.destroy();return}k[Ie]=k.originSet;{let O=this.sessions;if(h in O){let N=O[h];N.splice(ob(N,k,ab),0,k)}else O[h]=[k]}this._freeSessionsCount+=1,v=!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(),Si(this.sessions[h],k)})}),k[Zu]=k.request,k.request=(O,N)=>{if(k[$t])throw new Error("The session is gracefully closing. No new streams are allowed.");let W=k[Zu](O,N);return k.ref(),++k[be],k[be]===k.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,W.once("close",()=>{if(T=S(),--k[be],!k.destroyed&&!k.closed&&(cb(this.sessions[h],k),S()&&!k.closed)){T||(this._freeSessionsCount++,T=!0);let Y=k[be]===0;Y&&k.unref(),Y&&(this._freeSessionsCount>this.maxFreeSessions||k[$t])?k.close():(Si(this.sessions[h],k),E())}}),W}}catch(k){for(let S of i)S.reject(k);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),sb.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 eh({agent:this,isFree:!0})}get busySessions(){return eh({agent:this,isFree:!1})}};wt.kCurrentStreamsCount=be;wt.kGracefullyClosing=$t;sh.exports={Agent:wt,globalAgent:new wt}});var Ri=H((CC,nh)=>{"use strict";var{Readable:lb}=U("stream"),Ai=class extends lb{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()}};nh.exports=Ai});var Pi=H((EC,rh)=>{"use strict";rh.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 oh=H((kC,ih)=>{"use strict";ih.exports=(s,e,t)=>{for(let i of t)s.on(i,(...a)=>e.emit(i,...a))}});var ch=H((OC,ah)=>{"use strict";ah.exports=s=>{switch(s){case":method":case":scheme":case":authority":case":path":return!0;default:return!1}}});var uh=H((TC,lh)=>{"use strict";var Gt=(s,e,t)=>{lh.exports[e]=class extends s{constructor(...a){super(typeof t=="string"?t:t(a)),this.name=`${super.name} [${e}]`,this.code=e}}};Gt(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]}`});Gt(TypeError,"ERR_INVALID_PROTOCOL",s=>`Protocol "${s[0]}" not supported. Expected "${s[1]}"`);Gt(Error,"ERR_HTTP_HEADERS_SENT",s=>`Cannot ${s[0]} headers after they are sent to the client`);Gt(TypeError,"ERR_INVALID_HTTP_TOKEN",s=>`${s[0]} must be a valid HTTP token [${s[1]}]`);Gt(TypeError,"ERR_HTTP_INVALID_HEADER_VALUE",s=>`Invalid value "${s[0]} for header "${s[1]}"`);Gt(TypeError,"ERR_INVALID_CHAR",s=>`Invalid character in ${s[0]} [${s[1]}]`)});var Li=H((AC,yh)=>{"use strict";var ub=U("http2"),{Writable:hb}=U("stream"),{Agent:hh,globalAgent:db}=Ti(),fb=Ri(),pb=Pi(),gb=oh(),mb=ch(),{ERR_INVALID_ARG_TYPE:Ii,ERR_INVALID_PROTOCOL:yb,ERR_HTTP_HEADERS_SENT:dh,ERR_INVALID_HTTP_TOKEN:_b,ERR_HTTP_INVALID_HEADER_VALUE:bb,ERR_INVALID_CHAR:vb}=uh(),{HTTP2_HEADER_STATUS:fh,HTTP2_HEADER_METHOD:ph,HTTP2_HEADER_PATH:gh,HTTP2_METHOD_CONNECT:wb}=ub.constants,ye=Symbol("headers"),xi=Symbol("origin"),Mi=Symbol("session"),mh=Symbol("options"),Cn=Symbol("flushedHeaders"),ws=Symbol("jobs"),Cb=/^[\^`\-\w!#$%&*+.|~]+$/,Eb=/[^\t\u0020-\u007E\u0080-\u00FF]/,Ni=class extends hb{constructor(e,t,i){super({autoDestroy:!1});let a=typeof e=="string"||e instanceof URL;if(a&&(e=pb(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[Mi]=t.h2session;else if(t.agent===!1)this.agent=new hh({maxFreeSessions:0});else if(typeof t.agent>"u"||t.agent===null)typeof t.createConnection=="function"?(this.agent=new hh({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=db;else if(typeof t.agent.request=="function")this.agent=t.agent;else throw new Ii("options.agent",["Agent-like Object","undefined","false"],t.agent);if(t.protocol&&t.protocol!=="https:")throw new yb(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[ws]=[],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[mh]=t,l===443?(this[xi]=`https://${h}`,":authority"in this[ye]||(this[ye][":authority"]=h)):(this[xi]=`https://${h}:${l}`,":authority"in this[ye]||(this[ye][":authority"]=`${h}:${l}`)),p&&this.setTimeout(p),i&&this.once("response",i),this[Cn]=!1}get method(){return this[ye][ph]}set method(e){e&&(this[ye][ph]=e.toUpperCase())}get path(){return this[ye][gh]}set path(e){e&&(this[ye][gh]=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[ws].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[ws].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[Cn]||this.destroyed)return;this[Cn]=!0;let e=this.method===wb,t=i=>{if(this._request=i,this.destroyed){i.destroy();return}e||gb(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 fb(this.socket,i.readableHighWaterMark);this.res=y,y.req=this,y.statusCode=h[fh],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[fh]}))),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[ws])h();this.emit("socket",this.socket)};if(this[Mi])try{t(this[Mi].request(this[ye]))}catch(i){this.emit("error",i)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[xi],this[mh],this[ye]))}catch(i){this.emit("error",i)}}}getHeader(e){if(typeof e!="string")throw new Ii("name","string",e);return this[ye][e.toLowerCase()]}get headersSent(){return this[Cn]}removeHeader(e){if(typeof e!="string")throw new Ii("name","string",e);if(this.headersSent)throw new dh("remove");delete this[ye][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new dh("set");if(typeof e!="string"||!Cb.test(e)&&!mb(e))throw new _b("Header name",e);if(typeof t>"u")throw new bb(t,e);if(Eb.test(t))throw new vb("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[ws].push(i),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};yh.exports=Ni});var bh=H((RC,_h)=>{"use strict";var kb=U("tls");_h.exports=(s={},e=kb.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 wh=H((PC,vh)=>{"use strict";var Ob=U("net");vh.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]),Ob.isIP(e)?"":e}});var kh=H((IC,qi)=>{"use strict";var Ch=U("http"),ji=U("https"),Sb=bh(),Tb=Oi(),Ab=Li(),Rb=wh(),Pb=Pi(),En=new Tb({maxSize:100}),Cs=new Map,Eh=(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)},Ib=async s=>{let e=`${s.host}:${s.port}:${s.ALPNProtocols.sort()}`;if(!En.has(e)){if(Cs.has(e))return(await Cs.get(e)).alpnProtocol;let{path:t,agent:i}=s;s.path=s.socketPath;let a=Sb(s);Cs.set(e,a);try{let{socket:l,alpnProtocol:h}=await a;if(En.set(e,h),s.path=t,h==="h2")l.destroy();else{let{globalAgent:p}=ji,g=ji.Agent.prototype.createConnection;i?i.createConnection===g?Eh(i,l,s):l.destroy():p.createConnection===g?Eh(p,l,s):l.destroy()}return Cs.delete(e),h}catch(l){throw Cs.delete(e),l}}return En.get(e)};qi.exports=async(s,e,t)=>{if((typeof s=="string"||s instanceof URL)&&(s=Pb(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||Rb(e),e.port=e.port||(i?443:80),e._defaultAgent=i?ji.globalAgent:Ch.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 Ib(e)==="h2"?(a&&(e.agent=a.http2),new Ab(e,t)):Ch.request(e,t)};qi.exports.protocolCache=En});var Sh=H((xC,Oh)=>{"use strict";var xb=U("http2"),Mb=Ti(),Di=Li(),Nb=Ri(),Lb=kh(),jb=(s,e,t)=>new Di(s,e,t),qb=(s,e,t)=>{let i=new Di(s,e,t);return i.end(),i};Oh.exports={...xb,ClientRequest:Di,IncomingMessage:Nb,...Mb,request:jb,get:qb,auto:Lb}});var Bi=H(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var Th=tt();Ui.default=s=>Th.default.nodeStream(s)&&Th.default.function_(s.getBoundary)});var Ih=H(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});var Rh=U("fs"),Ph=U("util"),Ah=tt(),Db=Bi(),Ub=Ph.promisify(Rh.stat);Hi.default=async(s,e)=>{if(e&&"content-length"in e)return Number(e["content-length"]);if(!s)return 0;if(Ah.default.string(s))return Buffer.byteLength(s);if(Ah.default.buffer(s))return s.length;if(Db.default(s))return Ph.promisify(s.getLength.bind(s))();if(s instanceof Rh.ReadStream){let{size:t}=await Ub(s.path);return t===0?void 0:t}}});var Gi=H($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});function Bb(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])}}$i.default=Bb});var xh=H(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.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 Nh=H(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.TimeoutError=void 0;var Hb=U("net"),$b=xh(),Mh=Symbol("reentry"),Gb=()=>{},kn=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name="TimeoutError",this.code="ETIMEDOUT"}};Es.TimeoutError=kn;Es.default=(s,e,t)=>{if(Mh in s)return Gb;s[Mh]=!0;let i=[],{once:a,unhandleAll:l}=$b.default(),h=(v,k,S)=>{var T;let E=setTimeout(k,v,v,S);(T=E.unref)===null||T===void 0||T.call(E);let O=()=>{clearTimeout(E)};return i.push(O),O},{host:p,hostname:g}=t,y=(v,k)=>{s.destroy(new kn(v,k))},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 k;let{socketPath:S}=s;if(v.connecting){let T=!!(S??Hb.isIP((k=g??p)!==null&&k!==void 0?k:"")!==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",O=>{O===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 jh=H(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});var Lh=tt();Wi.default=s=>{s=s;let e={protocol:s.protocol,hostname:Lh.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 Lh.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 qh=H(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var Fb=U("url"),Wb=["protocol","host","hostname","port","pathname","search"];Vi.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 Fb.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 Wb)e[l]&&(a[l]=e[l].toString());return a}});var Dh=H(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var zi=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)}};Ki.default=zi});var Yi=H(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});var Vb=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(""))};Ji.default=Vb});var Bh=H(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.dnsLookupIpVersionToFamily=Ct.isDnsLookupIpVersion=void 0;var Uh={auto:0,ipv4:4,ipv6:6};Ct.isDnsLookupIpVersion=s=>s in Uh;Ct.dnsLookupIpVersionToFamily=s=>{if(Ct.isDnsLookupIpVersion(s))return Uh[s];throw new Error("Invalid DNS lookup IP version")}});var Qi=H(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.isResponseOk=void 0;On.isResponseOk=s=>{let{statusCode:e}=s,t=s.request.options.followRedirect?299:399;return e>=200&&e<=t||e===304}});var $h=H(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});var Hh=new Set;Xi.default=s=>{Hh.has(s)||(Hh.add(s),process.emitWarning(`Got: ${s}`,{type:"DeprecationWarning"}))}});var Gh=H(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var ne=tt(),zb=(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};Zi.default=zb});var Fh=H(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.retryAfterStatusCodes=void 0;ks.retryAfterStatusCodes=new Set([413,429,503]);var Kb=({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};ks.default=Kb});var Ts=H(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 Wh=U("util"),Vh=U("stream"),Jb=U("fs"),lt=U("url"),zh=U("http"),eo=U("http"),Yb=U("https"),Qb=ou(),Xb=fu(),Kh=zu(),Zb=Qu(),ev=Sh(),tv=vn(),x=tt(),sv=Ih(),Jh=Bi(),nv=Gi(),Yh=Nh(),rv=jh(),Qh=qh(),iv=Dh(),ov=Yi(),Xh=Bh(),av=Qi(),ut=$h(),cv=Gh(),lv=Fh(),to,fe=Symbol("request"),An=Symbol("response"),Ft=Symbol("responseSize"),Wt=Symbol("downloadedSize"),Vt=Symbol("bodySize"),zt=Symbol("uploadedSize"),Sn=Symbol("serverResponsesPiped"),Zh=Symbol("unproxyEvents"),ed=Symbol("isFromCache"),so=Symbol("cancelTimeouts"),td=Symbol("startedReading"),Kt=Symbol("stopReading"),Tn=Symbol("triggerRead"),ht=Symbol("body"),Os=Symbol("jobs"),sd=Symbol("originalResponse"),nd=Symbol("retryTimeout");Q.kIsNormalizedAlready=Symbol("isNormalizedAlready");var uv=x.default.string(process.versions.brotli);Q.withoutBody=new Set(["GET","HEAD"]);Q.knownHookEvents=["init","beforeRequest","beforeRedirect","beforeError","beforeRetry","afterResponse"];function hv(s){for(let e in s){let t=s[e];if(!x.default.string(t)&&!x.default.number(t)&&!x.default.boolean(t)&&!x.default.null_(t)&&!x.default.undefined(t))throw new TypeError(`The \`searchParams\` value '${String(t)}' must be a string, number, boolean or null`)}}function dv(s){return x.default.object(s)&&!("statusCode"in s)}var no=new iv.default,fv=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()})}),pv=new Set([300,301,302,303,304,307,308]),gv=["context","body","json","form"];Q.setNonEnumerableProperties=(s,e)=>{let t={};for(let i of s)if(i)for(let a of gv)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 Ln?(Object.defineProperty(this,"request",{enumerable:!1,value:i}),Object.defineProperty(this,"response",{enumerable:!1,value:i[An]}),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,x.default.string(t.stack)&&x.default.string(this.stack)){let h=this.stack.indexOf(this.message)+this.message.length,p=this.stack.slice(h).split(`
|
|
35
|
+
`).reverse(),g=t.stack.slice(t.stack.indexOf(t.message)+t.message.length).split(`
|
|
36
|
+
`).reverse();for(;g.length!==0&&g[0]===p[0];)p.shift();this.stack=`${this.stack.slice(0,h)}${p.reverse().join(`
|
|
37
|
+
`)}${g.reverse().join(`
|
|
38
|
+
`)}`}}};Q.RequestError=ae;var Rn=class extends ae{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name="MaxRedirectsError",this.code="ERR_TOO_MANY_REDIRECTS"}};Q.MaxRedirectsError=Rn;var Pn=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=Pn;var In=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=In;var xn=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=xn;var Mn=class extends ae{constructor(e,t,i){super(e.message,e,i),this.name="TimeoutError",this.event=e.event,this.timings=t}};Q.TimeoutError=Mn;var Ss=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=Ss;var Nn=class extends ae{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name="UnsupportedProtocolError",this.code="ERR_UNSUPPORTED_PROTOCOL"}};Q.UnsupportedProtocolError=Nn;var mv=["socket","connect","continue","information","upgrade","timeout"],Ln=class extends Vh.Duplex{constructor(e,t={},i){super({autoDestroy:!1,highWaterMark:0}),this[Wt]=0,this[zt]=0,this.requestInitialized=!1,this[Sn]=new Set,this.redirects=[],this[Kt]=!1,this[Tn]=!1,this[Os]=[],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 eo.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){x.default.nodeStream(t.body)&&t.body.destroy(),this.destroy(y);return}(async()=>{var y;try{this.options.body instanceof Jb.ReadStream&&await fv(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[Os])v();this[Os].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(x.default.object(e)&&!x.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),x.default.urlInstance(t.url)&&(t.url=new lt.URL(t.url.toString()))}if(t.cache===!1&&(t.cache=void 0),t.dnsCache===!1&&(t.dnsCache=void 0),x.assert.any([x.default.string,x.default.undefined],t.method),x.assert.any([x.default.object,x.default.undefined],t.headers),x.assert.any([x.default.string,x.default.urlInstance,x.default.undefined],t.prefixUrl),x.assert.any([x.default.object,x.default.undefined],t.cookieJar),x.assert.any([x.default.object,x.default.string,x.default.undefined],t.searchParams),x.assert.any([x.default.object,x.default.string,x.default.undefined],t.cache),x.assert.any([x.default.object,x.default.number,x.default.undefined],t.timeout),x.assert.any([x.default.object,x.default.undefined],t.context),x.assert.any([x.default.object,x.default.undefined],t.hooks),x.assert.any([x.default.boolean,x.default.undefined],t.decompress),x.assert.any([x.default.boolean,x.default.undefined],t.ignoreInvalidCookies),x.assert.any([x.default.boolean,x.default.undefined],t.followRedirect),x.assert.any([x.default.number,x.default.undefined],t.maxRedirects),x.assert.any([x.default.boolean,x.default.undefined],t.throwHttpErrors),x.assert.any([x.default.boolean,x.default.undefined],t.http2),x.assert.any([x.default.boolean,x.default.undefined],t.allowGetBody),x.assert.any([x.default.string,x.default.undefined],t.localAddress),x.assert.any([Xh.isDnsLookupIpVersion,x.default.undefined],t.dnsLookupIpVersion),x.assert.any([x.default.object,x.default.undefined],t.https),x.assert.any([x.default.boolean,x.default.undefined],t.rejectUnauthorized),t.https&&(x.assert.any([x.default.boolean,x.default.undefined],t.https.rejectUnauthorized),x.assert.any([x.default.function_,x.default.undefined],t.https.checkServerIdentity),x.assert.any([x.default.string,x.default.object,x.default.array,x.default.undefined],t.https.certificateAuthority),x.assert.any([x.default.string,x.default.object,x.default.array,x.default.undefined],t.https.key),x.assert.any([x.default.string,x.default.object,x.default.array,x.default.undefined],t.https.certificate),x.assert.any([x.default.string,x.default.undefined],t.https.passphrase),x.assert.any([x.default.string,x.default.buffer,x.default.array,x.default.undefined],t.https.pfx)),x.assert.any([x.default.object,x.default.undefined],t.cacheOptions),x.default.string(t.method)?t.method=t.method.toUpperCase():t.method="GET",t.headers===i?.headers?t.headers={...t.headers}:t.headers=tv({...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(x.default.string(t.searchParams)||t.searchParams instanceof lt.URLSearchParams)S=new lt.URLSearchParams(t.searchParams);else{hv(t.searchParams),S=new lt.URLSearchParams;for(let T in t.searchParams){let E=t.searchParams[T];E===null?S.append(T,""):E!==void 0&&S.append(T,E)}}(a=i?.searchParams)===null||a===void 0||a.forEach((T,E)=>{S.has(E)||S.append(E,T)}),t.searchParams=S}if(t.username=(l=t.username)!==null&&l!==void 0?l:"",t.password=(h=t.password)!==null&&h!==void 0?h:"",x.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+="/")),x.default.string(t.url)){if(t.url.startsWith("/"))throw new Error("`input` must not start with a slash when using `prefixUrl`");t.url=Qh.default(t.prefixUrl+t.url,t)}else(x.default.undefined(t.url)&&t.prefixUrl!==""||t.protocol)&&(t.url=Qh.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 lt.URL(E+O.href.slice(S.length)),S=E},get:()=>S});let{protocol:T}=t.url;if(T==="unix:"&&(T="http:",t.url=new lt.URL(`http://unix${t.url.pathname}${t.url.search}`)),t.searchParams&&(t.url.search=t.searchParams.toString()),T!=="http:"&&T!=="https:")throw new Nn(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:S,getCookieString:T}=C;x.assert.function_(S),x.assert.function_(T),S.length===4&&T.length===0&&(S=Wh.promisify(S.bind(t.cookieJar)),T=Wh.promisify(T.bind(t.cookieJar)),t.cookieJar={setCookie:S,getCookieString:T})}let{cache:v}=t;if(v&&(no.has(v)||no.set(v,new Kh((S,T)=>{let E=S[fe](S,T);return x.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},v))),t.cacheOptions={...t.cacheOptions},t.dnsCache===!0)to||(to=new Xb.default),t.dnsCache=to;else if(!x.default.undefined(t.dnsCache)&&!t.dnsCache.lookup)throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${x.default(t.dnsCache)}`);x.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(x.default.array(t.hooks[S]))t.hooks[S]=[...t.hooks[S]];else throw new TypeError(`Parameter \`${S}\` must be an Array, got ${x.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&&ut.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'),i?.https&&(t.https={...i.https,...t.https}),"rejectUnauthorized"in t&&ut.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'),"checkServerIdentity"in t&&ut.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'),"ca"in t&&ut.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'),"key"in t&&ut.default('"options.key" was never documented, please use "options.https.key"'),"cert"in t&&ut.default('"options.cert" was never documented, please use "options.https.certificate"'),"passphrase"in t&&ut.default('"options.passphrase" was never documented, please use "options.https.passphrase"'),"pfx"in t&&ut.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,y],t),cv.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=!x.default.undefined(e.form),a=!x.default.undefined(e.json),l=!x.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 Vh.Readable)&&!x.default.string(e.body)&&!x.default.buffer(e.body)&&!Jh.default(e.body))throw new TypeError("The `body` option must be a stream.Readable, string or Buffer");if(i&&!x.default.object(e.form))throw new TypeError("The `form` option must be an Object");{let g=!x.default.string(t["content-type"]);l?(Jh.default(e.body)&&g&&(t["content-type"]=`multipart/form-data; boundary=${e.body.getBoundary()}`),this[ht]=e.body):i?(g&&(t["content-type"]="application/x-www-form-urlencoded"),this[ht]=new lt.URLSearchParams(e.form).toString()):(g&&(t["content-type"]="application/json"),this[ht]=e.stringifyJson(e.json));let y=await sv.default(this[ht],e.headers);x.default.undefined(t["content-length"])&&x.default.undefined(t["transfer-encoding"])&&!p&&!x.default.undefined(y)&&(t["content-length"]=String(y))}}else p?this._lockWrite():this._unlockWrite();this[Vt]=Number(t["content-length"])||void 0}async _onResponseBase(e){let{options:t}=this,{url:i}=t;this[sd]=e,t.decompress&&(e=Zb(e));let a=e.statusCode,l=e;l.statusMessage=l.statusMessage?l.statusMessage:zh.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[ed]=l.isFromCache,this[Ft]=Number(e.headers["content-length"])||void 0,this[An]=e,e.once("end",()=>{this[Ft]=this[Wt],this.emit("downloadProgress",this.downloadProgress)}),e.once("error",p=>{e.destroy(),this._beforeError(new Ss(p,this))}),e.once("aborted",()=>{this._beforeError(new Ss({name:"Error",message:"The server aborted pending request",code:"ECONNRESET"},this))}),this.emit("downloadProgress",this.downloadProgress);let h=e.headers["set-cookie"];if(x.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&&pv.has(a)){if(e.resume(),this[fe]&&(this[so](),delete this[fe],this[Zh]()),(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[ht]=void 0,delete t.headers["content-length"]),this.redirects.length>=t.maxRedirects){this._beforeError(new Rn(this));return}try{let v=function(k){return k.protocol==="unix:"||k.hostname==="unix"},g=Buffer.from(e.headers.location,"binary").toString(),y=new lt.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 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&&!av.isResponseOk(l)){this._beforeError(new Pn(l));return}e.on("readable",()=>{this[Tn]&&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[Sn])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;Qb.default(e),this[so]=Yh.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 Yh.TimeoutError?new Mn(g,this.timings,this):new ae(g.message,g,this),this._beforeError(g)}),this[Zh]=nv.default(e,this,mv),this[fe]=e,this.emit("uploadProgress",this.uploadProgress);let h=this[ht],p=this.redirects.length===0?this:e;x.default.nodeStream(h)?(h.pipe(p),h.once("error",g=>{this._beforeError(new xn(g,this))})):(this._unlockWrite(),x.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,rv.default(e)),delete t.url;let l,h=no.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(x.default.undefined(p[N]))delete p[N];else if(x.default.null_(p[N]))throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${N}\` header`);if(h.decompress&&x.default.undefined(p["accept-encoding"])&&(p["accept-encoding"]=uv?"gzip, deflate, br":"gzip, deflate"),h.cookieJar){let N=await h.cookieJar.getCookieString(h.url.toString());x.default.nonEmptyString(N)&&(h.headers.cookie=N)}for(let N of h.hooks.beforeRequest){let W=await N(h);if(!x.default.undefined(W)){h.request=()=>W;break}}h.body&&this[ht]!==h.body&&(this[ht]=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 k=v.protocol==="https:",S;h.http2?S=ev.auto:S=k?Yb.request:zh.request;let T=(e=h.request)!==null&&e!==void 0?e:S,E=h.cache?this._createCacheableRequest:T;g&&!h.http2&&(h.agent=g[k?"https":"http"]),h[fe]=T,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=Xh.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(v,O);x.default.undefined(N)&&(N=S(v,O)),h.request=y,h.timeout=C,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),dv(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 Kh.CacheError?new In(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[Kt])return;let{options:t}=this,i=this.retryCount+1;this[Kt]=!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 ov.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:lv.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[nd]=setTimeout(p,h);return}}this._error(a)})()}_read(){this[Tn]=!0;let e=this[An];if(e&&!this[Kt]){e.readableLength&&(this[Tn]=!1);let t;for(;(t=e.read())!==null;){this[Wt]+=t.length,this[td]=!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[Os].push(a)}_writeRequest(e,t,i){this[fe].destroyed||(this._progressCallbacks.push(()=>{this[zt]+=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[Vt]=this[zt],this.emit("uploadProgress",this.uploadProgress),this[fe].emit("upload-complete")),e(i)})};this.requestInitialized?t():this[Os].push(t)}_destroy(e,t){var i;this[Kt]=!0,clearTimeout(this[nd]),fe in this&&(this[so](),!((i=this[An])===null||i===void 0)&&i.complete||this[fe].destroy()),e!==null&&!x.default.undefined(e)&&!(e instanceof ae)&&(e=new ae(e.message,e,this)),t(e)}get _isAboutToError(){return this[Kt]}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[sd])===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[Ft]?e=this[Wt]/this[Ft]:this[Ft]===this[Wt]?e=1:e=0,{percent:e,transferred:this[Wt],total:this[Ft]}}get uploadProgress(){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 timings(){var e;return(e=this[fe])===null||e===void 0?void 0:e.timings}get isFromCache(){return this[ed]}pipe(e,t){if(this[td])throw new Error("Failed to pipe. The response has been emitted already.");return e instanceof eo.ServerResponse&&this[Sn].add(e),super.pipe(e,t)}unpipe(e){return e instanceof eo.ServerResponse&&this[Sn].delete(e),super.unpipe(e),this}};Q.default=Ln});var As=H(Ue=>{"use strict";var yv=Ue&&Ue.__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=Ue&&Ue.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&yv(e,s,t)};Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CancelError=Ue.ParseError=void 0;var rd=Ts(),ro=class extends rd.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}};Ue.ParseError=ro;var io=class extends rd.RequestError{constructor(e){super("Promise was canceled",{},e),this.name="CancelError",this.code="ERR_CANCELED"}get isCanceled(){return!0}};Ue.CancelError=io;_v(Ts(),Ue)});var od=H(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var id=As(),bv=(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 id.ParseError({message:`Unknown body type '${e}'`,name:"Error"},s)}catch(l){throw new id.ParseError(l,s)}};oo.default=bv});var ao=H(dt=>{"use strict";var vv=dt&&dt.__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]}),wv=dt&&dt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vv(e,s,t)};Object.defineProperty(dt,"__esModule",{value:!0});var Cv=U("events"),Ev=tt(),kv=ru(),jn=As(),ad=od(),cd=Ts(),Ov=Gi(),Sv=Yi(),ld=Qi(),Tv=["request","response","redirect","uploadProgress","downloadProgress"];function ud(s){let e,t,i=new Cv.EventEmitter,a=new kv((h,p,g)=>{let y=C=>{let v=new cd.default(void 0,s);v.retryCount=C,v._noPipe=!0,g(()=>v.destroy()),g.shouldReject=!1,g(()=>p(new jn.CancelError(v))),e=v,v.once("response",async T=>{var E;if(T.retryCount=C,T.request.aborted)return;let O;try{O=await Sv.default(v),T.rawBody=O}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=O;else try{T.body=ad.default(T,Y.responseType,Y.parseJson,Y.encoding)}catch(se){if(T.body=O.toString(),ld.isResponseOk(T)){v._beforeError(se);return}}try{for(let[se,Z]of Y.hooks.afterResponse.entries())T=await Z(T,async Se=>{let Ne=cd.default.normalizeArguments(void 0,{...Se,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},Y);Ne.hooks.afterResponse=Ne.hooks.afterResponse.slice(0,se);for(let ft of Ne.hooks.beforeRetry)await ft(Ne);let rt=ud(Ne);return g(()=>{rt.catch(()=>{}),rt.cancel()}),rt})}catch(se){v._beforeError(new jn.RequestError(se.message,se,v));return}if(t=T,!ld.isResponseOk(T)){v._beforeError(new jn.HTTPError(T));return}v.destroy(),h(v.options.resolveBodyOnly?T.body:T)});let k=T=>{if(a.isCanceled)return;let{options:E}=v;if(T instanceof jn.HTTPError&&!E.throwHttpErrors){let{response:O}=T;h(v.options.resolveBodyOnly?O.body:O);return}p(T)};v.once("error",k);let S=v.options.body;v.once("retry",(T,E)=>{var O,N;if(S===((O=E.request)===null||O===void 0?void 0:O.options.body)&&Ev.default.nodeStream((N=E.request)===null||N===void 0?void 0:N.options.body)){k(E);return}y(T)}),Ov.default(v,i,Tv)};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 ad.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}dt.default=ud;wv(As(),dt)});var hd=H(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var Av=As();function Rv(s,...e){let t=(async()=>{if(s instanceof Av.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}co.default=Rv});var pd=H(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});var dd=tt();function fd(s){for(let e of Object.values(s))(dd.default.plainObject(e)||dd.default.array(e))&&fd(e);return Object.freeze(s)}lo.default=fd});var md=H(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0})});var uo=H(Me=>{"use strict";var Pv=Me&&Me.__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=Me&&Me.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Pv(e,s,t)};Object.defineProperty(Me,"__esModule",{value:!0});Me.defaultHandler=void 0;var yd=tt(),xe=ao(),xv=hd(),Dn=Ts(),Mv=pd(),Nv={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},Lv=async s=>new Promise(e=>{setTimeout(e,s)}),{normalizeArguments:qn}=Dn.default,_d=(...s)=>{let e;for(let t of s)e=qn(void 0,t,e);return e},jv=s=>s.isStream?new Dn.default(void 0,s):xe.default(s),qv=s=>"defaults"in s&&"options"in s.defaults,Dv=["get","post","put","patch","head","delete"];Me.defaultHandler=(s,e)=>e(s);var bd=(s,e)=>{if(s)for(let t of s)t(e)},vd=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?jv:y);if(yd.default.plainObject(i)){let C={...i,...a};Dn.setNonEnumerableProperties([i,a],C),a=C,i=void 0}try{let C;try{bd(s.options.hooks.init,a),bd((h=a.hooks)===null||h===void 0?void 0:h.init,a)}catch(k){C=k}let v=qn(i,a,l??s.options);if(v[Dn.kIsNormalizedAlready]=!0,C)throw new xe.RequestError(C.message,C,v);return y(v)}catch(C){if(a.isStream)throw C;return xv.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)qv(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!==Me.defaultHandler),l.length===0&&l.push(Me.defaultHandler),vd({options:_d(...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(!yd.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 Lv(h.backoff);let C=await e(void 0,void 0,l),v=await h.transform(C),k=[];for(let T of v)if(h.filter(T,p,k)&&(!h.shouldContinue(T,p,k)||(yield T,h.stackAllItems&&p.push(T),k.push(T),--g<=0)))return;let S=h.paginate(C,p,k);if(S===!1)return;S===C.request.options?l=C.request.options:S!==void 0&&(l=qn(void 0,S,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 Dv)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,Nv),Object.defineProperty(e,"defaults",{value:s.mutableDefaults?s:Mv.default(s),writable:s.mutableDefaults,configurable:s.mutableDefaults,enumerable:!0}),e.mergeOptions=_d,e};Me.default=vd;Iv(md(),Me)});var Bn=H((nt,Un)=>{"use strict";var Uv=nt&&nt.__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]}),wd=nt&&nt.__exportStar||function(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Uv(e,s,t)};Object.defineProperty(nt,"__esModule",{value:!0});var Bv=U("url"),Cd=uo(),Hv={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 Bv.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:[Cd.defaultHandler],mutableDefaults:!1},ho=Cd.default(Hv);nt.default=ho;Un.exports=ho;Un.exports.default=ho;Un.exports.__esModule=!0;wd(uo(),nt);wd(ao(),nt)});var Ad=H((xs,Co)=>{(function(s,e){typeof xs=="object"&&typeof Co=="object"?Co.exports=e(un(),Bn()):typeof define=="function"&&define.amd?define(["ws","got"],e):typeof xs=="object"?xs.Ably=e(un(),Bn()):s.Ably=e(s.ws,s.got)})(xs,(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,k=Object.prototype.hasOwnProperty,S=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={}))k.call(n,o)&&T(r,o,n[o]);if(C)for(var o of C(n))S.call(n,o)&&T(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&&C)for(var c of C(r))n.indexOf(c)<0&&S.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))!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(v(r)):{},se(n||!r||!r.__esModule?l(o,"default",{value:r,enumerable:!0}):o,r)),Se=function(r,n){this[0]=r,this[1]=n},Ne=(r,n,o)=>{var c=(m,_,A,I)=>{try{var q=o[m](_),j=(_=q.value)instanceof Se,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},rt=W({"node_modules/bops/from.js"(r,n){var o=U("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)}}}),ft=W({"node_modules/bops/to.js"(r,n){n.exports=function(o,c){return o.toString(c)}}}),Fn=W({"node_modules/bops/is.js"(r,n){var o=U("buffer").Buffer;n.exports=function(c){return o.isBuffer(c)}}}),Wd=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)}}}),Vd=W({"node_modules/bops/join.js"(r,n){var o=U("buffer").Buffer;n.exports=function(c,u){return u!==void 0?o.concat(c,u):o.concat(c)}}}),zd=W({"node_modules/bops/copy.js"(r,n){n.exports=o;function o(c,u,f,m,_){return c.copy(u,f,m,_)}}}),Kd=W({"node_modules/bops/create.js"(r,n){var o=U("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)}}}),Jd=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}}),Yd=W({"node_modules/bops/write.js"(r,n){var o=U("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}}),Qd=W({"node_modules/bops/index.js"(r,n){var o={};n.exports=o,o.from=rt(),o.to=ft(),o.is=Fn(),o.subarray=Wd(),o.join=Vd(),o.copy=zd(),o.create=Kd(),c(Jd(),o),c(Yd(),o);function c(u,f){for(var m in u)f[m]=u[m]}}}),Xd=W({"node_modules/@ably/msgpack-js/msgpack.js"(r){"use strict";var n=Qd();r.encode=function(w,R){var P=G(w,R);if(P!=0){var D=n.create(P);return j(w,D,0,R),D}},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 D=this.parse();R[D]=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,D;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),D=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,[D,this.bin(P)];case 200:return P=n.readUInt16BE(this.buffer,this.offset+1),D=n.readUInt8(this.buffer,this.offset+3),this.offset+=4,[D,this.bin(P)];case 201:return P=n.readUInt32BE(this.buffer,this.offset+1),D=n.readUInt8(this.buffer,this.offset+5),this.offset+=6,[D,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 D=n.readUInt8(this.buffer,this.offset+1),R=n.readUInt8(this.buffer,this.offset+2),this.offset+=3,D===0&&R===0?void 0:[D,R];case 213:return D=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[D,this.bin(2)];case 214:return D=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[D,this.bin(4)];case 215:return D=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[D,this.bin(8)];case 216:return D=n.readUInt8(this.buffer,this.offset+1),this.offset+=2,[D,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 D=w[P],$=typeof D;return(!R||D!=null)&&($!=="function"||!!D.toJSON)})}function j(w,R,P,D,$){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 D&&$?0:(R[P]=212,R[P+1]=0,R[P+2]=0,3);if(w===null)return D&&$?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,D);if(V==="object"){X=0;var Ce=Array.isArray(w);if(Ce)F=w.length;else{var _e=q(w,D);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 Ve=0;Ve<F;Ve++)X+=j(w[Ve],R,P+X,D);else for(var Ve=0;Ve<F;Ve++){var dc=_e[Ve];X+=j(dc,R,P+X),X+=j(w[dc],R,P+X,D,!0)}return X}if(V!=="function")throw new Error("Unknown type "+V)}function G(w,R,P){var D=typeof w,$,V;if(D==="string"){if($=n.from(w).length,$<32)return 1+$;if($<256)return 2+$;if($<65536)return 3+$;if($<4294967296)return 5+$}if(n.is(w)){if($=w.length,$<256)return 2+$;if($<65536)return 3+$;if($<4294967296)return 5+$}if(D==="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(D==="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(D==="object"){if(V=0,Array.isArray(w)){$=w.length;for(var F=0;F<$;F++)V+=G(w[F],R)}else{var X=q(w,R);$=X.length;for(var F=0;F<$;F++){var Ce=X[F];V+=G(Ce)+G(w[Ce],R,!0)}}if($<16)return 1+V;if($<65536)return 3+V;if($<4294967296)return 5+V;throw new Error("Array or object too long 0x"+$.toString(16))}if(D==="function")return 0;throw new Error("Unknown type "+D)}}}),L=class{},So=typeof global<"u"?global:typeof window<"u"?window:self;function Ms(r,n){return`${r}`.padStart(n?3:2,"0")}function Zd(r){return L.Config.logTimestamps?function(n){let o=new Date;r(Ms(o.getHours())+":"+Ms(o.getMinutes())+":"+Ms(o.getSeconds())+"."+Ms(o.getMilliseconds(),1)+" "+n)}:function(n){r(n)}}var ef=()=>{var r;let n,o;return typeof((r=So?.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(Zd)},$e=class Rs{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=Rs.defaultLogLevel,this.logHandler=Rs.defaultLogHandler,this.logErrorHandler=Rs.defaultLogErrorHandler}static initLogHandlers(){let[n,o]=ef();this.defaultLogHandler=n,this.defaultLogErrorHandler=o,this.defaultLogger=new Rs}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)}};$e.defaultLogLevel=1,$e.LOG_NONE=0,$e.LOG_ERROR=1,$e.LOG_MAJOR=2,$e.LOG_MINOR=3,$e.LOG_MICRO=4,$e.logAction=(r,n,o,c)=>{$e.logActionNoStrip(r,n,o,c)};var tf=$e,d=tf,Qt={};Y(Qt,{Format:()=>jo,allSame:()=>lf,allToLowerCase:()=>$o,allToUpperCase:()=>Go,arrChooseN:()=>Ho,arrDeleteValue:()=>Mo,arrEquals:()=>zo,arrIntersect:()=>Io,arrIntersectOb:()=>xo,arrPopRandomElement:()=>Wn,arrWithoutValue:()=>cf,cheapRandStr:()=>Uo,containsValue:()=>af,copy:()=>Xt,createMissingPluginError:()=>es,dataSizeBytes:()=>Do,decodeBody:()=>ue,encodeBody:()=>Le,ensureArray:()=>Ao,forInOwnNonNullProperties:()=>Lo,getBackoffCoefficient:()=>Fo,getGlobalObject:()=>uf,getJitterCoefficient:()=>Wo,getRetryTime:()=>Kn,inherits:()=>of,inspectBody:()=>qo,inspectError:()=>ee,intersect:()=>Po,isEmpty:()=>nf,isErrorInfoOrPartialErrorInfo:()=>zn,isNil:()=>Ge,isObject:()=>Et,keysArray:()=>Ns,listenerToAsyncIterator:()=>hf,matchDerivedChannel:()=>Vo,mixin:()=>J,parseQueryString:()=>Ls,prototypicalClone:()=>Ro,randomString:()=>Bo,shallowClone:()=>rf,shallowEquals:()=>Jn,stringifyValues:()=>Vn,throwMissingPluginError:()=>pe,toBase64:()=>js,toQueryString:()=>Zt,valuesArray:()=>No,whenPromiseSettles:()=>ke,withTimeoutAsync:()=>Ko});function To(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 M=class fo extends Error{constructor(n,o,c,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,fo.prototype),this.code=o,this.statusCode=c,this.cause=u}toString(){return To(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 fo(o,c,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}},Ee=class po extends Error{constructor(n,o,c,u){super(n),typeof Object.setPrototypeOf<"u"&&Object.setPrototypeOf(this,po.prototype),this.code=o,this.statusCode=c,this.cause=u}toString(){return To(this)}static fromValues(n){let{message:o,code:c,statusCode:u}=n;if(typeof o!="string"||!Ge(c)&&typeof c!="number"||!Ge(u)&&typeof u!="number")throw new Error("PartialErrorInfo.fromValues(): invalid values: "+L.Config.inspect(n));let f=Object.assign(new po(o,c,u),n);return f.code&&!f.href&&(f.href="https://help.ably.io/error/"+f.code),f}};function sf(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 Xt(r){return J({},r)}function Ao(r){return Ge(r)?[]:Array.isArray(r)?r:[r]}function Et(r){return Object.prototype.toString.call(r)=="[object Object]"}function nf(r){for(let n in r)return!1;return!0}function Ge(r){return r==null}function rf(r){let n=new Object;for(let o in r)n[o]=r[o];return n}function Ro(r,n){class o{}o.prototype=r;let c=new o;return n&&J(c,n),c}var of=function(r,n){if(L.Config.inherits){L.Config.inherits(r,n);return}r.super_=n,r.prototype=Ro(n.prototype,{constructor:r})};function af(r,n){for(let o in r)if(r[o]==n)return!0;return!1}function Po(r,n){return Array.isArray(n)?Io(r,n):xo(r,n)}function Io(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 xo(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 Mo(r,n){let o=r.indexOf(n),c=o!=-1;return c&&r.splice(o,1),c}function cf(r,n){let o=r.slice();return Mo(o,n),o}function Ns(r,n){let o=[];for(let c in r)n&&!Object.prototype.hasOwnProperty.call(r,c)||o.push(c);return o}function No(r,n){let o=[];for(let c in r)n&&!Object.prototype.hasOwnProperty.call(r,c)||o.push(r[c]);return o}function Lo(r,n){for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&r[o]&&n(o)}function lf(r,n){if(r.length===0)return!0;let o=r[0][n];return r.every(function(c){return c[n]===o})}var jo=(r=>(r.msgpack="msgpack",r.json="json",r))(jo||{});function Wn(r){return r.splice(sf(r),1)[0]}function Zt(r){let n=[];if(r)for(let o in r)n.push(encodeURIComponent(o)+"="+encodeURIComponent(r[o]));return n.length?"?"+n.join("&"):""}function Vn(r){return Object.fromEntries(Object.entries(r).map(([n,o])=>[n,String(o)]))}function Ls(r){let n,o=/([^?&=]+)=?([^&]*)/g,c={};for(;n=o.exec(r);)c[decodeURIComponent(n[1])]=decodeURIComponent(n[2]);return c}function zn(r){return typeof r=="object"&&r!==null&&(r instanceof M||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 qo(r){return L.BufferUtils.isBuffer(r)?r.toString():typeof r=="string"?r:L.Config.inspect(r)}function Do(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 Uo(){return String(Math.random()).substr(2)}var Bo=async r=>{let n=await L.Config.getRandomArrayBuffer(r);return L.BufferUtils.base64Encode(n)};function Ho(r,n){let o=Math.min(n,r.length),c=r.slice(),u=[];for(let f=0;f<o;f++)u.push(Wn(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 Le(r,n,o){return o=="msgpack"?(n||pe("MsgPack"),n.encode(r,!0)):JSON.stringify(r)}function $o(r){return r.map(function(n){return n&&n.toLowerCase()})}function Go(r){return r.map(function(n){return n&&n.toUpperCase()})}function Fo(r){return Math.min((r+2)/3,2)}function Wo(){return 1-Math.random()*.2}function Kn(r,n){return r*Fo(n)*Wo()}function uf(){return typeof global<"u"?global:typeof window<"u"?window:self}function Jn(r,n){return Object.keys(r).every(o=>r[o]===n[o])&&Object.keys(n).every(o=>n[o]===r[o])}function Vo(r){let n=/^(\[([^?]*)(?:(.*))\])?(.+)$/,o=r.match(n);if(!o||!o.length||o.length<5)throw new M("regex match failed",400,40010);if(o[2])throw new M(`cannot use a derived option with a ${o[2]} channel`,400,40010);return{qualifierParam:o[3]||"",channelName:o[4]}}function js(r){let n=L.BufferUtils,o=n.utf8Encode(r);return n.base64Encode(o)}function zo(r,n){return r.length===n.length&&r.every(function(o,c){return o===n[c]})}function es(r){return new M(`${r} plugin not provided`,40019,400)}function pe(r){throw es(r)}async function Ko(r,n=5e3,o="Timeout expired"){let c=new M(o,5e4,500);return Promise.race([r,new Promise((u,f)=>setTimeout(()=>f(c),n))])}function hf(r){return Ne(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 M("Concurrent next() calls are not supported",4e4,400);yield yield new Se(new Promise(f=>{o=f}))}}finally{c()}})}var Jo="2.17.0",df="ably-js/"+Jo,je={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:Jo,protocolVersion:5,agent:df,getPort:ff,getHttpScheme:pf,getPrimaryDomainFromEndpoint:Qo,getEndpointFallbackHosts:Xo,getFallbackHosts:ea,getHosts:gf,checkHost:ta,objectifyOptions:yf,normaliseOptions:bf,defaultGetHeaders:vf,defaultPostHeaders:wf};function ff(r,n){return n||r.tls?r.tlsPort:r.port}function pf(r){return r.tls?"https://":"http://"}function Yo(r){return r.includes(".")||r.includes("::")||r==="localhost"}function Qo(r){return Yo(r)?r:r.startsWith("nonprod:")?`${r.replace("nonprod:","")}.realtime.ably-nonprod.net`:`${r}.realtime.ably.net`}function Xo(r){if(Yo(r))return[];if(r.startsWith("nonprod:")){let n=r.replace("nonprod:","");return Zo(n,"ably-realtime-nonprod.com")}return Zo(r,"ably-realtime.com")}function Zo(r,n){return["a","b","c","d","e"].map(o=>`${r}.${o}.fallback.${n}`)}function ea(r){let n=r.fallbackHosts,o=typeof r.httpMaxRetryCount<"u"?r.httpMaxRetryCount:je.httpMaxRetryCount;return n?Ho(n,o):[]}function gf(r){return[r.primaryDomain].concat(ea(r))}function ta(r){if(typeof r!="string")throw new M("host must be a string; was a "+typeof r,4e4,400);if(!r.length)throw new M("host must not be zero-length",4e4,400)}function mf(r){let n={};for(let o in je.TIMEOUTS)n[o]=r[o]||je.TIMEOUTS[o];return n}function Yn(r){let n=je.agent;if(r.agents)for(var o in r.agents)n+=" "+o+"/"+r.agents[o];return n}function yf(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=O(E({},f),{plugins:E(E({},u),f.plugins)})),f}function _f(r){if(r.endpoint&&(r.environment||r.restHost||r.realtimeHost))throw new M("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 M("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400)}function bf(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."),_f(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||je.ENDPOINT;!r.fallbackHosts&&!r.restHost&&!r.realtimeHost&&!r.port&&!r.tlsPort&&(r.fallbackHosts=Xo(r.environment||u));let f=r.environment&&`${r.environment}.realtime.ably.net`,_=r.restHost||r.realtimeHost||f||Qo(u);(r.fallbackHosts||[]).concat(_).forEach(ta),r.port=r.port||je.PORT,r.tlsPort=r.tlsPort||je.TLS_PORT,"tls"in r||(r.tls=!0);let A=mf(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?Ls(R):{},w.indexOf("://")===-1&&(w="https://"+w),j=w}let G=r.wsConnectivityCheckUrl;return G&&G.indexOf("://")===-1&&(G="wss://"+G),O(E({},r),{primaryDomain:_,maxMessageSize:r.maxMessageSize||je.maxMessageSize,timeouts:A,connectivityCheckParams:q,connectivityCheckUrl:j,wsConnectivityCheckUrl:G,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 sa={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},na={format:"json",protocolVersion:je.protocolVersion};function vf(r,{format:n,protocolVersion:o=na.protocolVersion}={}){return{accept:sa[n??(r.useBinaryProtocol?"msgpack":"json")],"X-Ably-Version":o.toString(),"Ably-Agent":Yn(r)}}function wf(r,{format:n,protocolVersion:o=na.protocolVersion}={}){let c=sa[n??(r.useBinaryProtocol?"msgpack":"json")];return{accept:c,"content-type":c,"X-Ably-Version":o.toString(),"Ably-Agent":Yn(r)}}var K=je;function Cf(r){return Object.assign(je,r)}var Ef=class Ed{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 Ed(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)})}},ra=Ef,ia=(r=>(r.Get="get",r.Delete="delete",r.Post="post",r.Put="put",r.Patch="patch",r))(ia||{}),ce=ia,oa=(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))(oa||{});function kf(r){return r>=200&&r<400}var ts=oa,Qn=Math.pow(2,17);function Of(){return("000000"+Math.floor(Math.random()*1e16)).slice(-16)}function Sf(r){return!!r.connection}function aa(r){return zn(r)?(r.code||(r.statusCode===403?r.code=40300:(r.code=40170,r.statusCode=401)),r):new M(ee(r),r.code||40170,r.statusCode||401)}var Tf=(r,n)=>{let o=L.BufferUtils,c=o.utf8Encode(r),u=o.utf8Encode(n),f=o.hmacSha256(c,u);return o.base64Encode(f)};function ca(r){if(!r)return"";typeof r=="string"&&(r=JSON.parse(r));let n=Object.create(null),o=Ns(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 la(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 Af(r){return"useTokenAuth"in r&&!r.useTokenAuth}function ua(r){return r.useTokenAuth||!Af(r)&&(r.authCallback||r.authUrl||r.token||r.tokenDetails)}function Rf(r){return!r.key&&!r.authCallback&&!r.authUrl}var Pf=0;function If(){return Pf++}var xf=class{constructor(r,n){if(this.authOptions={},this.client=r,this.tokenParams=n.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,ua(n))Rf(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),la(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 M(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 M("Unable to update auth options with incompatible key",40102,401);try{let o=await this._forceNewToken(r??null,n??null);return Sf(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===ts.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(o),o}}async _forceNewToken(r,n){this.tokenDetails=null,this._saveTokenOptions(r,n),la(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||Xt(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=Ls(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 D,$;let V=(D=P.body)!=null?D:null,F=null;if(P.error)d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+ee(P.error));else{let _e=($=P.headers["content-type"])!=null?$:null;Array.isArray(_e)?F=_e.join(", "):F=_e,d.logAction(this.logger,d.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+F+"; body: "+qo(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 M("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 M("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>Qn){A(new M("authUrl response exceeded max permitted length",40170,401),null);return}try{V=JSON.parse(V)}catch(_e){A(new M("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 D=Zt(w).slice(1);ke(this.client.http.doUri(ce.Post,o.authUrl,P,D,j),($,V)=>R($||V))}else ke(this.client.http.doUri(ce.Get,o.authUrl,I||{},null,w),(P,D)=>R(P||D))};else if(o.key)d.logAction(this.logger,d.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),u=(_,A)=>{ke(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 M(_,40171,403)}"capability"in c&&(c.capability=ca(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(_)),ke(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 M(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(aa(G));return}if(typeof w=="string"){w.length===0?A(new M("Token string is empty",40170,401)):w.length>Qn?A(new M("Token string exceeded max permitted length (was "+w.length+" bytes)",40170,401)):w==="undefined"||w==="null"?A(new M("Token string was literal null/undefined",40170,401)):w[0]==="{"&&!(R&&R.indexOf("application/jwt")>-1)?A(new M("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 D="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()",D),A(new M(D,40170,401));return}let P=JSON.stringify(w).length;if(P>Qn&&!o.suppressMaxLengthCheck){A(new M("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 D="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()",D),A(new M(D,40170,401));return}m(w,(D,$,V)=>{if(D){d.logAction(this.logger,d.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+ee(D)),A(aa(D));return}V||($=JSON.parse($)),d.logAction(this.logger,d.LOG_MINOR,"Auth.getToken()","token received"),_($)})})})}async createTokenRequest(r,n){n=n||this.authOptions,r=r||Xt(this.tokenParams);let o=n.key;if(!o)throw new M("No key specified",40101,403);let c=o.split(":"),u=c[0],f=c[1];if(!f)throw new M("Invalid key specified",40101,403);if(r.clientId==="")throw new M("clientId can\u2019t be an empty string",40012,400);"capability"in r&&(r.capability=ca(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=Of()),j=m.timestamp,G=m.keyName+`
|
|
39
|
+
`+A+`
|
|
40
|
+
`+I+`
|
|
41
|
+
`+_+`
|
|
42
|
+
`+j+`
|
|
43
|
+
`+q+`
|
|
44
|
+
`;return m.mac=m.mac||Tf(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 "+js(r.token)}}}_saveBasicOptions(r){this.method="basic",this.key=r.key,this.basicKey=js(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 M("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=ra.create(this.logger))).createPromise();if(this.currentTokenRequestId!==null&&!r)return o;let c=this.currentTokenRequestId=If(),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 M('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 M("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 M(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)}},Fe=xf;function Xn(r){let n=[];if(r)for(let o in r)n.push(o+"="+r[o]);return n.join("&")}function kt(r,n){return r+(n?"?":"")+Xn(n)}function Mf(r,n,o,c,u){r.error?d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received Error; "+kt(o,c)+"; Error: "+ee(r.error)):d.logActionNoStrip(u,d.LOG_MICRO,"Http."+n+"()","Received; "+kt(o,c)+"; Headers: "+Xn(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+r.body))}function Nf(r,n,o,c,u){u.shouldLog(d.LOG_MICRO)&&d.logActionNoStrip(u,d.LOG_MICRO,"Http."+r+"()","Sending; "+kt(n,c)+"; Body"+(L.BufferUtils.isBuffer(o)?" (Base64): "+L.BufferUtils.base64Encode(o):": "+o))}var Zn=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 M("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 M(`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 M(`Unexpected error in Http.do: ${ee(f)}`,500,5e4)}}}async doUri(r,n,o,c,u){try{Nf(r,n,c,u,this.logger);let f=await this.platformHttp.doUri(r,n,o,c,u);return this.logger.shouldLog(d.LOG_MICRO)&&Mf(f,r,n,u,this.logger),f}catch(f){return{error:new M(`Unexpected error in Http.doUri: ${ee(f)}`,500,5e4)}}}};function Lf(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 er(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(Et(c))for(f in c)Object.prototype.hasOwnProperty.call(c,f)&&Array.isArray(c[f])&&er([c],n,f)}var jf=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(Ge(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||Ge(r[0])&&Ge(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&&Ge(u)){er([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?er([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=>{Lf(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(Ge(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=jf,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},ha=[];Object.keys(z).forEach(function(r){ha[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},qf=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 da=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function Df(r){return!r||!r.channelOptions?{channelOptions:r,plugins:{},baseEncodedPreviousPayload:void 0}:r}function fa(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 Uf(r,n){let{data:o,encoding:c}=await pa(r.data,r.encoding,n);return r.data=o,r.encoding=c,r}async function pa(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 tr(r,n){let{data:o,encoding:c}=ga(r.data,r.encoding);return r.data=o,r.encoding=c,n!=null&&n.cipher?Uf(r,n):r}function ga(r,n){if(typeof r=="string"||L.BufferUtils.isBuffer(r)||r===null||r===void 0)return{data:r,encoding:n};if(Et(r)||Array.isArray(r))return{data:JSON.stringify(r),encoding:n?n+"/json":"json"};throw new M("Data type is unsupported",40013,400)}async function sr(r,n){let{data:o,encoding:c,error:u}=await ma(r.data,r.encoding,n);if(r.data=o,r.encoding=c,u)throw u}async function ma(r,n,o){let c=Df(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 M("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if(typeof Uint8Array>"u")throw new M("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 M("Vcdiff delta decode failed with "+w,40018,400)}continue;default:throw new Error("Unknown encoding")}}}catch(G){let w=G;_=new M(`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 nr(...r){let n=r.length>0?"json":"msgpack",{data:o,encoding:c}=ya(this.data,this.encoding,n);return Object.assign({},this,{encoding:c,data:o})}function ya(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 Ds={encryptData:pa,encodeData:ga,encodeDataForWire:ya,decodeData:ma};function Us(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 M("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 Ot(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 St=class{},_a=class{constructor(r){this.Platform=L,this.ErrorInfo=M,this.Logger=d,this.Defaults=K,this.Utils=Qt,this.EventEmitter=he,this.MessageEncoding=Ds;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 M(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 M('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 M("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 Zn(this),this.auth=new Fe(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}};_a.Platform=L;var ba=_a,Bf=class Jt{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 Le(n,o,c)}static fromResponseBody(n,o,c){return c&&(n=ue(n,o,c)),Array.isArray(n)?Jt.fromValuesArray(n):Jt.fromValues(n)}static fromValues(n){return n.error=n.error&&M.fromValues(n.error),Object.assign(new Jt,n)}static fromLocalDevice(n){return Object.assign(new Jt,n)}static fromValuesArray(n){let o=n.length,c=new Array(o);for(let u=0;u<o;u++)c[u]=Jt.fromValues(n[u]);return c}},Tt=Bf;async function va(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 Hf(r,n,o){if(r.err&&!r.body)return{err:r.err};if(r.statusCode===ts.NoContent)return O(E({},r),{body:[],unpacked:!0});let c=r.body;if(!r.unpacked)try{c=ue(c,n,o)}catch(_){return zn(_)?{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 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:m,unpacked:!0,statusCode:u}}return{err:r.err,body:f,headers:m,unpacked:!0,statusCode:u}}function $f(r,n,o,c,u){r.err?d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received Error; "+kt(o,c)+"; Error: "+ee(r.err)):d.logAction(u,d.LOG_MICRO,"Resource."+n+"()","Received; "+kt(o,c)+"; Headers: "+Xn(r.headers)+"; StatusCode: "+r.statusCode+"; Body: "+(L.BufferUtils.isBuffer(r.body)?" (Base64): "+L.BufferUtils.base64Encode(r.body):": "+L.Config.inspect(r.body)))}var Gf=class Yt{static async get(n,o,c,u,f,m){return Yt.do(ce.Get,n,o,null,c,u,f,m??!1)}static async delete(n,o,c,u,f,m){return Yt.do(ce.Delete,n,o,null,c,u,f,m)}static async post(n,o,c,u,f,m,_){return Yt.do(ce.Post,n,o,c,u,f,m,_)}static async patch(n,o,c,u,f,m,_){return Yt.do(ce.Patch,n,o,c,u,f,m,_)}static async put(n,o,c,u,f,m,_){return Yt.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 D=u;if(((R=G["content-type"])==null?void 0:R.indexOf("msgpack"))>0)try{o._MsgPack||pe("MsgPack"),D=o._MsgPack.decode(u)}catch($){d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending MsgPack Decoding Error: "+ee($))}d.logAction(I,d.LOG_MICRO,"Resource."+n+"()","Sending; "+kt(c,w)+"; Body: "+D)}let P=await o.http.do(n,c,G,u,w);return P.error&&Fe.isTokenErr(P.error)?(await o.auth.authorize(null,null),va(o,G,w,q)):{err:P.error,body:P.body,headers:P.headers,unpacked:P.unpacked,statusCode:P.statusCode}}let j=await va(o,f,m,q);if(_&&(j=Hf(j,o._MsgPack,_)),I.shouldLog(d.LOG_MICRO)&&$f(j,n,c,m,I),A){if(j.err)throw j.err;{let G=E({},j);return delete G.err,G}}return j}},ie=Gf;function Ff(r){let n=r.match(/^\.\/(\w+)\?(.*)$/);return n&&n[2]&&Ls(n[2])}function Wf(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=Ff(c[1]);u&&(n[c[2]]=u)}}return n}function Vf(r,n,o){return!(o&&(n||typeof r.code=="number"))}var zf=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&&Vf(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==ts.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=Wf(o)),this.useHttpPaginatedResponse?new Kf(this,n,r.headers||{},r.statusCode,c,r.err):new wa(this,n,c)}},wa=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 M("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new M("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)}},Kf=class extends wa{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}}},qe=zf,Ca=class Ps{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)?Ps.fromValuesArray(n):Ps.fromValues(n)}static fromValues(n){return Object.assign(new Ps,n)}static fromValuesArray(n){let o=n.length,c=new Array(o);for(let u=0;u<o;u++)c[u]=Ps.fromValues(n[u]);return c}};Ca.toRequestBody=Le;var Jf=Ca,Bs=Jf,Yf=class{constructor(r){var n;this.client=r,this.admin=new Qf(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(Tt))}async activate(r,n){await new Promise((o,c)=>{var u;if(!((u=this.client.options.plugins)!=null&&u.Push)){c(es("Push"));return}if(!this.stateMachine){c(new M("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.activatedCallback){c(new M("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(es("Push"));return}if(!this.stateMachine){o(new M("This platform is not supported as a target of push notifications",4e4,400));return}if(this.stateMachine.deactivatedCallback){o(new M("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))})}},Qf=class{constructor(r){this.client=r,this.deviceRegistrations=new Xf(r),this.channelSubscriptions=new Zf(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 _=Le(m,o._MsgPack,c);await ie.post(o,"/push/publish",_,u,f,null,!0)}},Xf=class{constructor(r){this.client=r}async save(r){let n=this.client,o=Tt.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=Le(o,n._MsgPack,c),_=await ie.put(n,"/push/deviceRegistrations/"+encodeURIComponent(r.id),m,u,f,null,!0);return Tt.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 M("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 Tt.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 qe(n,"/push/deviceRegistrations",u,c,async function(f,m,_){return Tt.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 M("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)}},Zf=class kd{constructor(n){this.remove=kd.prototype.removeWhere,this.client=n}async save(n){let o=this.client,c=Bs.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 _=Le(c,o._MsgPack,u),A=await ie.post(o,"/push/channelSubscriptions",_,f,m,null,!0);return Bs.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 qe(o,"/push/channelSubscriptions",f,u,async function(m,_,A){return Bs.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 qe(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)}},ep=Yf,Ea=["absent","present","enter","leave","update"];async function ka(r,n,o,c){let u=fa(n,r,c??null);return ss.fromValues(o).decode(u,r)}async function tp(r,n,o,c){return Promise.all(o.map(function(u){return ka(r,n,u,c)}))}async function sp(r,n){return ss.fromValues(r).decode(n.channelOptions,n.logger)}async function Oa(r,n){return Promise.all(r.map(function(o){return sp(o,n)}))}var Sa=class Is extends St{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 ss,this,{action:Ea.indexOf(this.action||"present")});return tr(o,n)}static fromValues(n){return Object.assign(new Is,n)}static fromValuesArray(n){return n.map(o=>Is.fromValues(o))}static fromData(n){return n instanceof Is?n:Is.fromValues({data:n})}toString(){return Ot(this,"PresenceMessage")}},ss=class go extends St{toJSON(...n){return nr.call(this,...n)}static fromValues(n){return Object.assign(new go,n)}static fromValuesArray(n){return n.map(o=>go.fromValues(o))}async decode(n,o){let c=Object.assign(new Sa,O(E({},this),{action:Ea[this.action]}));try{await sr(c,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WirePresenceMessage.decode()",ee(u))}return c}toString(){return Ot(this,"WirePresenceMessage")}},We=Sa,np=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 qe(n,this.channel.client.rest.presenceMixin.basePath(this),u,c,async(f,m,_)=>{let A=_?f:ue(f,n._MsgPack,o);return Oa(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)}},rp=np,Ta=["message.create","message.update","message.delete","meta","message.summary","message.append"];function ip(r){return Ta[r||0]||"unknown"}function op(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+=Do(r.data)),n}async function Aa(r,n,o,c){let u=fa(n,r,c??null);return ns.fromValues(o).decode(u,r)}async function ap(r,n,o,c){return Promise.all(o.map(function(u){return Aa(r,n,u,c)}))}async function Ra(r,n){return ns.fromValues(r).decode(n.channelOptions,n.logger)}async function Pa(r,n){return Promise.all(r.map(function(o){return Ra(o,n)}))}async function Ia(r,n){return Promise.all(r.map(o=>o.encode(n)))}var xa=Le;function Ma(r){let n,o=0;for(let c=0;c<r.length;c++)n=r[c],o+=n.size||(n.size=op(n));return o}var Na=class mo extends St{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 ns,this,{action:Ta.indexOf(this.action||"message.create")});return tr(o,n)}static fromValues(n){return Object.assign(new mo,n)}static fromValuesArray(n){return n.map(o=>mo.fromValues(o))}toString(){return Ot(this,"Message")}},ns=class yo extends St{toJSON(...n){return nr.call(this,...n)}static fromValues(n){return Object.assign(new yo,n)}static fromValuesArray(n){return n.map(o=>yo.fromValues(o))}async decodeWithErr(n,o){let c=Object.assign(new Na,O(E({},this),{action:ip(this.action)})),u;try{await sr(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 Ot(this,"WireMessage")}},Be=Na,cp=9;function lp(r){return r.every(function(n){return!n.id})}var up=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 rp(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=[Be.fromValues({name:n,data:o})],u=r[2];else if(Et(n))c=[Be.fromValues(n)],u=r[1];else if(Array.isArray(n))c=Be.fromValuesArray(n),u=r[1];else throw new M("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&&lp(c)){let w=await Bo(cp);c.forEach(function(R,P){R.id=w+":"+P.toString()})}let q=await Ia(c,this.channelOptions),j=Ma(q),G=m.maxMessageSize;if(j>G)throw new M(`Maximum size of messages that can be published at once exceeded (was ${j} bytes; limit is ${G} bytes)`,40009,400);return this._publish(xa(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)}},hp=up,dp=class Od{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 Od(n)}},fp=dp,La=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 qe(o,this.basePath(r)+"/messages",f,u,async function(m,_,A){let I=A?m:ue(m,o._MsgPack,c);return Pa(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 M('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 Ra(A,r)}static async updateDeleteMessage(r,n,o,c,u){if(!o.serial)throw new M('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=Be.fromValues(o);A.action=n,A.version=c;let I=await A.encode(r.channelOptions),q=xa(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 M('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 qe(u,this.basePath(r)+"/messages/"+encodeURIComponent(c)+"/versions",_,m,async(A,I,q)=>{let j=q?A:ue(A,u._MsgPack,f);return Pa(j,r)}).get(o||{})}},pp=class{static basePath(r){return La.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 qe(o,this.basePath(r)+"/history",f,u,async(m,_,A)=>{let I=A?m:ue(m,o._MsgPack,c);return Oa(I,r.channel)}).get(n)}},ja=class{constructor(r){this.channelMixin=La,this.presenceMixin=pp,this.Resource=ie,this.PaginatedResource=qe,this.DeviceDetails=Tt,this.PushChannelSubscription=Bs,this.client=r,this.channels=new gp(this.client),this.push=new ep(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 qe(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]=fp.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 M("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 qe(this.client,n,G,q,async function(R,P,D){return Ao(D?R:A(R))},!0);if(!L.Http.methods.includes(j))throw new M("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=Le(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(ua(this.client.options))throw new M("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 _=Le(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)}},gp=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 hp(this.client,r,n),o}release(r){delete this.all[String(r)]}},mp=class extends ba{constructor(r){super(K.objectifyOptions(r,!1,"BaseRest",d.defaultLogger,{Rest:ja}))}},qa={Rest:ja},Da=class extends Be{static async fromEncoded(r,n){return Aa(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return ap(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return Be.fromValues(r)}},Ua=class extends We{static async fromEncoded(r,n){return ka(d.defaultLogger,L.Crypto,r,n)}static async fromEncodedArray(r,n){return tp(d.defaultLogger,L.Crypto,r,n)}static fromValues(r){return We.fromValues(r)}},Ba=["annotation.create","annotation.delete"];async function Ha(r,n,o){return At.fromValues(n).decode(o||{},r)}async function yp(r,n,o){return Promise.all(n.map(function(c){return Ha(r,c,o)}))}async function _p(r,n){return At.fromValues(r).decode(n.channelOptions,n.logger)}async function bp(r,n){return Promise.all(r.map(function(o){return _p(o,n)}))}var $a=class _o extends St{async encode(){let n=Object.assign(new At,this,{action:Ba.indexOf(this.action||"annotation.create")});return tr(n,{})}static fromValues(n){return Object.assign(new _o,n)}static fromValuesArray(n){return n.map(o=>_o.fromValues(o))}toString(){return Ot(this,"Annotation")}},At=class bo extends St{toJSON(...n){return nr.call(this,...n)}static fromValues(n){return Object.assign(new bo,n)}static fromValuesArray(n){return n.map(o=>bo.fromValues(o))}async decode(n,o){let c=Object.assign(new $a,O(E({},this),{action:Ba[this.action]}));try{await sr(c,n)}catch(u){d.logAction(o,d.LOG_ERROR,"WireAnnotation.decode()",ee(u))}return c}toString(){return Ot(this,"WireAnnotation")}},Rt=$a,Ga=class extends Rt{static async fromEncoded(r,n){return Ha(d.defaultLogger,r,n)}static async fromEncodedArray(r,n){return yp(d.defaultLogger,r,n)}static fromValues(r){return Rt.fromValues(r)}};function Fa(r){let n;switch(typeof r){case"string":n=r;break;case"object":n=r.serial;break}if(!n||typeof n!="string")throw new M("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 Wa(r,n){let o=Fa(r);if(!n||typeof n!="object")throw new M("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let c=Rt.fromValues(n);return c.messageSerial=o,c.action||(c.action="annotation.create"),c}function Va(r,n){return r.client.rest.channelMixin.basePath(r)+"/messages/"+encodeURIComponent(n)+"/annotations"}var vp=class{constructor(r){this.channel=r}async publish(r,n){let o=Wa(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=Le([c],u._MsgPack,m);await ie.post(u,Va(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=Fa(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 qe(o,Va(this.channel,c),m,f,async(_,A,I)=>{let q=I?_:ue(_,o._MsgPack,u);return bp(q,this.channel)}).get(n)}},Hs=vp,wp=Le;function $s(r){let n=[];if(r)for(let o=0;o<r.length;o++)n.push(r[o].toString());return"[ "+n.join(", ")+" ]"}function Cp(r,n,o,c,u,f){let m=ue(r,n,f);return rr(m,o,c,u)}function rr(r,n,o,c){let u;r.error&&(u=M.fromValues(r.error));let f;r.messages&&(f=ns.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,Qt,Ds)),Object.assign(new or,O(E({},r),{presence:m,messages:f,annotations:_,state:A,error:u}))}function Ep(r){return n=>{var o;return rr(n,{PresenceMessage:We,WirePresenceMessage:ss},{Annotation:Rt,WireAnnotation:At,RealtimeAnnotations:cr,RestAnnotations:Hs},(o=r?.LiveObjectsPlugin)!=null?o:null)}}function we(r){return Object.assign(new or,r)}function ir(r,n,o,c){let u="[ProtocolMessage";r.action!==void 0&&(u+="; action="+ha[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="+$s(ns.fromValuesArray(r.messages))),r.presence&&n&&(u+="; presence="+$s(n.WirePresenceMessage.fromValuesArray(r.presence))),r.annotations&&o&&(u+="; annotations="+$s(o.WireAnnotation.fromValuesArray(r.annotations))),r.state&&c&&(u+="; state="+$s(c.WireObjectMessage.fromValuesArray(r.state,Qt,Ds))),r.error&&(u+="; error="+M.fromValues(r.error).toString()),r.auth&&r.auth.accessToken&&(u+="; token="+r.auth.accessToken),r.flags&&(u+="; flags="+qf.filter(r.hasFlag).join(",")),r.params){let _="";Lo(r.params,function(A){_.length>0&&(_+="; "),_+=A+"="+r.params[A]}),_.length>0&&(u+="; params=["+_+"]")}return u+="]",u}var or=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 da.forEach(n=>{this.hasFlag(n)&&r.push(n)}),r.length>0?r:void 0}},kp=or,Op=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)}},ar=Op,za=function(){};function Sp(r){if(r&&"params"in r&&!Et(r.params))return new M("options.params must be an object",4e4,400);if(r&&"modes"in r){if(!Array.isArray(r.modes))return new M("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"||!da.includes(String.prototype.toUpperCase.call(o)))return new M("Invalid channel mode: "+o,4e4,400)}}}var Tp=class vo 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 M("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new M("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=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)),(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 M("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=Sp(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,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=Ka(n.params),u=Ka(o.params);if(Object.keys(c).length!==Object.keys(u).length||!Jn(u,c))return!0}return!!(n?.modes&&(!o.modes||!zo(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=[Be.fromValues({name:o,data:c})],f=n[2];else if(Et(o))u=[Be.fromValues(o)],f=n[1];else if(Array.isArray(o))u=Be.fromValuesArray(o),f=n[1];else throw new M("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 Ia(u,this.channelOptions),A=Ma(_);if(A>m)throw new M(`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?Vn(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 M("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":c?.(new M("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(Go(this.channelOptions.modes)),this._attachResume&&n.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(n.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(n).catch(za)}async detach(){let n=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new M("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 M("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":c(new M("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(za)}async subscribe(...n){let[o,c]=vo.processListenerArgs(n);if(this.state==="failed")throw M.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]=vo.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&&$o(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 ar(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?M.fromValues(n.error):new M("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;Us(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;Us(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}Us(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 M(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:{Us(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",M.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 ar(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 M("Channel attach timed out",90007,408);this.notifyState("suspended",n);break}case"detaching":{let n=new M("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=Kn(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 M("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 M('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 Be.fromValues(O(E({},n),{action:o,version:c})).encode(this.channelOptions),I=we({action:z.MESSAGE,channel:this.name,messages:[A],params:u?Vn(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 M.fromValues(this.invalidStateError())}}};function Ka(r){let n=r||{},{agent:o}=n;return N(n,["agent"])}var rs=Tp,Ap=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=Wa(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=rs.processListenerArgs(r),o=n[0],c=n[1],u=this.channel;if(u.state==="failed")throw M.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 M("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=rs.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 Hs.prototype.get.call(this,r,n)}},cr=Ap,pt=class Hn extends mp{constructor(n){var o,c;if(!Hn._MsgPack)throw new Error("Expected DefaultRest._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Rest",d.defaultLogger,O(E({},qa),{Crypto:(o=Hn.Crypto)!=null?o:void 0,MsgPack:(c=Hn._MsgPack)!=null?c:void 0,Annotations:{Annotation:Rt,WireAnnotation:At,RealtimeAnnotations:cr,RestAnnotations:Hs}})))}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}};pt._Crypto=null,pt.Message=Da,pt.PresenceMessage=Ua,pt.Annotation=Ga,pt._MsgPack=null,pt._Http=Zn;var Ja=pt,Rp=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")}},Ya=Rp,Qa=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)}},Pp=class extends he{constructor(r){super(r.logger),this.transport=r,this.messageQueue=new Ya(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 M("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; "+ir(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()})}},Ip=Pp,xp=class{constructor(r,n,o,c){this.previous=r,this.current=n,o&&(this.retryIn=o),c&&(this.reason=c)}},Gs=xp,it={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},Mp={disconnected:()=>M.fromValues({statusCode:400,code:it.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>M.fromValues({statusCode:400,code:it.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>M.fromValues({statusCode:400,code:it.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>M.fromValues({statusCode:400,code:it.CLOSING,message:"Connection closing"}),closed:()=>M.fromValues({statusCode:400,code:it.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>M.fromValues({statusCode:500,code:it.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>M.fromValues({statusCode:500,code:it.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})};function Np(r){return!r.statusCode||!r.code||r.statusCode>=500?!0:Object.values(it).includes(r.code)}var gt=Mp,Lp=we({action:z.CLOSE}),jp=we({action:z.DISCONNECT}),qp=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",gt.closed())}disconnect(r){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",r||gt.disconnected())}fail(r){this.isConnected&&this.requestDisconnect(),this.finish("failed",r||gt.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+": "+ir(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(Lp)}requestDisconnect(){d.logAction(this.logger,d.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(jp)}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 M(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 M("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 M("isAvailable not implemented for transport",5e4,500)}},Pt=qp,ge;(r=>{r.WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling"})(ge||(ge={}));var Dp=typeof global<"u"?global:typeof window<"u"?window:self,lr=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.localSupported)},is=()=>{var r;return typeof L.WebStorage<"u"&&((r=L.WebStorage)==null?void 0:r.sessionSupported)},Xa=function(){},ur="ably-transport-preference";function hr(r){try{return JSON.parse(r)}catch{return null}}var Up=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?Xt(r):{},o=this.options;switch(this.mode){case"resume":n.resume=this.connectionKey;break;case"recover":{let c=hr(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=Yn(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}},Bp=class Sd 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 Ya(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=Po(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&&(is()&&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(){Sd.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(n,o){return new Up(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=hr(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=Pt.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()),Fe.isTokenErr(u.error)&&!(this.errorReason&&Fe.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"&&(Np(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 Ip(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 Gs(m,m,null,I))})}),f.state===this.states.connected.state?n&&(this.errorReason=this.realtime.connection.errorReason=n,this.emit("update",new Gs(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"&&Fe.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(is()){let n=this.createRecoveryKey();n&&this.setSessionRecoverData({recoveryKey:n,disconnectedAt:Date.now(),location:Dp.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=gt)[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 M("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&&Fe.isTokenErr(n.error)&&!(this.errorReason&&Fe.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++,_=Kn(m.retryDelay,this.disconnectedRetryCount));let A=new Gs(this.state.state,m.state,_,n.error||((c=(o=gt)[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 Gs(this.state.state,f.state,null,n.error||((c=(o=gt)[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=hr(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&&Fe.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(Xa),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 M("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 M("Unable to connect (no available host)",80003,404));return}o.host=I;let q=()=>{if(!_.length){m(new M("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}ke(this.realtime.http.checkConnectivity(),(j,G)=>{if(u===this.connectCounter&&f()){if(j){m(j);return}if(!G){m(new M("Unable to connect (network unreachable)",80003,404));return}o.host=Wn(_),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||Xa;let u=this.state;if(u.sendEvents){d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new Qa(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 M(m,9e4,400));return}this.logger.shouldLog(d.LOG_MICRO)&&d.logAction(this.logger,d.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+ir(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 Qa(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 M("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=Uo();return Ko(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||lr()&&((o=(n=L.WebStorage)==null?void 0:n.get)==null?void 0:o.call(n,ur))}persistTransportPreference(n){var o,c;this.transportPreference=n.shortName,lr()&&((c=(o=L.WebStorage)==null?void 0:o.set)==null||c.call(o,ur,n.shortName))}unpersistTransportPreference(){var n,o;this.transportPreference=null,lr()&&((o=(n=L.WebStorage)==null?void 0:n.remove)==null||o.call(n,ur))}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===ts.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 M(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 M(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 is()&&((o=(n=L.WebStorage)==null?void 0:n.getSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}setSessionRecoverData(n){var o,c;return is()&&((c=(o=L.WebStorage)==null?void 0:o.setSession)==null?void 0:c.call(o,this.sessionRecoveryName(),n))}clearSessionRecoverData(){var n,o;return is()&&((o=(n=L.WebStorage)==null?void 0:n.removeSession)==null?void 0:o.call(n,this.sessionRecoveryName()))}},Za=Bp,Hp=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 Za(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()}},$p=Hp,ec=class Td extends ba{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 M(`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=Td.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 $p(this,this.options),this._channels=new Fp(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()}};ec.EventEmitter=he;var Gp=ec,Fp=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 Ns(this.all,!0)){let o=this.all[n];o.properties.channelSerial&&(r[n]=o.properties.channelSerial)}return r}recoverChannels(r){for(let n of Ns(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 rs(this.realtime,r,n);else if(n){if(o._shouldReattachToSetOptions(n,o.channelOptions))throw new M("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=js(n.filter),u=Vo(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]}},Wp=Gp;function Vp(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 dr=class extends he{constructor(r,n,o=Vp){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=We.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=We.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=Xt(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(No(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 zp(r){return r.channel.client.auth.clientId}function fr(r){let n=r.channel.client,o=n.auth.clientId;return(!o||o==="*")&&n.connection.state==="connected"}var Kp=class extends he{constructor(r){super(r.logger),this.channel=r,this.syncComplete=!1,this.members=new dr(this,n=>n.clientId+":"+n.connectionId),this._myMembers=new dr(this,n=>n.clientId),this.subscriptions=new he(this.logger),this.pendingPresence=[]}async enter(r){if(fr(this))throw new M("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,r,"enter")}async update(r){if(fr(this))throw new M("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) "+zp(this)));let f=We.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(fr(this))throw new M("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=We.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 M.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 M("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=ra.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 M("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 ar(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=We.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=rs.processListenerArgs(r),o=n[0],c=n[1],u=this.channel;if(u.state==="failed")throw M.fromValues(u.invalidStateError());this.subscriptions.on(o,c),u.channelOptions.attachOnSubscribe!==!1&&await u.attach()}unsubscribe(...r){let n=rs.processListenerArgs(r),o=n[0],c=n[1];this.subscriptions.off(o,c)}},Jp=Kp,Yp=ge.WebSocket;function Qp(r){return!!r.on}var Xp=class extends Pt{constructor(r,n,o){super(r,n,o),this.shortName=Yp,o.heartbeats=L.Config.useProtocolHeartbeats,this.wsHost=o.host}static isAvailable(){return!!L.Config.WebSocket}createWebSocket(r,n){return this.uri=r+Zt(n),new L.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){d.logAction(this.logger,d.LOG_MINOR,"WebSocketTransport.connect()","starting"),Pt.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),ke(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)},Qp(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(wp(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 M(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(Cp(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 M("Websocket closed",80003,400);this.finish("disconnected",c)}else{let c="Unclean disconnection of WebSocket ; code = "+o,u=new M(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()}))}},tc=Xp,Zp=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||[]}},Te=class wo extends Wp{constructor(n){var o;let c=wo._MsgPack;if(!c)throw new Error("Expected DefaultRealtime._MsgPack to have been set");super(K.objectifyOptions(n,!0,"Realtime",d.defaultLogger,O(E({},qa),{Crypto:(o=wo.Crypto)!=null?o:void 0,MsgPack:c,RealtimePresence:{RealtimePresence:Jp,PresenceMessage:We,WirePresenceMessage:ss},Annotations:{Annotation:Rt,WireAnnotation:At,RealtimeAnnotations:cr,RestAnnotations:Hs},WebSocketTransport:tc,MessageInteractions:Zp})))}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}};Te.Utils=Qt,Te.ConnectionManager=Za,Te.ProtocolMessage=kp,Te._Crypto=null,Te.Message=Da,Te.PresenceMessage=Ua,Te.Annotation=Ga,Te._MsgPack=null,Te._Http=Zn,Te._PresenceMap=dr,Te._MessageEncoding=Ds;var sc=Te,nc=Z(U("crypto")),eg=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 nc.default.createHash("SHA256").update(n).digest()}hmacSha256(r,n){let o=this.toBuffer(r),c=this.toBuffer(n);return nc.default.createHmac("SHA256",c).update(o).digest()}},rc=new eg,pr=Z(U("crypto")),tg=Z(U("util")),sg=function(r){var n="aes",o=256,c="cbc",u=16;async function f(D){return tg.default.promisify(pr.default.randomBytes)(D)}function m(D){return D+u&-u}function _(D){if(D.algorithm==="aes"&&D.mode==="cbc"){if(D.keyLength===128||D.keyLength===256)return;throw new Error("Unsupported key length "+D.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}}function A(D){return D.replace("_","/").replace("-","+")}function I(D,$){var V=Buffer.alloc(D);return V.fill($),V}for(var q=[I(16,16)],j=1;j<=16;j++)q.push(I(j,j));class G{constructor($,V,F,X){this.algorithm=$,this.keyLength=V,this.mode=F,this.key=X,this.iv=null}}function w(D){return!!(D.algorithm&&D.key&&D.keyLength&&D.mode)}class R{static getDefaultParams($){var V;if(!$.key)throw new Error("Crypto.getDefaultParams: a key is required");typeof $.key=="string"?V=r.base64Decode(A($.key)):$.key instanceof ArrayBuffer?V=Buffer.from($.key):V=$.key;var F=$.algorithm||n,X=V.length*8,Ce=$.mode||c,_e=new G(F,X,Ce,V);if($.keyLength&&$.keyLength!==_e.keyLength)throw new Error("Crypto.getDefaultParams: a keyLength of "+$.keyLength+" was specified, but the key actually has length "+_e.keyLength);return _(_e),_e}static async generateRandomKey($){try{return f(($||o)/8)}catch(V){throw new M("Failed to generate random key: "+V.message,500,5e4,V)}}static getCipher($,V){var F,X=w($)?$:this.getDefaultParams($);return{cipherParams:X,cipher:new P(X,(F=$.iv)!=null?F:null,V)}}}R.CipherParams=G;class P{constructor($,V,F){this.logger=F,this.encryptCipher=null,this.algorithm=$.algorithm+"-"+String($.keyLength)+"-"+$.mode,this.key=$.key,this.iv=V}async encrypt($){d.logAction(this.logger,d.LOG_MICRO,"CBCCipher.encrypt()","");let V=await this.getIv();this.encryptCipher||(this.encryptCipher=pr.default.createCipheriv(this.algorithm,this.key,V));var F=r.toBuffer($),X=F.length,Ce=m(X),_e=this.encryptCipher.update(Buffer.concat([F,q[Ce-X]])),Ve=Buffer.concat([V,_e]);return Ve}async decrypt($){var V=pr.default.createDecipheriv(this.algorithm,this.key,$.slice(0,u)),F=V.update($.slice(u)),X=V.final();return X&&X.length&&(F=Buffer.concat([F,X])),F}async getIv(){if(this.iv){var $=this.iv;return this.iv=null,$}var V=await f(u);return this.encryptCipher?this.encryptCipher.update(V):V}}return R},ic=Z(Bn()),ng=Z(U("http")),rg=Z(U("https")),oc=[],os,ig=(os=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?kf(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=oc.find(I=>Jn(m,I.options)))==null?void 0:f.agents;A?this.agent=A:(this.agent={http:new ng.default.Agent(m),https:new rg.default.Agent(m)},oc.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 ic.default[r](_);return this._handler(null,A,A.body)}catch(A){return A instanceof ic.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:es("MsgPack")};o=this.client._MsgPack.decode(o);break}return{error:o.error?M.fromValues(o.error):new M(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}}},os.methods=[ce.Get,ce.Delete,ce.Post,ce.Put,ce.Patch],os.methodsWithoutBody=[ce.Get,ce.Delete],os.methodsWithBody=[ce.Post,ce.Put,ce.Patch],os),og=ig,ag=Z(U("crypto")),cg=Z(un()),gr=Z(U("util")),lg={agent:"nodejs/"+process.versions.node,logTimestamps:!0,userAgent:null,binaryType:"nodebuffer",WebSocket:cg.default,useProtocolHeartbeats:!1,supportsBinary:!0,preferBinary:!0,nextTick:process.nextTick,inspect:gr.default.inspect,stringByteSize:Buffer.byteLength,inherits:gr.default.inherits,addEventListener:null,getRandomArrayBuffer:async function(r){return gr.default.promisify(ag.default.randomBytes)(r)}},ug=lg,ac=(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))(ac||{}),ot=ac;function hg(r){let n=[80015,80017,80030];return r.code?Fe.isTokenErr(r)?!1:n.includes(r.code)?!0:r.code>=4e4&&r.code<5e4:!1}function mr(r){return hg(r)?[we({action:z.ERROR,error:r})]:[we({action:z.DISCONNECTED,error:r})]}var dg=class extends Pt{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"),Pt.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),ke(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:"+Zt(A));let I=!1,q=this.recvRequest=this.createRequest(f,null,A,null,this.stream?ot.REQ_RECV_STREAM:ot.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 M("Request cancelled",80003,400)),this.recvRequest=null,!I&&!j&&(I=!0,this.emit("preconnect")),this.onActivity(),j){j.code?this.onData(mr(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,ot.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",gt.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;Pt.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),ot.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(mr(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?ot.REQ_RECV_STREAM:ot.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(mr(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(rr(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}},cc=dg,lc=Z(U("http")),uc=Z(U("https")),fg=Z(U("url")),pg=Z(U("util")),gg=function(){},mg=ge.Comet,yg=class extends cc{constructor(r,n,o){super(r,n,o),this.httpAgent=null,this.httpsAgent=null,this.pendingRequests=0,this.shortName=mg}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?uc.default:lc.default).Agent({keepAlive:!0})),o}dispose(){var r=this;this.onceNoPending(function(){r.httpAgent&&r.httpAgent.destroy(),r.httpsAgent&&r.httpsAgent.destroy()}),cc.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 _g(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)}},_g=class extends he{constructor(r,n,o,c,u,f,m,_){super(_.logger),typeof r=="string"&&(r=fg.default.parse(r));var A=r.protocol=="https:";this.client=A?uc.default:lc.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+Zt(o),method:I,headers:n};_&&(j.agent=_.getAgent(A))}exec(){var r=this.requestMode==ot.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==ts.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==ot.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&&M.fromValues(c.error);m||(m=new Ee("Error response received from server: "+u+", body was: "+pg.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",gg),n.abort(),this.req=null),this.complete({statusCode:400,code:80003,message:"Cancelled"})}},bg=yg,vg={order:[ge.Comet],bundledImplementations:{[ge.WebSocket]:tc,[ge.Comet]:bg}},wg={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}},Cg=wg,Eg=Xd(),hc=sg(rc);L.Crypto=hc,L.BufferUtils=rc,L.Http=og,L.Config=ug,L.Transports=vg,L.WebStorage=null;for(let r of[Ja,sc])r.Crypto=hc,r._MsgPack=Eg;if(d.initLogHandlers(),L.Defaults=Cf(Cg),L.Config.agent&&(L.Defaults.agent+=" "+L.Config.agent),i.exports={ErrorInfo:M,Rest:Ja,Realtime:sc,msgpack:null,makeProtocolMessageFromDeserialized:Ep},typeof i.exports=="object"&&typeof t=="object"){var kg=(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=kg(i.exports,t)}return i.exports})});var Sc=yr(Oc(),1),{program:cs,createCommand:lw,createArgument:uw,createOption:hw,CommanderError:dw,InvalidArgumentError:fw,InvalidOptionArgumentError:pw,Command:gw,Argument:mw,Option:yw,Help:_w}=Sc.default;var Gd=yr(Mc(),1);import{resolve as $d}from"path";import{existsSync as ew}from"fs";function Nc(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_AGENT_SDK==="true",C=s.streamProgress??process.env.STREAM_PROGRESS==="true",v=s.conversationOnly??process.env.CONVERSATION_ONLY==="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}}var zs=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 Ks}from"child_process";import{existsSync as Lc,writeFileSync as jc,unlinkSync as qc}from"fs";import{homedir as lm,tmpdir as Dc}from"os";import{join as Lr}from"path";function Js(){let s=[Lr(lm(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of s)if(Lc(e))return e;return"claude"}var me=null;function um(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 Uc(s,e){let t=um(s);return me||(me=Js()),new Promise(i=>{let a="",l="",h=!1,p=!1,g=Ks(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 y=setTimeout(()=>{h=!0,p=!0,g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},5e3)},e);g.stdout?.on("data",C=>{a+=C.toString()}),g.stderr?.on("data",C=>{l+=C.toString()}),g.on("close",C=>{if(clearTimeout(y),h){i({success:!1,output:a,error:"Process timed out",timedOut:!0});return}let v=a.includes("TASK_COMPLETE")&&!a.includes("TASK_BLOCKED");if(C!==0&&!p){i({success:!1,output:a,error:l||`Process exited with code ${C}`,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:v,output:a,error:v?void 0:"Task did not complete successfully",timedOut:!1})}),g.on("error",C=>{clearTimeout(y),i({success:!1,output:a,error:`Failed to spawn claude: ${C.message}`,timedOut:!1})})})}async function Bc(){return me=Js(),me&&me!=="claude"&&Lc(me)?(console.log(`Found Claude CLI at: ${me}`),!0):new Promise(s=>{let e=Ks(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 hm(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 dm(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 Hc(s,e,t={}){let i=hm(s),a=t.verbose??!0;return a&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",i.length,"characters")),me||(me=Js()),new Promise(l=>{let h="",p="",g=!1,y=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let C=Lr(Dc(),`claude-prompt-${Date.now()}.txt`);jc(C,i,"utf-8");let v=`cat "${C}" | ${me} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Working directory:",process.cwd()),console.log("[Claude] Temp file:",C),console.log("[Claude] Running via shell..."));let k=Ks("sh",["-c",v],{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{qc(C),a&&console.log("[Claude] Temp file cleaned up")}catch{}},T=setTimeout(()=>{g=!0,y=!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(T),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=dm(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&&!y){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(T),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 fm(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
|
+
|
|
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 $c(s,e,t={}){let i=fm(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=Js()),a&&console.log("[Claude] Claude path:",me),new Promise(h=>{let p="",g="",y=!1,C=!1;a&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let v=Lr(Dc(),`claude-task-${Date.now()}.txt`);jc(v,i,"utf-8");let k=`cat "${v}" | ${me} --print --dangerously-skip-permissions`;a&&(console.log("[Claude] Temp file:",v),console.log("[Claude] Running via shell..."));let S=Ks("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 T=0,E=setInterval(()=>{if(a&&!y){let Y=Math.floor((Date.now()-O)/1e3);p.length===T&&console.log(`[Claude] Still running... ${Y}s elapsed, ${p.length} bytes output, waiting for response...`),T=p.length}},3e4),O=Date.now();S.stdin?.end();let N=()=>{try{qc(v),a&&console.log("[Claude] Temp file cleaned up")}catch{}},W=setTimeout(()=>{y=!0,C=!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",Y=>{let se=Y.toString();p+=se,a&&process.stdout.write(se)}),S.stderr?.on("data",Y=>{let se=Y.toString();g+=se,a&&process.stderr.write(`[Claude stderr] ${se}`)}),S.on("close",(Y,se)=>{clearTimeout(W),clearInterval(E),N(),a&&(console.log(""),console.log(`[Claude] Process exited with code ${Y}, 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"),Se=p.match(/TASK_BLOCKED:\s*(.+)/);if(y&&!Z){h({success:!1,output:p,error:"Process timed out",timedOut:!0});return}if(Se){h({success:!1,output:p,error:`Task blocked: ${Se[1]}`,timedOut:!1});return}if(Y!==0&&!C){h({success:!1,output:p,error:g||`Process exited with code ${Y}`,timedOut:!1});return}h({success:!0,output:p,timedOut:!1})}),S.on("error",Y=>{clearTimeout(W),clearInterval(E),N(),console.error("[Claude] Spawn error:",Y),h({success:!1,output:p,error:`Failed to spawn claude: ${Y.message}`,timedOut:!1})}),S.on("spawn",()=>{a&&console.log("[Claude] Process spawned successfully")})})}import{query as jr}from"@anthropic-ai/claude-agent-sdk";function pm(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}=pm(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 gm(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 Gc(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 Fc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=gm(s),g=Date.now(),y="",C=!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 v=new AbortController,k=setTimeout(()=>{C=!0,v.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(T,E)=>{l&&l({type:T,timestamp:Date.now(),data:E})};S("session_start",{prompt:p.substring(0,200),cwd:h});try{let T=jr({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits"}});for await(let E of T)switch(E.type){case"assistant":if(E.message.content){for(let N of E.message.content)if(N.type==="text")y+=N.text,i&&process.stdout.write(N.text),S("assistant_message",{text:N.text,uuid:E.uuid});else if(N.type==="thinking"){let W=N;i&&console.log(`[Agent] Thinking: ${W.thinking.substring(0,100)}...`),S("thinking",{text:W.thinking,uuid:E.uuid})}else if(N.type==="tool_use"||"name"in N){let W=N;i&&console.log(`[Agent] Tool: ${W.name}`),S("tool_start",{tool:W.name,toolUseId:W.id,input:W.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 W=N;S("tool_end",{toolUseId:W.tool_use_id,isError:W.is_error||!1,hasContent:!!W.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=Gc(y);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:y,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:y,error:`Agent error: ${E.subtype} - ${N}`,timedOut:!1,totalCostUsd:E.total_cost_usd}}return{success:!1,output:y,error:"Failed to parse analysis JSON from output",timedOut:!1,totalCostUsd:E.total_cost_usd}}return clearTimeout(k),{success:!1,output:y,error:"Query stream ended without result",timedOut:C}}catch(T){clearTimeout(k);let E=T instanceof Error?T.message:String(T);i&&console.error("[Agent] Error:",E),S("error",{error:E});let O=Gc(y);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:y,timedOut:!1}):{success:!1,output:y,error:C?"Process timed out":E,timedOut:C}}}function mm(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
|
+
|
|
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 Wc(s,e={}){let{timeoutMs:t=6e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=mm(s),g=Date.now(),y="",C=!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 v=new AbortController,k=setTimeout(()=>{C=!0,v.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(T,E)=>{l&&l({type:T,timestamp:Date.now(),data:E})};S("session_start",{task:s.title,cwd:h});try{let T=jr({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","Write"],permissionMode:"acceptEdits"}});for await(let E of T)switch(E.type){case"assistant":if(E.message.content){for(let W of E.message.content)if(W.type==="text")y+=W.text,i&&process.stdout.write(W.text);else if("name"in W){let Y=W;i&&console.log(`[Agent] Tool: ${Y.name}`),S("tool_start",{tool:Y.name,toolUseId:Y.id,input:Y.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=y.includes("TASK_COMPLETE"),N=y.match(/TASK_BLOCKED:\s*(.+)/);return N?{success:!1,output:y,error:`Task blocked: ${N[1]}`,timedOut:!1,totalCostUsd:E.total_cost_usd}:{success:O||E.subtype==="success",output:y,timedOut:!1,totalCostUsd:E.total_cost_usd}}return clearTimeout(k),{success:!1,output:y,error:"Query stream ended without result",timedOut:C}}catch(T){clearTimeout(k);let E=T instanceof Error?T.message:String(T);return i&&console.error("[Agent] Error:",E),S("error",{error:E}),{success:!1,output:y,error:C?"Process timed out":E,timedOut:C}}}async function Vc(){try{return!0}catch{return!1}}function zc(s){return s.includes("[CONVERSATIONAL SESSION]")}function ym(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 _m(s){let e=ym(s.description),t=["You are a helpful assistant for a project management platform. You are having a conversation with a user who wants to discuss and create tasks for their project.","",`**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 in an ongoing conversation. The user is continuing a previous discussion."),t.push(`DO NOT start over or re-introduce yourself. DO NOT say "I'll help you with..." as if this is a new request.`),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. Don't ask additional clarifying questions unless they specifically ask for options.")):(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 Approach"),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(`
|
|
55
|
+
`)}function bm(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;for(;(a=i.exec(s))!==null;){console.log("[Agent] Found task block, parsing JSON...");try{let l=JSON.parse(a[1].trim());console.log(`[Agent] Parsed task: ${l.title}`),e.push({title:l.title||"Untitled Task",description:l.description||"",acceptanceCriteria:l.acceptanceCriteria||[],estimatedHours:l.estimatedHours||4,priority:l.priority||"MEDIUM",type:l.type||"FEATURE",technicalNotes:l.technicalNotes,aiConfidence:l.aiConfidence||l.confidence||.8})}catch(l){console.error("[Agent] Failed to parse task JSON:",l),console.error("[Agent] Task content:",a[1].substring(0,200))}}return console.log(`[Agent] parseTasksFromOutput: returning ${e.length} tasks`),e}async function Kc(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:l}=e,h=a||process.cwd(),p=_m(s),g="",y=!1;i&&(console.log("[Agent] Starting conversational session..."),console.log("[Agent] Working directory:",h));let C=new AbortController,v=setTimeout(()=>{y=!0,C.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),k=(S,T)=>{l&&l({type:S,timestamp:Date.now(),data:T})};k("session_start",{cwd:h});try{let S=jr({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits"}});for await(let T of S)switch(T.type){case"assistant":if(T.message.content){for(let O of T.message.content)if(O.type==="text")g+=O.text,i&&process.stdout.write(O.text),k("assistant_message",{text:O.text,uuid:T.uuid});else if(O.type==="thinking"){let N=O;i&&console.log(`[Agent] Thinking: ${N.thinking.substring(0,100)}...`),k("thinking",{text:N.thinking,uuid:T.uuid})}else if(O.type==="tool_use"||"name"in O){let N=O;i&&console.log(`[Agent] Tool: ${N.name}`),k("tool_start",{tool:N.name,toolUseId:N.id,input:N.input})}}break;case"user":if(T.message.content){for(let O of T.message.content)if(typeof O=="object"&&O!==null&&"type"in O&&O.type==="tool_result"){let N=O;k("tool_end",{toolUseId:N.tool_use_id,isError:N.is_error||!1,hasContent:!!N.content})}}break;case"result":clearTimeout(v),i&&(console.log(""),console.log(`[Agent] Completed in ${T.duration_ms}ms`),console.log(`[Agent] Cost: $${T.total_cost_usd?.toFixed(4)||"N/A"}`));let E=bm(g);return i&&E.length>0&&console.log(`[Agent] Found ${E.length} task(s) in output`),k("result",{success:!0,output:g,tasks:E,costUsd:T.total_cost_usd}),{success:!0,output:g,tasks:E,timedOut:!1,totalCostUsd:T.total_cost_usd}}return clearTimeout(v),{success:!1,output:g,tasks:[],error:"Query stream ended without result",timedOut:y}}catch(S){clearTimeout(v);let T=S instanceof Error?S.message:String(S);return i&&console.error("[Agent] Error:",T),k("error",{error:T}),{success:!1,output:g,tasks:[],error:y?"Process timed out":T,timedOut:y}}}var Rd=yr(Ad(),1),$n=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 Rd.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{randomBytes as $v}from"crypto";var Gn=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 zs(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${$v(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 $n(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=zc(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 k=qr(v);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 v=await Kc(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:p});console.log("-".repeat(60));let k=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(S){console.error("[Monitor] Failed to send timeout event:",S)}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(S){console.error("[Monitor] Failed to send error event:",S)}return}if(console.log(`[Monitor] Conversation completed (${k}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 S of v.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${S.title}`,emoji:"\u{1F4CB}",data:{task:S}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${S.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:k}}),console.log("[Monitor] \u2705 Sent result event")}catch(S){console.error("[Monitor] Failed to send result event:",S)}return}let g;this.config.useAgentSdk?(g=await Fc(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 Hc(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 Wc(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async l=>{let h=qr(l);console.log(`[Monitor] ${h.emoji} ${h.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,h)}catch(p){console.error("[Monitor] Failed to send progress event:",p)}}:void 0}),i.totalCostUsd&&console.log(`[Monitor] Agent cost: $${i.totalCostUsd.toFixed(4)}`)):i=await $c(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}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:i.output?.substring(0,1e3)||"Task completed by auto-monitor"}),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 Uc(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 l=i.length>5e3?`${i.substring(0,5e3)}...
|
|
56
|
+
|
|
57
|
+
[Output truncated]`:i;await this.client.completeTask(e,"COMPLETED",{comment:`## Auto-Task Completed
|
|
58
|
+
|
|
59
|
+
${l}`}),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)}...
|
|
60
|
+
|
|
61
|
+
[Output truncated]`:a,g=[`## Auto-Task ${i==="TIMEOUT"?"Timed Out":"Failed"}`,"",l?`**Error:** ${l}`:"","","### Output","```",p,"```"].filter(Boolean).join(`
|
|
62
|
+
`);await this.client.completeTask(e,i,{comment:g,errorMessage:l}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let y=await this.client.sendAlert(e,i,l);console.log(`[Monitor] Alert sent to ${y.emailsSent} recipients`)}catch(y){console.error("[Monitor] Failed to send alert:",y)}}};import{createInterface as Gv}from"readline";import{writeFileSync as Pd,existsSync as Fv}from"fs";import{resolve as Id}from"path";function Wv(){let s=Gv({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{s.question(e,i=>{t(i.trim())})}),close:()=>s.close()}}async function xd(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 Md(s){let e=`# Sego Auto-Task Monitor Configuration
|
|
63
|
+
# Generated by sego-auto-task init
|
|
64
|
+
|
|
65
|
+
# Required: Your Sego PM API key
|
|
66
|
+
SEGO_API_KEY=${s.apiKey}
|
|
67
|
+
|
|
68
|
+
# API URL (default: https://sego.pm)
|
|
69
|
+
SEGO_API_URL=${s.apiUrl}
|
|
70
|
+
`;return s.projectId&&(e+=`
|
|
71
|
+
# Filter to specific project
|
|
72
|
+
SEGO_PROJECT_ID=${s.projectId}
|
|
73
|
+
`),e}async function Ld(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 xd(a,i)||(console.error(`
|
|
74
|
+
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=Id(process.cwd(),".env"),y=Md(p);Pd(g,y),Nd(g);return}let t=Wv();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(`
|
|
75
|
+
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 xd(l,i)||(console.error(`
|
|
76
|
+
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 y=Id(process.cwd(),".env");if(Fv(y)&&(console.log(`Warning: .env file already exists at ${y}`),(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 v=Md(g);Pd(y,v),Nd(y)}finally{t.close()}}function Nd(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 qd,mkdirSync as Vv,readFileSync as zv,writeFileSync as Kv}from"fs";import{homedir as Jv}from"os";import{join as Dd}from"path";var Ud="@segosolutions/auto-task",Eo=Dd(Jv(),".sego-auto-task"),ko=Dd(Eo,"version-check.json"),Yv=24*60*60*1e3;function jd(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 Qv(){try{if(!qd(ko))return null;let s=JSON.parse(zv(ko,"utf-8"));return Date.now()-s.checkedAt<Yv?s:null}catch{return null}}function Xv(s){try{qd(Eo)||Vv(Eo,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};Kv(ko,JSON.stringify(e,null,2))}catch{}}async function Zv(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(Ud)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function Bd(s){let e=Qv();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:jd(s,e.latestVersion)<0};let t=await Zv();return t&&Xv(t),{currentVersion:s,latestVersion:t,updateAvailable:t?jd(s,t)<0:!1}}function Hd(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 ${Ud}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var Fd="1.3.0",Oo=null;cs.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
|
|
77
|
+
|
|
78
|
+
Runs in hybrid mode:
|
|
79
|
+
- SSE: Listens for client request events and processes them with local Claude
|
|
80
|
+
- Polling: Checks for eligible auto-tasks to execute
|
|
81
|
+
|
|
82
|
+
Environment variables are loaded from .env in the working directory.
|
|
83
|
+
|
|
84
|
+
Use "sego-auto-task init" to run the interactive setup wizard.`).version(Fd);cs.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async s=>{await Ld({yes:s.yes})});cs.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-agent-sdk","Use Claude Agent SDK instead of CLI subprocess (experimental)").option("--stream-progress","Stream agent progress events to the web app via SSE").option("--conversation-only","Only handle conversational sessions, skip automatic task processing").action(async s=>{try{s.updateCheck!==!1&&(Oo=Bd(Fd).then(Hd).catch(()=>{}));let e=s.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=$d(e),i=$d(t,".env");ew(i)?(console.log(`Loading environment from: ${i}`),Gd.default.config({path:i})):console.log(`No .env file found in: ${t}`),s.useAgentSdk||process.env.USE_AGENT_SDK==="true"?(console.log("Checking for Claude Agent SDK..."),await Vc()||(console.error("Error: Claude Agent SDK is not available."),process.exit(1)),console.log("Claude Agent SDK is available")):(console.log("Checking for Claude CLI..."),await Bc()||(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"));let l=Nc({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,dryRun:s.dryRun,workingDirectory:t,useAgentSdk:s.useAgentSdk||!1,streamProgress:s.streamProgress||!1,conversationOnly:s.conversationOnly||!1}),p=l.apiUrl.includes("sego.pm")||l.apiUrl.includes("vercel")?"PRODUCTION":"DEVELOPMENT";console.log(""),console.log("=".repeat(60)),console.log("Sego Auto-Task Monitor - Environment Configuration"),console.log("=".repeat(60)),console.log(`Environment: ${p}`),console.log(`API URL: ${l.apiUrl}`),console.log(`SSE Mode: ${l.sseEnabled?"enabled":"disabled"}`),console.log(`Project Filter: ${l.projectId||"all projects"}`),console.log(`Poll Interval: ${l.pollIntervalMs/1e3}s`),console.log(`Task Timeout: ${l.timeoutMs/6e4}min`),console.log(`Dry Run: ${l.dryRun?"yes":"no"}`),console.log(`Working Dir: ${l.workingDirectory}`),console.log(`Agent SDK Mode: ${l.useAgentSdk?"yes (experimental)":"no (CLI subprocess)"}`),console.log(`Stream Progress: ${l.streamProgress?"yes":"no"}`),console.log(`Conv. Only: ${l.conversationOnly?"yes (no auto-task processing)":"no"}`),console.log("=".repeat(60)),console.log(""),Oo&&await Oo;let g=new Gn(l),y=()=>{console.log(`
|
|
85
|
+
Received shutdown signal`),g.stop(),process.exit(0)};process.on("SIGINT",y),process.on("SIGTERM",y),await g.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});cs.parse();
|
|
86
|
+
/*! Bundled license information:
|
|
87
|
+
|
|
88
|
+
ably/build/ably-node.js:
|
|
89
|
+
(*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com)
|
|
90
|
+
|
|
91
|
+
Ably JavaScript Library v2.17.0
|
|
92
|
+
https://github.com/ably/ably-js
|
|
93
|
+
|
|
94
|
+
Released under the Apache Licence v2.0*)
|
|
95
|
+
*/
|