mobsession 0.1.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.
Files changed (3) hide show
  1. package/README.md +21 -0
  2. package/index.js +42 -0
  3. package/package.json +24 -0
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # Mob Squad (msq)
2
+
3
+ Drive Claude Code together. `msq` runs a real Claude Code session on your machine and shares a
4
+ link so your whole team can steer it in real time, with your own Claude subscription.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm i -g mobsession
10
+ ```
11
+
12
+ ## Use
13
+
14
+ In any project directory:
15
+
16
+ ```bash
17
+ msq start
18
+ ```
19
+
20
+ It prints a link. Open it (and share it) at https://mobsession.ai to watch the session live and add
21
+ prompts together. No account required.
package/index.js ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __msqCreateRequire } from 'node:module';
3
+ const require = __msqCreateRequire(import.meta.url);
4
+ var Io=Object.create;var ds=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var $o=Object.getPrototypeOf,Mo=Object.prototype.hasOwnProperty;var ve=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var se=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Cn=(r,e)=>{for(var t in e)ds(r,t,{get:e[t],enumerable:!0})},qo=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of No(e))!Mo.call(r,n)&&n!==t&&ds(r,n,{get:()=>e[n],enumerable:!(s=Po(e,n))||s.enumerable});return r};var kn=(r,e,t)=>(t=r!=null?Io($o(r)):{},qo(e||!r||!r.__esModule?ds(t,"default",{value:r,enumerable:!0}):t,r));var tr=se(ps=>{"use strict";var wr=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},fs=class extends wr{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ps.CommanderError=wr;ps.InvalidArgumentError=fs});var xr=se(gs=>{"use strict";var{InvalidArgumentError:Lo}=tr(),ms=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,s)=>{if(!this.argChoices.includes(t))throw new Lo(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Vo(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}gs.Argument=ms;gs.humanReadableArgName=Vo});var vs=se(_s=>{"use strict";var{humanReadableArgName:jo}=xr(),ys=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((n,i)=>n.name().localeCompare(i.name())),t}compareOptions(e,t){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?t.push(s):s.long&&!i?t.push(e.createOption(s.long,s.description)):s.short&&!n&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);t.push(...n)}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(s=>jo(s)).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((s,n)=>Math.max(s,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,n)=>Math.max(s,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+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(s=>JSON.stringify(s)).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(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),n=t.helpWidth??80;function i(h,p){return t.formatItem(h,s,p,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(c),n),""]));let a=t.visibleArguments(e).map(h=>i(t.styleArgumentTerm(t.argumentTerm(h)),t.styleArgumentDescription(t.argumentDescription(h))));a.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...a,""]));let u=t.visibleOptions(e).map(h=>i(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));if(u.length>0&&(o=o.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(p=>i(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));h.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...h,""]))}let l=t.visibleCommands(e).map(h=>i(t.styleSubcommandTerm(t.subcommandTerm(h)),t.styleSubcommandDescription(t.subcommandDescription(h))));return l.length>0&&(o=o.concat([t.styleTitle("Commands:"),...l,""])),o.join(`
5
+ `)}displayWidth(e){return En(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,s,n){let o=" ".repeat(2);if(!s)return o+e;let c=e.padEnd(t+e.length-n.displayWidth(e)),a=2,l=(this.helpWidth??80)-t-a-2,h;return l<this.minWidthToWrap||n.preformatted(s)?h=s:h=n.boxWrap(s,l).replace(/\n/g,`
6
+ `+" ".repeat(t+a)),o+c+" ".repeat(a)+h.replace(/\n/g,`
7
+ ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,i=[];return s.forEach(o=>{let c=o.match(n);if(c===null){i.push("");return}let a=[c.shift()],u=this.displayWidth(a[0]);c.forEach(l=>{let h=this.displayWidth(l);if(u+h<=t){a.push(l),u+=h;return}i.push(a.join(""));let p=l.trimStart();a=[p],u=this.displayWidth(p)}),i.push(a.join(""))}),i.join(`
8
+ `)}};function En(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}_s.Help=ys;_s.stripColor=En});var Ss=se(xs=>{"use strict";var{InvalidArgumentError:Fo}=tr(),bs=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 s=Bo(e);this.short=s.shortFlag,this.long=s.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,s)=>{if(!this.argChoices.includes(t))throw new Fo(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Tn(this.name().replace(/^no-/,"")):Tn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ws=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,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,t){let s=t.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return t.negate===(i===e)}};function Tn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Bo(r){let e,t,s=/^-[^-]$/,n=/^--[^-]/,i=r.split(/[ |,]+/).concat("guard");if(s.test(i[0])&&(e=i.shift()),n.test(i[0])&&(t=i.shift()),!e&&s.test(i[0])&&(e=i.shift()),!e&&n.test(i[0])&&(e=t,t=i.shift()),i[0].startsWith("-")){let o=i[0],c=`option creation failed due to '${o}' in option flags '${r}'`;throw/^-[^-][^-]/.test(o)?new Error(`${c}
9
+ - a short flag is a single dash and a single character
10
+ - either use a single dash and a single character (for a short flag)
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(o)?new Error(`${c}
12
+ - too many short flags`):n.test(o)?new Error(`${c}
13
+ - too many long flags`):new Error(`${c}
14
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}xs.Option=bs;xs.DualOptions=ws});var An=se(On=>{"use strict";function Do(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let s=0;s<=r.length;s++)t[s]=[s];for(let s=0;s<=e.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let n=1;n<=r.length;n++){let i=1;r[n-1]===e[s-1]?i=0:i=1,t[n][s]=Math.min(t[n-1][s]+1,t[n][s-1]+1,t[n-1][s-1]+i),n>1&&s>1&&r[n-1]===e[s-2]&&r[n-2]===e[s-1]&&(t[n][s]=Math.min(t[n][s],t[n-2][s-2]+1))}return t[r.length][e.length]}function Uo(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let s=[],n=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let c=Do(r,o),a=Math.max(r.length,o.length);(a-c)/a>i&&(c<n?(n=c,s=[o]):c===n&&s.push(o))}),s.sort((o,c)=>o.localeCompare(c)),t&&(s=s.map(o=>`--${o}`)),s.length>1?`
15
+ (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
16
+ (Did you mean ${s[0]}?)`:""}On.suggestSimilar=Uo});var Nn=se(Os=>{"use strict";var Wo=ve("events").EventEmitter,Cs=ve("child_process"),Fe=ve("path"),Sr=ve("fs"),K=ve("process"),{Argument:Qo,humanReadableArgName:Ho}=xr(),{CommanderError:ks}=tr(),{Help:zo,stripColor:Go}=vs(),{Option:Rn,DualOptions:Jo}=Ss(),{suggestSimilar:In}=An(),Es=class r extends Wo{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,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._savedState=null,this._outputConfiguration={writeOut:t=>K.stdout.write(t),writeErr:t=>K.stderr.write(t),outputError:(t,s)=>s(t),getOutHelpWidth:()=>K.stdout.isTTY?K.stdout.columns:void 0,getErrHelpWidth:()=>K.stderr.isTTY?K.stderr.columns:void 0,getOutHasColors:()=>Ts()??(K.stdout.isTTY&&K.stdout.hasColors?.()),getErrHasColors:()=>Ts()??(K.stderr.isTTY&&K.stderr.hasColors?.()),stripColor:t=>Go(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,s){let n=t,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,c]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return n&&(a.description(n),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,c&&a.arguments(c),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new zo,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
17
+ - 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 Qo(e,t)}argument(e,t,s,n){let i=this.createArgument(e,t);return typeof s=="function"?i.default(n).argParser(s):i.default(s),this.addArgument(i),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[,s,n]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,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 s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
18
+ Expecting one of '${s.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,s){this._exitCallback&&this._exitCallback(new ks(e,t,s)),K.exit(e)}action(e){let t=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Rn(e,t)}_callParseArg(e,t,s,n){try{return e.parseArg(t,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${n} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let s=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 '${s}'
19
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),s=t(e).find(n=>this._findCommand(n));if(s){let n=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,o,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let a=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,a,o):i!==null&&e.variadic&&(i=e._concatValue(i,a)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,c)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,o,"env")}),this}_optionEx(e,t,s,n,i){if(typeof t=="object"&&t instanceof Rn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,s);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(i).argParser(n);else if(n instanceof RegExp){let c=n;n=(a,u)=>{let l=c.exec(a);return l?l[0]:u},o.default(i).argParser(n)}else o.default(n);return this.addOption(o)}option(e,t,s,n){return this._optionEx({},e,t,s,n)}requiredOption(e,t,s,n){return this._optionEx({mandatory:!0},e,t,s,n)}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,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.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){K.versions?.electron&&(t.from="electron");let n=K.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=K.argv),this.rawArgs=e.slice();let s;switch(t.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":K.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=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",s}parse(e,t){this._prepareForParse();let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){this._prepareForParse();let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,s){if(Sr.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
21
+ - if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
+ - ${n}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(l,h){let p=Fe.resolve(l,h);if(Sr.existsSync(p))return p;if(n.includes(Fe.extname(h)))return;let m=n.find(g=>Sr.existsSync(`${p}${g}`));if(m)return`${p}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let l;try{l=Sr.realpathSync(this._scriptPath)}catch{l=this._scriptPath}c=Fe.resolve(Fe.dirname(l),c)}if(c){let l=i(c,o);if(!l&&!e._executableFile&&this._scriptPath){let h=Fe.basename(this._scriptPath,Fe.extname(this._scriptPath));h!==this._name&&(l=i(c,`${h}-${e._name}`))}o=l||o}s=n.includes(Fe.extname(o));let a;K.platform!=="win32"?s?(t.unshift(o),t=Pn(K.execArgv).concat(t),a=Cs.spawn(K.argv[0],t,{stdio:"inherit"})):a=Cs.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,c,e._name),t.unshift(o),t=Pn(K.execArgv).concat(t),a=Cs.spawn(K.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{K.on(h,()=>{a.killed===!1&&a.exitCode===null&&a.kill(h)})});let u=this._exitCallback;a.on("close",l=>{l=l??1,u?u(new ks(l,"commander.executeSubCommandAsync","(close)")):K.exit(l)}),a.on("error",l=>{if(l.code==="ENOENT")this._checkForMissingExecutable(o,c,e._name);else if(l.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)K.exit(1);else{let h=new ks(1,"commander.executeSubCommandAsync","(error)");h.nestedError=l,u(h)}}),this.runningCommand=a}_dispatchSubcommand(e,t,s){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(s));else return n._parseCommand(t,s)}),i}_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=(s,n,i)=>{let o=n;if(n!==null&&s.parseArg){let c=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,i,c)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((o,c)=>e(s,c,o),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),t[n]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),t==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,t))}),n}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.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(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,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():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),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(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],n=t,i=e.slice();function o(a){return a.length>1&&a[0]==="-"}let c=null;for(;i.length;){let a=i.shift();if(a==="--"){n===s&&n.push(a),n.push(...i);break}if(c&&!o(a)){this.emit(`option:${c.name()}`,a);continue}if(c=null,o(a)){let u=this._findOption(a);if(u){if(u.required){let l=i.shift();l===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,l)}else if(u.optional){let l=null;i.length>0&&!o(i[0])&&(l=i.shift()),this.emit(`option:${u.name()}`,l)}else this.emit(`option:${u.name()}`);c=u.variadic?u:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let u=this._findOption(`-${a[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,a.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let u=a.indexOf("="),l=this._findOption(a.slice(0,u));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,a.slice(u+1));continue}}if(o(a)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(a)){t.push(a),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){s.push(a),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){n.push(a),i.length>0&&n.push(...i);break}n.push(a)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
24
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
+ `),this.outputHelp({error:!0}));let s=t||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in K.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()}`,K.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Jo(this.options),t=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&t(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"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 s=o=>{let c=o.attributeName(),a=this.getOptionValue(c),u=this.options.find(h=>h.negate&&c===h.attributeName()),l=this.options.find(h=>!h.negate&&c===h.attributeName());return u&&(u.presetArg===void 0&&a===!1||u.presetArg!==void 0&&a===u.presetArg)?u:l||o},n=o=>{let c=s(o),a=c.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=In(e,n)}let s=`error: unknown option '${e}'${t}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,s=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),t=In(e,n)}let s=`error: unknown command '${e}'${t}`;this.error(s,{code:"commander.unknownCommand"})}version(e,t,s){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",s=s||"output the version number";let n=this.createOption(t,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
27
+ `),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 s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}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(s=>Ho(s));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=Fe.basename(e,Fe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),s=this._getOutputContext(e);t.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let n=t.formatHelp(this,t);return s.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,s,n,i;return t?(s=c=>this._outputConfiguration.writeErr(c),n=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(s=c=>this._outputConfiguration.writeOut(c),n=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(n||(c=this._outputConfiguration.stripColor(c)),s(c)),hasColors:n,helpWidth:i}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let s=this._getOutputContext(e),n={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation({error:s.error});if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}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=Number(K.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
28
+ Expecting one of '${s.join("', '")}'`);let n=`${e}Help`;return this.on(n,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
29
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Pn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],s=i[3],n=i[4]),t&&n!=="0"?`${t}=${s}:${parseInt(n)+1}`:e})}function Ts(){if(K.env.NO_COLOR||K.env.FORCE_COLOR==="0"||K.env.FORCE_COLOR==="false")return!1;if(K.env.FORCE_COLOR||K.env.CLICOLOR_FORCE!==void 0)return!0}Os.Command=Es;Os.useColor=Ts});var Ln=se(we=>{"use strict";var{Argument:$n}=xr(),{Command:As}=Nn(),{CommanderError:Zo,InvalidArgumentError:Mn}=tr(),{Help:Ko}=vs(),{Option:qn}=Ss();we.program=new As;we.createCommand=r=>new As(r);we.createOption=(r,e)=>new qn(r,e);we.createArgument=(r,e)=>new $n(r,e);we.Command=As;we.Option=qn;we.Argument=$n;we.Help=Ko;we.CommanderError=Zo;we.InvalidArgumentError=Mn;we.InvalidOptionArgumentError=Mn});var Qn=se((ah,Wn)=>{"use strict";Wn.exports=Un;Un.sync=Xo;var Bn=ve("fs");function Yo(r,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var s=0;s<t.length;s++){var n=t[s].toLowerCase();if(n&&r.substr(-n.length).toLowerCase()===n)return!0}return!1}function Dn(r,e,t){return!r.isSymbolicLink()&&!r.isFile()?!1:Yo(e,t)}function Un(r,e,t){Bn.stat(r,function(s,n){t(s,s?!1:Dn(n,r,e))})}function Xo(r,e){return Dn(Bn.statSync(r),r,e)}});var Zn=se((ch,Jn)=>{"use strict";Jn.exports=zn;zn.sync=ea;var Hn=ve("fs");function zn(r,e,t){Hn.stat(r,function(s,n){t(s,s?!1:Gn(n,e))})}function ea(r,e){return Gn(Hn.statSync(r),e)}function Gn(r,e){return r.isFile()&&ta(r,e)}function ta(r,e){var t=r.mode,s=r.uid,n=r.gid,i=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),c=parseInt("100",8),a=parseInt("010",8),u=parseInt("001",8),l=c|a,h=t&u||t&a&&n===o||t&c&&s===i||t&l&&i===0;return h}});var Yn=se((lh,Kn)=>{"use strict";var uh=ve("fs"),Cr;process.platform==="win32"||global.TESTING_WINDOWS?Cr=Qn():Cr=Zn();Kn.exports=Is;Is.sync=ra;function Is(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(s,n){Is(r,e||{},function(i,o){i?n(i):s(o)})})}Cr(r,e||{},function(s,n){s&&(s.code==="EACCES"||e&&e.ignoreErrors)&&(s=null,n=!1),t(s,n)})}function ra(r,e){try{return Cr.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var ii=se((hh,ni)=>{"use strict";var It=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Xn=ve("path"),sa=It?";":":",ei=Yn(),ti=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),ri=(r,e)=>{let t=e.colon||sa,s=r.match(/\//)||It&&r.match(/\\/)?[""]:[...It?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],n=It?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=It?n.split(t):[""];return It&&r.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:s,pathExt:i,pathExtExe:n}},si=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:s,pathExt:n,pathExtExe:i}=ri(r,e),o=[],c=u=>new Promise((l,h)=>{if(u===s.length)return e.all&&o.length?l(o):h(ti(r));let p=s[u],m=/^".*"$/.test(p)?p.slice(1,-1):p,g=Xn.join(m,r),O=!m&&/^\.[\\\/]/.test(r)?r.slice(0,2)+g:g;l(a(O,u,0))}),a=(u,l,h)=>new Promise((p,m)=>{if(h===n.length)return p(c(l+1));let g=n[h];ei(u+g,{pathExt:i},(O,P)=>{if(!O&&P)if(e.all)o.push(u+g);else return p(u+g);return p(a(u,l,h+1))})});return t?c(0).then(u=>t(null,u),t):c(0)},na=(r,e)=>{e=e||{};let{pathEnv:t,pathExt:s,pathExtExe:n}=ri(r,e),i=[];for(let o=0;o<t.length;o++){let c=t[o],a=/^".*"$/.test(c)?c.slice(1,-1):c,u=Xn.join(a,r),l=!a&&/^\.[\\\/]/.test(r)?r.slice(0,2)+u:u;for(let h=0;h<s.length;h++){let p=l+s[h];try{if(ei.sync(p,{pathExt:n}))if(e.all)i.push(p);else return p}catch{}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw ti(r)};ni.exports=si;si.sync=na});var ai=se((dh,Ps)=>{"use strict";var oi=(r={})=>{let e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(s=>s.toUpperCase()==="PATH")||"Path"};Ps.exports=oi;Ps.exports.default=oi});var hi=se((fh,li)=>{"use strict";var ci=ve("path"),ia=ii(),oa=ai();function ui(r,e){let t=r.options.env||process.env,s=process.cwd(),n=r.options.cwd!=null,i=n&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(r.options.cwd)}catch{}let o;try{o=ia.sync(r.command,{path:t[oa({env:t})],pathExt:e?ci.delimiter:void 0})}catch{}finally{i&&process.chdir(s)}return o&&(o=ci.resolve(n?r.options.cwd:"",o)),o}function aa(r){return ui(r)||ui(r,!0)}li.exports=aa});var di=se((ph,$s)=>{"use strict";var Ns=/([()\][%!^"`<>&|;, *?])/g;function ca(r){return r=r.replace(Ns,"^$1"),r}function ua(r,e){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(Ns,"^$1"),e&&(r=r.replace(Ns,"^$1")),r}$s.exports.command=ca;$s.exports.argument=ua});var pi=se((mh,fi)=>{"use strict";fi.exports=/^#!(.*)/});var gi=se((gh,mi)=>{"use strict";var la=pi();mi.exports=(r="")=>{let e=r.match(la);if(!e)return null;let[t,s]=e[0].replace(/#! ?/,"").split(" "),n=t.split("/").pop();return n==="env"?s:s?`${n} ${s}`:n}});var _i=se((yh,yi)=>{"use strict";var Ms=ve("fs"),ha=gi();function da(r){let t=Buffer.alloc(150),s;try{s=Ms.openSync(r,"r"),Ms.readSync(s,t,0,150,0),Ms.closeSync(s)}catch{}return ha(t.toString())}yi.exports=da});var xi=se((_h,wi)=>{"use strict";var fa=ve("path"),vi=hi(),bi=di(),pa=_i(),ma=process.platform==="win32",ga=/\.(?:com|exe)$/i,ya=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function _a(r){r.file=vi(r);let e=r.file&&pa(r.file);return e?(r.args.unshift(r.file),r.command=e,vi(r)):r.file}function va(r){if(!ma)return r;let e=_a(r),t=!ga.test(e);if(r.options.forceShell||t){let s=ya.test(e);r.command=fa.normalize(r.command),r.command=bi.command(r.command),r.args=r.args.map(i=>bi.argument(i,s));let n=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${n}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function ba(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);let s={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?s:va(s)}wi.exports=ba});var ki=se((vh,Ci)=>{"use strict";var qs=process.platform==="win32";function Ls(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function wa(r,e){if(!qs)return;let t=r.emit;r.emit=function(s,n){if(s==="exit"){let i=Si(n,e);if(i)return t.call(r,"error",i)}return t.apply(r,arguments)}}function Si(r,e){return qs&&r===1&&!e.file?Ls(e.original,"spawn"):null}function xa(r,e){return qs&&r===1&&!e.file?Ls(e.original,"spawnSync"):null}Ci.exports={hookChildProcess:wa,verifyENOENT:Si,verifyENOENTSync:xa,notFoundError:Ls}});var Oi=se((bh,Pt)=>{"use strict";var Ei=ve("child_process"),Vs=xi(),js=ki();function Ti(r,e,t){let s=Vs(r,e,t),n=Ei.spawn(s.command,s.args,s.options);return js.hookChildProcess(n,s),n}function Sa(r,e,t){let s=Vs(r,e,t),n=Ei.spawnSync(s.command,s.args,s.options);return n.error=n.error||js.verifyENOENTSync(n.status,s),n}Pt.exports=Ti;Pt.exports.spawn=Ti;Pt.exports.sync=Sa;Pt.exports._parse=Vs;Pt.exports._enoent=js});var Vn=kn(Ln(),1),{program:zl,createCommand:Gl,createArgument:Jl,createOption:Zl,CommanderError:Kl,InvalidArgumentError:Yl,InvalidOptionArgumentError:Xl,Command:jn,Argument:eh,Option:th,Help:rh}=Vn.default;import*as Ui from"readline";function Rs(r,e=[]){let s={type:"user",message:{role:"user",content:e.length===0?r:[...r?[{type:"text",text:r}]:[],...e.map(n=>({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.data}}))]},parent_tool_use_id:null};return JSON.stringify(s)+`
30
+ `}var rr=class{buffer="";push(e){if(this.buffer+=e,this.buffer.length>8e6){let n=this.buffer.lastIndexOf(`
31
+ `);this.buffer=n>=0?this.buffer.slice(n+1):""}let t=[],s;for(;(s=this.buffer.indexOf(`
32
+ `))>=0;){let n=this.buffer.slice(0,s).trim();this.buffer=this.buffer.slice(s+1),n&&t.push(n)}return t}};function sr(r){return typeof r=="object"&&r!==null?r:null}function Fn(r){let e=sr(r.message),t=e?e.content:void 0;return Array.isArray(t)?t.filter(sr):[]}var nr=class{constructor(e){this.ctx=e}ctx;currentTurnId=null;streamedText=!1;beginTurn(e){return this.currentTurnId=e,this.streamedText=!1,[{type:"agent.status",state:"thinking"}]}ingest(e){let t=sr(e);if(!t)return[];switch(t.type){case"system":return this.handleSystem(t);case"stream_event":return this.handleStreamEvent(t);case"assistant":return this.handleAssistant(t);case"user":return this.handleUser(t);case"result":return this.handleResult(t);default:return[]}}handleStreamEvent(e){let t=sr(e.event);if(!t||t.type!=="content_block_delta")return[];let s=sr(t.delta);return!s||s.type!=="text_delta"||typeof s.text!="string"?[]:(this.streamedText=!0,[{type:"agent.text",turnId:this.turnId,text:s.text}])}get turnId(){return this.currentTurnId??"unknown"}handleSystem(e){if(e.subtype!=="init")return[];let t=Array.isArray(e.tools)?e.tools.filter(s=>typeof s=="string"):[];return[{type:"session.started",cwd:this.ctx.cwd,model:typeof e.model=="string"?e.model:"unknown",claudeVersion:this.ctx.claudeVersion,tools:t}]}handleAssistant(e){let t=[],s=!1;for(let n of Fn(e))n.type==="text"&&typeof n.text=="string"?this.streamedText||t.push({type:"agent.text",turnId:this.turnId,text:n.text}):n.type==="tool_use"&&(t.push({type:"agent.tool_call",turnId:this.turnId,toolCallId:typeof n.id=="string"?n.id:"unknown",name:typeof n.name=="string"?n.name:"unknown",input:n.input}),s=!0);return s&&t.push({type:"agent.status",state:"running_tool"}),t}handleUser(e){let t=[],s=!1;for(let n of Fn(e))if(n.type==="tool_result"){let i=n.content,o=typeof i=="string"?i:JSON.stringify(i);t.push({type:"agent.tool_result",turnId:this.turnId,toolCallId:typeof n.tool_use_id=="string"?n.tool_use_id:"unknown",output:o,isError:n.is_error===!0}),s=!0}return s&&t.push({type:"agent.status",state:"thinking"}),t}handleResult(e){let t=this.turnId,s=[{type:"agent.status",state:"idle"},{type:"agent.turn_result",turnId:t,success:e.subtype==="success",usage:e.usage,costUsd:typeof e.total_cost_usd=="number"?e.total_cost_usd:void 0,durationMs:typeof e.duration_ms=="number"?e.duration_ms:void 0}];return this.currentTurnId=null,this.streamedText=!1,s}};var Ai=kn(Oi(),1);import{randomUUID as Ca}from"crypto";var ka=["--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages"],Ea=1e3,Ta=2e3,Oa=5e3;function ir(r){let e=r.spawnFn??Ai.default,t=e(r.claudeBin??"claude",ka,{cwd:r.cwd,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32"}),s=new rr,n=new nr({cwd:r.cwd,claudeVersion:r.claudeVersion??"unknown"}),i=[],o=[],c=p=>{for(let m of i)m(p)},a=!1,u=!1;t.stdout?.setEncoding("utf8"),t.stdout?.on("data",p=>{for(let m of s.push(p)){let g;try{g=JSON.parse(m)}catch{c({type:"agent.error",message:"Failed to parse agent output line",detail:m.slice(0,200)});continue}for(let O of n.ingest(g))c(O)}});let l="";t.stderr?.setEncoding("utf8"),t.stderr?.on("data",p=>{l=(l+p).slice(-Ea)}),t.on("error",p=>{for(let m of o)m(p)}),t.on("exit",(p,m)=>{a=!0,!u&&(p!==null&&p!==0||m!==null)&&c({type:"agent.error",message:m!==null?`Agent terminated by signal ${m}`:`Agent process exited with code ${p}`,detail:l.trim()||void 0})});let h=p=>{try{t.kill(p)}catch{}let m=t.pid;if(m!==void 0)if(process.platform==="win32")try{e("taskkill",["/pid",String(m),"/T","/F"],{stdio:"ignore"})}catch{}else try{process.kill(-m,p)}catch{}};return{sendPrompt(p,m=[]){let g=Ca();for(let O of n.beginTurn(g))c(O);return t.stdin?.write(Rs(p,m)),g},onEvent(p){i.push(p)},onError(p){o.push(p)},stop(){if(a)return Promise.resolve();u=!0;try{t.stdin?.end()}catch{}return new Promise(p=>{let m=!1,g=setTimeout(()=>h("SIGKILL"),Ta),O=setTimeout(()=>{h("SIGKILL"),P()},Oa),P=()=>{m||(m=!0,clearTimeout(g),clearTimeout(O),p())};if(t.once("exit",P),a)return P();h("SIGTERM")})}}}var L={};Cn(L,{BRAND:()=>ec,DIRTY:()=>st,EMPTY_PATH:()=>Pa,INVALID:()=>B,NEVER:()=>Vc,OK:()=>he,ParseStatus:()=>ce,Schema:()=>J,ZodAny:()=>Je,ZodArray:()=>We,ZodBigInt:()=>it,ZodBoolean:()=>ot,ZodBranded:()=>ar,ZodCatch:()=>yt,ZodDate:()=>at,ZodDefault:()=>gt,ZodDiscriminatedUnion:()=>Tr,ZodEffects:()=>Ce,ZodEnum:()=>pt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>Ar,ZodIntersection:()=>ht,ZodIssueCode:()=>x,ZodLazy:()=>dt,ZodLiteral:()=>ft,ZodMap:()=>Vt,ZodNaN:()=>Ft,ZodNativeEnum:()=>mt,ZodNever:()=>Oe,ZodNull:()=>ut,ZodNullable:()=>Pe,ZodNumber:()=>nt,ZodObject:()=>ye,ZodOptional:()=>xe,ZodParsedType:()=>I,ZodPipeline:()=>cr,ZodPromise:()=>Ze,ZodReadonly:()=>_t,ZodRecord:()=>Or,ZodSchema:()=>J,ZodSet:()=>jt,ZodString:()=>Ge,ZodSymbol:()=>qt,ZodTransformer:()=>Ce,ZodTuple:()=>Ie,ZodType:()=>J,ZodUndefined:()=>ct,ZodUnion:()=>lt,ZodUnknown:()=>Ue,ZodVoid:()=>Lt,addIssueToContext:()=>A,any:()=>uc,array:()=>fc,bigint:()=>nc,boolean:()=>Fi,coerce:()=>Lc,custom:()=>Li,date:()=>ic,datetimeRegex:()=>Mi,defaultErrorMap:()=>Be,discriminatedUnion:()=>yc,effect:()=>Ac,enum:()=>Ec,function:()=>Sc,getErrorMap:()=>Nt,getParsedType:()=>Re,instanceof:()=>rc,intersection:()=>_c,isAborted:()=>kr,isAsync:()=>$t,isDirty:()=>Er,isValid:()=>ze,late:()=>tc,lazy:()=>Cc,literal:()=>kc,makeIssue:()=>or,map:()=>wc,nan:()=>sc,nativeEnum:()=>Tc,never:()=>hc,null:()=>cc,nullable:()=>Ic,number:()=>ji,object:()=>pc,objectUtil:()=>Fs,oboolean:()=>qc,onumber:()=>Mc,optional:()=>Rc,ostring:()=>$c,pipeline:()=>Nc,preprocess:()=>Pc,promise:()=>Oc,quotelessJson:()=>Aa,record:()=>bc,set:()=>xc,setErrorMap:()=>Ia,strictObject:()=>mc,string:()=>Vi,symbol:()=>oc,transformer:()=>Ac,tuple:()=>vc,undefined:()=>ac,union:()=>gc,unknown:()=>lc,util:()=>Z,void:()=>dc});var Z;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let i={};for(let o of n)i[o]=o;return i},r.getValidEnumValues=n=>{let i=r.objectKeys(n).filter(c=>typeof n[n[c]]!="number"),o={};for(let c of i)o[c]=n[c];return r.objectValues(o)},r.objectValues=n=>r.objectKeys(n).map(function(i){return n[i]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},r.find=(n,i)=>{for(let o of n)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=s,r.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(Z||(Z={}));var Fs;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Fs||(Fs={}));var I=Z.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=r=>{switch(typeof r){case"undefined":return I.undefined;case"string":return I.string;case"number":return Number.isNaN(r)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":return Array.isArray(r)?I.array:r===null?I.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?I.promise:typeof Map<"u"&&r instanceof Map?I.map:typeof Set<"u"&&r instanceof Set?I.set:typeof Date<"u"&&r instanceof Date?I.date:I.object;default:return I.unknown}};var x=Z.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Aa=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},s={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)s._errors.push(t(o));else{let c=s,a=0;for(;a<o.path.length;){let u=o.path[a];a===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(o))):c[u]=c[u]||{_errors:[]},c=c[u],a++}}};return n(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Z.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ge.create=r=>new ge(r);var Ra=(r,e)=>{let t;switch(r.code){case x.invalid_type:r.received===I.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case x.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Z.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:t=`Unrecognized key(s) in object: ${Z.joinValues(r.keys,", ")}`;break;case x.invalid_union:t="Invalid input";break;case x.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Z.joinValues(r.options)}`;break;case x.invalid_enum_value:t=`Invalid enum value. Expected ${Z.joinValues(r.options)}, received '${r.received}'`;break;case x.invalid_arguments:t="Invalid function arguments";break;case x.invalid_return_type:t="Invalid function return type";break;case x.invalid_date:t="Invalid date";break;case x.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Z.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case x.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case x.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case x.custom:t="Invalid input";break;case x.invalid_intersection_types:t="Intersection results could not be merged";break;case x.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case x.not_finite:t="Number must be finite";break;default:t=e.defaultError,Z.assertNever(r)}return{message:t}},Be=Ra;var Ri=Be;function Ia(r){Ri=r}function Nt(){return Ri}var or=r=>{let{data:e,path:t,errorMaps:s,issueData:n}=r,i=[...t,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let c="",a=s.filter(u=>!!u).slice().reverse();for(let u of a)c=u(o,{data:e,defaultError:c}).message;return{...n,path:i,message:c}},Pa=[];function A(r,e){let t=Nt(),s=or({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Be?void 0:Be].filter(n=>!!n)});r.common.issues.push(s)}var ce=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let s=[];for(let n of t){if(n.status==="aborted")return B;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let n of t){let i=await n.key,o=await n.value;s.push({key:i,value:o})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let n of t){let{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return B;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}},B=Object.freeze({status:"aborted"}),st=r=>({status:"dirty",value:r}),he=r=>({status:"valid",value:r}),kr=r=>r.status==="aborted",Er=r=>r.status==="dirty",ze=r=>r.status==="valid",$t=r=>typeof Promise<"u"&&r instanceof Promise;var M;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(M||(M={}));var Se=class{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ii=(r,e)=>{if(ze(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ge(r.common.issues);return this._error=t,this._error}}};function z(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,c)=>{let{message:a}=r;return o.code==="invalid_enum_value"?{message:a??c.defaultError}:typeof c.data>"u"?{message:a??s??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:a??t??c.defaultError}},description:n}}var J=class{get description(){return this._def.description}_getType(e){return Re(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ce,ctx:{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if($t(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},n=this._parseSync({data:e,path:s.path,parent:s});return Ii(s,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return ze(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>ze(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},n=this._parse({data:e,path:s.path,parent:s}),i=await($t(n)?n:Promise.resolve(n));return Ii(s,i)}refine(e,t){let s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,i)=>{let o=e(n),c=()=>i.addIssue({code:x.custom,...s(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(a=>a?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new Ce({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return xe.create(this,this._def)}nullable(){return Pe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return We.create(this)}promise(){return Ze.create(this,this._def)}or(e){return lt.create([this,e],this._def)}and(e){return ht.create(this,e,this._def)}transform(e){return new Ce({...z(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new gt({...z(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new ar({typeName:U.ZodBranded,type:this,...z(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new yt({...z(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return cr.create(this,e)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Na=/^c[^\s-]{8,}$/i,$a=/^[0-9a-z]+$/,Ma=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qa=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,La=/^[a-z0-9_-]{21}$/i,Va=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ja=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Fa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ba="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Bs,Da=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ua=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Wa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Qa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ha=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,za=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ni="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ga=new RegExp(`^${Ni}$`);function $i(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Ja(r){return new RegExp(`^${$i(r)}$`)}function Mi(r){let e=`${Ni}T${$i(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Za(r,e){return!!((e==="v4"||!e)&&Da.test(r)||(e==="v6"||!e)&&Wa.test(r))}function Ka(r,e){if(!Va.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ya(r,e){return!!((e==="v4"||!e)&&Ua.test(r)||(e==="v6"||!e)&&Qa.test(r))}var Ge=class r extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.string){let i=this._getOrReturnCtx(e);return A(i,{code:x.invalid_type,expected:I.string,received:i.parsedType}),B}let s=new ce,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),A(n,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),A(n,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,c=e.data.length<i.value;(o||c)&&(n=this._getOrReturnCtx(e,n),o?A(n,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&A(n,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")Fa.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"email",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")Bs||(Bs=new RegExp(Ba,"u")),Bs.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"emoji",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")qa.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"uuid",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")La.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"nanoid",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Na.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"cuid",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")$a.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"cuid2",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Ma.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"ulid",code:x.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),A(n,{validation:"url",code:x.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"regex",code:x.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),A(n,{code:x.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),A(n,{code:x.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),A(n,{code:x.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Mi(i).test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:x.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ga.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:x.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Ja(i).test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:x.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ja.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"duration",code:x.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Za(e.data,i.version)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"ip",code:x.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Ka(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"jwt",code:x.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ya(e.data,i.version)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"cidr",code:x.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Ha.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"base64",code:x.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?za.test(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{validation:"base64url",code:x.invalid_string,message:i.message}),s.dirty()):Z.assertNever(i);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:x.invalid_string,...M.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...M.errToObj(e)})}url(e){return this._addCheck({kind:"url",...M.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...M.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...M.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...M.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...M.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...M.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...M.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...M.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...M.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...M.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...M.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...M.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...M.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...M.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...M.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...M.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...M.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...M.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...M.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...M.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...M.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...M.errToObj(t)})}nonempty(e){return this.min(1,M.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ge.create=r=>new Ge({checks:[],typeName:U.ZodString,coerce:r?.coerce??!1,...z(r)});function Xa(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,i=Number.parseInt(r.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}var nt=class r extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==I.number){let i=this._getOrReturnCtx(e);return A(i,{code:x.invalid_type,expected:I.number,received:i.parsedType}),B}let s,n=new ce;for(let i of this._def.checks)i.kind==="int"?Z.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:x.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:x.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:x.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Xa(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),A(s,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:x.not_finite,message:i.message}),n.dirty()):Z.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,M.toString(t))}gt(e,t){return this.setLimit("min",e,!1,M.toString(t))}lte(e,t){return this.setLimit("max",e,!0,M.toString(t))}lt(e,t){return this.setLimit("max",e,!1,M.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:M.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:M.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:M.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Z.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};nt.create=r=>new nt({checks:[],typeName:U.ZodNumber,coerce:r?.coerce||!1,...z(r)});var it=class r extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==I.bigint)return this._getInvalidInput(e);let s,n=new ce;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:x.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),A(s,{code:x.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),A(s,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):Z.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:x.invalid_type,expected:I.bigint,received:t.parsedType}),B}gte(e,t){return this.setLimit("min",e,!0,M.toString(t))}gt(e,t){return this.setLimit("min",e,!1,M.toString(t))}lte(e,t){return this.setLimit("max",e,!0,M.toString(t))}lt(e,t){return this.setLimit("max",e,!1,M.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:M.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:M.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};it.create=r=>new it({checks:[],typeName:U.ZodBigInt,coerce:r?.coerce??!1,...z(r)});var ot=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let s=this._getOrReturnCtx(e);return A(s,{code:x.invalid_type,expected:I.boolean,received:s.parsedType}),B}return he(e.data)}};ot.create=r=>new ot({typeName:U.ZodBoolean,coerce:r?.coerce||!1,...z(r)});var at=class r extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.date){let i=this._getOrReturnCtx(e);return A(i,{code:x.invalid_type,expected:I.date,received:i.parsedType}),B}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return A(i,{code:x.invalid_date}),B}let s=new ce,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),A(n,{code:x.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),A(n,{code:x.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):Z.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:M.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:M.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};at.create=r=>new at({checks:[],coerce:r?.coerce||!1,typeName:U.ZodDate,...z(r)});var qt=class extends J{_parse(e){if(this._getType(e)!==I.symbol){let s=this._getOrReturnCtx(e);return A(s,{code:x.invalid_type,expected:I.symbol,received:s.parsedType}),B}return he(e.data)}};qt.create=r=>new qt({typeName:U.ZodSymbol,...z(r)});var ct=class extends J{_parse(e){if(this._getType(e)!==I.undefined){let s=this._getOrReturnCtx(e);return A(s,{code:x.invalid_type,expected:I.undefined,received:s.parsedType}),B}return he(e.data)}};ct.create=r=>new ct({typeName:U.ZodUndefined,...z(r)});var ut=class extends J{_parse(e){if(this._getType(e)!==I.null){let s=this._getOrReturnCtx(e);return A(s,{code:x.invalid_type,expected:I.null,received:s.parsedType}),B}return he(e.data)}};ut.create=r=>new ut({typeName:U.ZodNull,...z(r)});var Je=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return he(e.data)}};Je.create=r=>new Je({typeName:U.ZodAny,...z(r)});var Ue=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return he(e.data)}};Ue.create=r=>new Ue({typeName:U.ZodUnknown,...z(r)});var Oe=class extends J{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:x.invalid_type,expected:I.never,received:t.parsedType}),B}};Oe.create=r=>new Oe({typeName:U.ZodNever,...z(r)});var Lt=class extends J{_parse(e){if(this._getType(e)!==I.undefined){let s=this._getOrReturnCtx(e);return A(s,{code:x.invalid_type,expected:I.void,received:s.parsedType}),B}return he(e.data)}};Lt.create=r=>new Lt({typeName:U.ZodVoid,...z(r)});var We=class r extends J{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==I.array)return A(t,{code:x.invalid_type,expected:I.array,received:t.parsedType}),B;if(n.exactLength!==null){let o=t.data.length>n.exactLength.value,c=t.data.length<n.exactLength.value;(o||c)&&(A(t,{code:o?x.too_big:x.too_small,minimum:c?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(A(t,{code:x.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(A(t,{code:x.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,c)=>n.type._parseAsync(new Se(t,o,t.path,c)))).then(o=>ce.mergeArray(s,o));let i=[...t.data].map((o,c)=>n.type._parseSync(new Se(t,o,t.path,c)));return ce.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:M.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:M.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:M.toString(t)}})}nonempty(e){return this.min(1,e)}};We.create=(r,e)=>new We({type:r,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...z(e)});function Mt(r){if(r instanceof ye){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=xe.create(Mt(s))}return new ye({...r._def,shape:()=>e})}else return r instanceof We?new We({...r._def,type:Mt(r.element)}):r instanceof xe?xe.create(Mt(r.unwrap())):r instanceof Pe?Pe.create(Mt(r.unwrap())):r instanceof Ie?Ie.create(r.items.map(e=>Mt(e))):r}var ye=class r extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Z.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==I.object){let u=this._getOrReturnCtx(e);return A(u,{code:x.invalid_type,expected:I.object,received:u.parsedType}),B}let{status:s,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof Oe&&this._def.unknownKeys==="strip"))for(let u in n.data)o.includes(u)||c.push(u);let a=[];for(let u of o){let l=i[u],h=n.data[u];a.push({key:{status:"valid",value:u},value:l._parse(new Se(n,h,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Oe){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of c)a.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(u==="strict")c.length>0&&(A(n,{code:x.unrecognized_keys,keys:c}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of c){let h=n.data[l];a.push({key:{status:"valid",value:l},value:u._parse(new Se(n,h,n.path,l)),alwaysSet:l in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of a){let h=await l.key,p=await l.value;u.push({key:h,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>ce.mergeObjectSync(s,u)):ce.mergeObjectSync(s,a)}get shape(){return this._def.shape()}strict(e){return M.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:M.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of Z.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of Z.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return Mt(this)}partial(e){let t={};for(let s of Z.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of Z.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof xe;)i=i._def.innerType;t[s]=i}return new r({...this._def,shape:()=>t})}keyof(){return qi(Z.objectKeys(this.shape))}};ye.create=(r,e)=>new ye({shape:()=>r,unknownKeys:"strip",catchall:Oe.create(),typeName:U.ZodObject,...z(e)});ye.strictCreate=(r,e)=>new ye({shape:()=>r,unknownKeys:"strict",catchall:Oe.create(),typeName:U.ZodObject,...z(e)});ye.lazycreate=(r,e)=>new ye({shape:r,unknownKeys:"strip",catchall:Oe.create(),typeName:U.ZodObject,...z(e)});var lt=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function n(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let o=i.map(c=>new ge(c.ctx.common.issues));return A(t,{code:x.invalid_union,unionErrors:o}),B}if(t.common.async)return Promise.all(s.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);{let i,o=[];for(let a of s){let u={...t,common:{...t.common,issues:[]},parent:null},l=a._parseSync({data:t.data,path:t.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let c=o.map(a=>new ge(a));return A(t,{code:x.invalid_union,unionErrors:c}),B}}get options(){return this._def.options}};lt.create=(r,e)=>new lt({options:r,typeName:U.ZodUnion,...z(e)});var De=r=>r instanceof dt?De(r.schema):r instanceof Ce?De(r.innerType()):r instanceof ft?[r.value]:r instanceof pt?r.options:r instanceof mt?Z.objectValues(r.enum):r instanceof gt?De(r._def.innerType):r instanceof ct?[void 0]:r instanceof ut?[null]:r instanceof xe?[void 0,...De(r.unwrap())]:r instanceof Pe?[null,...De(r.unwrap())]:r instanceof ar||r instanceof _t?De(r.unwrap()):r instanceof yt?De(r._def.innerType):[],Tr=class r extends J{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.object)return A(t,{code:x.invalid_type,expected:I.object,received:t.parsedType}),B;let s=this.discriminator,n=t.data[s],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(A(t,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let n=new Map;for(let i of t){let o=De(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(n.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);n.set(c,i)}}return new r({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...z(s)})}};function Ds(r,e){let t=Re(r),s=Re(e);if(r===e)return{valid:!0,data:r};if(t===I.object&&s===I.object){let n=Z.objectKeys(e),i=Z.objectKeys(r).filter(c=>n.indexOf(c)!==-1),o={...r,...e};for(let c of i){let a=Ds(r[c],e[c]);if(!a.valid)return{valid:!1};o[c]=a.data}return{valid:!0,data:o}}else if(t===I.array&&s===I.array){if(r.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<r.length;i++){let o=r[i],c=e[i],a=Ds(o,c);if(!a.valid)return{valid:!1};n.push(a.data)}return{valid:!0,data:n}}else return t===I.date&&s===I.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var ht=class extends J{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(i,o)=>{if(kr(i)||kr(o))return B;let c=Ds(i.value,o.value);return c.valid?((Er(i)||Er(o))&&t.dirty(),{status:t.value,value:c.data}):(A(s,{code:x.invalid_intersection_types}),B)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ht.create=(r,e,t)=>new ht({left:r,right:e,typeName:U.ZodIntersection,...z(t)});var Ie=class r extends J{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==I.array)return A(s,{code:x.invalid_type,expected:I.array,received:s.parsedType}),B;if(s.data.length<this._def.items.length)return A(s,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&s.data.length>this._def.items.length&&(A(s,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...s.data].map((o,c)=>{let a=this._def.items[c]||this._def.rest;return a?a._parse(new Se(s,o,s.path,c)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>ce.mergeArray(t,o)):ce.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ie.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ie({items:r,typeName:U.ZodTuple,rest:null,...z(e)})};var Or=class r extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==I.object)return A(s,{code:x.invalid_type,expected:I.object,received:s.parsedType}),B;let n=[],i=this._def.keyType,o=this._def.valueType;for(let c in s.data)n.push({key:i._parse(new Se(s,c,s.path,c)),value:o._parse(new Se(s,s.data[c],s.path,c)),alwaysSet:c in s.data});return s.common.async?ce.mergeObjectAsync(t,n):ce.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof J?new r({keyType:e,valueType:t,typeName:U.ZodRecord,...z(s)}):new r({keyType:Ge.create(),valueType:e,typeName:U.ZodRecord,...z(t)})}},Vt=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==I.map)return A(s,{code:x.invalid_type,expected:I.map,received:s.parsedType}),B;let n=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([c,a],u)=>({key:n._parse(new Se(s,c,s.path,[u,"key"])),value:i._parse(new Se(s,a,s.path,[u,"value"]))}));if(s.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let a of o){let u=await a.key,l=await a.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&t.dirty(),c.set(u.value,l.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let a of o){let u=a.key,l=a.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&t.dirty(),c.set(u.value,l.value)}return{status:t.value,value:c}}}};Vt.create=(r,e,t)=>new Vt({valueType:e,keyType:r,typeName:U.ZodMap,...z(t)});var jt=class r extends J{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==I.set)return A(s,{code:x.invalid_type,expected:I.set,received:s.parsedType}),B;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(A(s,{code:x.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(A(s,{code:x.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let i=this._def.valueType;function o(a){let u=new Set;for(let l of a){if(l.status==="aborted")return B;l.status==="dirty"&&t.dirty(),u.add(l.value)}return{status:t.value,value:u}}let c=[...s.data.values()].map((a,u)=>i._parse(new Se(s,a,s.path,u)));return s.common.async?Promise.all(c).then(a=>o(a)):o(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:M.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:M.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};jt.create=(r,e)=>new jt({valueType:r,minSize:null,maxSize:null,typeName:U.ZodSet,...z(e)});var Ar=class r extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.function)return A(t,{code:x.invalid_type,expected:I.function,received:t.parsedType}),B;function s(c,a){return or({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Nt(),Be].filter(u=>!!u),issueData:{code:x.invalid_arguments,argumentsError:a}})}function n(c,a){return or({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Nt(),Be].filter(u=>!!u),issueData:{code:x.invalid_return_type,returnTypeError:a}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Ze){let c=this;return he(async function(...a){let u=new ge([]),l=await c._def.args.parseAsync(a,i).catch(m=>{throw u.addIssue(s(a,m)),u}),h=await Reflect.apply(o,this,l);return await c._def.returns._def.type.parseAsync(h,i).catch(m=>{throw u.addIssue(n(h,m)),u})})}else{let c=this;return he(function(...a){let u=c._def.args.safeParse(a,i);if(!u.success)throw new ge([s(a,u.error)]);let l=Reflect.apply(o,this,u.data),h=c._def.returns.safeParse(l,i);if(!h.success)throw new ge([n(l,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ie.create(e).rest(Ue.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||Ie.create([]).rest(Ue.create()),returns:t||Ue.create(),typeName:U.ZodFunction,...z(s)})}},dt=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};dt.create=(r,e)=>new dt({getter:r,typeName:U.ZodLazy,...z(e)});var ft=class extends J{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:x.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};ft.create=(r,e)=>new ft({value:r,typeName:U.ZodLiteral,...z(e)});function qi(r,e){return new pt({values:r,typeName:U.ZodEnum,...z(e)})}var pt=class r extends J{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return A(t,{expected:Z.joinValues(s),received:t.parsedType,code:x.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return A(t,{received:t.data,code:x.invalid_enum_value,options:s}),B}return he(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};pt.create=qi;var mt=class extends J{_parse(e){let t=Z.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==I.string&&s.parsedType!==I.number){let n=Z.objectValues(t);return A(s,{expected:Z.joinValues(n),received:s.parsedType,code:x.invalid_type}),B}if(this._cache||(this._cache=new Set(Z.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=Z.objectValues(t);return A(s,{received:s.data,code:x.invalid_enum_value,options:n}),B}return he(e.data)}get enum(){return this._def.values}};mt.create=(r,e)=>new mt({values:r,typeName:U.ZodNativeEnum,...z(e)});var Ze=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.promise&&t.common.async===!1)return A(t,{code:x.invalid_type,expected:I.promise,received:t.parsedType}),B;let s=t.parsedType===I.promise?t.data:Promise.resolve(t.data);return he(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Ze.create=(r,e)=>new Ze({type:r,typeName:U.ZodPromise,...z(e)});var Ce=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{A(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let o=n.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async c=>{if(t.value==="aborted")return B;let a=await this._def.schema._parseAsync({data:c,path:s.path,parent:s});return a.status==="aborted"?B:a.status==="dirty"?st(a.value):t.value==="dirty"?st(a.value):a});{if(t.value==="aborted")return B;let c=this._def.schema._parseSync({data:o,path:s.path,parent:s});return c.status==="aborted"?B:c.status==="dirty"?st(c.value):t.value==="dirty"?st(c.value):c}}if(n.type==="refinement"){let o=c=>{let a=n.refinement(c,i);if(s.common.async)return Promise.resolve(a);if(a instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(s.common.async===!1){let c=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?B:(c.status==="dirty"&&t.dirty(),o(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(c=>c.status==="aborted"?B:(c.status==="dirty"&&t.dirty(),o(c.value).then(()=>({status:t.value,value:c.value}))))}if(n.type==="transform")if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ze(o))return B;let c=n.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>ze(o)?Promise.resolve(n.transform(o.value,i)).then(c=>({status:t.value,value:c})):B);Z.assertNever(n)}};Ce.create=(r,e,t)=>new Ce({schema:r,typeName:U.ZodEffects,effect:e,...z(t)});Ce.createWithPreprocess=(r,e,t)=>new Ce({schema:e,effect:{type:"preprocess",transform:r},typeName:U.ZodEffects,...z(t)});var xe=class extends J{_parse(e){return this._getType(e)===I.undefined?he(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xe.create=(r,e)=>new xe({innerType:r,typeName:U.ZodOptional,...z(e)});var Pe=class extends J{_parse(e){return this._getType(e)===I.null?he(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pe.create=(r,e)=>new Pe({innerType:r,typeName:U.ZodNullable,...z(e)});var gt=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===I.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};gt.create=(r,e)=>new gt({innerType:r,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...z(e)});var yt=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return $t(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ge(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};yt.create=(r,e)=>new yt({innerType:r,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...z(e)});var Ft=class extends J{_parse(e){if(this._getType(e)!==I.nan){let s=this._getOrReturnCtx(e);return A(s,{code:x.invalid_type,expected:I.nan,received:s.parsedType}),B}return{status:"valid",value:e.data}}};Ft.create=r=>new Ft({typeName:U.ZodNaN,...z(r)});var ec=Symbol("zod_brand"),ar=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},cr=class r extends J{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?B:i.status==="dirty"?(t.dirty(),st(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?B:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:U.ZodPipeline})}},_t=class extends J{_parse(e){let t=this._def.innerType._parse(e),s=n=>(ze(n)&&(n.value=Object.freeze(n.value)),n);return $t(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};_t.create=(r,e)=>new _t({innerType:r,typeName:U.ZodReadonly,...z(e)});function Pi(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Li(r,e={},t){return r?Je.create().superRefine((s,n)=>{let i=r(s);if(i instanceof Promise)return i.then(o=>{if(!o){let c=Pi(e,s),a=c.fatal??t??!0;n.addIssue({code:"custom",...c,fatal:a})}});if(!i){let o=Pi(e,s),c=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:c})}}):Je.create()}var tc={object:ye.lazycreate},U;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(U||(U={}));var rc=(r,e={message:`Input not instance of ${r.name}`})=>Li(t=>t instanceof r,e),Vi=Ge.create,ji=nt.create,sc=Ft.create,nc=it.create,Fi=ot.create,ic=at.create,oc=qt.create,ac=ct.create,cc=ut.create,uc=Je.create,lc=Ue.create,hc=Oe.create,dc=Lt.create,fc=We.create,pc=ye.create,mc=ye.strictCreate,gc=lt.create,yc=Tr.create,_c=ht.create,vc=Ie.create,bc=Or.create,wc=Vt.create,xc=jt.create,Sc=Ar.create,Cc=dt.create,kc=ft.create,Ec=pt.create,Tc=mt.create,Oc=Ze.create,Ac=Ce.create,Rc=xe.create,Ic=Pe.create,Pc=Ce.createWithPreprocess,Nc=cr.create,$c=()=>Vi().optional(),Mc=()=>ji().optional(),qc=()=>Fi().optional(),Lc={string:(r=>Ge.create({...r,coerce:!0})),number:(r=>nt.create({...r,coerce:!0})),boolean:(r=>ot.create({...r,coerce:!0})),bigint:(r=>it.create({...r,coerce:!0})),date:(r=>at.create({...r,coerce:!0}))};var Vc=B;var jc=L.enum(["idle","thinking","running_tool","awaiting_input"]),Fc=L.object({type:L.literal("session.started"),cwd:L.string(),model:L.string(),claudeVersion:L.string(),tools:L.array(L.string())}),Bc=L.object({type:L.literal("agent.status"),state:jc}),Dc=L.object({type:L.literal("agent.text"),turnId:L.string(),text:L.string()}),Uc=L.object({type:L.literal("agent.tool_call"),turnId:L.string(),toolCallId:L.string(),name:L.string(),input:L.unknown()}),Wc=L.object({type:L.literal("agent.tool_result"),turnId:L.string(),toolCallId:L.string(),output:L.string(),isError:L.boolean()}),Qc=L.object({type:L.literal("agent.turn_result"),turnId:L.string(),success:L.boolean(),usage:L.unknown().optional(),costUsd:L.number().optional(),durationMs:L.number().optional()}),Hc=L.object({type:L.literal("agent.error"),message:L.string(),detail:L.string().optional()}),Bi=L.discriminatedUnion("type",[Fc,Bc,Dc,Uc,Wc,Qc,Hc]);var zc=L.object({type:L.literal("prompt.inject"),promptId:L.string(),text:L.string(),submittedBy:L.string()}),Gc=L.object({type:L.literal("control.interrupt")}),Jc=L.object({type:L.literal("control.permission_decision"),toolCallId:L.string(),decision:L.enum(["allow","deny"])}),od=L.discriminatedUnion("type",[zc,Gc,Jc]);var Zc=L.object({v:L.literal(1),clientEventId:L.number().int().nonnegative(),event:Bi}),ld=Zc.extend({sessionId:L.string(),seq:L.number().int().nonnegative()});function Di(r){return!Number.isFinite(r)||r<=0?"$0":r<.01?"<$0.01":`$${r.toFixed(r<1?4:2)}`}function Rr(r){switch(r.type){case"session.started":return`[session] ${r.model} in ${r.cwd}`;case"agent.text":return`claude> ${r.text}`;case"agent.tool_call":return`[tool] ${r.name} ${JSON.stringify(r.input)}`;case"agent.tool_result":return`[tool result]${r.isError?" (error)":""} ${r.output}`;case"agent.turn_result":return`[turn done] success=${r.success}${r.costUsd!==void 0?` cost=${Di(r.costUsd)}`:""}`;case"agent.error":return`[error] ${r.message}`;case"agent.status":return null;default:return r}}function Wi(r){let e=ir({cwd:r});e.onEvent(i=>{let o=Rr(i);o!==null&&console.log(o)}),e.onError(i=>console.error("[agent error]",i.message));let t=Ui.createInterface({input:process.stdin,output:process.stdout,prompt:"you> "});console.log(`Mob Squad dev session in ${r}. Type a prompt and press Enter. Ctrl+C to exit.`),t.prompt();let s=!1,n=async()=>{if(s)return;s=!0,t.close();let i=setTimeout(()=>process.exit(0),6e3);try{await e.stop()}finally{clearTimeout(i),process.exit(0)}};t.on("line",i=>{let o=i.trim();o&&e.sendPrompt(o),t.prompt()}),t.on("close",()=>{n()}),process.on("SIGINT",()=>{n()}),process.on("SIGTERM",()=>{n()})}import*as tt from"readline";var ke="1.41.0";var Dt={};Cn(Dt,{byteLength:()=>Yc,fromByteArray:()=>bt,fromByteArrayUrlSafeNoPadding:()=>ru,toByteArray:()=>Bt});var Ne=[],Ee=[],Kc=Uint8Array,Us="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(vt=0,Qi=Us.length;vt<Qi;++vt)Ne[vt]=Us[vt],Ee[Us.charCodeAt(vt)]=vt;var vt,Qi;Ee[45]=62;Ee[95]=63;function Hi(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var s=t===e?0:4-t%4;return[t,s]}function Yc(r){var e=Hi(r),t=e[0],s=e[1];return(t+s)*3/4-s}function Xc(r,e,t){return(e+t)*3/4-t}function Bt(r){var e,t=Hi(r),s=t[0],n=t[1],i=new Kc(Xc(r,s,n)),o=0,c=n>0?s-4:s,a;for(a=0;a<c;a+=4)e=Ee[r.charCodeAt(a)]<<18|Ee[r.charCodeAt(a+1)]<<12|Ee[r.charCodeAt(a+2)]<<6|Ee[r.charCodeAt(a+3)],i[o++]=e>>16&255,i[o++]=e>>8&255,i[o++]=e&255;return n===2&&(e=Ee[r.charCodeAt(a)]<<2|Ee[r.charCodeAt(a+1)]>>4,i[o++]=e&255),n===1&&(e=Ee[r.charCodeAt(a)]<<10|Ee[r.charCodeAt(a+1)]<<4|Ee[r.charCodeAt(a+2)]>>2,i[o++]=e>>8&255,i[o++]=e&255),i}function eu(r){return Ne[r>>18&63]+Ne[r>>12&63]+Ne[r>>6&63]+Ne[r&63]}function tu(r,e,t){for(var s,n=[],i=e;i<t;i+=3)s=(r[i]<<16&16711680)+(r[i+1]<<8&65280)+(r[i+2]&255),n.push(eu(s));return n.join("")}function bt(r){for(var e,t=r.length,s=t%3,n=[],i=16383,o=0,c=t-s;o<c;o+=i)n.push(tu(r,o,o+i>c?c:o+i));return s===1?(e=r[t-1],n.push(Ne[e>>2]+Ne[e<<4&63]+"==")):s===2&&(e=(r[t-2]<<8)+r[t-1],n.push(Ne[e>>10]+Ne[e>>4&63]+Ne[e<<2&63]+"=")),n.join("")}function ru(r){return bt(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fe(r){if(r===void 0)return{};if(!Ir(r))throw new Error(`The arguments to a Convex function must be an object. Received: ${r}`);return r}function ur(r){if(typeof r>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof r!="string")throw new Error(`Invalid deployment address: found ${r}".`);if(!(r.startsWith("http:")||r.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${r}".`);try{new URL(r)}catch{throw new Error(`Invalid deployment address: "${r}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(r.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${r}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function Ir(r){let e=typeof r=="object",t=Object.getPrototypeOf(r),s=t===null||t===Object.prototype||t?.constructor?.name==="Object";return e&&s}var Ji=!0,Ut=BigInt("-9223372036854775808"),zs=BigInt("9223372036854775807"),Qs=BigInt("0"),su=BigInt("8"),nu=BigInt("256");function Zi(r){return Number.isNaN(r)||!Number.isFinite(r)||Object.is(r,-0)}function iu(r){r<Qs&&(r-=Ut+Ut);let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Uint8Array(new ArrayBuffer(8)),s=0;for(let n of e.match(/.{2}/g).reverse())t.set([parseInt(n,16)],s++),r>>=su;return bt(t)}function ou(r){let e=Bt(r);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let t=Qs,s=Qs;for(let n of e)t+=BigInt(n)*nu**s,s++;return t>zs&&(t+=Ut+Ut),t}function au(r){if(r<Ut||zs<r)throw new Error(`BigInt ${r} does not fit into a 64-bit signed integer.`);let e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,r,!0),bt(new Uint8Array(e))}function cu(r){let e=Bt(r);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}var uu=DataView.prototype.setBigInt64?au:iu,lu=DataView.prototype.getBigInt64?cu:ou,zi=1024;function Hs(r){if(r.length>zi)throw new Error(`Field name ${r} exceeds maximum field name length ${zi}.`);if(r.startsWith("$"))throw new Error(`Field name ${r} starts with a '$', which is reserved.`);for(let e=0;e<r.length;e+=1){let t=r.charCodeAt(e);if(t<32||t>=127)throw new Error(`Field name ${r} has invalid character '${r[e]}': Field names can only contain non-control ASCII characters`)}}function de(r){if(r===null||typeof r=="boolean"||typeof r=="number"||typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>de(s));if(typeof r!="object")throw new Error(`Unexpected type of ${r}`);let e=Object.entries(r);if(e.length===1){let s=e[0][0];if(s==="$bytes"){if(typeof r.$bytes!="string")throw new Error(`Malformed $bytes field on ${r}`);return Bt(r.$bytes).buffer}if(s==="$integer"){if(typeof r.$integer!="string")throw new Error(`Malformed $integer field on ${r}`);return lu(r.$integer)}if(s==="$float"){if(typeof r.$float!="string")throw new Error(`Malformed $float field on ${r}`);let n=Bt(r.$float);if(n.byteLength!==8)throw new Error(`Received ${n.byteLength} bytes, expected 8 for $float`);let o=new DataView(n.buffer).getFloat64(0,Ji);if(!Zi(o))throw new Error(`Float ${o} should be encoded as a number`);return o}if(s==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(s==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}let t={};for(let[s,n]of Object.entries(r))Hs(s),t[s]=de(n);return t}var Gi=16384;function wt(r){let e=JSON.stringify(r,(t,s)=>s===void 0?"undefined":typeof s=="bigint"?`${s.toString()}n`:s);if(e.length>Gi){let t="[...truncated]",s=Gi-t.length,n=e.codePointAt(s-1);return n!==void 0&&n>65535&&(s-=1),e.substring(0,s)+t}return e}function Pr(r,e,t,s){if(r===void 0){let o=t&&` (present at path ${t} in original object ${wt(e)})`;throw new Error(`undefined is not a valid Convex value${o}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(r===null)return r;if(typeof r=="bigint"){if(r<Ut||zs<r)throw new Error(`BigInt ${r} does not fit into a 64-bit signed integer.`);return{$integer:uu(r)}}if(typeof r=="number")if(Zi(r)){let o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,r,Ji),{$float:bt(new Uint8Array(o))}}else return r;if(typeof r=="boolean"||typeof r=="string")return r;if(r instanceof ArrayBuffer)return{$bytes:bt(new Uint8Array(r))};if(Array.isArray(r))return r.map((o,c)=>Pr(o,e,t+`[${c}]`,!1));if(r instanceof Set)throw new Error(Ws(t,"Set",[...r],e));if(r instanceof Map)throw new Error(Ws(t,"Map",[...r],e));if(!Ir(r)){let o=r?.constructor?.name,c=o?`${o} `:"";throw new Error(Ws(t,c,r,e))}let n={},i=Object.entries(r);i.sort(([o,c],[a,u])=>o===a?0:o<a?-1:1);for(let[o,c]of i)c!==void 0?(Hs(o),n[o]=Pr(c,e,t+`.${o}`,!1)):s&&(Hs(o),n[o]=hu(c,e,t+`.${o}`));return n}function Ws(r,e,t,s){return r?`${e}${wt(t)} is not a supported Convex type (present at path ${r} in original object ${wt(s)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${wt(t)} is not a supported Convex type.`}function hu(r,e,t){if(r===void 0)return{$undefined:null};if(e===void 0)throw new Error(`Programming error. Current value is ${wt(r)} but original value is undefined`);return Pr(r,e,t,!1)}function oe(r){return Pr(r,r,"",!1)}var du=Object.defineProperty,fu=(r,e,t)=>e in r?du(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,te=(r,e,t)=>fu(r,typeof e!="symbol"?e+"":e,t),pu="https://docs.convex.dev/error#undefined-validator";function lr(r,e){let t=e!==void 0?` for field "${e}"`:"";throw new Error(`A validator is undefined${t} in ${r}. This is often caused by circular imports. See ${pu} for details.`)}var pe=class{constructor({isOptional:e}){te(this,"type"),te(this,"fieldPaths"),te(this,"isOptional"),te(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}},Nr=class r extends pe{constructor({isOptional:e,tableName:t}){if(super({isOptional:e}),te(this,"tableName"),te(this,"kind","id"),typeof t!="string")throw new Error("v.id(tableName) requires a string");this.tableName=t}get json(){return{type:"id",tableName:this.tableName}}asOptional(){return new r({isOptional:"optional",tableName:this.tableName})}},hr=class r extends pe{constructor(){super(...arguments),te(this,"kind","float64")}get json(){return{type:"number"}}asOptional(){return new r({isOptional:"optional"})}},dr=class r extends pe{constructor(){super(...arguments),te(this,"kind","int64")}get json(){return{type:"bigint"}}asOptional(){return new r({isOptional:"optional"})}},$r=class r extends pe{constructor(){super(...arguments),te(this,"kind","boolean")}get json(){return{type:this.kind}}asOptional(){return new r({isOptional:"optional"})}},Mr=class r extends pe{constructor(){super(...arguments),te(this,"kind","bytes")}get json(){return{type:this.kind}}asOptional(){return new r({isOptional:"optional"})}},qr=class r extends pe{constructor(){super(...arguments),te(this,"kind","string")}get json(){return{type:this.kind}}asOptional(){return new r({isOptional:"optional"})}},Lr=class r extends pe{constructor(){super(...arguments),te(this,"kind","null")}get json(){return{type:this.kind}}asOptional(){return new r({isOptional:"optional"})}},Vr=class r extends pe{constructor(){super(...arguments),te(this,"kind","any")}get json(){return{type:this.kind}}asOptional(){return new r({isOptional:"optional"})}},jr=class r extends pe{constructor({isOptional:e,fields:t}){super({isOptional:e}),te(this,"fields"),te(this,"kind","object"),globalThis.Object.entries(t).forEach(([s,n])=>{if(n===void 0&&lr("v.object()",s),!n.isConvexValidator)throw new Error("v.object() entries must be validators")}),this.fields=t}get json(){return{type:this.kind,value:globalThis.Object.fromEntries(globalThis.Object.entries(this.fields).map(([e,t])=>[e,{fieldType:t.json,optional:t.isOptional==="optional"}]))}}asOptional(){return new r({isOptional:"optional",fields:this.fields})}omit(...e){let t={...this.fields};for(let s of e)delete t[s];return new r({isOptional:this.isOptional,fields:t})}pick(...e){let t={};for(let s of e)t[s]=this.fields[s];return new r({isOptional:this.isOptional,fields:t})}partial(){let e={};for(let[t,s]of globalThis.Object.entries(this.fields))e[t]=s.asOptional();return new r({isOptional:this.isOptional,fields:e})}extend(e){return new r({isOptional:this.isOptional,fields:{...this.fields,...e}})}},Fr=class r extends pe{constructor({isOptional:e,value:t}){if(super({isOptional:e}),te(this,"value"),te(this,"kind","literal"),typeof t!="string"&&typeof t!="boolean"&&typeof t!="number"&&typeof t!="bigint")throw new Error("v.literal(value) must be a string, number, or boolean");this.value=t}get json(){return{type:this.kind,value:oe(this.value)}}asOptional(){return new r({isOptional:"optional",value:this.value})}},Br=class r extends pe{constructor({isOptional:e,element:t}){super({isOptional:e}),te(this,"element"),te(this,"kind","array"),t===void 0&&lr("v.array()"),this.element=t}get json(){return{type:this.kind,value:this.element.json}}asOptional(){return new r({isOptional:"optional",element:this.element})}},Dr=class r extends pe{constructor({isOptional:e,key:t,value:s}){if(super({isOptional:e}),te(this,"key"),te(this,"value"),te(this,"kind","record"),t===void 0&&lr("v.record()","key"),s===void 0&&lr("v.record()","value"),t.isOptional==="optional")throw new Error("Record validator cannot have optional keys");if(s.isOptional==="optional")throw new Error("Record validator cannot have optional values");if(!t.isConvexValidator||!s.isConvexValidator)throw new Error("Key and value of v.record() but be validators");this.key=t,this.value=s}get json(){return{type:this.kind,keys:this.key.json,values:{fieldType:this.value.json,optional:!1}}}asOptional(){return new r({isOptional:"optional",key:this.key,value:this.value})}},Ur=class r extends pe{constructor({isOptional:e,members:t}){super({isOptional:e}),te(this,"members"),te(this,"kind","union"),t.forEach((s,n)=>{if(s===void 0&&lr("v.union()",`member at index ${n}`),!s.isConvexValidator)throw new Error("All members of v.union() must be validators")}),this.members=t}get json(){return{type:this.kind,value:this.members.map(e=>e.json)}}asOptional(){return new r({isOptional:"optional",members:this.members})}};function Gs(r){return!!r.isConvexValidator}var H={id:r=>new Nr({isOptional:"required",tableName:r}),null:()=>new Lr({isOptional:"required"}),number:()=>new hr({isOptional:"required"}),float64:()=>new hr({isOptional:"required"}),bigint:()=>new dr({isOptional:"required"}),int64:()=>new dr({isOptional:"required"}),boolean:()=>new $r({isOptional:"required"}),string:()=>new qr({isOptional:"required"}),bytes:()=>new Mr({isOptional:"required"}),literal:r=>new Fr({isOptional:"required",value:r}),array:r=>new Br({isOptional:"required",element:r}),object:r=>new jr({isOptional:"required",fields:r}),record:(r,e)=>new Dr({isOptional:"required",key:r,value:e}),union:(...r)=>new Ur({isOptional:"required",members:r}),any:()=>new Vr({isOptional:"required"}),optional:r=>r.asOptional(),nullable:r=>H.union(r,H.null())};var mu=Object.defineProperty,gu=(r,e,t)=>e in r?mu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Js=(r,e,t)=>gu(r,typeof e!="symbol"?e+"":e,t),Ki,Yi,yu=Symbol.for("ConvexError"),Qe=class extends(Yi=Error,Ki=yu,Yi){constructor(e){super(typeof e=="string"?e:wt(e)),Js(this,"name","ConvexError"),Js(this,"data"),Js(this,Ki,!0),this.data=e}};var Xi=()=>Array.from({length:4},()=>0),Nd=Xi(),$d=Xi();var vu=Object.defineProperty,bu=(r,e,t)=>e in r?vu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,eo=(r,e,t)=>bu(r,typeof e!="symbol"?e+"":e,t),wu="color:rgb(0, 145, 255)";function to(r){switch(r){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}var Wr=class{constructor(e){eo(this,"_onLogLineFuncs"),eo(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let s=0;s<10&&this._onLogLineFuncs[t]!==void 0;s++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t("debug",`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t("error",...e)}};function Zs(r){let e=new Wr(r);return e.addLogLineListener((t,...s)=>{switch(t){case"debug":console.debug(...s);break;case"info":console.log(...s);break;case"warn":console.warn(...s);break;case"error":console.error(...s);break;default:console.log(...s)}}),e}function Ks(r){return new Wr(r)}function xt(r,e,t,s,n){let i=to(t);if(typeof n=="object"&&(n=`ConvexError ${JSON.stringify(n.errorData,null,2)}`),e==="info"){let o=n.match(/^\[.*?\] /);if(o===null){r.error(`[CONVEX ${i}(${s})] Could not parse console.log`);return}let c=n.slice(1,o[0].length-2),a=n.slice(o[0].length);r.log(`%c[CONVEX ${i}(${s})] [${c}]`,wu,a)}else r.error(`[CONVEX ${i}(${s})] ${n}`)}function ro(r,e){let t=`[CONVEX FATAL ERROR] ${e}`;return r.error(t),new Error(t)}function Ke(r,e,t){return`[CONVEX ${to(r)}(${e})] ${t.errorMessage}
33
+ Called by client`}function fr(r,e){return e.data=r.errorData,e}function $e(r){let e=r.split(":"),t,s;return e.length===1?(t=e[0],s="default"):(t=e.slice(0,e.length-1).join(":"),s=e[e.length-1]),t.endsWith(".js")&&(t=t.slice(0,-3)),`${t}:${s}`}function Me(r,e){return JSON.stringify({udfPath:$e(r),args:oe(e)})}function Ys(r,e,t){let{initialNumItems:s,id:n}=t;return JSON.stringify({type:"paginated",udfPath:$e(r),args:oe(e),options:oe({initialNumItems:s,id:n})})}function so(r){return JSON.parse(r).type==="paginated"}var xu=Object.defineProperty,Su=(r,e,t)=>e in r?xu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,qe=(r,e,t)=>Su(r,typeof e!="symbol"?e+"":e,t),Qr=class{constructor(){qe(this,"nextQueryId"),qe(this,"querySetVersion"),qe(this,"querySet"),qe(this,"queryIdToToken"),qe(this,"identityVersion"),qe(this,"auth"),qe(this,"outstandingQueriesOlderThanRestart"),qe(this,"outstandingAuthOlderThanRestart"),qe(this,"paused"),qe(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,s,n){let i=$e(e),o=Me(i,t),c=this.querySet.get(o);if(c!==void 0)return c.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{let a=this.nextQueryId++,u={id:a,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:s,componentPath:n};this.querySet.set(o,u),this.queryIdToToken.set(a,o);let l=this.querySetVersion,h=this.querySetVersion+1,p={type:"Add",queryId:a,udfPath:i,args:[oe(t)],journal:s,componentPath:n};return this.paused?this.pendingQuerySetModifications.set(a,p):this.querySetVersion=h,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:l,newVersion:h,modifications:[p]},unsubscribe:()=>this.removeSubscriber(o)}}}transition(e){for(let t of e.modifications)switch(t.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let s=t.journal;if(s!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=s)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);break}default:throw new Error(`Invalid modification ${t.type}`)}}queryId(e,t){let s=$e(e),n=Me(s,t),i=this.querySet.get(n);return i!==void 0?i.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:"Authenticate",baseVersion:t,...this.auth}}setAdminAuth(e,t){let s={tokenType:"Admin",value:e,impersonating:t};this.auth=s;let n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...s}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let n of this.querySet.values()){let i={type:"Add",queryId:n.id,udfPath:n.canonicalizedUdfPath,args:[oe(n.args)],journal:n.journal,componentPath:n.componentPath};e.push(i),this.outstandingQueriesOlderThanRestart.add(n.id)}this.querySetVersion=1;let t={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let s={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[t,s]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return t.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let s=this.querySetVersion,n=this.querySetVersion+1,i={type:"Remove",queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,i):this.querySetVersion=n,{type:"ModifyQuerySet",baseVersion:s,newVersion:n,modifications:[i]}}}};var Cu=Object.defineProperty,ku=(r,e,t)=>e in r?Cu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Hr=(r,e,t)=>ku(r,typeof e!="symbol"?e+"":e,t),zr=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,Hr(this,"inflightRequests"),Hr(this,"requestsOlderThanRestart"),Hr(this,"inflightMutationsCount",0),Hr(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let s=new Promise(n=>{let i=t?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:i,requestedAt:new Date,onResult:n}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),s}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status==="Completed")return null;let s=t.message.type==="Mutation"?"mutation":"action",n=t.message.udfPath;for(let a of e.logLines)xt(this.logger,"info",s,n,a);let i=t.status,o,c;if(e.success)o={success:!0,logLines:e.logLines,value:de(e.result)},c=()=>i.onResult(o);else{let a=e.result,{errorData:u}=e;xt(this.logger,"error",s,n,a),o={success:!1,errorMessage:a,errorData:u!==void 0?de(u):void 0,logLines:e.logLines},c=()=>i.onResult(o)}return e.type==="ActionResponse"||!e.success?(c(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type==="Action"?this.inflightActionsCount--:t.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:o}):(t.status={status:"Completed",result:o,ts:e.ts,onResolve:c},null)}removeCompleted(e){let t=new Map;for(let[s,n]of this.inflightRequests.entries()){let i=n.status;i.status==="Completed"&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(s,i.result),n.message.type==="Mutation"?this.inflightMutationsCount--:n.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(s),this.requestsOlderThanRestart.delete(s))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,s]of this.inflightRequests){if(s.status.status==="NotSent"){s.status.status="Requested",e.push(s.message);continue}if(s.message.type==="Mutation")e.push(s.message);else if(s.message.type==="Action"){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,s.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");s.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if(t.status.status==="NotSent"){t.status.status="Requested",e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!=="Completed"&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}};var Wt=Symbol.for("functionName");var Xs=Symbol.for("toReferencePath");function Eu(r){return r[Xs]??null}function Tu(r){return r.startsWith("function://")}function Ye(r){let e;if(typeof r=="string")Tu(r)?e={functionHandle:r}:e={name:r};else if(r[Wt])e={name:r[Wt]};else{let t=Eu(r);if(!t)throw new Error(`${r} is not a functionReference`);e={reference:t}}return e}function _e(r){let e=Ye(r);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof r=="string")return r;let t=r[Wt];if(!t)throw new Error(`${r} is not a functionReference`);return t}function no(r=[]){let e={get(t,s){if(typeof s=="string"){let n=[...r,s];return no(n)}else if(s===Wt){if(r.length<2){let o=["api",...r].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${o}\``)}let n=r.slice(0,-1).join("/"),i=r[r.length-1];return i==="default"?n:n+":"+i}else return s===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}var en=no();var Ou=Object.defineProperty,Au=(r,e,t)=>e in r?Ou(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gr=(r,e,t)=>Au(r,typeof e!="symbol"?e+"":e,t),Jr=class r{constructor(e){Gr(this,"queryResults"),Gr(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=fe(t[0]),n=_e(e),i=this.queryResults.get(Me(n,s));if(i!==void 0)return r.queryValue(i.result)}getAllQueries(e){let t=[],s=_e(e);for(let n of this.queryResults.values())n.udfPath===$e(s)&&t.push({args:n.args,value:r.queryValue(n.result)});return t}setQuery(e,t,s){let n=fe(t),i=_e(e),o=Me(i,n),c;s===void 0?c=void 0:c={success:!0,value:s,logLines:[]};let a={udfPath:i,args:n,result:c};this.queryResults.set(o,a),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}},Zr=class{constructor(){Gr(this,"queryResults"),Gr(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(o=>!t.has(o.mutationId));let s=this.queryResults;this.queryResults=new Map(e);let n=new Jr(this.queryResults);for(let o of this.optimisticUpdates)o.update(n);let i=[];for(let[o,c]of this.queryResults){let a=s.get(o);(a===void 0||a.result!==c.result)&&i.push(o)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let s=new Jr(this.queryResults);return e(s),s.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let s=t.result;if(s!==void 0){if(s.success)return s.value;throw s.errorData!==void 0?fr(s,new Qe(Ke("query",t.udfPath,s))):new Error(Ke("query",t.udfPath,s))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}};var Ru=Object.defineProperty,Iu=(r,e,t)=>e in r?Ru(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,tn=(r,e,t)=>Iu(r,typeof e!="symbol"?e+"":e,t),Le=class r{constructor(e,t){tn(this,"low"),tn(this,"high"),tn(this,"__isUnsignedLong__"),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?io:e>=Pu?Nu:new r(e%pr|0,e/pr|0)}toString(){return(BigInt(this.high)*BigInt(pr)+BigInt(this.low)).toString()}equals(e){return r.isLong(e)||(e=r.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return r.isLong(e)||(e=r.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?r.fromNumber(e):new r(e.low,e.high)}},io=new Le(0,0),oo=65536,pr=oo*oo,Pu=pr*pr,Nu=new Le(-1,-1);var $u=Object.defineProperty,Mu=(r,e,t)=>e in r?$u(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Kr=(r,e,t)=>Mu(r,typeof e!="symbol"?e+"":e,t),mr=class{constructor(e,t){Kr(this,"version"),Kr(this,"remoteQuerySet"),Kr(this,"queryPath"),Kr(this,"logger"),this.version={querySet:0,ts:Le.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw new Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let s of e.modifications)switch(s.type){case"QueryUpdated":{let n=this.queryPath(s.queryId);if(n)for(let o of s.logLines)xt(this.logger,"info","query",n,o);let i=de(s.value??null);this.remoteQuerySet.set(s.queryId,{success:!0,value:i,logLines:s.logLines});break}case"QueryFailed":{let n=this.queryPath(s.queryId);if(n)for(let o of s.logLines)xt(this.logger,"info","query",n,o);let{errorData:i}=s;this.remoteQuerySet.set(s.queryId,{success:!1,errorMessage:s.errorMessage,errorData:i!==void 0?de(i):void 0,logLines:s.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(s.queryId);break}default:throw new Error(`Invalid modification ${s.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}};function rn(r){let e=Dt.toByteArray(r);return Le.fromBytesLE(Array.from(e))}function qu(r){let e=new Uint8Array(r.toBytesLE());return Dt.fromByteArray(e)}function sn(r){switch(r.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...r};case"MutationResponse":return r.success?{...r,ts:rn(r.ts)}:{...r};case"Transition":return{...r,startVersion:{...r.startVersion,ts:rn(r.startVersion.ts)},endVersion:{...r.endVersion,ts:rn(r.endVersion.ts)}};default:}}function ao(r){switch(r.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...r};case"Connect":return r.maxObservedTimestamp!==void 0?{...r,maxObservedTimestamp:qu(r.maxObservedTimestamp)}:{...r,maxObservedTimestamp:void 0};default:}}var Lu=Object.defineProperty,Vu=(r,e,t)=>e in r?Lu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ne=(r,e,t)=>Vu(r,typeof e!="symbol"?e+"":e,t),ju=1e3,Fu=1001,Bu=1005,Du=4040,Yr;function Qt(){return Yr===void 0&&(Yr=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(Yr+performance.now())}function co(){return`t=${Math.round((Qt()-Yr)/100)/10}s`}var uo={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Uu(r){if(r===void 0)return"Unknown";for(let e of Object.keys(uo))if(r.startsWith(e))return e;return"Unknown"}var Xr=class{constructor(e,t,s,n,i,o){this.markConnectionStateDirty=i,this.debug=o,ne(this,"socket"),ne(this,"connectionCount"),ne(this,"_hasEverConnected",!1),ne(this,"lastCloseReason"),ne(this,"transitionChunkBuffer",null),ne(this,"defaultInitialBackoff"),ne(this,"maxBackoff"),ne(this,"retries"),ne(this,"serverInactivityThreshold"),ne(this,"reconnectDueToServerInactivityTimeout"),ne(this,"scheduledReconnect",null),ne(this,"networkOnlineHandler",null),ne(this,"pendingNetworkRecoveryInfo",null),ne(this,"uri"),ne(this,"onOpen"),ne(this,"onResume"),ne(this,"onMessage"),ne(this,"webSocketConstructor"),ne(this,"logger"),ne(this,"onServerDisconnectError"),this.webSocketConstructor=s,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=n,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let t=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let s=sn(JSON.parse(t));if(s.type!=="Transition")throw new Error(`Expected Transition, got ${s.type} after assembling chunks`);return s}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:Qt()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",co(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",co())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:t}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:t}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(t/1e3)}s of waiting`)}},e.onerror=t=>{this.transitionChunkBuffer=null;let s=t.message;s&&this.logger.log(`WebSocket error message: ${s}`)},e.onmessage=t=>{this.resetServerInactivityTimeout();let s=t.data.length,n=sn(JSON.parse(t.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type==="Ping")return;if(n.type==="TransitionChunk"){let o=this.assembleTransition(n);if(!o)return;n=o,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type==="Transition"&&this.reportLargeTransition({messageLength:s,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=t=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=t.reason||`closed with code ${t.code}`),t.code!==ju&&t.code!==Fu&&t.code!==Bu&&t.code!==Du){let n=`WebSocket closed with code ${t.code}`;t.reason&&(n+=`: ${t.reason}`),this.logger.log(n),this.onServerDisconnectError&&t.reason&&this.onServerDisconnectError(n)}let s=Uu(t.reason);this.scheduleReconnect(s)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){let s=ao(e),n=JSON.stringify(s),i=!1;try{this.socket.ws.send(n),i=!0}catch(o){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${o}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let s=Qt(),n=setTimeout(()=>{this.scheduledReconnect?.timeout===n&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:n,scheduledAt:s,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let e=this.socket.ws;return e.onmessage=t=>{this._logVerbose("Ignoring message received after close")},new Promise(t=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),t()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");let e=this.socket.ws;e.onmessage=s=>{this._logVerbose("Ignoring message received after close")};let t=new Promise(s=>{e.onclose=()=>{s()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=Qt()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=e!==null?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:Qt()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let s=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:uo[e].timeout)*Math.pow(2,this.retries);this.retries+=1;let n=Math.min(s,this.maxBackoff),i=n*(Math.random()-.5);return n+i}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let s=Qt()-e.clientClockSkew-e.serverTs/1e6,n=`${Math.round(s)}ms`,i=`${Math.round(t/1e4)/100}MB`,o=t/(s/1e3),c=`${Math.round(o/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${n} at ${c}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${i}) which will take a long time to download on slower connections`):s>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${n})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:s,messageLength:t}})}};function lo(){return Wu()}function Wu(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var St=class extends Error{};St.prototype.name="InvalidTokenError";function Qu(r){return decodeURIComponent(atob(r).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}function Hu(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Qu(e)}catch{return atob(e)}}function es(r,e){if(typeof r!="string")throw new St("Invalid token specified: must be a string");e||(e={});let t=e.header===!0?0:1,s=r.split(".")[t];if(typeof s!="string")throw new St(`Invalid token specified: missing part #${t+1}`);let n;try{n=Hu(s)}catch(i){throw new St(`Invalid token specified: invalid base64 for part #${t+1} (${i.message})`)}try{return JSON.parse(n)}catch(i){throw new St(`Invalid token specified: invalid json for part #${t+1} (${i.message})`)}}var zu=Object.defineProperty,Gu=(r,e,t)=>e in r?zu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,be=(r,e,t)=>Gu(r,typeof e!="symbol"?e+"":e,t),Ju=480*60*60*1e3,ho=2,ts=class{constructor(e,t,s){be(this,"authState",{state:"noAuth"}),be(this,"configVersion",0),be(this,"syncState"),be(this,"authenticate"),be(this,"stopSocket"),be(this,"tryRestartSocket"),be(this,"pauseSocket"),be(this,"resumeSocket"),be(this,"clearAuth"),be(this,"logger"),be(this,"refreshTokenLeewaySeconds"),be(this,"lastRefreshChange"),be(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=s.logger,this.refreshTokenLeewaySeconds=s.refreshTokenLeewaySeconds,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!=="noAuth"&&this.authState.state!=="initialRefetch"&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,s){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let n=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(n.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:s};n.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:i,hasRetried:!1}),this.authenticate(n.value)):(this.setAuthState({state:"initialRefetch",config:i}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=ho){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${ho-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state==="noAuth")return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:t.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;let t=this.decodeToken(e);if(!t){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}let{iat:s,exp:n}=t;if(!s||!n){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}let i=n-s;if(i<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let o=Math.min(Ju,(i-this.refreshTokenLeewaySeconds)*1e3);o<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${i}s`),o=0);let c=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},o);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${o}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let s=++this.configVersion;this._logVerbose(`fetching token with config version ${s}`);let n=await e(t);return this.configVersion!==s?(this._logVerbose(`stale config version, expected ${s}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:n}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:"noAuth"})}setAuthState(e){let t=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break;case"waitingForServerConfirmationOfFreshToken":case"waitingForServerConfirmationOfCachedToken":case"initialRefetch":break;default:}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return es(e)}catch(t){return this._logVerbose(`Error decoding token: ${t instanceof Error?t.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}};var Zu=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function fo(r,e){let t={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(r,{detail:t})}function Ku(r){let e=r.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:r.startTime}}function po(r){if(typeof performance>"u"||!performance.getEntriesByName)return[];let e=[];for(let t of Zu){let s=performance.getEntriesByName(t).filter(n=>n.entryType==="mark").filter(n=>n.detail.sessionId===r);e.push(...s)}return e.map(Ku)}var Yu=Object.defineProperty,Xu=(r,e,t)=>e in r?Yu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ie=(r,e,t)=>Xu(r,typeof e!="symbol"?e+"":e,t),Ht=class{constructor(e,t,s){if(ie(this,"address"),ie(this,"state"),ie(this,"requestManager"),ie(this,"webSocketManager"),ie(this,"authenticationManager"),ie(this,"remoteQuerySet"),ie(this,"optimisticQueryResults"),ie(this,"_transitionHandlerCounter",0),ie(this,"_nextRequestId"),ie(this,"_onTransitionFns",new Map),ie(this,"_sessionId"),ie(this,"firstMessageReceived",!1),ie(this,"debug"),ie(this,"logger"),ie(this,"maxObservedTimestamp"),ie(this,"connectionStateSubscribers",new Map),ie(this,"nextConnectionStateSubscriberId",0),ie(this,"_lastPublishedConnectionState"),ie(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let m=this.connectionState();if(JSON.stringify(m)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=m;for(let g of this.connectionStateSubscribers.values())g(m)}})}),ie(this,"mark",m=>{this.debug&&fo(m,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");s?.skipConvexDeploymentUrlCheck!==!0&&ur(e),s={...s};let n=s.authRefreshTokenLeewaySeconds??10,i=s.webSocketConstructor;if(!i&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");i=i||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=s.logger===!1?Ks({verbose:s.verbose??!1}):s.logger!==!0&&s.logger?s.logger:Zs({verbose:s.verbose??!1});let o=e.search("://");if(o===-1)throw new Error("Provided address was not an absolute URL.");let c=e.substring(o+3),a=e.substring(0,o),u;if(a==="http")u="ws";else if(a==="https")u="wss";else throw new Error(`Unknown parent protocol ${a}`);let l=`${u}://${c}/api/${ke}/sync`;this.state=new Qr,this.remoteQuerySet=new mr(m=>this.state.queryPath(m),this.logger),this.requestManager=new zr(this.logger,this.markConnectionStateDirty);let h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new ts(this.state,{authenticate:m=>{let g=this.state.setAuth(m);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:n}),this.optimisticQueryResults=new Zr,this.addOnTransitionHandler(m=>{t(m.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=lo();let{unsavedChangesWarning:p}=s;if(typeof window>"u"||typeof window.addEventListener>"u"){if(p===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else p!==!1&&window.addEventListener("beforeunload",m=>{if(this.requestManager.hasIncompleteRequests()){m.preventDefault();let g="Are you sure you want to leave? Your changes may not be saved.";return(m||window.event).returnValue=g,g}});this.webSocketManager=new Xr(l,{onOpen:m=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...m,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new mr(P=>this.state.queryPath(P),this.logger);let[g,O]=this.state.restart();O&&this.webSocketManager.sendMessage(O),this.webSocketManager.sendMessage(g);for(let P of this.requestManager.restart())this.webSocketManager.sendMessage(P)},onResume:()=>{let[m,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),m&&this.webSocketManager.sendMessage(m);for(let O of this.requestManager.resume())this.webSocketManager.sendMessage(O)},onMessage:m=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),m.type){case"Transition":{this.observedTimestamp(m.endVersion.ts),this.authenticationManager.onTransition(m),this.remoteQuerySet.transition(m),this.state.transition(m);let g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{m.success&&this.observedTimestamp(m.ts);let g=this.requestManager.onResponse(m);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(m);break}case"AuthError":{this.authenticationManager.onAuthError(m);break}case"FatalError":{let g=ro(this.logger,m.error);throw this.webSocketManager.terminate(),g}default:}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),s=new Map;for(let[i,o]of t){let c=this.state.queryToken(i);if(c!==null){let a={result:o,udfPath:this.state.queryPath(i),args:this.state.queryArgs(i)};s.set(c,a)}}let n=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:n.map(i=>{let o=this.optimisticQueryResults.rawQueryResult(i);return{token:i,modification:{kind:"Updated",result:o}}}),reflectedMutations:Array.from(e).map(([i,o])=>({requestId:i,result:o})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&e.tokenType==="User")try{t=e?es(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,s){this.authenticationManager.setConfig(e,t,s)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let s=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(s)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,s){let n=fe(t),{modification:i,queryToken:o,unsubscribe:c}=this.state.subscribe(e,n,s?.journal,s?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:o,unsubscribe:()=>{let a=c();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,t){let s=fe(t),n=Me(e,s);return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let s=fe(t),n=Me(e,s);return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let s=fe(t),n=Me(e,s);return this.state.queryJournal(n)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,s){let n=await this.mutationInternal(e,t,s);if(!n.success)throw n.errorData!==void 0?fr(n,new Qe(Ke("mutation",e,n))):new Error(Ke("mutation",e,n));return n.value}async mutationInternal(e,t,s,n){let{mutationPromise:i}=this.enqueueMutation(e,t,s,n);return i}enqueueMutation(e,t,s,n){let i=fe(t);this.tryReportLongDisconnect();let o=this.nextRequestId;if(this._nextRequestId++,s!==void 0){let l=s.optimisticUpdate;if(l!==void 0){let h=g=>{l(g,i)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},m=this.optimisticQueryResults.applyOptimisticUpdate(h,o).map(g=>{let O=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:O===void 0?void 0:{success:!0,value:O,logLines:[]}}}});this.handleTransition({queries:m,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let c={type:"Mutation",requestId:o,udfPath:e,componentPath:n,args:[oe(i)]},a=this.webSocketManager.sendMessage(c),u=this.requestManager.request(c,a);return{requestId:o,mutationPromise:u}}async action(e,t){let s=await this.actionInternal(e,t);if(!s.success)throw s.errorData!==void 0?fr(s,new Qe(Ke("action",e,s))):new Error(Ke("action",e,s));return s.value}async actionInternal(e,t,s){let n=fe(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let o={type:"Action",requestId:i,udfPath:e,componentPath:s,args:[oe(n)]},c=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,c)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let e=po(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${ke}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(s=>{s.ok||this.logger.warn("Analytics request failed with response:",s.body)}).catch(s=>{this.logger.warn("Analytics response failed with error:",s)})}};import{createRequire as ol}from"module";import{resolve as al}from"path";function rs(r){if(typeof r!="object"||r===null||!Array.isArray(r.page)||typeof r.isDone!="boolean"||typeof r.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${r?.toString()}`);return r}var rl=Object.defineProperty,sl=(r,e,t)=>e in r?rl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,mo=(r,e,t)=>sl(r,typeof e!="symbol"?e+"":e,t),ss=class{constructor(e,t){this.client=e,this.onTransition=t,mo(this,"paginatedQuerySet",new Map),mo(this,"lastTransitionTs"),this.lastTransitionTs=Le.fromNumber(0),this.client.addOnTransitionHandler(s=>this.onBaseTransition(s))}subscribe(e,t,s){let n=$e(e),i=Ys(n,t,s),o=()=>this.removePaginatedQuerySubscriber(i),c=this.paginatedQuerySet.get(i);return c?(c.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:o}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:n,args:t,numSubscribers:1,options:{initialNumItems:s.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:s.id}),this.addPageToPaginatedQuery(i,null,s.initialNumItems),{paginatedQueryToken:i,unsubscribe:o})}localQueryResult(e,t,s){let n=$e(e),i=Ys(n,t,s);return this.localQueryResultByToken(i)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let s=this.activePageQueryTokens(t);if(s.length===0)return{results:[],status:"LoadingFirstPage",loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)};let n=[],i=!1,o=!1;for(let a of s){let u=this.client.localQueryResultByToken(a);if(u===void 0){i=!0,o=!1;continue}let l=rs(u);n=n.concat(l.page),o=!!l.isDone}let c;return i?c=n.length===0?"LoadingFirstPage":"LoadingMore":o?c="Exhausted":c="CanLoadMore",{results:n,status:c,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){let t=e.queries.map(o=>o.token),s=this.queriesContainingTokens(t),n=[];s.length>0&&(this.processPaginatedQuerySplits(s,o=>this.client.localQueryResultByToken(o)),n=s.map(o=>({token:o,modification:{kind:"Updated",result:this.localQueryResultByToken(o)}})));let i={...e,paginatedQueries:n};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let s=this.queryTokenForLastPageOfPaginatedQuery(e),n=this.client.localQueryResultByToken(s);if(!n)return!1;let i=rs(n);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let o={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(o),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],s=new Set(e);for(let[n,i]of this.paginatedQuerySet)for(let o of this.allQueryTokens(i))if(s.has(o)){t.push(n);break}return t}processPaginatedQuerySplits(e,t){for(let s of e){let n=this.mustGetPaginatedQuery(s),{ongoingSplits:i,pageKeyToQuery:o,pageKeys:c}=n;for(let[a,[u,l]]of i)t(o.get(u).queryToken)!==void 0&&t(o.get(l).queryToken)!==void 0&&this.completePaginatedQuerySplit(n,a,u,l);for(let a of c){if(i.has(a))continue;let u=o.get(a).queryToken,l=t(u);if(!l)continue;let h=rs(l);h.splitCursor&&(h.pageStatus==="SplitRecommended"||h.pageStatus==="SplitRequired"||h.page.length>n.options.initialNumItems*2)&&this.splitPaginatedQueryPage(n,a,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(e,t,s,n){let i=e.nextPageKey++,o=e.nextPageKey++,c={cursor:n,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...c,cursor:null,endCursor:s}});e.pageKeyToQuery.set(i,a);let u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...c,cursor:s,endCursor:n}});e.pageKeyToQuery.set(o,u),e.ongoingSplits.set(t,[i,o])}addPageToPaginatedQuery(e,t,s){let n=this.mustGetPaginatedQuery(e),i=n.nextPageKey++,o={cursor:t,numItems:s,id:n.id},c={...n.args,paginationOpts:o},a=this.client.subscribe(n.canonicalizedUdfPath,c);return n.pageKeys.push(i),n.pageKeyToQuery.set(i,a),a}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(t.numSubscribers-=1,!(t.numSubscribers>0))){for(let s of t.pageKeyToQuery.values())s.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,s,n){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let o=e.pageKeys.indexOf(t);e.pageKeys.splice(o,1,s,n),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(t=>t.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),s=t.pageKeys[t.pageKeys.length-1];if(s===void 0)throw new Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(s).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw new Error("paginated query no longer exists for token "+e);return t}};var nl=Object.defineProperty,il=(r,e,t)=>e in r?nl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zt=(r,e,t)=>il(r,typeof e!="symbol"?e+"":e,t),nn;function go(r){nn=r}var Ct=class{constructor(e,t={}){zt(this,"listeners"),zt(this,"_client"),zt(this,"_paginatedClient"),zt(this,"callNewListenersWithCurrentValuesTimer"),zt(this,"_closed"),zt(this,"_disabled"),t.skipConvexDeploymentUrlCheck!==!0&&ur(e);let{disabled:s,...n}=t;this._closed=!1,this._disabled=!!s,nn&&!("webSocketConstructor"in n)&&typeof WebSocket>"u"&&(n.webSocketConstructor=nn),typeof window>"u"&&!("unsavedChangesWarning"in n)&&(n.unsavedChangesWarning=!1),this.disabled||(this._client=new Ht(e,()=>{},n),this._paginatedClient=new ss(this._client,i=>this._transition(i))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw new Error("ConvexClient is disabled")}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw new Error("ConvexClient is disabled")}get disabled(){return this._disabled}onUpdate(e,t,s,n){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:i,unsubscribe:o}=this.client.subscribe(_e(e),t),c={queryToken:i,callback:s,onError:n,unsubscribe:o,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(c),this.queryResultReady(i)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let a={unsubscribe:()=>{this.closed||(this.listeners.delete(c),o())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},u=a.unsubscribe;return Object.assign(u,a),u}onPaginatedUpdate_experimental(e,t,s,n,i){if(this.disabled)return this.createDisabledUnsubscribe();let o={initialNumItems:s.initialNumItems,id:-1},{paginatedQueryToken:c,unsubscribe:a}=this.paginatedClient.subscribe(_e(e),t,o),u={queryToken:c,callback:n,onError:i,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:o};this.listeners.add(u),this.paginatedClient.localQueryResultByToken(c)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let l={unsubscribe:()=>{this.closed||(this.listeners.delete(u),a())},getCurrentValue:()=>this.paginatedClient.localQueryResult(_e(e),t,o),getQueryLogs:()=>[]},h=l.unsubscribe;return Object.assign(h,l),h}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>{},getQueryLogs:()=>{}}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw new Error("ConvexClient has already been closed.");this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},s=!1){let n=[...e.map(i=>i.token),...t.map(i=>i.token)];for(let i of this.listeners){let{callback:o,queryToken:c,onError:a,hasEverRun:u}=i,l=so(c),h=l?!!this.paginatedClient.localQueryResultByToken(c):this.client.hasLocalQueryResultByToken(c);if(n.includes(c)||s&&!u&&h){i.hasEverRun=!0;let p;try{l?p=this.paginatedClient.localQueryResultByToken(c):p=this.client.localQueryResultByToken(c)}catch(m){if(!(m instanceof Error))throw m;a?a(m,"Second argument to onUpdate onError is reserved for later use"):Promise.reject(m);continue}o(p,"Second argument to onUpdate callback is reserved for later use")}}}async mutation(e,t,s){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.mutation(_e(e),t,s)}async action(e,t){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.action(_e(e),t)}async query(e,t){if(this.disabled)throw new Error("ConvexClient is disabled");let s=this.client.localQueryResult(_e(e),t);return s!==void 0?Promise.resolve(s):new Promise((n,i)=>{let{unsubscribe:o}=this.onUpdate(e,t,c=>{o(),n(c)},c=>{o(),i(c)})})}connectionState(){if(this.disabled)throw new Error("ConvexClient is disabled");return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}};var Gt=ol(al(".")),cl=Object.create,yo=Object.defineProperty,ul=Object.getOwnPropertyDescriptor,_o=Object.getOwnPropertyNames,ll=Object.getPrototypeOf,hl=Object.prototype.hasOwnProperty,ee=(r=>typeof Gt<"u"?Gt:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof Gt<"u"?Gt:e)[t]}):r)(function(r){if(typeof Gt<"u")return Gt.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),ue=(r,e)=>function(){return e||(0,r[_o(r)[0]])((e={exports:{}}).exports,e),e.exports},dl=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _o(e))!hl.call(r,n)&&n!==t&&yo(r,n,{get:()=>e[n],enumerable:!(s=ul(e,n))||s.enumerable});return r},Xe=(r,e,t)=>(t=r!=null?cl(ll(r)):{},dl(e||!r||!r.__esModule?yo(t,"default",{value:r,enumerable:!0}):t,r)),et=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/constants.js"(r,e){"use strict";var t=["nodebuffer","arraybuffer","fragments"],s=typeof Blob<"u";s&&t.push("blob"),e.exports={BINARY_TYPES:t,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:s,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}}),fl=ue({"../common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(r,e){var t=ee("fs"),s=ee("path"),n=ee("os"),i=typeof __webpack_require__=="function"?__non_webpack_require__:ee,o=process.config&&process.config.variables||{},c=!!process.env.PREBUILDS_ONLY,a=process.versions.modules,u=E()?"electron":T()?"node-webkit":"node",l=process.env.npm_config_arch||n.arch(),h=process.env.npm_config_platform||n.platform(),p=process.env.LIBC||(W(h)?"musl":"glibc"),m=process.env.ARM_VERSION||(l==="arm64"?"8":o.arm_version)||"",g=(process.versions.uv||"").split(".")[0];e.exports=O;function O(C){return i(O.resolve(C))}O.resolve=O.path=function(C){C=s.resolve(C||".");try{var $=i(s.join(C,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[$+"_PREBUILD"]&&(C=process.env[$+"_PREBUILD"])}catch{}if(!c){var R=j(s.join(C,"build/Release"),w);if(R)return R;var D=j(s.join(C,"build/Debug"),w);if(D)return D}var G=Ae(C);if(G)return G;var F=Ae(s.dirname(process.execPath));if(F)return F;var Te=["platform="+h,"arch="+l,"runtime="+u,"abi="+a,"uv="+g,m?"armv="+m:"","libc="+p,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"",typeof __webpack_require__=="function"?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+Te+`
34
+ loaded from: `+C+`
35
+ `);function Ae(rt){var Jt=P(s.join(rt,"prebuilds")).map(v),le=Jt.filter(k(h,l)).sort(q)[0];if(le){var Et=s.join(rt,"prebuilds",le.name),cs=P(Et).map(y),us=cs.filter(f(u,a)),vr=us.sort(d(u))[0];if(vr)return s.join(Et,vr.file)}}};function P(C){try{return t.readdirSync(C)}catch{return[]}}function j(C,$){var R=P(C).filter($);return R[0]&&s.join(C,R[0])}function w(C){return/\.node$/.test(C)}function v(C){var $=C.split("-");if($.length===2){var R=$[0],D=$[1].split("+");if(R&&D.length&&D.every(Boolean))return{name:C,platform:R,architectures:D}}}function k(C,$){return function(R){return R==null||R.platform!==C?!1:R.architectures.includes($)}}function q(C,$){return C.architectures.length-$.architectures.length}function y(C){var $=C.split("."),R=$.pop(),D={file:C,specificity:0};if(R==="node"){for(var G=0;G<$.length;G++){var F=$[G];if(F==="node"||F==="electron"||F==="node-webkit")D.runtime=F;else if(F==="napi")D.napi=!0;else if(F.slice(0,3)==="abi")D.abi=F.slice(3);else if(F.slice(0,2)==="uv")D.uv=F.slice(2);else if(F.slice(0,4)==="armv")D.armv=F.slice(4);else if(F==="glibc"||F==="musl")D.libc=F;else continue;D.specificity++}return D}}function f(C,$){return function(R){return!(R==null||R.runtime&&R.runtime!==C&&!S(R)||R.abi&&R.abi!==$&&!R.napi||R.uv&&R.uv!==g||R.armv&&R.armv!==m||R.libc&&R.libc!==p)}}function S(C){return C.runtime==="node"&&C.napi}function d(C){return function($,R){return $.runtime!==R.runtime?$.runtime===C?-1:1:$.abi!==R.abi?$.abi?-1:1:$.specificity!==R.specificity?$.specificity>R.specificity?-1:1:0}}function T(){return!!(process.versions&&process.versions.nw)}function E(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<"u"&&window.process&&window.process.type==="renderer"}function W(C){return C==="linux"&&t.existsSync("/etc/alpine-release")}O.parseTags=y,O.matchTags=f,O.compareTags=d,O.parseTuple=v,O.matchTuple=k,O.compareTuples=q}}),pl=ue({"../common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(r,e){var t=typeof __webpack_require__=="function"?__non_webpack_require__:ee;typeof t.addon=="function"?e.exports=t.addon.bind(t):e.exports=fl()}}),ml=ue({"../common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js"(r,e){"use strict";var t=(n,i,o,c,a)=>{for(var u=0;u<a;u++)o[c+u]=n[u]^i[u&3]},s=(n,i)=>{let o=n.length;for(var c=0;c<o;c++)n[c]^=i[c&3]};e.exports={mask:t,unmask:s}}}),gl=ue({"../common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js"(r,e){"use strict";try{e.exports=pl()(__dirname)}catch{e.exports=ml()}}}),ns=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/buffer-util.js"(r,e){"use strict";var{EMPTY_BUFFER:t}=et(),s=Buffer[Symbol.species];function n(u,l){if(u.length===0)return t;if(u.length===1)return u[0];let h=Buffer.allocUnsafe(l),p=0;for(let m=0;m<u.length;m++){let g=u[m];h.set(g,p),p+=g.length}return p<l?new s(h.buffer,h.byteOffset,p):h}function i(u,l,h,p,m){for(let g=0;g<m;g++)h[p+g]=u[g]^l[g&3]}function o(u,l){for(let h=0;h<u.length;h++)u[h]^=l[h&3]}function c(u){return u.length===u.buffer.byteLength?u.buffer:u.buffer.slice(u.byteOffset,u.byteOffset+u.length)}function a(u){if(a.readOnly=!0,Buffer.isBuffer(u))return u;let l;return u instanceof ArrayBuffer?l=new s(u):ArrayBuffer.isView(u)?l=new s(u.buffer,u.byteOffset,u.byteLength):(l=Buffer.from(u),a.readOnly=!1),l}if(e.exports={concat:n,mask:i,toArrayBuffer:c,toBuffer:a,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let u=gl();e.exports.mask=function(l,h,p,m,g){g<48?i(l,h,p,m,g):u.mask(l,h,p,m,g)},e.exports.unmask=function(l,h){l.length<32?o(l,h):u.unmask(l,h)}}catch{}}}),yl=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/limiter.js"(r,e){"use strict";var t=Symbol("kDone"),s=Symbol("kRun"),n=class{constructor(i){this[t]=()=>{this.pending--,this[s]()},this.concurrency=i||1/0,this.jobs=[],this.pending=0}add(i){this.jobs.push(i),this[s]()}[s](){if(this.pending!==this.concurrency&&this.jobs.length){let i=this.jobs.shift();this.pending++,i(this[t])}}};e.exports=n}}),gr=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/permessage-deflate.js"(r,e){"use strict";var t=ee("zlib"),s=ns(),n=yl(),{kStatusCode:i}=et(),o=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),a=Symbol("permessage-deflate"),u=Symbol("total-length"),l=Symbol("callback"),h=Symbol("buffers"),p=Symbol("error"),m,g=class{constructor(w){if(this._options=w||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!m){let v=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;m=new n(v)}}static get extensionName(){return"permessage-deflate"}offer(){let w={};return this._options.serverNoContextTakeover&&(w.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(w.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(w.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?w.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(w.client_max_window_bits=!0),w}accept(w){return w=this.normalizeParams(w),this.params=this._isServer?this.acceptAsServer(w):this.acceptAsClient(w),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let w=this._deflate[l];this._deflate.close(),this._deflate=null,w&&w(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(w){let v=this._options,k=w.find(q=>!(v.serverNoContextTakeover===!1&&q.server_no_context_takeover||q.server_max_window_bits&&(v.serverMaxWindowBits===!1||typeof v.serverMaxWindowBits=="number"&&v.serverMaxWindowBits>q.server_max_window_bits)||typeof v.clientMaxWindowBits=="number"&&!q.client_max_window_bits));if(!k)throw new Error("None of the extension offers can be accepted");return v.serverNoContextTakeover&&(k.server_no_context_takeover=!0),v.clientNoContextTakeover&&(k.client_no_context_takeover=!0),typeof v.serverMaxWindowBits=="number"&&(k.server_max_window_bits=v.serverMaxWindowBits),typeof v.clientMaxWindowBits=="number"?k.client_max_window_bits=v.clientMaxWindowBits:(k.client_max_window_bits===!0||v.clientMaxWindowBits===!1)&&delete k.client_max_window_bits,k}acceptAsClient(w){let v=w[0];if(this._options.clientNoContextTakeover===!1&&v.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!v.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(v.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&v.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return v}normalizeParams(w){return w.forEach(v=>{Object.keys(v).forEach(k=>{let q=v[k];if(q.length>1)throw new Error(`Parameter "${k}" must have only a single value`);if(q=q[0],k==="client_max_window_bits"){if(q!==!0){let y=+q;if(!Number.isInteger(y)||y<8||y>15)throw new TypeError(`Invalid value for parameter "${k}": ${q}`);q=y}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${k}": ${q}`)}else if(k==="server_max_window_bits"){let y=+q;if(!Number.isInteger(y)||y<8||y>15)throw new TypeError(`Invalid value for parameter "${k}": ${q}`);q=y}else if(k==="client_no_context_takeover"||k==="server_no_context_takeover"){if(q!==!0)throw new TypeError(`Invalid value for parameter "${k}": ${q}`)}else throw new Error(`Unknown parameter "${k}"`);v[k]=q})}),w}decompress(w,v,k){m.add(q=>{this._decompress(w,v,(y,f)=>{q(),k(y,f)})})}compress(w,v,k){m.add(q=>{this._compress(w,v,(y,f)=>{q(),k(y,f)})})}_decompress(w,v,k){let q=this._isServer?"client":"server";if(!this._inflate){let y=`${q}_max_window_bits`,f=typeof this.params[y]!="number"?t.Z_DEFAULT_WINDOWBITS:this.params[y];this._inflate=t.createInflateRaw({...this._options.zlibInflateOptions,windowBits:f}),this._inflate[a]=this,this._inflate[u]=0,this._inflate[h]=[],this._inflate.on("error",j),this._inflate.on("data",P)}this._inflate[l]=k,this._inflate.write(w),v&&this._inflate.write(c),this._inflate.flush(()=>{let y=this._inflate[p];if(y){this._inflate.close(),this._inflate=null,k(y);return}let f=s.concat(this._inflate[h],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[h]=[],v&&this.params[`${q}_no_context_takeover`]&&this._inflate.reset()),k(null,f)})}_compress(w,v,k){let q=this._isServer?"server":"client";if(!this._deflate){let y=`${q}_max_window_bits`,f=typeof this.params[y]!="number"?t.Z_DEFAULT_WINDOWBITS:this.params[y];this._deflate=t.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:f}),this._deflate[u]=0,this._deflate[h]=[],this._deflate.on("data",O)}this._deflate[l]=k,this._deflate.write(w),this._deflate.flush(t.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let y=s.concat(this._deflate[h],this._deflate[u]);v&&(y=new o(y.buffer,y.byteOffset,y.length-4)),this._deflate[l]=null,this._deflate[u]=0,this._deflate[h]=[],v&&this.params[`${q}_no_context_takeover`]&&this._deflate.reset(),k(null,y)})}};e.exports=g;function O(w){this[h].push(w),this[u]+=w.length}function P(w){if(this[u]+=w.length,this[a]._maxPayload<1||this[u]<=this[a]._maxPayload){this[h].push(w);return}this[p]=new RangeError("Max payload size exceeded"),this[p].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[p][i]=1009,this.removeListener("data",P),this.reset()}function j(w){if(this[a]._inflate=null,this[p]){this[l](this[p]);return}w[i]=1007,this[l](w)}}}),yr=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/validation.js"(r,e){"use strict";var{isUtf8:t}=ee("buffer"),{hasBlob:s}=et(),n=[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 i(a){return a>=1e3&&a<=1014&&a!==1004&&a!==1005&&a!==1006||a>=3e3&&a<=4999}function o(a){let u=a.length,l=0;for(;l<u;)if((a[l]&128)===0)l++;else if((a[l]&224)===192){if(l+1===u||(a[l+1]&192)!==128||(a[l]&254)===192)return!1;l+=2}else if((a[l]&240)===224){if(l+2>=u||(a[l+1]&192)!==128||(a[l+2]&192)!==128||a[l]===224&&(a[l+1]&224)===128||a[l]===237&&(a[l+1]&224)===160)return!1;l+=3}else if((a[l]&248)===240){if(l+3>=u||(a[l+1]&192)!==128||(a[l+2]&192)!==128||(a[l+3]&192)!==128||a[l]===240&&(a[l+1]&240)===128||a[l]===244&&a[l+1]>143||a[l]>244)return!1;l+=4}else return!1;return!0}function c(a){return s&&typeof a=="object"&&typeof a.arrayBuffer=="function"&&typeof a.type=="string"&&typeof a.stream=="function"&&(a[Symbol.toStringTag]==="Blob"||a[Symbol.toStringTag]==="File")}if(e.exports={isBlob:c,isValidStatusCode:i,isValidUTF8:o,tokenChars:n},t)e.exports.isValidUTF8=function(a){return a.length<24?o(a):t(a)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let a=ee("utf-8-validate");e.exports.isValidUTF8=function(u){return u.length<32?o(u):a(u)}}catch{}}}),vo=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/receiver.js"(r,e){"use strict";var{Writable:t}=ee("stream"),s=gr(),{BINARY_TYPES:n,EMPTY_BUFFER:i,kStatusCode:o,kWebSocket:c}=et(),{concat:a,toArrayBuffer:u,unmask:l}=ns(),{isValidStatusCode:h,isValidUTF8:p}=yr(),m=Buffer[Symbol.species],g=0,O=1,P=2,j=3,w=4,v=5,k=6,q=class extends t{constructor(y={}){super(),this._allowSynchronousEvents=y.allowSynchronousEvents!==void 0?y.allowSynchronousEvents:!0,this._binaryType=y.binaryType||n[0],this._extensions=y.extensions||{},this._isServer=!!y.isServer,this._maxPayload=y.maxPayload|0,this._skipUTF8Validation=!!y.skipUTF8Validation,this[c]=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=g}_write(y,f,S){if(this._opcode===8&&this._state==g)return S();this._bufferedBytes+=y.length,this._buffers.push(y),this.startLoop(S)}consume(y){if(this._bufferedBytes-=y,y===this._buffers[0].length)return this._buffers.shift();if(y<this._buffers[0].length){let S=this._buffers[0];return this._buffers[0]=new m(S.buffer,S.byteOffset+y,S.length-y),new m(S.buffer,S.byteOffset,y)}let f=Buffer.allocUnsafe(y);do{let S=this._buffers[0],d=f.length-y;y>=S.length?f.set(this._buffers.shift(),d):(f.set(new Uint8Array(S.buffer,S.byteOffset,y),d),this._buffers[0]=new m(S.buffer,S.byteOffset+y,S.length-y)),y-=S.length}while(y>0);return f}startLoop(y){this._loop=!0;do switch(this._state){case g:this.getInfo(y);break;case O:this.getPayloadLength16(y);break;case P:this.getPayloadLength64(y);break;case j:this.getMask();break;case w:this.getData(y);break;case v:case k:this._loop=!1;return}while(this._loop);this._errored||y()}getInfo(y){if(this._bufferedBytes<2){this._loop=!1;return}let f=this.consume(2);if((f[0]&48)!==0){let d=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");y(d);return}let S=(f[0]&64)===64;if(S&&!this._extensions[s.extensionName]){let d=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");y(d);return}if(this._fin=(f[0]&128)===128,this._opcode=f[0]&15,this._payloadLength=f[1]&127,this._opcode===0){if(S){let d=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");y(d);return}if(!this._fragmented){let d=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");y(d);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let d=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");y(d);return}this._compressed=S}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let d=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");y(d);return}if(S){let d=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");y(d);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let d=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");y(d);return}}else{let d=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");y(d);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(f[1]&128)===128,this._isServer){if(!this._masked){let d=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");y(d);return}}else if(this._masked){let d=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");y(d);return}this._payloadLength===126?this._state=O:this._payloadLength===127?this._state=P:this.haveLength(y)}getPayloadLength16(y){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(y)}getPayloadLength64(y){if(this._bufferedBytes<8){this._loop=!1;return}let f=this.consume(8),S=f.readUInt32BE(0);if(S>Math.pow(2,21)-1){let d=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");y(d);return}this._payloadLength=S*Math.pow(2,32)+f.readUInt32BE(4),this.haveLength(y)}haveLength(y){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let f=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");y(f);return}this._masked?this._state=j:this._state=w}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=w}getData(y){let f=i;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}f=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&l(f,this._mask)}if(this._opcode>7){this.controlMessage(f,y);return}if(this._compressed){this._state=v,this.decompress(f,y);return}f.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(f)),this.dataMessage(y)}decompress(y,f){this._extensions[s.extensionName].decompress(y,this._fin,(d,T)=>{if(d)return f(d);if(T.length){if(this._messageLength+=T.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let E=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");f(E);return}this._fragments.push(T)}this.dataMessage(f),this._state===g&&this.startLoop(f)})}dataMessage(y){if(!this._fin){this._state=g;return}let f=this._messageLength,S=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let d;this._binaryType==="nodebuffer"?d=a(S,f):this._binaryType==="arraybuffer"?d=u(a(S,f)):this._binaryType==="blob"?d=new Blob(S):d=S,this._allowSynchronousEvents?(this.emit("message",d,!0),this._state=g):(this._state=k,setImmediate(()=>{this.emit("message",d,!0),this._state=g,this.startLoop(y)}))}else{let d=a(S,f);if(!this._skipUTF8Validation&&!p(d)){let T=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");y(T);return}this._state===v||this._allowSynchronousEvents?(this.emit("message",d,!1),this._state=g):(this._state=k,setImmediate(()=>{this.emit("message",d,!1),this._state=g,this.startLoop(y)}))}}controlMessage(y,f){if(this._opcode===8){if(y.length===0)this._loop=!1,this.emit("conclude",1005,i),this.end();else{let S=y.readUInt16BE(0);if(!h(S)){let T=this.createError(RangeError,`invalid status code ${S}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");f(T);return}let d=new m(y.buffer,y.byteOffset+2,y.length-2);if(!this._skipUTF8Validation&&!p(d)){let T=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");f(T);return}this._loop=!1,this.emit("conclude",S,d),this.end()}this._state=g;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",y),this._state=g):(this._state=k,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",y),this._state=g,this.startLoop(f)}))}createError(y,f,S,d,T){this._loop=!1,this._errored=!0;let E=new y(S?`Invalid WebSocket frame: ${f}`:f);return Error.captureStackTrace(E,this.createError),E.code=T,E[o]=d,E}};e.exports=q}}),bo=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/sender.js"(r,e){"use strict";var{Duplex:t}=ee("stream"),{randomFillSync:s}=ee("crypto"),{types:{isUint8Array:n}}=ee("util"),i=gr(),{EMPTY_BUFFER:o,kWebSocket:c,NOOP:a}=et(),{isBlob:u,isValidStatusCode:l}=yr(),{mask:h,toBuffer:p}=ns(),m=Symbol("kByteLength"),g=Buffer.alloc(4),O=8*1024,P,j=O,w=0,v=1,k=2,q=class kt{constructor(d,T,E){this._extensions=T||{},E&&(this._generateMask=E,this._maskBuffer=Buffer.alloc(4)),this._socket=d,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=a,this[c]=void 0}static frame(d,T){let E,W=!1,C=2,$=!1;T.mask&&(E=T.maskBuffer||g,T.generateMask?T.generateMask(E):(j===O&&(P===void 0&&(P=Buffer.alloc(O)),s(P,0,O),j=0),E[0]=P[j++],E[1]=P[j++],E[2]=P[j++],E[3]=P[j++]),$=(E[0]|E[1]|E[2]|E[3])===0,C=6);let R;typeof d=="string"?(!T.mask||$)&&T[m]!==void 0?R=T[m]:(d=Buffer.from(d),R=d.length):(R=d.length,W=T.mask&&T.readOnly&&!$);let D=R;R>=65536?(C+=8,D=127):R>125&&(C+=2,D=126);let G=Buffer.allocUnsafe(W?R+C:C);return G[0]=T.fin?T.opcode|128:T.opcode,T.rsv1&&(G[0]|=64),G[1]=D,D===126?G.writeUInt16BE(R,2):D===127&&(G[2]=G[3]=0,G.writeUIntBE(R,4,6)),T.mask?(G[1]|=128,G[C-4]=E[0],G[C-3]=E[1],G[C-2]=E[2],G[C-1]=E[3],$?[G,d]:W?(h(d,E,G,C,R),[G]):(h(d,E,d,0,R),[G,d])):[G,d]}close(d,T,E,W){let C;if(d===void 0)C=o;else{if(typeof d!="number"||!l(d))throw new TypeError("First argument must be a valid error code number");if(T===void 0||!T.length)C=Buffer.allocUnsafe(2),C.writeUInt16BE(d,0);else{let R=Buffer.byteLength(T);if(R>123)throw new RangeError("The message must not be greater than 123 bytes");if(C=Buffer.allocUnsafe(2+R),C.writeUInt16BE(d,0),typeof T=="string")C.write(T,2);else if(n(T))C.set(T,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let $={[m]:C.length,fin:!0,generateMask:this._generateMask,mask:E,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,C,!1,$,W]):this.sendFrame(kt.frame(C,$),W)}ping(d,T,E){let W,C;if(typeof d=="string"?(W=Buffer.byteLength(d),C=!1):u(d)?(W=d.size,C=!1):(d=p(d),W=d.length,C=p.readOnly),W>125)throw new RangeError("The data size must not be greater than 125 bytes");let $={[m]:W,fin:!0,generateMask:this._generateMask,mask:T,maskBuffer:this._maskBuffer,opcode:9,readOnly:C,rsv1:!1};u(d)?this._state!==w?this.enqueue([this.getBlobData,d,!1,$,E]):this.getBlobData(d,!1,$,E):this._state!==w?this.enqueue([this.dispatch,d,!1,$,E]):this.sendFrame(kt.frame(d,$),E)}pong(d,T,E){let W,C;if(typeof d=="string"?(W=Buffer.byteLength(d),C=!1):u(d)?(W=d.size,C=!1):(d=p(d),W=d.length,C=p.readOnly),W>125)throw new RangeError("The data size must not be greater than 125 bytes");let $={[m]:W,fin:!0,generateMask:this._generateMask,mask:T,maskBuffer:this._maskBuffer,opcode:10,readOnly:C,rsv1:!1};u(d)?this._state!==w?this.enqueue([this.getBlobData,d,!1,$,E]):this.getBlobData(d,!1,$,E):this._state!==w?this.enqueue([this.dispatch,d,!1,$,E]):this.sendFrame(kt.frame(d,$),E)}send(d,T,E){let W=this._extensions[i.extensionName],C=T.binary?2:1,$=T.compress,R,D;typeof d=="string"?(R=Buffer.byteLength(d),D=!1):u(d)?(R=d.size,D=!1):(d=p(d),R=d.length,D=p.readOnly),this._firstFragment?(this._firstFragment=!1,$&&W&&W.params[W._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&($=R>=W._threshold),this._compress=$):($=!1,C=0),T.fin&&(this._firstFragment=!0);let G={[m]:R,fin:T.fin,generateMask:this._generateMask,mask:T.mask,maskBuffer:this._maskBuffer,opcode:C,readOnly:D,rsv1:$};u(d)?this._state!==w?this.enqueue([this.getBlobData,d,this._compress,G,E]):this.getBlobData(d,this._compress,G,E):this._state!==w?this.enqueue([this.dispatch,d,this._compress,G,E]):this.dispatch(d,this._compress,G,E)}getBlobData(d,T,E,W){this._bufferedBytes+=E[m],this._state=k,d.arrayBuffer().then(C=>{if(this._socket.destroyed){let R=new Error("The socket was closed while the blob was being read");process.nextTick(y,this,R,W);return}this._bufferedBytes-=E[m];let $=p(C);T?this.dispatch($,T,E,W):(this._state=w,this.sendFrame(kt.frame($,E),W),this.dequeue())}).catch(C=>{process.nextTick(f,this,C,W)})}dispatch(d,T,E,W){if(!T){this.sendFrame(kt.frame(d,E),W);return}let C=this._extensions[i.extensionName];this._bufferedBytes+=E[m],this._state=v,C.compress(d,E.fin,($,R)=>{if(this._socket.destroyed){let D=new Error("The socket was closed while data was being compressed");y(this,D,W);return}this._bufferedBytes-=E[m],this._state=w,E.readOnly=!1,this.sendFrame(kt.frame(R,E),W),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){let d=this._queue.shift();this._bufferedBytes-=d[3][m],Reflect.apply(d[0],this,d.slice(1))}}enqueue(d){this._bufferedBytes+=d[3][m],this._queue.push(d)}sendFrame(d,T){d.length===2?(this._socket.cork(),this._socket.write(d[0]),this._socket.write(d[1],T),this._socket.uncork()):this._socket.write(d[0],T)}};e.exports=q;function y(S,d,T){typeof T=="function"&&T(d);for(let E=0;E<S._queue.length;E++){let W=S._queue[E],C=W[W.length-1];typeof C=="function"&&C(d)}}function f(S,d,T){y(S,d,T),S.onerror(d)}}}),_l=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/event-target.js"(r,e){"use strict";var{kForOnEventAttribute:t,kListener:s}=et(),n=Symbol("kCode"),i=Symbol("kData"),o=Symbol("kError"),c=Symbol("kMessage"),a=Symbol("kReason"),u=Symbol("kTarget"),l=Symbol("kType"),h=Symbol("kWasClean"),p=class{constructor(w){this[u]=null,this[l]=w}get target(){return this[u]}get type(){return this[l]}};Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});var m=class extends p{constructor(w,v={}){super(w),this[n]=v.code===void 0?0:v.code,this[a]=v.reason===void 0?"":v.reason,this[h]=v.wasClean===void 0?!1:v.wasClean}get code(){return this[n]}get reason(){return this[a]}get wasClean(){return this[h]}};Object.defineProperty(m.prototype,"code",{enumerable:!0}),Object.defineProperty(m.prototype,"reason",{enumerable:!0}),Object.defineProperty(m.prototype,"wasClean",{enumerable:!0});var g=class extends p{constructor(w,v={}){super(w),this[o]=v.error===void 0?null:v.error,this[c]=v.message===void 0?"":v.message}get error(){return this[o]}get message(){return this[c]}};Object.defineProperty(g.prototype,"error",{enumerable:!0}),Object.defineProperty(g.prototype,"message",{enumerable:!0});var O=class extends p{constructor(w,v={}){super(w),this[i]=v.data===void 0?null:v.data}get data(){return this[i]}};Object.defineProperty(O.prototype,"data",{enumerable:!0});var P={addEventListener(w,v,k={}){for(let y of this.listeners(w))if(!k[t]&&y[s]===v&&!y[t])return;let q;if(w==="message")q=function(f,S){let d=new O("message",{data:S?f:f.toString()});d[u]=this,j(v,this,d)};else if(w==="close")q=function(f,S){let d=new m("close",{code:f,reason:S.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});d[u]=this,j(v,this,d)};else if(w==="error")q=function(f){let S=new g("error",{error:f,message:f.message});S[u]=this,j(v,this,S)};else if(w==="open")q=function(){let f=new p("open");f[u]=this,j(v,this,f)};else return;q[t]=!!k[t],q[s]=v,k.once?this.once(w,q):this.on(w,q)},removeEventListener(w,v){for(let k of this.listeners(w))if(k[s]===v&&!k[t]){this.removeListener(w,k);break}}};e.exports={CloseEvent:m,ErrorEvent:g,Event:p,EventTarget:P,MessageEvent:O};function j(w,v,k){typeof w=="object"&&w.handleEvent?w.handleEvent.call(w,k):w.call(v,k)}}}),on=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/extension.js"(r,e){"use strict";var{tokenChars:t}=yr();function s(o,c,a){o[c]===void 0?o[c]=[a]:o[c].push(a)}function n(o){let c=Object.create(null),a=Object.create(null),u=!1,l=!1,h=!1,p,m,g=-1,O=-1,P=-1,j=0;for(;j<o.length;j++)if(O=o.charCodeAt(j),p===void 0)if(P===-1&&t[O]===1)g===-1&&(g=j);else if(j!==0&&(O===32||O===9))P===-1&&g!==-1&&(P=j);else if(O===59||O===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${j}`);P===-1&&(P=j);let v=o.slice(g,P);O===44?(s(c,v,a),a=Object.create(null)):p=v,g=P=-1}else throw new SyntaxError(`Unexpected character at index ${j}`);else if(m===void 0)if(P===-1&&t[O]===1)g===-1&&(g=j);else if(O===32||O===9)P===-1&&g!==-1&&(P=j);else if(O===59||O===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${j}`);P===-1&&(P=j),s(a,o.slice(g,P),!0),O===44&&(s(c,p,a),a=Object.create(null),p=void 0),g=P=-1}else if(O===61&&g!==-1&&P===-1)m=o.slice(g,j),g=P=-1;else throw new SyntaxError(`Unexpected character at index ${j}`);else if(l){if(t[O]!==1)throw new SyntaxError(`Unexpected character at index ${j}`);g===-1?g=j:u||(u=!0),l=!1}else if(h)if(t[O]===1)g===-1&&(g=j);else if(O===34&&g!==-1)h=!1,P=j;else if(O===92)l=!0;else throw new SyntaxError(`Unexpected character at index ${j}`);else if(O===34&&o.charCodeAt(j-1)===61)h=!0;else if(P===-1&&t[O]===1)g===-1&&(g=j);else if(g!==-1&&(O===32||O===9))P===-1&&(P=j);else if(O===59||O===44){if(g===-1)throw new SyntaxError(`Unexpected character at index ${j}`);P===-1&&(P=j);let v=o.slice(g,P);u&&(v=v.replace(/\\/g,""),u=!1),s(a,m,v),O===44&&(s(c,p,a),a=Object.create(null),p=void 0),m=void 0,g=P=-1}else throw new SyntaxError(`Unexpected character at index ${j}`);if(g===-1||h||O===32||O===9)throw new SyntaxError("Unexpected end of input");P===-1&&(P=j);let w=o.slice(g,P);return p===void 0?s(c,w,a):(m===void 0?s(a,w,!0):u?s(a,m,w.replace(/\\/g,"")):s(a,m,w),s(c,p,a)),c}function i(o){return Object.keys(o).map(c=>{let a=o[c];return Array.isArray(a)||(a=[a]),a.map(u=>[c].concat(Object.keys(u).map(l=>{let h=u[l];return Array.isArray(h)||(h=[h]),h.map(p=>p===!0?l:`${l}=${p}`).join("; ")})).join("; ")).join(", ")}).join(", ")}e.exports={format:i,parse:n}}}),an=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/websocket.js"(r,e){"use strict";var t=ee("events"),s=ee("https"),n=ee("http"),i=ee("net"),o=ee("tls"),{randomBytes:c,createHash:a}=ee("crypto"),{Duplex:u,Readable:l}=ee("stream"),{URL:h}=ee("url"),p=gr(),m=vo(),g=bo(),{isBlob:O}=yr(),{BINARY_TYPES:P,CLOSE_TIMEOUT:j,EMPTY_BUFFER:w,GUID:v,kForOnEventAttribute:k,kListener:q,kStatusCode:y,kWebSocket:f,NOOP:S}=et(),{EventTarget:{addEventListener:d,removeEventListener:T}}=_l(),{format:E,parse:W}=on(),{toBuffer:C}=ns(),$=Symbol("kAborted"),R=[8,13],D=["CONNECTING","OPEN","CLOSING","CLOSED"],G=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,F=class re extends t{constructor(b,V,Q){super(),this._binaryType=P[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=w,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=re.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,b!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,V===void 0?V=[]:Array.isArray(V)||(typeof V=="object"&&V!==null?(Q=V,V=[]):V=[V]),Te(this,b,V,Q)):(this._autoPong=Q.autoPong,this._closeTimeout=Q.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(b){P.includes(b)&&(this._binaryType=b,this._receiver&&(this._receiver._binaryType=b))}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(b,V,Q){let N=new m({allowSynchronousEvents:Q.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:Q.maxPayload,skipUTF8Validation:Q.skipUTF8Validation}),X=new g(b,this._extensions,Q.generateMask);this._receiver=N,this._sender=X,this._socket=b,N[f]=this,X[f]=this,b[f]=this,N.on("conclude",cs),N.on("drain",us),N.on("error",vr),N.on("message",Eo),N.on("ping",To),N.on("pong",Oo),X.onerror=Ao,b.setTimeout&&b.setTimeout(0),b.setNoDelay&&b.setNoDelay(),V.length>0&&b.unshift(V),b.on("close",mn),b.on("data",br),b.on("end",gn),b.on("error",yn),this._readyState=re.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=re.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=re.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(b,V){if(this.readyState!==re.CLOSED){if(this.readyState===re.CONNECTING){le(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===re.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=re.CLOSING,this._sender.close(b,V,!this._isServer,Q=>{Q||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),pn(this)}}pause(){this.readyState===re.CONNECTING||this.readyState===re.CLOSED||(this._paused=!0,this._socket.pause())}ping(b,V,Q){if(this.readyState===re.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof b=="function"?(Q=b,b=V=void 0):typeof V=="function"&&(Q=V,V=void 0),typeof b=="number"&&(b=b.toString()),this.readyState!==re.OPEN){Et(this,b,Q);return}V===void 0&&(V=!this._isServer),this._sender.ping(b||w,V,Q)}pong(b,V,Q){if(this.readyState===re.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof b=="function"?(Q=b,b=V=void 0):typeof V=="function"&&(Q=V,V=void 0),typeof b=="number"&&(b=b.toString()),this.readyState!==re.OPEN){Et(this,b,Q);return}V===void 0&&(V=!this._isServer),this._sender.pong(b||w,V,Q)}resume(){this.readyState===re.CONNECTING||this.readyState===re.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(b,V,Q){if(this.readyState===re.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof V=="function"&&(Q=V,V={}),typeof b=="number"&&(b=b.toString()),this.readyState!==re.OPEN){Et(this,b,Q);return}let N={binary:typeof b!="string",mask:!this._isServer,compress:!0,fin:!0,...V};this._extensions[p.extensionName]||(N.compress=!1),this._sender.send(b||w,N,Q)}terminate(){if(this.readyState!==re.CLOSED){if(this.readyState===re.CONNECTING){le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=re.CLOSING,this._socket.destroy())}}};Object.defineProperty(F,"CONNECTING",{enumerable:!0,value:D.indexOf("CONNECTING")}),Object.defineProperty(F.prototype,"CONNECTING",{enumerable:!0,value:D.indexOf("CONNECTING")}),Object.defineProperty(F,"OPEN",{enumerable:!0,value:D.indexOf("OPEN")}),Object.defineProperty(F.prototype,"OPEN",{enumerable:!0,value:D.indexOf("OPEN")}),Object.defineProperty(F,"CLOSING",{enumerable:!0,value:D.indexOf("CLOSING")}),Object.defineProperty(F.prototype,"CLOSING",{enumerable:!0,value:D.indexOf("CLOSING")}),Object.defineProperty(F,"CLOSED",{enumerable:!0,value:D.indexOf("CLOSED")}),Object.defineProperty(F.prototype,"CLOSED",{enumerable:!0,value:D.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(_=>{Object.defineProperty(F.prototype,_,{enumerable:!0})}),["open","error","close","message"].forEach(_=>{Object.defineProperty(F.prototype,`on${_}`,{enumerable:!0,get(){for(let b of this.listeners(_))if(b[k])return b[q];return null},set(b){for(let V of this.listeners(_))if(V[k]){this.removeListener(_,V);break}typeof b=="function"&&this.addEventListener(_,b,{[k]:!0})}})}),F.prototype.addEventListener=d,F.prototype.removeEventListener=T,e.exports=F;function Te(_,b,V,Q){let N={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:j,protocolVersion:R[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...Q,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(_._autoPong=N.autoPong,_._closeTimeout=N.closeTimeout,!R.includes(N.protocolVersion))throw new RangeError(`Unsupported protocol version: ${N.protocolVersion} (supported versions: ${R.join(", ")})`);let X;if(b instanceof h)X=b;else try{X=new h(b)}catch{throw new SyntaxError(`Invalid URL: ${b}`)}X.protocol==="http:"?X.protocol="ws:":X.protocol==="https:"&&(X.protocol="wss:"),_._url=X.href;let Tt=X.protocol==="wss:",Ot=X.protocol==="ws+unix:",Zt;if(X.protocol!=="ws:"&&!Tt&&!Ot?Zt=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:Ot&&!X.pathname?Zt="The URL's pathname is empty":X.hash&&(Zt="The URL contains a fragment identifier"),Zt){let Y=new SyntaxError(Zt);if(_._redirects===0)throw Y;Ae(_,Y);return}let _n=Tt?443:80,vn=c(16).toString("base64"),bn=Tt?s.request:n.request,Kt=new Set,Yt;if(N.createConnection=N.createConnection||(Tt?Jt:rt),N.defaultPort=N.defaultPort||_n,N.port=X.port||_n,N.host=X.hostname.startsWith("[")?X.hostname.slice(1,-1):X.hostname,N.headers={...N.headers,"Sec-WebSocket-Version":N.protocolVersion,"Sec-WebSocket-Key":vn,Connection:"Upgrade",Upgrade:"websocket"},N.path=X.pathname+X.search,N.timeout=N.handshakeTimeout,N.perMessageDeflate&&(Yt=new p({...N.perMessageDeflate,isServer:!1,maxPayload:N.maxPayload}),N.headers["Sec-WebSocket-Extensions"]=E({[p.extensionName]:Yt.offer()})),V.length){for(let Y of V){if(typeof Y!="string"||!G.test(Y)||Kt.has(Y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");Kt.add(Y)}N.headers["Sec-WebSocket-Protocol"]=V.join(",")}if(N.origin&&(N.protocolVersion<13?N.headers["Sec-WebSocket-Origin"]=N.origin:N.headers.Origin=N.origin),(X.username||X.password)&&(N.auth=`${X.username}:${X.password}`),Ot){let Y=N.path.split(":");N.socketPath=Y[0],N.path=Y[1]}let ae;if(N.followRedirects){if(_._redirects===0){_._originalIpc=Ot,_._originalSecure=Tt,_._originalHostOrSocketPath=Ot?N.socketPath:X.host;let Y=Q&&Q.headers;if(Q={...Q,headers:{}},Y)for(let[me,At]of Object.entries(Y))Q.headers[me.toLowerCase()]=At}else if(_.listenerCount("redirect")===0){let Y=Ot?_._originalIpc?N.socketPath===_._originalHostOrSocketPath:!1:_._originalIpc?!1:X.host===_._originalHostOrSocketPath;(!Y||_._originalSecure&&!Tt)&&(delete N.headers.authorization,delete N.headers.cookie,Y||delete N.headers.host,N.auth=void 0)}N.auth&&!Q.headers.authorization&&(Q.headers.authorization="Basic "+Buffer.from(N.auth).toString("base64")),ae=_._req=bn(N),_._redirects&&_.emit("redirect",_.url,ae)}else ae=_._req=bn(N);N.timeout&&ae.on("timeout",()=>{le(_,ae,"Opening handshake has timed out")}),ae.on("error",Y=>{ae===null||ae[$]||(ae=_._req=null,Ae(_,Y))}),ae.on("response",Y=>{let me=Y.headers.location,At=Y.statusCode;if(me&&N.followRedirects&&At>=300&&At<400){if(++_._redirects>N.maxRedirects){le(_,ae,"Maximum redirects exceeded");return}ae.abort();let Xt;try{Xt=new h(me,b)}catch{let Rt=new SyntaxError(`Invalid URL: ${me}`);Ae(_,Rt);return}Te(_,Xt,V,Q)}else _.emit("unexpected-response",ae,Y)||le(_,ae,`Unexpected server response: ${Y.statusCode}`)}),ae.on("upgrade",(Y,me,At)=>{if(_.emit("upgrade",Y),_.readyState!==F.CONNECTING)return;ae=_._req=null;let Xt=Y.headers.upgrade;if(Xt===void 0||Xt.toLowerCase()!=="websocket"){le(_,me,"Invalid Upgrade header");return}let wn=a("sha1").update(vn+v).digest("base64");if(Y.headers["sec-websocket-accept"]!==wn){le(_,me,"Invalid Sec-WebSocket-Accept header");return}let Rt=Y.headers["sec-websocket-protocol"],er;if(Rt!==void 0?Kt.size?Kt.has(Rt)||(er="Server sent an invalid subprotocol"):er="Server sent a subprotocol but none was requested":Kt.size&&(er="Server sent no subprotocol"),er){le(_,me,er);return}Rt&&(_._protocol=Rt);let xn=Y.headers["sec-websocket-extensions"];if(xn!==void 0){if(!Yt){le(_,me,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ls;try{ls=W(xn)}catch{le(_,me,"Invalid Sec-WebSocket-Extensions header");return}let Sn=Object.keys(ls);if(Sn.length!==1||Sn[0]!==p.extensionName){le(_,me,"Server indicated an extension that was not requested");return}try{Yt.accept(ls[p.extensionName])}catch{le(_,me,"Invalid Sec-WebSocket-Extensions header");return}_._extensions[p.extensionName]=Yt}_.setSocket(me,At,{allowSynchronousEvents:N.allowSynchronousEvents,generateMask:N.generateMask,maxPayload:N.maxPayload,skipUTF8Validation:N.skipUTF8Validation})}),N.finishRequest?N.finishRequest(ae,_):ae.end()}function Ae(_,b){_._readyState=F.CLOSING,_._errorEmitted=!0,_.emit("error",b),_.emitClose()}function rt(_){return _.path=_.socketPath,i.connect(_)}function Jt(_){return _.path=void 0,!_.servername&&_.servername!==""&&(_.servername=i.isIP(_.host)?"":_.host),o.connect(_)}function le(_,b,V){_._readyState=F.CLOSING;let Q=new Error(V);Error.captureStackTrace(Q,le),b.setHeader?(b[$]=!0,b.abort(),b.socket&&!b.socket.destroyed&&b.socket.destroy(),process.nextTick(Ae,_,Q)):(b.destroy(Q),b.once("error",_.emit.bind(_,"error")),b.once("close",_.emitClose.bind(_)))}function Et(_,b,V){if(b){let Q=O(b)?b.size:C(b).length;_._socket?_._sender._bufferedBytes+=Q:_._bufferedAmount+=Q}if(V){let Q=new Error(`WebSocket is not open: readyState ${_.readyState} (${D[_.readyState]})`);process.nextTick(V,Q)}}function cs(_,b){let V=this[f];V._closeFrameReceived=!0,V._closeMessage=b,V._closeCode=_,V._socket[f]!==void 0&&(V._socket.removeListener("data",br),process.nextTick(fn,V._socket),_===1005?V.close():V.close(_,b))}function us(){let _=this[f];_.isPaused||_._socket.resume()}function vr(_){let b=this[f];b._socket[f]!==void 0&&(b._socket.removeListener("data",br),process.nextTick(fn,b._socket),b.close(_[y])),b._errorEmitted||(b._errorEmitted=!0,b.emit("error",_))}function dn(){this[f].emitClose()}function Eo(_,b){this[f].emit("message",_,b)}function To(_){let b=this[f];b._autoPong&&b.pong(_,!this._isServer,S),b.emit("ping",_)}function Oo(_){this[f].emit("pong",_)}function fn(_){_.resume()}function Ao(_){let b=this[f];b.readyState!==F.CLOSED&&(b.readyState===F.OPEN&&(b._readyState=F.CLOSING,pn(b)),this._socket.end(),b._errorEmitted||(b._errorEmitted=!0,b.emit("error",_)))}function pn(_){_._closeTimer=setTimeout(_._socket.destroy.bind(_._socket),_._closeTimeout)}function mn(){let _=this[f];if(this.removeListener("close",mn),this.removeListener("data",br),this.removeListener("end",gn),_._readyState=F.CLOSING,!this._readableState.endEmitted&&!_._closeFrameReceived&&!_._receiver._writableState.errorEmitted&&this._readableState.length!==0){let b=this.read(this._readableState.length);_._receiver.write(b)}_._receiver.end(),this[f]=void 0,clearTimeout(_._closeTimer),_._receiver._writableState.finished||_._receiver._writableState.errorEmitted?_.emitClose():(_._receiver.on("error",dn),_._receiver.on("finish",dn))}function br(_){this[f]._receiver.write(_)||this.pause()}function gn(){let _=this[f];_._readyState=F.CLOSING,_._receiver.end(),this.end()}function yn(){let _=this[f];this.removeListener("error",yn),this.on("error",S),_&&(_._readyState=F.CLOSING,this.destroy())}}}),vl=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/stream.js"(r,e){"use strict";var t=an(),{Duplex:s}=ee("stream");function n(a){a.emit("close")}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(a){this.removeListener("error",o),this.destroy(),this.listenerCount("error")===0&&this.emit("error",a)}function c(a,u){let l=!0,h=new s({...u,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return a.on("message",function(m,g){let O=!g&&h._readableState.objectMode?m.toString():m;h.push(O)||a.pause()}),a.once("error",function(m){h.destroyed||(l=!1,h.destroy(m))}),a.once("close",function(){h.destroyed||h.push(null)}),h._destroy=function(p,m){if(a.readyState===a.CLOSED){m(p),process.nextTick(n,h);return}let g=!1;a.once("error",function(P){g=!0,m(P)}),a.once("close",function(){g||m(p),process.nextTick(n,h)}),l&&a.terminate()},h._final=function(p){if(a.readyState===a.CONNECTING){a.once("open",function(){h._final(p)});return}a._socket!==null&&(a._socket._writableState.finished?(p(),h._readableState.endEmitted&&h.destroy()):(a._socket.once("finish",function(){p()}),a.close()))},h._read=function(){a.isPaused&&a.resume()},h._write=function(p,m,g){if(a.readyState===a.CONNECTING){a.once("open",function(){h._write(p,m,g)});return}a.send(p,g)},h.on("end",i),h.on("error",o),h}e.exports=c}}),wo=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/subprotocol.js"(r,e){"use strict";var{tokenChars:t}=yr();function s(n){let i=new Set,o=-1,c=-1,a=0;for(a;a<n.length;a++){let l=n.charCodeAt(a);if(c===-1&&t[l]===1)o===-1&&(o=a);else if(a!==0&&(l===32||l===9))c===-1&&o!==-1&&(c=a);else if(l===44){if(o===-1)throw new SyntaxError(`Unexpected character at index ${a}`);c===-1&&(c=a);let h=n.slice(o,c);if(i.has(h))throw new SyntaxError(`The "${h}" subprotocol is duplicated`);i.add(h),o=c=-1}else throw new SyntaxError(`Unexpected character at index ${a}`)}if(o===-1||c!==-1)throw new SyntaxError("Unexpected end of input");let u=n.slice(o,a);if(i.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);return i.add(u),i}e.exports={parse:s}}}),bl=ue({"../common/temp/node_modules/.pnpm/ws@8.20.1_bufferutil@4.0.9/node_modules/ws/lib/websocket-server.js"(r,e){"use strict";var t=ee("events"),s=ee("http"),{Duplex:n}=ee("stream"),{createHash:i}=ee("crypto"),o=on(),c=gr(),a=wo(),u=an(),{CLOSE_TIMEOUT:l,GUID:h,kWebSocket:p}=et(),m=/^[+/0-9A-Za-z]{22}==$/,g=0,O=1,P=2,j=class extends t{constructor(f,S){if(super(),f={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:l,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...f},f.port==null&&!f.server&&!f.noServer||f.port!=null&&(f.server||f.noServer)||f.server&&f.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(f.port!=null?(this._server=s.createServer((d,T)=>{let E=s.STATUS_CODES[426];T.writeHead(426,{"Content-Length":E.length,"Content-Type":"text/plain"}),T.end(E)}),this._server.listen(f.port,f.host,f.backlog,S)):f.server&&(this._server=f.server),this._server){let d=this.emit.bind(this,"connection");this._removeListeners=w(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(T,E,W)=>{this.handleUpgrade(T,E,W,d)}})}f.perMessageDeflate===!0&&(f.perMessageDeflate={}),f.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=f,this._state=g}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(f){if(this._state===P){f&&this.once("close",()=>{f(new Error("The server is not running"))}),process.nextTick(v,this);return}if(f&&this.once("close",f),this._state!==O)if(this._state=O,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(v,this):process.nextTick(v,this);else{let S=this._server;this._removeListeners(),this._removeListeners=this._server=null,S.close(()=>{v(this)})}}shouldHandle(f){if(this.options.path){let S=f.url.indexOf("?");if((S!==-1?f.url.slice(0,S):f.url)!==this.options.path)return!1}return!0}handleUpgrade(f,S,d,T){S.on("error",k);let E=f.headers["sec-websocket-key"],W=f.headers.upgrade,C=+f.headers["sec-websocket-version"];if(f.method!=="GET"){y(this,f,S,405,"Invalid HTTP method");return}if(W===void 0||W.toLowerCase()!=="websocket"){y(this,f,S,400,"Invalid Upgrade header");return}if(E===void 0||!m.test(E)){y(this,f,S,400,"Missing or invalid Sec-WebSocket-Key header");return}if(C!==13&&C!==8){y(this,f,S,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(f)){q(S,400);return}let $=f.headers["sec-websocket-protocol"],R=new Set;if($!==void 0)try{R=a.parse($)}catch{y(this,f,S,400,"Invalid Sec-WebSocket-Protocol header");return}let D=f.headers["sec-websocket-extensions"],G={};if(this.options.perMessageDeflate&&D!==void 0){let F=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let Te=o.parse(D);Te[c.extensionName]&&(F.accept(Te[c.extensionName]),G[c.extensionName]=F)}catch{y(this,f,S,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let F={origin:f.headers[`${C===8?"sec-websocket-origin":"origin"}`],secure:!!(f.socket.authorized||f.socket.encrypted),req:f};if(this.options.verifyClient.length===2){this.options.verifyClient(F,(Te,Ae,rt,Jt)=>{if(!Te)return q(S,Ae||401,rt,Jt);this.completeUpgrade(G,E,R,f,S,d,T)});return}if(!this.options.verifyClient(F))return q(S,401)}this.completeUpgrade(G,E,R,f,S,d,T)}completeUpgrade(f,S,d,T,E,W,C){if(!E.readable||!E.writable)return E.destroy();if(E[p])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>g)return q(E,503);let R=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${i("sha1").update(S+h).digest("base64")}`],D=new this.options.WebSocket(null,void 0,this.options);if(d.size){let G=this.options.handleProtocols?this.options.handleProtocols(d,T):d.values().next().value;G&&(R.push(`Sec-WebSocket-Protocol: ${G}`),D._protocol=G)}if(f[c.extensionName]){let G=f[c.extensionName].params,F=o.format({[c.extensionName]:[G]});R.push(`Sec-WebSocket-Extensions: ${F}`),D._extensions=f}this.emit("headers",R,T),E.write(R.concat(`\r
36
+ `).join(`\r
37
+ `)),E.removeListener("error",k),D.setSocket(E,W,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(D),D.on("close",()=>{this.clients.delete(D),this._shouldEmitClose&&!this.clients.size&&process.nextTick(v,this)})),C(D,T)}};e.exports=j;function w(f,S){for(let d of Object.keys(S))f.on(d,S[d]);return function(){for(let T of Object.keys(S))f.removeListener(T,S[T])}}function v(f){f._state=P,f.emit("close")}function k(){this.destroy()}function q(f,S,d,T){d=d||s.STATUS_CODES[S],T={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(d),...T},f.once("finish",f.destroy),f.end(`HTTP/1.1 ${S} ${s.STATUS_CODES[S]}\r
38
+ `+Object.keys(T).map(E=>`${E}: ${T[E]}`).join(`\r
39
+ `)+`\r
40
+ \r
41
+ `+d)}function y(f,S,d,T,E,W){if(f.listenerCount("wsClientError")){let C=new Error(E);Error.captureStackTrace(C,y),f.emit("wsClientError",C,d,S)}else q(d,T,E,W)}}}),wp=Xe(vl(),1),xp=Xe(on(),1),Sp=Xe(gr(),1),Cp=Xe(vo(),1),kp=Xe(bo(),1),Ep=Xe(wo(),1),wl=Xe(an(),1),Tp=Xe(bl(),1),xl=wl.default,Sl=xl;go(Sl);var $g=H.object({numItems:H.number(),cursor:H.union(H.string(),H.null()),endCursor:H.optional(H.union(H.string(),H.null())),id:H.optional(H.number()),maximumRowsRead:H.optional(H.number()),maximumBytesRead:H.optional(H.number())});function xo(r,e){let t={get(s,n){if(typeof n=="string"){let i=[...e,n];return xo(r,i)}else if(n===Xs){if(e.length<1){let i=[r,...e].join(".");throw new Error(`API path is expected to be of the form \`${r}.childComponent.functionName\`. Found: \`${i}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},t)}var un=()=>xo("components",[]);var Tl=Symbol("var.requestId"),Ol=Symbol("var.ip"),Al=Symbol("var.userAgent"),Rl=Symbol("var.now"),Il={[Tl]:"requestId",[Ol]:"ip",[Al]:"userAgent",[Rl]:"now"};var Pl=Object.defineProperty,Nl=(r,e,t)=>e in r?Pl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,je=(r,e,t)=>Nl(r,typeof e!="symbol"?e+"":e,t),is=class{constructor(e){je(this,"indexes"),je(this,"stagedDbIndexes"),je(this,"searchIndexes"),je(this,"stagedSearchIndexes"),je(this,"vectorIndexes"),je(this,"stagedVectorIndexes"),je(this,"validator"),this.indexes=[],this.stagedDbIndexes=[],this.searchIndexes=[],this.stagedSearchIndexes=[],this.vectorIndexes=[],this.stagedVectorIndexes=[],this.validator=e}" indexes"(){return this.indexes}index(e,t){return Array.isArray(t)?this.indexes.push({indexDescriptor:e,fields:t}):t.staged?this.stagedDbIndexes.push({indexDescriptor:e,fields:t.fields}):this.indexes.push({indexDescriptor:e,fields:t.fields}),this}searchIndex(e,t){return t.staged?this.stagedSearchIndexes.push({indexDescriptor:e,searchField:t.searchField,filterFields:t.filterFields||[]}):this.searchIndexes.push({indexDescriptor:e,searchField:t.searchField,filterFields:t.filterFields||[]}),this}vectorIndex(e,t){return t.staged?this.stagedVectorIndexes.push({indexDescriptor:e,vectorField:t.vectorField,dimensions:t.dimensions,filterFields:t.filterFields||[]}):this.vectorIndexes.push({indexDescriptor:e,vectorField:t.vectorField,dimensions:t.dimensions,filterFields:t.filterFields||[]}),this}self(){return this}export(){let e=this.validator.json;if(typeof e!="object")throw new Error("Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)");return{indexes:this.indexes,stagedDbIndexes:this.stagedDbIndexes,searchIndexes:this.searchIndexes,stagedSearchIndexes:this.stagedSearchIndexes,vectorIndexes:this.vectorIndexes,stagedVectorIndexes:this.stagedVectorIndexes,documentType:e}}};function ln(r){return Gs(r)?new is(r):new is(H.object(r))}var hn=class{constructor(e,t){je(this,"tables"),je(this,"strictTableNameTypes"),je(this,"schemaValidation"),this.tables=e,this.schemaValidation=t?.schemaValidation===void 0?!0:t.schemaValidation}export(){return JSON.stringify({tables:Object.entries(this.tables).map(([e,t])=>{let{indexes:s,stagedDbIndexes:n,searchIndexes:i,stagedSearchIndexes:o,vectorIndexes:c,stagedVectorIndexes:a,documentType:u}=t.export();return{tableName:e,indexes:s,stagedDbIndexes:n,searchIndexes:i,stagedSearchIndexes:o,vectorIndexes:c,stagedVectorIndexes:a,documentType:u}}),schemaValidation:this.schemaValidation})}};function So(r,e){return new hn(r,e)}var oy=So({_scheduled_functions:ln({name:H.string(),args:H.array(H.any()),scheduledTime:H.float64(),completedTime:H.optional(H.float64()),state:H.union(H.object({kind:H.literal("pending")}),H.object({kind:H.literal("inProgress")}),H.object({kind:H.literal("success")}),H.object({kind:H.literal("failed"),error:H.string()}),H.object({kind:H.literal("canceled")}))}),_storage:ln({sha256:H.string(),size:H.float64(),contentType:H.optional(H.string())})});var He=en;var By=un();var $l={maxBatch:25,windowMs:200,setTimer:(r,e)=>setTimeout(r,e),clearTimer:r=>clearTimeout(r)},os=class{constructor(e,t={}){this.flush=e;this.opts={...$l,...t}}flush;buffer=[];nextClientEventId=0;timer=null;opts;add(e){this.buffer.push({v:1,clientEventId:this.nextClientEventId++,event:e}),this.buffer.length>=this.opts.maxBatch?this.flushNow():this.timer===null&&(this.timer=this.opts.setTimer(()=>this.flushNow(),this.opts.windowMs))}flushNow(){if(this.timer!==null&&(this.opts.clearTimer(this.timer),this.timer=null),this.buffer.length===0)return;let e=Ml(this.buffer);this.buffer=[],this.flush(e)}};function Ml(r){let e=[];for(let t of r){let s=e[e.length-1];t.event.type==="agent.text"&&s&&s.event.type==="agent.text"&&s.event.turnId===t.event.turnId?s.event={...s.event,text:s.event.text+t.event.text}:e.push(t)}return e}async function Co(r){let e=new Ct(r.convexUrl),t=!1,s=!1,n=null,i=null,o=[],c=new Set,a=v=>{let k=n;t=!1,n=null,i=null,k&&e.mutation(He.prompts.markTurn,{promptId:k,status:v}).catch(()=>{}),l()};async function u(v){if(!v.attachments?.length)return[];let k=await e.query(He.files.attachmentUrls,{storageIds:v.attachments.map(f=>f.storageId)}),q=new Map(k.map(f=>[f.storageId,f.url])),y=[];for(let f of v.attachments){let S=q.get(f.storageId);if(S)try{let d=await fetch(S),T=Buffer.from(await d.arrayBuffer()).toString("base64");y.push({mediaType:f.mediaType,data:T})}catch{}}return y}async function l(){if(!(t||s)){s=!0;try{let v=[...o].sort((k,q)=>k.queueOrder-q.queueOrder);for(let k of v)if(await e.mutation(He.prompts.claimPrompt,{promptId:k._id})){t=!0,n=k._id;try{let y=await u(k);i=r.agent.sendPrompt(k.text,y),r.onPromptInjected?.({text:k.text,submittedBy:k.submittedBy,local:c.has(k._id)})}catch{a("failed");continue}return}}finally{s=!1}}}let h=null,p=[];r.agent.onEvent(v=>{v.type==="agent.turn_result"&&i&&v.turnId===i?a(v.success?"done":"failed"):v.type==="agent.error"&&t&&a("failed"),r.onAgentEvent?.(v),h?h.add(v):p.push(v)}),r.agent.onError(v=>{let k={type:"agent.error",message:v.message};r.onAgentEvent?.(k),h?h.add(k):p.push(k),t&&a("failed")});let m;try{m=await e.mutation(He.sessions.createSession,{cwd:r.cwd,model:r.model})}catch(v){throw await r.agent.stop(),await e.close(),v}let{sessionId:g,joinCode:O}=m,P=Promise.resolve(),j=v=>new Promise(k=>setTimeout(k,v));h=new os(v=>{P=P.then(async()=>{for(let k=0;k<3;k+=1)try{await e.mutation(He.events.appendEvents,{sessionId:g,events:v});return}catch(q){if(k===2){console.error(`Failed to mirror ${v.length} events after retries:`,q);return}await j(200*(k+1))}})});for(let v of p)h.add(v);p.length=0;let w=e.onUpdate(He.prompts.pendingPrompts,{sessionId:g},v=>{o=v,l()});return{joinCode:O,submitLocalPrompt:async v=>{let k=await e.mutation(He.prompts.submitLocalPrompt,{sessionId:g,text:v});c.add(k)},stop:async()=>{h?.flushNow(),await P,w(),await e.mutation(He.sessions.endSession,{sessionId:g}).catch(()=>{}),await e.close()}}}var ql=6e3;async function ko(r){let e=ir({cwd:r.cwd}),t=tt.createInterface({input:process.stdin,output:process.stdout,prompt:"you> "}),s=!1,n=l=>{s&&process.stdout.isTTY&&(tt.cursorTo(process.stdout,0),tt.clearLine(process.stdout,0)),console.log(l),s&&t.prompt(!0)},i=!1,o=l=>{if(l.type==="agent.text"){i||(s&&process.stdout.isTTY&&(tt.cursorTo(process.stdout,0),tt.clearLine(process.stdout,0)),process.stdout.write("claude> "),i=!0),process.stdout.write(l.text);return}i&&(process.stdout.write(`
42
+ `),i=!1);let h=Rr(l);h!==null&&n(h)},c,a=!1,u=async()=>{if(a)return;a=!0,t.close();let l=setTimeout(()=>process.exit(0),ql);try{await c?.stop(),await e.stop()}finally{clearTimeout(l),process.exit(0)}};e.onError(l=>n(`[agent error] ${l.message}`)),process.on("SIGINT",()=>{u()}),process.on("SIGTERM",()=>{u()}),process.on("uncaughtException",l=>{console.error("[fatal]",l),u()}),process.on("unhandledRejection",l=>{console.error("[fatal]",l),u()}),t.on("close",()=>{u()});try{c=await Co({convexUrl:r.convexUrl,cwd:r.cwd,model:r.model,agent:e,onAgentEvent:o,onPromptInjected:({text:l,submittedBy:h,local:p})=>{p||n(`${h}> ${l}`)}})}catch(l){console.error("Could not start the session:",l instanceof Error?l.message:l),await e.stop(),process.exit(1);return}console.log("Mob Squad session is live."),console.log(`Join: ${r.webBaseUrl}/s/${c.joinCode}`),console.log("You and everyone on the link share this agent. Type a prompt and press Enter. Ctrl+C to end."),s=!0,t.prompt(),t.on("line",l=>{let h=l.trim();h&&c?.submitLocalPrompt(h),t.prompt()})}var Ll="https://standing-mongoose-114.convex.cloud",Vl="https://mobsession.ai",as=new jn;as.name("msq").description("Mob Squad daemon");as.command("dev").description("Run a local agent session and round-trip prompts from the terminal (no cloud)").option("--cwd <dir>","working directory for the agent",process.cwd()).action(r=>Wi(r.cwd));as.command("start").description("Run a cloud session: mirror the agent to the web and inject approved prompts").option("--cwd <dir>","working directory for the agent",process.cwd()).option("--convex-url <url>","Convex deployment URL",process.env.MOB_SQUAD_CONVEX_URL??Ll).option("--web-url <url>","web app base URL for the join link",process.env.MOB_SQUAD_WEB_URL??Vl).option("--model <model>","model label for the session","claude").action(r=>{if(!r.convexUrl){console.error("Missing Convex URL. Set MOB_SQUAD_CONVEX_URL or pass --convex-url."),process.exitCode=1;return}ko({cwd:r.cwd,convexUrl:r.convexUrl,webBaseUrl:r.webUrl,model:r.model})});as.parse();
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "mobsession",
3
+ "version": "0.1.0",
4
+ "description": "Mob Squad: drive Claude Code together. A shared, collaborative Claude Code session your whole team can steer.",
5
+ "type": "module",
6
+ "bin": {
7
+ "msq": "./index.js",
8
+ "mobsession": "./index.js"
9
+ },
10
+ "engines": {
11
+ "node": ">=22"
12
+ },
13
+ "license": "MIT",
14
+ "homepage": "https://mobsession.ai",
15
+ "keywords": [
16
+ "claude",
17
+ "claude-code",
18
+ "ai",
19
+ "agent",
20
+ "pair-programming",
21
+ "mob-programming",
22
+ "cli"
23
+ ]
24
+ }