@acemarke/diffloupe 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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/dist/index.js +547 -0
  4. package/package.json +56 -0
package/dist/index.js ADDED
@@ -0,0 +1,547 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as pq}from"node:module";var hq=Object.create;var{getPrototypeOf:gq,defineProperty:r7,getOwnPropertyNames:uq}=Object;var mq=Object.prototype.hasOwnProperty;var E0=(Z,Y,X)=>{X=Z!=null?hq(gq(Z)):{};let Q=Y||!Z||!Z.__esModule?r7(X,"default",{value:Z,enumerable:!0}):X;for(let $ of uq(Z))if(!mq.call(Q,$))r7(Q,$,{get:()=>Z[$],enumerable:!0});return Q};var E1=(Z,Y)=>()=>(Y||Z((Y={exports:{}}).exports,Y),Y.exports);var O0=pq(import.meta.url);var L2=E1((dq)=>{class p8 extends Error{constructor(Z,Y,X){super(X);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=Y,this.exitCode=Z,this.nestedError=void 0}}class s7 extends p8{constructor(Z){super(1,"commander.invalidArgument",Z);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}dq.CommanderError=p8;dq.InvalidArgumentError=s7});var l6=E1((nq)=>{var{InvalidArgumentError:iq}=L2();class t7{constructor(Z,Y){switch(this.description=Y||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,Z[0]){case"<":this.required=!0,this._name=Z.slice(1,-1);break;case"[":this.required=!1,this._name=Z.slice(1,-1);break;default:this.required=!0,this._name=Z;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(Z,Y){if(Y===this.defaultValue||!Array.isArray(Y))return[Z];return Y.push(Z),Y}default(Z,Y){return this.defaultValue=Z,this.defaultValueDescription=Y,this}argParser(Z){return this.parseArg=Z,this}choices(Z){return this.argChoices=Z.slice(),this.parseArg=(Y,X)=>{if(!this.argChoices.includes(Y))throw new iq(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(Y,X);return Y},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function oq(Z){let Y=Z.name()+(Z.variadic===!0?"...":"");return Z.required?"<"+Y+">":"["+Y+"]"}nq.Argument=t7;nq.humanReadableArgName=oq});var d8=E1((tq)=>{var{humanReadableArgName:sq}=l6();class e7{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(Z){this.helpWidth=this.helpWidth??Z.helpWidth??80}visibleCommands(Z){let Y=Z.commands.filter((Q)=>!Q._hidden),X=Z._getHelpCommand();if(X&&!X._hidden)Y.push(X);if(this.sortSubcommands)Y.sort((Q,$)=>{return Q.name().localeCompare($.name())});return Y}compareOptions(Z,Y){let X=(Q)=>{return Q.short?Q.short.replace(/^-/,""):Q.long.replace(/^--/,"")};return X(Z).localeCompare(X(Y))}visibleOptions(Z){let Y=Z.options.filter((Q)=>!Q.hidden),X=Z._getHelpOption();if(X&&!X.hidden){let Q=X.short&&Z._findOption(X.short),$=X.long&&Z._findOption(X.long);if(!Q&&!$)Y.push(X);else if(X.long&&!$)Y.push(Z.createOption(X.long,X.description));else if(X.short&&!Q)Y.push(Z.createOption(X.short,X.description))}if(this.sortOptions)Y.sort(this.compareOptions);return Y}visibleGlobalOptions(Z){if(!this.showGlobalOptions)return[];let Y=[];for(let X=Z.parent;X;X=X.parent){let Q=X.options.filter(($)=>!$.hidden);Y.push(...Q)}if(this.sortOptions)Y.sort(this.compareOptions);return Y}visibleArguments(Z){if(Z._argsDescription)Z.registeredArguments.forEach((Y)=>{Y.description=Y.description||Z._argsDescription[Y.name()]||""});if(Z.registeredArguments.find((Y)=>Y.description))return Z.registeredArguments;return[]}subcommandTerm(Z){let Y=Z.registeredArguments.map((X)=>sq(X)).join(" ");return Z._name+(Z._aliases[0]?"|"+Z._aliases[0]:"")+(Z.options.length?" [options]":"")+(Y?" "+Y:"")}optionTerm(Z){return Z.flags}argumentTerm(Z){return Z.name()}longestSubcommandTermLength(Z,Y){return Y.visibleCommands(Z).reduce((X,Q)=>{return Math.max(X,this.displayWidth(Y.styleSubcommandTerm(Y.subcommandTerm(Q))))},0)}longestOptionTermLength(Z,Y){return Y.visibleOptions(Z).reduce((X,Q)=>{return Math.max(X,this.displayWidth(Y.styleOptionTerm(Y.optionTerm(Q))))},0)}longestGlobalOptionTermLength(Z,Y){return Y.visibleGlobalOptions(Z).reduce((X,Q)=>{return Math.max(X,this.displayWidth(Y.styleOptionTerm(Y.optionTerm(Q))))},0)}longestArgumentTermLength(Z,Y){return Y.visibleArguments(Z).reduce((X,Q)=>{return Math.max(X,this.displayWidth(Y.styleArgumentTerm(Y.argumentTerm(Q))))},0)}commandUsage(Z){let Y=Z._name;if(Z._aliases[0])Y=Y+"|"+Z._aliases[0];let X="";for(let Q=Z.parent;Q;Q=Q.parent)X=Q.name()+" "+X;return X+Y+" "+Z.usage()}commandDescription(Z){return Z.description()}subcommandDescription(Z){return Z.summary()||Z.description()}optionDescription(Z){let Y=[];if(Z.argChoices)Y.push(`choices: ${Z.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if(Z.defaultValue!==void 0){if(Z.required||Z.optional||Z.isBoolean()&&typeof Z.defaultValue==="boolean")Y.push(`default: ${Z.defaultValueDescription||JSON.stringify(Z.defaultValue)}`)}if(Z.presetArg!==void 0&&Z.optional)Y.push(`preset: ${JSON.stringify(Z.presetArg)}`);if(Z.envVar!==void 0)Y.push(`env: ${Z.envVar}`);if(Y.length>0){let X=`(${Y.join(", ")})`;if(Z.description)return`${Z.description} ${X}`;return X}return Z.description}argumentDescription(Z){let Y=[];if(Z.argChoices)Y.push(`choices: ${Z.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if(Z.defaultValue!==void 0)Y.push(`default: ${Z.defaultValueDescription||JSON.stringify(Z.defaultValue)}`);if(Y.length>0){let X=`(${Y.join(", ")})`;if(Z.description)return`${Z.description} ${X}`;return X}return Z.description}formatItemList(Z,Y,X){if(Y.length===0)return[];return[X.styleTitle(Z),...Y,""]}groupItems(Z,Y,X){let Q=new Map;return Z.forEach(($)=>{let W=X($);if(!Q.has(W))Q.set(W,[])}),Y.forEach(($)=>{let W=X($);if(!Q.has(W))Q.set(W,[]);Q.get(W).push($)}),Q}formatHelp(Z,Y){let X=Y.padWidth(Z,Y),Q=Y.helpWidth??80;function $(U,H){return Y.formatItem(U,X,H,Y)}let W=[`${Y.styleTitle("Usage:")} ${Y.styleUsage(Y.commandUsage(Z))}`,""],J=Y.commandDescription(Z);if(J.length>0)W=W.concat([Y.boxWrap(Y.styleCommandDescription(J),Q),""]);let z=Y.visibleArguments(Z).map((U)=>{return $(Y.styleArgumentTerm(Y.argumentTerm(U)),Y.styleArgumentDescription(Y.argumentDescription(U)))});if(W=W.concat(this.formatItemList("Arguments:",z,Y)),this.groupItems(Z.options,Y.visibleOptions(Z),(U)=>U.helpGroupHeading??"Options:").forEach((U,H)=>{let G=U.map((K)=>{return $(Y.styleOptionTerm(Y.optionTerm(K)),Y.styleOptionDescription(Y.optionDescription(K)))});W=W.concat(this.formatItemList(H,G,Y))}),Y.showGlobalOptions){let U=Y.visibleGlobalOptions(Z).map((H)=>{return $(Y.styleOptionTerm(Y.optionTerm(H)),Y.styleOptionDescription(Y.optionDescription(H)))});W=W.concat(this.formatItemList("Global Options:",U,Y))}return this.groupItems(Z.commands,Y.visibleCommands(Z),(U)=>U.helpGroup()||"Commands:").forEach((U,H)=>{let G=U.map((K)=>{return $(Y.styleSubcommandTerm(Y.subcommandTerm(K)),Y.styleSubcommandDescription(Y.subcommandDescription(K)))});W=W.concat(this.formatItemList(H,G,Y))}),W.join(`
3
+ `)}displayWidth(Z){return ZX(Z).length}styleTitle(Z){return Z}styleUsage(Z){return Z.split(" ").map((Y)=>{if(Y==="[options]")return this.styleOptionText(Y);if(Y==="[command]")return this.styleSubcommandText(Y);if(Y[0]==="["||Y[0]==="<")return this.styleArgumentText(Y);return this.styleCommandText(Y)}).join(" ")}styleCommandDescription(Z){return this.styleDescriptionText(Z)}styleOptionDescription(Z){return this.styleDescriptionText(Z)}styleSubcommandDescription(Z){return this.styleDescriptionText(Z)}styleArgumentDescription(Z){return this.styleDescriptionText(Z)}styleDescriptionText(Z){return Z}styleOptionTerm(Z){return this.styleOptionText(Z)}styleSubcommandTerm(Z){return Z.split(" ").map((Y)=>{if(Y==="[options]")return this.styleOptionText(Y);if(Y[0]==="["||Y[0]==="<")return this.styleArgumentText(Y);return this.styleSubcommandText(Y)}).join(" ")}styleArgumentTerm(Z){return this.styleArgumentText(Z)}styleOptionText(Z){return Z}styleArgumentText(Z){return Z}styleSubcommandText(Z){return Z}styleCommandText(Z){return Z}padWidth(Z,Y){return Math.max(Y.longestOptionTermLength(Z,Y),Y.longestGlobalOptionTermLength(Z,Y),Y.longestSubcommandTermLength(Z,Y),Y.longestArgumentTermLength(Z,Y))}preformatted(Z){return/\n[^\S\r\n]/.test(Z)}formatItem(Z,Y,X,Q){let W=" ".repeat(2);if(!X)return W+Z;let J=Z.padEnd(Y+Z.length-Q.displayWidth(Z)),z=2,q=(this.helpWidth??80)-Y-z-2,U;if(q<this.minWidthToWrap||Q.preformatted(X))U=X;else U=Q.boxWrap(X,q).replace(/\n/g,`
4
+ `+" ".repeat(Y+z));return W+J+" ".repeat(z)+U.replace(/\n/g,`
5
+ ${W}`)}boxWrap(Z,Y){if(Y<this.minWidthToWrap)return Z;let X=Z.split(/\r\n|\n/),Q=/[\s]*[^\s]+/g,$=[];return X.forEach((W)=>{let J=W.match(Q);if(J===null){$.push("");return}let z=[J.shift()],V=this.displayWidth(z[0]);J.forEach((q)=>{let U=this.displayWidth(q);if(V+U<=Y){z.push(q),V+=U;return}$.push(z.join(""));let H=q.trimStart();z=[H],V=this.displayWidth(H)}),$.push(z.join(""))}),$.join(`
6
+ `)}}function ZX(Z){let Y=/\x1b\[\d*(;\d*)*m/g;return Z.replace(Y,"")}tq.Help=e7;tq.stripColor=ZX});var c8=E1((QU)=>{var{InvalidArgumentError:YU}=L2();class XX{constructor(Z,Y){this.flags=Z,this.description=Y||"",this.required=Z.includes("<"),this.optional=Z.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(Z),this.mandatory=!1;let X=XU(Z);if(this.short=X.shortFlag,this.long=X.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,this.helpGroupHeading=void 0}default(Z,Y){return this.defaultValue=Z,this.defaultValueDescription=Y,this}preset(Z){return this.presetArg=Z,this}conflicts(Z){return this.conflictsWith=this.conflictsWith.concat(Z),this}implies(Z){let Y=Z;if(typeof Z==="string")Y={[Z]:!0};return this.implied=Object.assign(this.implied||{},Y),this}env(Z){return this.envVar=Z,this}argParser(Z){return this.parseArg=Z,this}makeOptionMandatory(Z=!0){return this.mandatory=!!Z,this}hideHelp(Z=!0){return this.hidden=!!Z,this}_collectValue(Z,Y){if(Y===this.defaultValue||!Array.isArray(Y))return[Z];return Y.push(Z),Y}choices(Z){return this.argChoices=Z.slice(),this.parseArg=(Y,X)=>{if(!this.argChoices.includes(Y))throw new YU(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(Y,X);return Y},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return YX(this.name().replace(/^no-/,""));return YX(this.name())}helpGroup(Z){return this.helpGroupHeading=Z,this}is(Z){return this.short===Z||this.long===Z}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class QX{constructor(Z){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,Z.forEach((Y)=>{if(Y.negate)this.negativeOptions.set(Y.attributeName(),Y);else this.positiveOptions.set(Y.attributeName(),Y)}),this.negativeOptions.forEach((Y,X)=>{if(this.positiveOptions.has(X))this.dualOptions.add(X)})}valueFromOption(Z,Y){let X=Y.attributeName();if(!this.dualOptions.has(X))return!0;let Q=this.negativeOptions.get(X).presetArg,$=Q!==void 0?Q:!1;return Y.negate===($===Z)}}function YX(Z){return Z.split("-").reduce((Y,X)=>{return Y+X[0].toUpperCase()+X.slice(1)})}function XU(Z){let Y,X,Q=/^-[^-]$/,$=/^--[^-]/,W=Z.split(/[ |,]+/).concat("guard");if(Q.test(W[0]))Y=W.shift();if($.test(W[0]))X=W.shift();if(!Y&&Q.test(W[0]))Y=W.shift();if(!Y&&$.test(W[0]))Y=X,X=W.shift();if(W[0].startsWith("-")){let J=W[0],z=`option creation failed due to '${J}' in option flags '${Z}'`;if(/^-[^-][^-]/.test(J))throw new Error(`${z}
7
+ - a short flag is a single dash and a single character
8
+ - either use a single dash and a single character (for a short flag)
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Q.test(J))throw new Error(`${z}
10
+ - too many short flags`);if($.test(J))throw new Error(`${z}
11
+ - too many long flags`);throw new Error(`${z}
12
+ - unrecognised flag format`)}if(Y===void 0&&X===void 0)throw new Error(`option creation failed due to no flags found in '${Z}'.`);return{shortFlag:Y,longFlag:X}}QU.Option=XX;QU.DualOptions=QX});var $X=E1((VU)=>{function JU(Z,Y){if(Math.abs(Z.length-Y.length)>3)return Math.max(Z.length,Y.length);let X=[];for(let Q=0;Q<=Z.length;Q++)X[Q]=[Q];for(let Q=0;Q<=Y.length;Q++)X[0][Q]=Q;for(let Q=1;Q<=Y.length;Q++)for(let $=1;$<=Z.length;$++){let W=1;if(Z[$-1]===Y[Q-1])W=0;else W=1;if(X[$][Q]=Math.min(X[$-1][Q]+1,X[$][Q-1]+1,X[$-1][Q-1]+W),$>1&&Q>1&&Z[$-1]===Y[Q-2]&&Z[$-2]===Y[Q-1])X[$][Q]=Math.min(X[$][Q],X[$-2][Q-2]+1)}return X[Z.length][Y.length]}function zU(Z,Y){if(!Y||Y.length===0)return"";Y=Array.from(new Set(Y));let X=Z.startsWith("--");if(X)Z=Z.slice(2),Y=Y.map((J)=>J.slice(2));let Q=[],$=3,W=0.4;if(Y.forEach((J)=>{if(J.length<=1)return;let z=JU(Z,J),V=Math.max(Z.length,J.length);if((V-z)/V>W){if(z<$)$=z,Q=[J];else if(z===$)Q.push(J)}}),Q.sort((J,z)=>J.localeCompare(z)),X)Q=Q.map((J)=>`--${J}`);if(Q.length>1)return`
13
+ (Did you mean one of ${Q.join(", ")}?)`;if(Q.length===1)return`
14
+ (Did you mean ${Q[0]}?)`;return""}VU.suggestSimilar=zU});var VX=E1((MU)=>{var UU=O0("node:events").EventEmitter,l8=O0("node:child_process"),P0=O0("node:path"),i6=O0("node:fs"),l=O0("node:process"),{Argument:HU,humanReadableArgName:GU}=l6(),{CommanderError:i8}=L2(),{Help:KU,stripColor:BU}=d8(),{Option:WX,DualOptions:LU}=c8(),{suggestSimilar:JX}=$X();class n8 extends UU{constructor(Z){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=Z||"",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:(Y)=>l.stdout.write(Y),writeErr:(Y)=>l.stderr.write(Y),outputError:(Y,X)=>X(Y),getOutHelpWidth:()=>l.stdout.isTTY?l.stdout.columns:void 0,getErrHelpWidth:()=>l.stderr.isTTY?l.stderr.columns:void 0,getOutHasColors:()=>o8()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>o8()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:(Y)=>BU(Y)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(Z){return this._outputConfiguration=Z._outputConfiguration,this._helpOption=Z._helpOption,this._helpCommand=Z._helpCommand,this._helpConfiguration=Z._helpConfiguration,this._exitCallback=Z._exitCallback,this._storeOptionsAsProperties=Z._storeOptionsAsProperties,this._combineFlagAndOptionalValue=Z._combineFlagAndOptionalValue,this._allowExcessArguments=Z._allowExcessArguments,this._enablePositionalOptions=Z._enablePositionalOptions,this._showHelpAfterError=Z._showHelpAfterError,this._showSuggestionAfterError=Z._showSuggestionAfterError,this}_getCommandAndAncestors(){let Z=[];for(let Y=this;Y;Y=Y.parent)Z.push(Y);return Z}command(Z,Y,X){let Q=Y,$=X;if(typeof Q==="object"&&Q!==null)$=Q,Q=null;$=$||{};let[,W,J]=Z.match(/([^ ]+) *(.*)/),z=this.createCommand(W);if(Q)z.description(Q),z._executableHandler=!0;if($.isDefault)this._defaultCommandName=z._name;if(z._hidden=!!($.noHelp||$.hidden),z._executableFile=$.executableFile||null,J)z.arguments(J);if(this._registerCommand(z),z.parent=this,z.copyInheritedSettings(this),Q)return this;return z}createCommand(Z){return new n8(Z)}createHelp(){return Object.assign(new KU,this.configureHelp())}configureHelp(Z){if(Z===void 0)return this._helpConfiguration;return this._helpConfiguration=Z,this}configureOutput(Z){if(Z===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...Z},this}showHelpAfterError(Z=!0){if(typeof Z!=="string")Z=!!Z;return this._showHelpAfterError=Z,this}showSuggestionAfterError(Z=!0){return this._showSuggestionAfterError=!!Z,this}addCommand(Z,Y){if(!Z._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);if(Y=Y||{},Y.isDefault)this._defaultCommandName=Z._name;if(Y.noHelp||Y.hidden)Z._hidden=!0;return this._registerCommand(Z),Z.parent=this,Z._checkForBrokenPassThrough(),this}createArgument(Z,Y){return new HU(Z,Y)}argument(Z,Y,X,Q){let $=this.createArgument(Z,Y);if(typeof X==="function")$.default(Q).argParser(X);else $.default(X);return this.addArgument($),this}arguments(Z){return Z.trim().split(/ +/).forEach((Y)=>{this.argument(Y)}),this}addArgument(Z){let Y=this.registeredArguments.slice(-1)[0];if(Y?.variadic)throw new Error(`only the last argument can be variadic '${Y.name()}'`);if(Z.required&&Z.defaultValue!==void 0&&Z.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${Z.name()}'`);return this.registeredArguments.push(Z),this}helpCommand(Z,Y){if(typeof Z==="boolean"){if(this._addImplicitHelpCommand=Z,Z&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let X=Z??"help [command]",[,Q,$]=X.match(/([^ ]+) *(.*)/),W=Y??"display help for command",J=this.createCommand(Q);if(J.helpOption(!1),$)J.arguments($);if(W)J.description(W);if(this._addImplicitHelpCommand=!0,this._helpCommand=J,Z||Y)this._initCommandGroup(J);return this}addHelpCommand(Z,Y){if(typeof Z!=="object")return this.helpCommand(Z,Y),this;return this._addImplicitHelpCommand=!0,this._helpCommand=Z,this._initCommandGroup(Z),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(Z,Y){let X=["preSubcommand","preAction","postAction"];if(!X.includes(Z))throw new Error(`Unexpected value for event passed to hook : '${Z}'.
16
+ Expecting one of '${X.join("', '")}'`);if(this._lifeCycleHooks[Z])this._lifeCycleHooks[Z].push(Y);else this._lifeCycleHooks[Z]=[Y];return this}exitOverride(Z){if(Z)this._exitCallback=Z;else this._exitCallback=(Y)=>{if(Y.code!=="commander.executeSubCommandAsync")throw Y};return this}_exit(Z,Y,X){if(this._exitCallback)this._exitCallback(new i8(Z,Y,X));l.exit(Z)}action(Z){let Y=(X)=>{let Q=this.registeredArguments.length,$=X.slice(0,Q);if(this._storeOptionsAsProperties)$[Q]=this;else $[Q]=this.opts();return $.push(this),Z.apply(this,$)};return this._actionHandler=Y,this}createOption(Z,Y){return new WX(Z,Y)}_callParseArg(Z,Y,X,Q){try{return Z.parseArg(Y,X)}catch($){if($.code==="commander.invalidArgument"){let W=`${Q} ${$.message}`;this.error(W,{exitCode:$.exitCode,code:$.code})}throw $}}_registerOption(Z){let Y=Z.short&&this._findOption(Z.short)||Z.long&&this._findOption(Z.long);if(Y){let X=Z.long&&this._findOption(Z.long)?Z.long:Z.short;throw new Error(`Cannot add option '${Z.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${X}'
17
+ - already used by option '${Y.flags}'`)}this._initOptionGroup(Z),this.options.push(Z)}_registerCommand(Z){let Y=(Q)=>{return[Q.name()].concat(Q.aliases())},X=Y(Z).find((Q)=>this._findCommand(Q));if(X){let Q=Y(this._findCommand(X)).join("|"),$=Y(Z).join("|");throw new Error(`cannot add command '${$}' as already have command '${Q}'`)}this._initCommandGroup(Z),this.commands.push(Z)}addOption(Z){this._registerOption(Z);let Y=Z.name(),X=Z.attributeName();if(Z.negate){let $=Z.long.replace(/^--no-/,"--");if(!this._findOption($))this.setOptionValueWithSource(X,Z.defaultValue===void 0?!0:Z.defaultValue,"default")}else if(Z.defaultValue!==void 0)this.setOptionValueWithSource(X,Z.defaultValue,"default");let Q=($,W,J)=>{if($==null&&Z.presetArg!==void 0)$=Z.presetArg;let z=this.getOptionValue(X);if($!==null&&Z.parseArg)$=this._callParseArg(Z,$,z,W);else if($!==null&&Z.variadic)$=Z._collectValue($,z);if($==null)if(Z.negate)$=!1;else if(Z.isBoolean()||Z.optional)$=!0;else $="";this.setOptionValueWithSource(X,$,J)};if(this.on("option:"+Y,($)=>{let W=`error: option '${Z.flags}' argument '${$}' is invalid.`;Q($,W,"cli")}),Z.envVar)this.on("optionEnv:"+Y,($)=>{let W=`error: option '${Z.flags}' value '${$}' from env '${Z.envVar}' is invalid.`;Q($,W,"env")});return this}_optionEx(Z,Y,X,Q,$){if(typeof Y==="object"&&Y instanceof WX)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let W=this.createOption(Y,X);if(W.makeOptionMandatory(!!Z.mandatory),typeof Q==="function")W.default($).argParser(Q);else if(Q instanceof RegExp){let J=Q;Q=(z,V)=>{let q=J.exec(z);return q?q[0]:V},W.default($).argParser(Q)}else W.default(Q);return this.addOption(W)}option(Z,Y,X,Q){return this._optionEx({},Z,Y,X,Q)}requiredOption(Z,Y,X,Q){return this._optionEx({mandatory:!0},Z,Y,X,Q)}combineFlagAndOptionalValue(Z=!0){return this._combineFlagAndOptionalValue=!!Z,this}allowUnknownOption(Z=!0){return this._allowUnknownOption=!!Z,this}allowExcessArguments(Z=!0){return this._allowExcessArguments=!!Z,this}enablePositionalOptions(Z=!0){return this._enablePositionalOptions=!!Z,this}passThroughOptions(Z=!0){return this._passThroughOptions=!!Z,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(Z=!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=!!Z,this}getOptionValue(Z){if(this._storeOptionsAsProperties)return this[Z];return this._optionValues[Z]}setOptionValue(Z,Y){return this.setOptionValueWithSource(Z,Y,void 0)}setOptionValueWithSource(Z,Y,X){if(this._storeOptionsAsProperties)this[Z]=Y;else this._optionValues[Z]=Y;return this._optionValueSources[Z]=X,this}getOptionValueSource(Z){return this._optionValueSources[Z]}getOptionValueSourceWithGlobals(Z){let Y;return this._getCommandAndAncestors().forEach((X)=>{if(X.getOptionValueSource(Z)!==void 0)Y=X.getOptionValueSource(Z)}),Y}_prepareUserArgs(Z,Y){if(Z!==void 0&&!Array.isArray(Z))throw new Error("first parameter to parse must be array or undefined");if(Y=Y||{},Z===void 0&&Y.from===void 0){if(l.versions?.electron)Y.from="electron";let Q=l.execArgv??[];if(Q.includes("-e")||Q.includes("--eval")||Q.includes("-p")||Q.includes("--print"))Y.from="eval"}if(Z===void 0)Z=l.argv;this.rawArgs=Z.slice();let X;switch(Y.from){case void 0:case"node":this._scriptPath=Z[1],X=Z.slice(2);break;case"electron":if(l.defaultApp)this._scriptPath=Z[1],X=Z.slice(2);else X=Z.slice(1);break;case"user":X=Z.slice(0);break;case"eval":X=Z.slice(1);break;default:throw new Error(`unexpected parse option { from: '${Y.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",X}parse(Z,Y){this._prepareForParse();let X=this._prepareUserArgs(Z,Y);return this._parseCommand([],X),this}async parseAsync(Z,Y){this._prepareForParse();let X=this._prepareUserArgs(Z,Y);return await this._parseCommand([],X),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else 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.
18
+ - 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(Z,Y,X){if(i6.existsSync(Z))return;let Q=Y?`searched for local subcommand relative to directory '${Y}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",$=`'${Z}' does not exist
19
+ - if '${X}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
+ - ${Q}`;throw new Error($)}_executeSubCommand(Z,Y){Y=Y.slice();let X=!1,Q=[".js",".ts",".tsx",".mjs",".cjs"];function $(q,U){let H=P0.resolve(q,U);if(i6.existsSync(H))return H;if(Q.includes(P0.extname(U)))return;let G=Q.find((K)=>i6.existsSync(`${H}${K}`));if(G)return`${H}${G}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let W=Z._executableFile||`${this._name}-${Z._name}`,J=this._executableDir||"";if(this._scriptPath){let q;try{q=i6.realpathSync(this._scriptPath)}catch{q=this._scriptPath}J=P0.resolve(P0.dirname(q),J)}if(J){let q=$(J,W);if(!q&&!Z._executableFile&&this._scriptPath){let U=P0.basename(this._scriptPath,P0.extname(this._scriptPath));if(U!==this._name)q=$(J,`${U}-${Z._name}`)}W=q||W}X=Q.includes(P0.extname(W));let z;if(l.platform!=="win32")if(X)Y.unshift(W),Y=zX(l.execArgv).concat(Y),z=l8.spawn(l.argv[0],Y,{stdio:"inherit"});else z=l8.spawn(W,Y,{stdio:"inherit"});else this._checkForMissingExecutable(W,J,Z._name),Y.unshift(W),Y=zX(l.execArgv).concat(Y),z=l8.spawn(l.execPath,Y,{stdio:"inherit"});if(!z.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((U)=>{l.on(U,()=>{if(z.killed===!1&&z.exitCode===null)z.kill(U)})});let V=this._exitCallback;z.on("close",(q)=>{if(q=q??1,!V)l.exit(q);else V(new i8(q,"commander.executeSubCommandAsync","(close)"))}),z.on("error",(q)=>{if(q.code==="ENOENT")this._checkForMissingExecutable(W,J,Z._name);else if(q.code==="EACCES")throw new Error(`'${W}' not executable`);if(!V)l.exit(1);else{let U=new i8(1,"commander.executeSubCommandAsync","(error)");U.nestedError=q,V(U)}}),this.runningCommand=z}_dispatchSubcommand(Z,Y,X){let Q=this._findCommand(Z);if(!Q)this.help({error:!0});Q._prepareForParse();let $;return $=this._chainOrCallSubCommandHook($,Q,"preSubcommand"),$=this._chainOrCall($,()=>{if(Q._executableHandler)this._executeSubCommand(Q,Y.concat(X));else return Q._parseCommand(Y,X)}),$}_dispatchHelpCommand(Z){if(!Z)this.help();let Y=this._findCommand(Z);if(Y&&!Y._executableHandler)Y.help();return this._dispatchSubcommand(Z,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((Z,Y)=>{if(Z.required&&this.args[Y]==null)this.missingArgument(Z.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let Z=(X,Q,$)=>{let W=Q;if(Q!==null&&X.parseArg){let J=`error: command-argument value '${Q}' is invalid for argument '${X.name()}'.`;W=this._callParseArg(X,Q,$,J)}return W};this._checkNumberOfArguments();let Y=[];this.registeredArguments.forEach((X,Q)=>{let $=X.defaultValue;if(X.variadic){if(Q<this.args.length){if($=this.args.slice(Q),X.parseArg)$=$.reduce((W,J)=>{return Z(X,J,W)},X.defaultValue)}else if($===void 0)$=[]}else if(Q<this.args.length){if($=this.args[Q],X.parseArg)$=Z(X,$,X.defaultValue)}Y[Q]=$}),this.processedArgs=Y}_chainOrCall(Z,Y){if(Z?.then&&typeof Z.then==="function")return Z.then(()=>Y());return Y()}_chainOrCallHooks(Z,Y){let X=Z,Q=[];if(this._getCommandAndAncestors().reverse().filter(($)=>$._lifeCycleHooks[Y]!==void 0).forEach(($)=>{$._lifeCycleHooks[Y].forEach((W)=>{Q.push({hookedCommand:$,callback:W})})}),Y==="postAction")Q.reverse();return Q.forEach(($)=>{X=this._chainOrCall(X,()=>{return $.callback($.hookedCommand,this)})}),X}_chainOrCallSubCommandHook(Z,Y,X){let Q=Z;if(this._lifeCycleHooks[X]!==void 0)this._lifeCycleHooks[X].forEach(($)=>{Q=this._chainOrCall(Q,()=>{return $(this,Y)})});return Q}_parseCommand(Z,Y){let X=this.parseOptions(Y);if(this._parseOptionsEnv(),this._parseOptionsImplied(),Z=Z.concat(X.operands),Y=X.unknown,this.args=Z.concat(Y),Z&&this._findCommand(Z[0]))return this._dispatchSubcommand(Z[0],Z.slice(1),Y);if(this._getHelpCommand()&&Z[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(Z[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(Y),this._dispatchSubcommand(this._defaultCommandName,Z,Y);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(X.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Q=()=>{if(X.unknown.length>0)this.unknownOption(X.unknown[0])},$=`command:${this.name()}`;if(this._actionHandler){Q(),this._processArguments();let W;if(W=this._chainOrCallHooks(W,"preAction"),W=this._chainOrCall(W,()=>this._actionHandler(this.processedArgs)),this.parent)W=this._chainOrCall(W,()=>{this.parent.emit($,Z,Y)});return W=this._chainOrCallHooks(W,"postAction"),W}if(this.parent?.listenerCount($))Q(),this._processArguments(),this.parent.emit($,Z,Y);else if(Z.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",Z,Y);if(this.listenerCount("command:*"))this.emit("command:*",Z,Y);else if(this.commands.length)this.unknownCommand();else Q(),this._processArguments()}else if(this.commands.length)Q(),this.help({error:!0});else Q(),this._processArguments()}_findCommand(Z){if(!Z)return;return this.commands.find((Y)=>Y._name===Z||Y._aliases.includes(Z))}_findOption(Z){return this.options.find((Y)=>Y.is(Z))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((Z)=>{Z.options.forEach((Y)=>{if(Y.mandatory&&Z.getOptionValue(Y.attributeName())===void 0)Z.missingMandatoryOptionValue(Y)})})}_checkForConflictingLocalOptions(){let Z=this.options.filter((X)=>{let Q=X.attributeName();if(this.getOptionValue(Q)===void 0)return!1;return this.getOptionValueSource(Q)!=="default"});Z.filter((X)=>X.conflictsWith.length>0).forEach((X)=>{let Q=Z.find(($)=>X.conflictsWith.includes($.attributeName()));if(Q)this._conflictingOption(X,Q)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((Z)=>{Z._checkForConflictingLocalOptions()})}parseOptions(Z){let Y=[],X=[],Q=Y;function $(q){return q.length>1&&q[0]==="-"}let W=(q)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(q))return!1;return!this._getCommandAndAncestors().some((U)=>U.options.map((H)=>H.short).some((H)=>/^-\d$/.test(H)))},J=null,z=null,V=0;while(V<Z.length||z){let q=z??Z[V++];if(z=null,q==="--"){if(Q===X)Q.push(q);Q.push(...Z.slice(V));break}if(J&&(!$(q)||W(q))){this.emit(`option:${J.name()}`,q);continue}if(J=null,$(q)){let U=this._findOption(q);if(U){if(U.required){let H=Z[V++];if(H===void 0)this.optionMissingArgument(U);this.emit(`option:${U.name()}`,H)}else if(U.optional){let H=null;if(V<Z.length&&(!$(Z[V])||W(Z[V])))H=Z[V++];this.emit(`option:${U.name()}`,H)}else this.emit(`option:${U.name()}`);J=U.variadic?U:null;continue}}if(q.length>2&&q[0]==="-"&&q[1]!=="-"){let U=this._findOption(`-${q[1]}`);if(U){if(U.required||U.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${U.name()}`,q.slice(2));else this.emit(`option:${U.name()}`),z=`-${q.slice(2)}`;continue}}if(/^--[^=]+=/.test(q)){let U=q.indexOf("="),H=this._findOption(q.slice(0,U));if(H&&(H.required||H.optional)){this.emit(`option:${H.name()}`,q.slice(U+1));continue}}if(Q===Y&&$(q)&&!(this.commands.length===0&&W(q)))Q=X;if((this._enablePositionalOptions||this._passThroughOptions)&&Y.length===0&&X.length===0){if(this._findCommand(q)){Y.push(q),X.push(...Z.slice(V));break}else if(this._getHelpCommand()&&q===this._getHelpCommand().name()){Y.push(q,...Z.slice(V));break}else if(this._defaultCommandName){X.push(q,...Z.slice(V));break}}if(this._passThroughOptions){Q.push(q,...Z.slice(V));break}Q.push(q)}return{operands:Y,unknown:X}}opts(){if(this._storeOptionsAsProperties){let Z={},Y=this.options.length;for(let X=0;X<Y;X++){let Q=this.options[X].attributeName();Z[Q]=Q===this._versionOptionName?this._version:this[Q]}return Z}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((Z,Y)=>Object.assign(Z,Y.opts()),{})}error(Z,Y){if(this._outputConfiguration.outputError(`${Z}
22
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
+ `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
24
+ `),this.outputHelp({error:!0});let X=Y||{},Q=X.exitCode||1,$=X.code||"commander.error";this._exit(Q,$,Z)}_parseOptionsEnv(){this.options.forEach((Z)=>{if(Z.envVar&&Z.envVar in l.env){let Y=Z.attributeName();if(this.getOptionValue(Y)===void 0||["default","config","env"].includes(this.getOptionValueSource(Y)))if(Z.required||Z.optional)this.emit(`optionEnv:${Z.name()}`,l.env[Z.envVar]);else this.emit(`optionEnv:${Z.name()}`)}})}_parseOptionsImplied(){let Z=new LU(this.options),Y=(X)=>{return this.getOptionValue(X)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(X))};this.options.filter((X)=>X.implied!==void 0&&Y(X.attributeName())&&Z.valueFromOption(this.getOptionValue(X.attributeName()),X)).forEach((X)=>{Object.keys(X.implied).filter((Q)=>!Y(Q)).forEach((Q)=>{this.setOptionValueWithSource(Q,X.implied[Q],"implied")})})}missingArgument(Z){let Y=`error: missing required argument '${Z}'`;this.error(Y,{code:"commander.missingArgument"})}optionMissingArgument(Z){let Y=`error: option '${Z.flags}' argument missing`;this.error(Y,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(Z){let Y=`error: required option '${Z.flags}' not specified`;this.error(Y,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(Z,Y){let X=(W)=>{let J=W.attributeName(),z=this.getOptionValue(J),V=this.options.find((U)=>U.negate&&J===U.attributeName()),q=this.options.find((U)=>!U.negate&&J===U.attributeName());if(V&&(V.presetArg===void 0&&z===!1||V.presetArg!==void 0&&z===V.presetArg))return V;return q||W},Q=(W)=>{let J=X(W),z=J.attributeName();if(this.getOptionValueSource(z)==="env")return`environment variable '${J.envVar}'`;return`option '${J.flags}'`},$=`error: ${Q(Z)} cannot be used with ${Q(Y)}`;this.error($,{code:"commander.conflictingOption"})}unknownOption(Z){if(this._allowUnknownOption)return;let Y="";if(Z.startsWith("--")&&this._showSuggestionAfterError){let Q=[],$=this;do{let W=$.createHelp().visibleOptions($).filter((J)=>J.long).map((J)=>J.long);Q=Q.concat(W),$=$.parent}while($&&!$._enablePositionalOptions);Y=JX(Z,Q)}let X=`error: unknown option '${Z}'${Y}`;this.error(X,{code:"commander.unknownOption"})}_excessArguments(Z){if(this._allowExcessArguments)return;let Y=this.registeredArguments.length,X=Y===1?"":"s",$=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${Y} argument${X} but got ${Z.length}.`;this.error($,{code:"commander.excessArguments"})}unknownCommand(){let Z=this.args[0],Y="";if(this._showSuggestionAfterError){let Q=[];this.createHelp().visibleCommands(this).forEach(($)=>{if(Q.push($.name()),$.alias())Q.push($.alias())}),Y=JX(Z,Q)}let X=`error: unknown command '${Z}'${Y}`;this.error(X,{code:"commander.unknownCommand"})}version(Z,Y,X){if(Z===void 0)return this._version;this._version=Z,Y=Y||"-V, --version",X=X||"output the version number";let Q=this.createOption(Y,X);return this._versionOptionName=Q.attributeName(),this._registerOption(Q),this.on("option:"+Q.name(),()=>{this._outputConfiguration.writeOut(`${Z}
25
+ `),this._exit(0,"commander.version",Z)}),this}description(Z,Y){if(Z===void 0&&Y===void 0)return this._description;if(this._description=Z,Y)this._argsDescription=Y;return this}summary(Z){if(Z===void 0)return this._summary;return this._summary=Z,this}alias(Z){if(Z===void 0)return this._aliases[0];let Y=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)Y=this.commands[this.commands.length-1];if(Z===Y._name)throw new Error("Command alias can't be the same as its name");let X=this.parent?._findCommand(Z);if(X){let Q=[X.name()].concat(X.aliases()).join("|");throw new Error(`cannot add alias '${Z}' to command '${this.name()}' as already have command '${Q}'`)}return Y._aliases.push(Z),this}aliases(Z){if(Z===void 0)return this._aliases;return Z.forEach((Y)=>this.alias(Y)),this}usage(Z){if(Z===void 0){if(this._usage)return this._usage;let Y=this.registeredArguments.map((X)=>{return GU(X)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?Y:[]).join(" ")}return this._usage=Z,this}name(Z){if(Z===void 0)return this._name;return this._name=Z,this}helpGroup(Z){if(Z===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=Z,this}commandsGroup(Z){if(Z===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=Z,this}optionsGroup(Z){if(Z===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=Z,this}_initOptionGroup(Z){if(this._defaultOptionGroup&&!Z.helpGroupHeading)Z.helpGroup(this._defaultOptionGroup)}_initCommandGroup(Z){if(this._defaultCommandGroup&&!Z.helpGroup())Z.helpGroup(this._defaultCommandGroup)}nameFromFilename(Z){return this._name=P0.basename(Z,P0.extname(Z)),this}executableDir(Z){if(Z===void 0)return this._executableDir;return this._executableDir=Z,this}helpInformation(Z){let Y=this.createHelp(),X=this._getOutputContext(Z);Y.prepareContext({error:X.error,helpWidth:X.helpWidth,outputHasColors:X.hasColors});let Q=Y.formatHelp(this,Y);if(X.hasColors)return Q;return this._outputConfiguration.stripColor(Q)}_getOutputContext(Z){Z=Z||{};let Y=!!Z.error,X,Q,$;if(Y)X=(J)=>this._outputConfiguration.writeErr(J),Q=this._outputConfiguration.getErrHasColors(),$=this._outputConfiguration.getErrHelpWidth();else X=(J)=>this._outputConfiguration.writeOut(J),Q=this._outputConfiguration.getOutHasColors(),$=this._outputConfiguration.getOutHelpWidth();return{error:Y,write:(J)=>{if(!Q)J=this._outputConfiguration.stripColor(J);return X(J)},hasColors:Q,helpWidth:$}}outputHelp(Z){let Y;if(typeof Z==="function")Y=Z,Z=void 0;let X=this._getOutputContext(Z),Q={error:X.error,write:X.write,command:this};this._getCommandAndAncestors().reverse().forEach((W)=>W.emit("beforeAllHelp",Q)),this.emit("beforeHelp",Q);let $=this.helpInformation({error:X.error});if(Y){if($=Y($),typeof $!=="string"&&!Buffer.isBuffer($))throw new Error("outputHelp callback must return a string or a Buffer")}if(X.write($),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Q),this._getCommandAndAncestors().forEach((W)=>W.emit("afterAllHelp",Q))}helpOption(Z,Y){if(typeof Z==="boolean"){if(Z){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(Z??"-h, --help",Y??"display help for command"),Z||Y)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(Z){return this._helpOption=Z,this._initOptionGroup(Z),this}help(Z){this.outputHelp(Z);let Y=Number(l.exitCode??0);if(Y===0&&Z&&typeof Z!=="function"&&Z.error)Y=1;this._exit(Y,"commander.help","(outputHelp)")}addHelpText(Z,Y){let X=["beforeAll","before","after","afterAll"];if(!X.includes(Z))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${X.join("', '")}'`);let Q=`${Z}Help`;return this.on(Q,($)=>{let W;if(typeof Y==="function")W=Y({error:$.error,command:$.command});else W=Y;if(W)$.write(`${W}
27
+ `)}),this}_outputHelpIfRequested(Z){let Y=this._getHelpOption();if(Y&&Z.find((Q)=>Y.is(Q)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function zX(Z){return Z.map((Y)=>{if(!Y.startsWith("--inspect"))return Y;let X,Q="127.0.0.1",$="9229",W;if((W=Y.match(/^(--inspect(-brk)?)$/))!==null)X=W[1];else if((W=Y.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(X=W[1],/^\d+$/.test(W[3]))$=W[3];else Q=W[3];else if((W=Y.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)X=W[1],Q=W[3],$=W[4];if(X&&$!=="0")return`${X}=${Q}:${parseInt($)+1}`;return Y})}function o8(){if(l.env.NO_COLOR||l.env.FORCE_COLOR==="0"||l.env.FORCE_COLOR==="false")return!1;if(l.env.FORCE_COLOR||l.env.CLICOLOR_FORCE!==void 0)return!0;return}MU.Command=n8;MU.useColor=o8});var GX=E1((AU)=>{var{Argument:qX}=l6(),{Command:a8}=VX(),{CommanderError:wU,InvalidArgumentError:UX}=L2(),{Help:DU}=d8(),{Option:HX}=c8();AU.program=new a8;AU.createCommand=(Z)=>new a8(Z);AU.createOption=(Z,Y)=>new HX(Z,Y);AU.createArgument=(Z,Y)=>new qX(Z,Y);AU.Command=a8;AU.Option=HX;AU.Argument=qX;AU.Help=DU;AU.CommanderError=wU;AU.InvalidArgumentError=UX;AU.InvalidOptionArgumentError=UX});var M2=E1((dD,r8)=>{var n6=process||{},BX=n6.argv||[],o6=n6.env||{},bU=!(!!o6.NO_COLOR||BX.includes("--no-color"))&&(!!o6.FORCE_COLOR||BX.includes("--color")||n6.platform==="win32"||(n6.stdout||{}).isTTY&&o6.TERM!=="dumb"||!!o6.CI),xU=(Z,Y,X=Z)=>(Q)=>{let $=""+Q,W=$.indexOf(Y,Z.length);return~W?Z+kU($,Y,X,W)+Y:Z+$+Y},kU=(Z,Y,X,Q)=>{let $="",W=0;do $+=Z.substring(W,Q)+X,W=Q+Y.length,Q=Z.indexOf(Y,W);while(~Q);return $+Z.substring(W)},LX=(Z=bU)=>{let Y=Z?xU:()=>String;return{isColorSupported:Z,reset:Y("\x1B[0m","\x1B[0m"),bold:Y("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:Y("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:Y("\x1B[3m","\x1B[23m"),underline:Y("\x1B[4m","\x1B[24m"),inverse:Y("\x1B[7m","\x1B[27m"),hidden:Y("\x1B[8m","\x1B[28m"),strikethrough:Y("\x1B[9m","\x1B[29m"),black:Y("\x1B[30m","\x1B[39m"),red:Y("\x1B[31m","\x1B[39m"),green:Y("\x1B[32m","\x1B[39m"),yellow:Y("\x1B[33m","\x1B[39m"),blue:Y("\x1B[34m","\x1B[39m"),magenta:Y("\x1B[35m","\x1B[39m"),cyan:Y("\x1B[36m","\x1B[39m"),white:Y("\x1B[37m","\x1B[39m"),gray:Y("\x1B[90m","\x1B[39m"),bgBlack:Y("\x1B[40m","\x1B[49m"),bgRed:Y("\x1B[41m","\x1B[49m"),bgGreen:Y("\x1B[42m","\x1B[49m"),bgYellow:Y("\x1B[43m","\x1B[49m"),bgBlue:Y("\x1B[44m","\x1B[49m"),bgMagenta:Y("\x1B[45m","\x1B[49m"),bgCyan:Y("\x1B[46m","\x1B[49m"),bgWhite:Y("\x1B[47m","\x1B[49m"),blackBright:Y("\x1B[90m","\x1B[39m"),redBright:Y("\x1B[91m","\x1B[39m"),greenBright:Y("\x1B[92m","\x1B[39m"),yellowBright:Y("\x1B[93m","\x1B[39m"),blueBright:Y("\x1B[94m","\x1B[39m"),magentaBright:Y("\x1B[95m","\x1B[39m"),cyanBright:Y("\x1B[96m","\x1B[39m"),whiteBright:Y("\x1B[97m","\x1B[39m"),bgBlackBright:Y("\x1B[100m","\x1B[49m"),bgRedBright:Y("\x1B[101m","\x1B[49m"),bgGreenBright:Y("\x1B[102m","\x1B[49m"),bgYellowBright:Y("\x1B[103m","\x1B[49m"),bgBlueBright:Y("\x1B[104m","\x1B[49m"),bgMagentaBright:Y("\x1B[105m","\x1B[49m"),bgCyanBright:Y("\x1B[106m","\x1B[49m"),bgWhiteBright:Y("\x1B[107m","\x1B[49m")}};r8.exports=LX();r8.exports.createColors=LX});var DX=E1((lD,wX)=>{var j9=1000,C9=j9*60,S9=C9*60,J9=S9*24,hU=J9*7,gU=J9*365.25;wX.exports=function(Z,Y){Y=Y||{};var X=typeof Z;if(X==="string"&&Z.length>0)return uU(Z);else if(X==="number"&&isFinite(Z))return Y.long?pU(Z):mU(Z);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(Z))};function uU(Z){if(Z=String(Z),Z.length>100)return;var Y=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(Z);if(!Y)return;var X=parseFloat(Y[1]),Q=(Y[2]||"ms").toLowerCase();switch(Q){case"years":case"year":case"yrs":case"yr":case"y":return X*gU;case"weeks":case"week":case"w":return X*hU;case"days":case"day":case"d":return X*J9;case"hours":case"hour":case"hrs":case"hr":case"h":return X*S9;case"minutes":case"minute":case"mins":case"min":case"m":return X*C9;case"seconds":case"second":case"secs":case"sec":case"s":return X*j9;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return X;default:return}}function mU(Z){var Y=Math.abs(Z);if(Y>=J9)return Math.round(Z/J9)+"d";if(Y>=S9)return Math.round(Z/S9)+"h";if(Y>=C9)return Math.round(Z/C9)+"m";if(Y>=j9)return Math.round(Z/j9)+"s";return Z+"ms"}function pU(Z){var Y=Math.abs(Z);if(Y>=J9)return t6(Z,Y,J9,"day");if(Y>=S9)return t6(Z,Y,S9,"hour");if(Y>=C9)return t6(Z,Y,C9,"minute");if(Y>=j9)return t6(Z,Y,j9,"second");return Z+" ms"}function t6(Z,Y,X,Q){var $=Y>=X*1.5;return Math.round(Z/X)+" "+Q+($?"s":"")}});var t8=E1((iD,AX)=>{function dU(Z){X.debug=X,X.default=X,X.coerce=V,X.disable=J,X.enable=$,X.enabled=z,X.humanize=DX(),X.destroy=q,Object.keys(Z).forEach((U)=>{X[U]=Z[U]}),X.names=[],X.skips=[],X.formatters={};function Y(U){let H=0;for(let G=0;G<U.length;G++)H=(H<<5)-H+U.charCodeAt(G),H|=0;return X.colors[Math.abs(H)%X.colors.length]}X.selectColor=Y;function X(U){let H,G=null,K,M;function E(...O){if(!E.enabled)return;let T=E,i=Number(new Date),g=i-(H||i);if(T.diff=g,T.prev=H,T.curr=i,H=i,O[0]=X.coerce(O[0]),typeof O[0]!=="string")O.unshift("%O");let Z1=0;O[0]=O[0].replace(/%([a-zA-Z%])/g,(W1,A0)=>{if(W1==="%%")return"%";Z1++;let z0=X.formatters[A0];if(typeof z0==="function"){let W9=O[Z1];W1=z0.call(T,W9),O.splice(Z1,1),Z1--}return W1}),X.formatArgs.call(T,O),(T.log||X.log).apply(T,O)}if(E.namespace=U,E.useColors=X.useColors(),E.color=X.selectColor(U),E.extend=Q,E.destroy=X.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(G!==null)return G;if(K!==X.namespaces)K=X.namespaces,M=X.enabled(U);return M},set:(O)=>{G=O}}),typeof X.init==="function")X.init(E);return E}function Q(U,H){let G=X(this.namespace+(typeof H==="undefined"?":":H)+U);return G.log=this.log,G}function $(U){X.save(U),X.namespaces=U,X.names=[],X.skips=[];let H=(typeof U==="string"?U:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let G of H)if(G[0]==="-")X.skips.push(G.slice(1));else X.names.push(G)}function W(U,H){let G=0,K=0,M=-1,E=0;while(G<U.length)if(K<H.length&&(H[K]===U[G]||H[K]==="*"))if(H[K]==="*")M=K,E=G,K++;else G++,K++;else if(M!==-1)K=M+1,E++,G=E;else return!1;while(K<H.length&&H[K]==="*")K++;return K===H.length}function J(){let U=[...X.names,...X.skips.map((H)=>"-"+H)].join(",");return X.enable(""),U}function z(U){for(let H of X.skips)if(W(U,H))return!1;for(let H of X.names)if(W(U,H))return!0;return!1}function V(U){if(U instanceof Error)return U.stack||U.message;return U}function q(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return X.enable(X.load()),X}AX.exports=dU});var OX=E1((EX,e6)=>{EX.formatArgs=lU;EX.save=iU;EX.load=oU;EX.useColors=cU;EX.storage=nU();EX.destroy=(()=>{let Z=!1;return()=>{if(!Z)Z=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();EX.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function cU(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let Z;return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&(Z=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(Z[1],10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function lU(Z){if(Z[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+Z[0]+(this.useColors?"%c ":" ")+"+"+e6.exports.humanize(this.diff),!this.useColors)return;let Y="color: "+this.color;Z.splice(1,0,Y,"color: inherit");let X=0,Q=0;Z[0].replace(/%[a-zA-Z%]/g,($)=>{if($==="%%")return;if(X++,$==="%c")Q=X}),Z.splice(Q,0,Y)}EX.log=console.debug||console.log||(()=>{});function iU(Z){try{if(Z)EX.storage.setItem("debug",Z);else EX.storage.removeItem("debug")}catch(Y){}}function oU(){let Z;try{Z=EX.storage.getItem("debug")||EX.storage.getItem("DEBUG")}catch(Y){}if(!Z&&typeof process!=="undefined"&&"env"in process)Z=process.env.DEBUG;return Z}function nU(){try{return localStorage}catch(Z){}}e6.exports=t8()(EX);var{formatters:aU}=e6.exports;aU.j=function(Z){try{return JSON.stringify(Z)}catch(Y){return"[UnexpectedJSONParseError]: "+Y.message}}});var RX=E1((TX,Y4)=>{var QH=O0("tty"),Z4=O0("util");TX.init=UH;TX.log=zH;TX.formatArgs=WH;TX.save=VH;TX.load=qH;TX.useColors=$H;TX.destroy=Z4.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");TX.colors=[6,2,3,4,5,1];try{let Z=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(Z&&(Z.stderr||Z).level>=2)TX.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(Z){}TX.inspectOpts=Object.keys(process.env).filter((Z)=>{return/^debug_/i.test(Z)}).reduce((Z,Y)=>{let X=Y.substring(6).toLowerCase().replace(/_([a-z])/g,($,W)=>{return W.toUpperCase()}),Q=process.env[Y];if(/^(yes|on|true|enabled)$/i.test(Q))Q=!0;else if(/^(no|off|false|disabled)$/i.test(Q))Q=!1;else if(Q==="null")Q=null;else Q=Number(Q);return Z[X]=Q,Z},{});function $H(){return"colors"in TX.inspectOpts?Boolean(TX.inspectOpts.colors):QH.isatty(process.stderr.fd)}function WH(Z){let{namespace:Y,useColors:X}=this;if(X){let Q=this.color,$="\x1B[3"+(Q<8?Q:"8;5;"+Q),W=` ${$};1m${Y} \x1B[0m`;Z[0]=W+Z[0].split(`
28
+ `).join(`
29
+ `+W),Z.push($+"m+"+Y4.exports.humanize(this.diff)+"\x1B[0m")}else Z[0]=JH()+Y+" "+Z[0]}function JH(){if(TX.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function zH(...Z){return process.stderr.write(Z4.formatWithOptions(TX.inspectOpts,...Z)+`
30
+ `)}function VH(Z){if(Z)process.env.DEBUG=Z;else delete process.env.DEBUG}function qH(){return process.env.DEBUG}function UH(Z){Z.inspectOpts={};let Y=Object.keys(TX.inspectOpts);for(let X=0;X<Y.length;X++)Z.inspectOpts[Y[X]]=TX.inspectOpts[Y[X]]}Y4.exports=t8()(TX);var{formatters:PX}=Y4.exports;PX.o=function(Z){return this.inspectOpts.colors=this.useColors,Z4.inspect(Z,this.inspectOpts).split(`
31
+ `).map((Y)=>Y.trim()).join(" ")};PX.O=function(Z){return this.inspectOpts.colors=this.useColors,Z4.inspect(Z,this.inspectOpts)}});var ZZ=E1((aD,e8)=>{if(typeof process==="undefined"||process.type==="renderer"||!1||process.__nwjs)e8.exports=OX();else e8.exports=RX()});var jX=E1((d1)=>{var NH=d1&&d1.__importDefault||function(Z){return Z&&Z.__esModule?Z:{default:Z}};Object.defineProperty(d1,"__esModule",{value:!0});var wH=O0("fs"),DH=NH(ZZ()),_9=DH.default("@kwsites/file-exists");function AH(Z,Y,X){_9("checking %s",Z);try{let Q=wH.statSync(Z);if(Q.isFile()&&Y)return _9("[OK] path represents a file"),!0;if(Q.isDirectory()&&X)return _9("[OK] path represents a directory"),!0;return _9("[FAIL] path represents something other than a file or directory"),!1}catch(Q){if(Q.code==="ENOENT")return _9("[FAIL] path is not accessible: %o",Q),!1;throw _9("[FATAL] %o",Q),Q}}function EH(Z,Y=d1.READABLE){return AH(Z,(Y&d1.FILE)>0,(Y&d1.FOLDER)>0)}d1.exists=EH;d1.FILE=1;d1.FOLDER=2;d1.READABLE=d1.FILE+d1.FOLDER});var CX=E1((YZ)=>{function OH(Z){for(var Y in Z)if(!YZ.hasOwnProperty(Y))YZ[Y]=Z[Y]}Object.defineProperty(YZ,"__esModule",{value:!0});OH(jX())});var QZ=E1((SX)=>{Object.defineProperty(SX,"__esModule",{value:!0});SX.createDeferred=SX.deferred=void 0;function XZ(){let Z,Y,X="pending";return{promise:new Promise(($,W)=>{Z=$,Y=W}),done($){if(X==="pending")X="resolved",Z($)},fail($){if(X==="pending")X="rejected",Y($)},get fulfilled(){return X!=="pending"},get status(){return X}}}SX.deferred=XZ;SX.createDeferred=XZ;SX.default=XZ});var KX=E0(GX(),1),{program:yD,createCommand:bD,createArgument:xD,createOption:kD,CommanderError:vD,InvalidArgumentError:fD,InvalidOptionArgumentError:hD,Command:R9,Argument:gD,Option:uD,Help:mD}=KX.default;var p=E0(M2(),1);var j=E0(M2(),1);function s8(Z,Y=!1){let X=Y?Z.toUpperCase():Z;switch(Z){case"low":return j.default.green(X);case"medium":return j.default.yellow(X);case"high":return j.default.red(X);case"critical":return j.default.bold(j.default.magenta(X))}}function MX(Z){switch(Z){case"aligned":return j.default.green(Z.toUpperCase());case"partial":return j.default.yellow(Z.toUpperCase());case"misaligned":return j.default.red(Z.toUpperCase())}}function FX(Z){return`[${s8(Z.severity,!0)}:${j.default.cyan(Z.category)}]`}function vU(Z){let Y=FX(Z),X=Z.file?j.default.dim(` (${Z.file})`):"";return` ${Y} ${Z.description}${X}`}function fU(Z,Y){let X=[],Q=FX(Z);if(X.push(`${Q} ${j.default.bold(`Risk #${Y+1}`)}`),Z.file)X.push(` File: ${j.default.blue(Z.file)}`);if(X.push(` ${Z.description}`),X.push(""),X.push(` ${j.default.dim("Evidence:")} ${Z.evidence}`),Z.mitigation)X.push(` ${j.default.dim("Mitigation:")} ${Z.mitigation}`);return X.join(`
32
+ `)}function NX(Z){return j.default.dim(`[${Z}]`)}function r6(Z,Y,X,Q){let $=[];if(X)$.push(j.default.bold("Stated Intent")),$.push(j.default.cyan(X)),$.push("");if($.push(j.default.bold("Derived Intent")),$.push(`${NX(Z.scope)} ${Z.summary}`),$.push(""),Q){$.push(`${j.default.bold("Intent Alignment")}: ${MX(Q.alignment)}`),$.push(` ${Q.summary}`);let z=[...Q.mismatches.slice(0,2),...Q.missing.slice(0,1),...Q.unstated.slice(0,1)];if(z.length>0)for(let V of z)$.push(j.default.dim(` > ${V}`));$.push("")}let W=s8(Y.overallRisk);if($.push(`${j.default.bold("Risk")}: ${W}`),Y.risks.length===0)$.push(j.default.dim(" No risks identified"));else{let z=Y.risks.slice(0,3);for(let V of z)$.push(vU(V));if(Y.risks.length>3)$.push(j.default.dim(` ... and ${Y.risks.length-3} more`))}$.push("");let J=Z.affectedAreas.length;return $.push(j.default.dim(`${J} area${J!==1?"s":""} affected: ${Z.affectedAreas.join(", ")}`)),$.join(`
33
+ `)}function a6(Z,Y="(none)"){if(Z.length===0)return[j.default.dim(` ${Y}`)];return Z.map((X)=>` ${j.default.blue(">")} ${X}`)}function s6(Z,Y,X,Q){let $=[],W=j.default.dim("─".repeat(60));if(X)$.push(W),$.push(j.default.bold(j.default.cyan("STATED INTENT"))),$.push(W),$.push(""),$.push(j.default.cyan(X)),$.push("");$.push(W),$.push(j.default.bold(j.default.cyan("DERIVED INTENT"))),$.push(W),$.push(""),$.push(`${j.default.bold("Summary:")} ${Z.summary}`),$.push(`${j.default.bold("Purpose:")} ${Z.purpose}`),$.push(`${j.default.bold("Scope:")} ${NX(Z.scope)}`),$.push(""),$.push(j.default.bold("Affected Areas:"));for(let z of Z.affectedAreas)$.push(` ${j.default.blue(">")} ${z}`);if($.push(""),Z.suggestedReviewOrder&&Z.suggestedReviewOrder.length>0)$.push(j.default.bold("Suggested Review Order:")),Z.suggestedReviewOrder.forEach((z,V)=>{$.push(` ${j.default.dim(`${V+1}.`)} ${j.default.blue(z)}`)}),$.push("");if(Q)$.push(W),$.push(j.default.bold(j.default.cyan(`INTENT ALIGNMENT: ${MX(Q.alignment)}`))),$.push(W),$.push(""),$.push(`${j.default.bold("Confidence:")} ${Q.confidence}`),$.push(`${j.default.bold("Summary:")} ${Q.summary}`),$.push(""),$.push(j.default.bold("Matches:")),$.push(...a6(Q.matches)),$.push(""),$.push(j.default.bold("Mismatches:")),$.push(...a6(Q.mismatches)),$.push(""),$.push(j.default.bold("Missing (stated but not implemented):")),$.push(...a6(Q.missing)),$.push(""),$.push(j.default.bold("Unstated Changes (scope creep):")),$.push(...a6(Q.unstated)),$.push("");$.push(W),$.push(j.default.bold(j.default.cyan("RISK ASSESSMENT"))),$.push(W),$.push("");let J=s8(Y.overallRisk);if($.push(`${j.default.bold("Overall Risk:")} ${J}`),$.push(`${j.default.bold("Confidence:")} ${Y.confidence}`),$.push(`${j.default.bold("Summary:")} ${Y.summary}`),$.push(""),Y.risks.length===0)$.push(j.default.green("No risks identified."));else $.push(j.default.bold(`Identified Risks (${Y.risks.length}):`)),$.push(""),Y.risks.forEach((z,V)=>{if($.push(fU(z,V)),V<Y.risks.length-1)$.push("")});return $.push(""),$.push(W),$.join(`
34
+ `)}var K4=E0(CX(),1),U4=E0(ZZ(),1),kQ=E0(QZ(),1),y9=E0(QZ(),1);import{Buffer as _H}from"node:buffer";import{spawn as KG}from"child_process";import{normalize as CK}from"node:path";import{EventEmitter as _3}from"node:events";var{defineProperty:OZ,getOwnPropertyDescriptor:IH,getOwnPropertyNames:PZ}=Object,RH=Object.prototype.hasOwnProperty,D=(Z,Y)=>function X(){return Z&&(Y=(0,Z[PZ(Z)[0]])(Z=0)),Y},jH=(Z,Y)=>function X(){return Y||(0,Z[PZ(Z)[0]])((Y={exports:{}}).exports,Y),Y.exports},H1=(Z,Y)=>{for(var X in Y)OZ(Z,X,{get:Y[X],enumerable:!0})},CH=(Z,Y,X,Q)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(let $ of PZ(Y))if(!RH.call(Z,$)&&$!==X)OZ(Z,$,{get:()=>Y[$],enumerable:!(Q=IH(Y,$))||Q.enumerable})}return Z},J1=(Z)=>CH(OZ({},"__esModule",{value:!0}),Z);function SH(...Z){let Y=new String(Z);return G4.set(Y,Z),Y}function z4(Z){return Z instanceof String&&G4.has(Z)}function yX(Z){return G4.get(Z)||[]}var G4,A2=D({"src/lib/args/pathspec.ts"(){G4=new WeakMap}}),I0,m0=D({"src/lib/errors/git-error.ts"(){I0=class extends Error{constructor(Z,Y){super(Y);this.task=Z,Object.setPrototypeOf(this,new.target.prototype)}}}}),E2,x9=D({"src/lib/errors/git-response-error.ts"(){m0(),E2=class extends I0{constructor(Z,Y){super(void 0,Y||String(Z));this.git=Z}}}}),q5,U5=D({"src/lib/errors/task-configuration-error.ts"(){m0(),q5=class extends I0{constructor(Z){super(void 0,Z)}}}});function H5(Z){if(typeof Z!=="function")return U9;return Z}function G5(Z){return typeof Z==="function"&&Z!==U9}function K5(Z,Y){let X=Z.indexOf(Y);if(X<=0)return[Z,""];return[Z.substr(0,X),Z.substr(X+1)]}function B5(Z,Y=0){return L5(Z)&&Z.length>Y?Z[Y]:void 0}function q9(Z,Y=0){if(L5(Z)&&Z.length>Y)return Z[Z.length-1-Y]}function L5(Z){return F4(Z)}function O2(Z="",Y=!0,X=`
35
+ `){return Z.split(X).reduce((Q,$)=>{let W=Y?$.trim():$;if(W)Q.push(W);return Q},[])}function TZ(Z,Y){return O2(Z,!0).map((X)=>Y(X))}function IZ(Z){return K4.exists(Z,K4.FOLDER)}function d(Z,Y){if(Array.isArray(Z)){if(!Z.includes(Y))Z.push(Y)}else Z.add(Y);return Y}function M5(Z,Y){if(Array.isArray(Z)&&!Z.includes(Y))Z.push(Y);return Z}function B4(Z,Y){if(Array.isArray(Z)){let X=Z.indexOf(Y);if(X>=0)Z.splice(X,1)}else Z.delete(Y);return Y}function L0(Z){return Array.isArray(Z)?Z:[Z]}function F5(Z){return Z.replace(/[\s-]+(.)/g,(Y,X)=>{return X.toUpperCase()})}function k9(Z){return L0(Z).map((Y)=>{return Y instanceof String?Y:String(Y)})}function a(Z,Y=0){if(Z==null)return Y;let X=parseInt(Z,10);return Number.isNaN(X)?Y:X}function w2(Z,Y){let X=[];for(let Q=0,$=Z.length;Q<$;Q++)X.push(Y,Z[Q]);return X}function D2(Z){return(Array.isArray(Z)?_H.concat(Z):Z).toString("utf-8")}function N5(Z,Y){let X={};return Y.forEach((Q)=>{if(Z[Q]!==void 0)X[Q]=Z[Q]}),X}function UZ(Z=0){return new Promise((Y)=>setTimeout(Y,Z))}function HZ(Z){if(Z===!1)return;return Z}var b9,U9,P2,L4=D({"src/lib/utils/util.ts"(){RZ(),b9="\x00",U9=()=>{},P2=Object.prototype.toString.call.bind(Object.prototype.toString)}});function l1(Z,Y,X){if(Y(Z))return Z;return arguments.length>2?X:void 0}function GZ(Z,Y){let X=z4(Z)?"string":typeof Z;return/number|string|boolean/.test(X)&&(!Y||!Y.includes(X))}function M4(Z){return!!Z&&P2(Z)==="[object Object]"}function w5(Z){return typeof Z==="function"}var T2,D5,D1,V4,F4,RZ=D({"src/lib/utils/argument-filters.ts"(){A2(),L4(),T2=(Z)=>{return Array.isArray(Z)},D5=(Z)=>{return typeof Z==="number"},D1=(Z)=>{return typeof Z==="string"},V4=(Z)=>{return D1(Z)||Array.isArray(Z)&&Z.every(D1)},F4=(Z)=>{if(Z==null||"number|boolean|function".includes(typeof Z))return!1;return typeof Z.length==="number"}}}),KZ,yH=D({"src/lib/utils/exit-codes.ts"(){KZ=((Z)=>{return Z[Z.SUCCESS=0]="SUCCESS",Z[Z.ERROR=1]="ERROR",Z[Z.NOT_FOUND=-2]="NOT_FOUND",Z[Z.UNCLEAN=128]="UNCLEAN",Z})(KZ||{})}}),q4,bH=D({"src/lib/utils/git-output-streams.ts"(){q4=class Z{constructor(Y,X){this.stdOut=Y,this.stdErr=X}asStrings(){return new Z(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}});function xH(){throw new Error("LineParser:useMatches not implemented")}var k,u0,kH=D({"src/lib/utils/line-parser.ts"(){k=class{constructor(Z,Y){if(this.matches=[],this.useMatches=xH,this.parse=(X,Q)=>{if(this.resetMatches(),!this._regExp.every(($,W)=>this.addMatch($,W,X(W))))return!1;return this.useMatches(Q,this.prepareMatches())!==!1},this._regExp=Array.isArray(Z)?Z:[Z],Y)this.useMatches=Y}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(Z,Y,X){let Q=X&&Z.exec(X);if(Q)this.pushMatch(Y,Q);return!!Q}pushMatch(Z,Y){this.matches.push(...Y.slice(1))}},u0=class extends k{addMatch(Z,Y,X){return/^remote:\s/.test(String(X))&&super.addMatch(Z,Y,X)}pushMatch(Z,Y){if(Z>0||Y.length>1)super.pushMatch(Z,Y)}}}});function A5(...Z){let Y=process.cwd(),X=Object.assign({baseDir:Y,...E5},...Z.filter((Q)=>typeof Q==="object"&&Q));return X.baseDir=X.baseDir||Y,X.trimmed=X.trimmed===!0,X}var E5,vH=D({"src/lib/utils/simple-git-options.ts"(){E5={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function jZ(Z,Y=[]){if(!M4(Z))return Y;return Object.keys(Z).reduce((X,Q)=>{let $=Z[Q];if(z4($))X.push($);else if(GZ($,["boolean"]))X.push(Q+"="+$);else if(Array.isArray($)){for(let W of $)if(!GZ(W,["string","number"]))X.push(Q+"="+W)}else X.push(Q);return X},Y)}function y1(Z,Y=0,X=!1){let Q=[];for(let $=0,W=Y<0?Z.length:Y;$<W;$++)if("string|number".includes(typeof Z[$]))Q.push(String(Z[$]));if(jZ(CZ(Z),Q),!X)Q.push(...fH(Z));return Q}function fH(Z){let Y=typeof q9(Z)==="function";return k9(l1(q9(Z,Y?1:0),T2,[]))}function CZ(Z){let Y=w5(q9(Z));return l1(q9(Z,Y?1:0),M4)}function z1(Z,Y=!0){let X=H5(q9(Z));return Y||G5(X)?X:void 0}var hH=D({"src/lib/utils/task-options.ts"(){RZ(),L4(),A2()}});function BZ(Z,Y){return Z(Y.stdOut,Y.stdErr)}function x1(Z,Y,X,Q=!0){return L0(X).forEach(($)=>{for(let W=O2($,Q),J=0,z=W.length;J<z;J++){let V=(q=0)=>{if(J+q>=z)return;return W[J+q]};Y.some(({parse:q})=>q(V,Z))}}),Z}var gH=D({"src/lib/utils/task-parser.ts"(){L4()}}),O5={};H1(O5,{ExitCodes:()=>KZ,GitOutputStreams:()=>q4,LineParser:()=>k,NOOP:()=>U9,NULL:()=>b9,RemoteLineParser:()=>u0,append:()=>d,appendTaskOptions:()=>jZ,asArray:()=>L0,asCamelCase:()=>F5,asFunction:()=>H5,asNumber:()=>a,asStringArray:()=>k9,bufferToString:()=>D2,callTaskParser:()=>BZ,createInstanceConfig:()=>A5,delay:()=>UZ,filterArray:()=>T2,filterFunction:()=>w5,filterHasLength:()=>F4,filterNumber:()=>D5,filterPlainObject:()=>M4,filterPrimitives:()=>GZ,filterString:()=>D1,filterStringOrStringArray:()=>V4,filterType:()=>l1,first:()=>B5,folderExists:()=>IZ,forEachLineWithContent:()=>TZ,getTrailingOptions:()=>y1,including:()=>M5,isUserFunction:()=>G5,last:()=>q9,objectToString:()=>P2,orVoid:()=>HZ,parseStringResponse:()=>x1,pick:()=>N5,prefixedArray:()=>w2,remove:()=>B4,splitOn:()=>K5,toLinesWithContent:()=>O2,trailingFunctionArgument:()=>z1,trailingOptionsArgument:()=>CZ});var _=D({"src/lib/utils/index.ts"(){RZ(),yH(),bH(),kH(),vH(),hH(),gH(),L4()}}),P5={};H1(P5,{CheckRepoActions:()=>LZ,checkIsBareRepoTask:()=>I5,checkIsRepoRootTask:()=>T5,checkIsRepoTask:()=>uH});function uH(Z){switch(Z){case"bare":return I5();case"root":return T5()}return{commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:N4,parser:SZ}}function T5(){return{commands:["rev-parse","--git-dir"],format:"utf-8",onError:N4,parser(Y){return/^\.(git)?$/.test(Y.trim())}}}function I5(){return{commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:N4,parser:SZ}}function mH(Z){return/(Not a git repository|Kein Git-Repository)/i.test(String(Z))}var LZ,N4,SZ,R5=D({"src/lib/tasks/check-is-repo.ts"(){_(),LZ=((Z)=>{return Z.BARE="bare",Z.IN_TREE="tree",Z.IS_REPO_ROOT="root",Z})(LZ||{}),N4=({exitCode:Z},Y,X,Q)=>{if(Z===128&&mH(Y))return X(Buffer.from("false"));Q(Y)},SZ=(Z)=>{return Z.trim()==="true"}}});function pH(Z,Y){let X=new j5(Z),Q=Z?S5:C5;return O2(Y).forEach(($)=>{let W=$.replace(Q,"");X.paths.push(W),(_5.test(W)?X.folders:X.files).push(W)}),X}var j5,C5,S5,_5,dH=D({"src/lib/responses/CleanSummary.ts"(){_(),j5=class{constructor(Z){this.dryRun=Z,this.paths=[],this.files=[],this.folders=[]}},C5=/^[a-z]+\s*/i,S5=/^[a-z]+\s+[a-z]+\s*/i,_5=/\/$/}}),MZ={};H1(MZ,{EMPTY_COMMANDS:()=>w4,adhocExecTask:()=>y5,configurationErrorTask:()=>b1,isBufferTask:()=>x5,isEmptyTask:()=>k5,straightThroughBufferTask:()=>b5,straightThroughStringTask:()=>j1});function y5(Z){return{commands:w4,format:"empty",parser:Z}}function b1(Z){return{commands:w4,format:"empty",parser(){throw typeof Z==="string"?new q5(Z):Z}}}function j1(Z,Y=!1){return{commands:Z,format:"utf-8",parser(X){return Y?String(X).trim():X}}}function b5(Z){return{commands:Z,format:"buffer",parser(Y){return Y}}}function x5(Z){return Z.format==="buffer"}function k5(Z){return Z.format==="empty"||!Z.commands.length}var w4,U1=D({"src/lib/tasks/task.ts"(){U5(),w4=[]}}),v5={};H1(v5,{CONFIG_ERROR_INTERACTIVE_MODE:()=>_Z,CONFIG_ERROR_MODE_REQUIRED:()=>yZ,CONFIG_ERROR_UNKNOWN_OPTION:()=>bZ,CleanOptions:()=>Q4,cleanTask:()=>f5,cleanWithOptionsTask:()=>cH,isCleanOptionsArray:()=>lH});function cH(Z,Y){let{cleanMode:X,options:Q,valid:$}=iH(Z);if(!X)return b1(yZ);if(!$.options)return b1(bZ+JSON.stringify(Z));if(Q.push(...Y),Q.some(aH))return b1(_Z);return f5(X,Q)}function f5(Z,Y){return{commands:["clean",`-${Z}`,...Y],format:"utf-8",parser(Q){return pH(Z==="n",Q)}}}function lH(Z){return Array.isArray(Z)&&Z.every((Y)=>xZ.has(Y))}function iH(Z){let Y,X=[],Q={cleanMode:!1,options:!0};return Z.replace(/[^a-z]i/g,"").split("").forEach(($)=>{if(oH($))Y=$,Q.cleanMode=!0;else Q.options=Q.options&&nH(X[X.length]=`-${$}`)}),{cleanMode:Y,options:X,valid:Q}}function oH(Z){return Z==="f"||Z==="n"}function nH(Z){return/^-[a-z]$/i.test(Z)&&xZ.has(Z.charAt(1))}function aH(Z){if(/^-[^\-]/.test(Z))return Z.indexOf("i")>0;return Z==="--interactive"}var _Z,yZ,bZ,Q4,xZ,h5=D({"src/lib/tasks/clean.ts"(){dH(),_(),U1(),_Z="Git clean interactive mode is not supported",yZ='Git clean mode parameter ("n" or "f") is required',bZ="Git clean unknown option found in: ",Q4=((Z)=>{return Z.DRY_RUN="n",Z.FORCE="f",Z.IGNORED_INCLUDED="x",Z.IGNORED_ONLY="X",Z.EXCLUDING="e",Z.QUIET="q",Z.RECURSIVE="d",Z})(Q4||{}),xZ=new Set(["i",...k9(Object.values(Q4))])}});function rH(Z){let Y=new u5;for(let X of g5(Z))Y.addValue(X.file,String(X.key),X.value);return Y}function sH(Z,Y){let X=null,Q=[],$=new Map;for(let W of g5(Z,Y)){if(W.key!==Y)continue;if(Q.push(X=W.value),!$.has(W.file))$.set(W.file,[]);$.get(W.file).push(X)}return{key:Y,paths:Array.from($.keys()),scopes:$,value:X,values:Q}}function tH(Z){return Z.replace(/^(file):/,"")}function*g5(Z,Y=null){let X=Z.split("\x00");for(let Q=0,$=X.length-1;Q<$;){let W=tH(X[Q++]),J=X[Q++],z=Y;if(J.includes(`
36
+ `)){let V=K5(J,`
37
+ `);z=V[0],J=V[1]}yield{file:W,key:z,value:J}}}var u5,eH=D({"src/lib/responses/ConfigList.ts"(){_(),u5=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){if(!this._all)this._all=this.files.reduce((Z,Y)=>{return Object.assign(Z,this.values[Y])},{});return this._all}addFile(Z){if(!(Z in this.values)){let Y=q9(this.files);this.values[Z]=Y?Object.create(this.values[Y]):{},this.files.push(Z)}return this.values[Z]}addValue(Z,Y,X){let Q=this.addFile(Z);if(!Object.hasOwn(Q,Y))Q[Y]=X;else if(Array.isArray(Q[Y]))Q[Y].push(X);else Q[Y]=[Q[Y],X];this._all=void 0}}}});function $Z(Z,Y){if(typeof Z==="string"&&Object.hasOwn(FZ,Z))return Z;return Y}function ZG(Z,Y,X,Q){let $=["config",`--${Q}`];if(X)$.push("--add");return $.push(Z,Y),{commands:$,format:"utf-8",parser(W){return W}}}function YG(Z,Y){let X=["config","--null","--show-origin","--get-all",Z];if(Y)X.splice(1,0,`--${Y}`);return{commands:X,format:"utf-8",parser(Q){return sH(Q,Z)}}}function XG(Z){let Y=["config","--list","--show-origin","--null"];if(Z)Y.push(`--${Z}`);return{commands:Y,format:"utf-8",parser(X){return rH(X)}}}function QG(){return{addConfig(Z,Y,...X){return this._runTask(ZG(Z,Y,X[0]===!0,$Z(X[1],"local")),z1(arguments))},getConfig(Z,Y){return this._runTask(YG(Z,$Z(Y,void 0)),z1(arguments))},listConfig(...Z){return this._runTask(XG($Z(Z[0],void 0)),z1(arguments))}}}var FZ,m5=D({"src/lib/tasks/config.ts"(){eH(),_(),FZ=((Z)=>{return Z.system="system",Z.global="global",Z.local="local",Z.worktree="worktree",Z})(FZ||{})}});function $G(Z){return p5.has(Z)}var WZ,p5,d5=D({"src/lib/tasks/diff-name-status.ts"(){WZ=((Z)=>{return Z.ADDED="A",Z.COPIED="C",Z.DELETED="D",Z.MODIFIED="M",Z.RENAMED="R",Z.CHANGED="T",Z.UNMERGED="U",Z.UNKNOWN="X",Z.BROKEN="B",Z})(WZ||{}),p5=new Set(Object.values(WZ))}});function WG(...Z){return new l5().param(...Z)}function JG(Z){let Y=new Set,X={};return TZ(Z,(Q)=>{let[$,W,J]=Q.split(b9);Y.add($),(X[$]=X[$]||[]).push({line:a(W),path:$,preview:J})}),{paths:Y,results:X}}function zG(){return{grep(Z){let Y=z1(arguments),X=y1(arguments);for(let $ of c5)if(X.includes($))return this._runTask(b1(`git.grep: use of "${$}" is not supported.`),Y);if(typeof Z==="string")Z=WG().param(Z);let Q=["grep","--null","-n","--full-name",...X,...Z];return this._runTask({commands:Q,format:"utf-8",parser($){return JG($)}},Y)}}}var c5,N2,bX,l5,i5=D({"src/lib/tasks/grep.ts"(){_(),U1(),c5=["-h"],N2=Symbol("grepQuery"),l5=class{constructor(){this[bX]=[]}*[(bX=N2,Symbol.iterator)](){for(let Z of this[N2])yield Z}and(...Z){return Z.length&&this[N2].push("--and","(",...w2(Z,"-e"),")"),this}param(...Z){return this[N2].push(...w2(Z,"-e")),this}}}}),o5={};H1(o5,{ResetMode:()=>$4,getResetMode:()=>qG,resetTask:()=>VG});function VG(Z,Y){let X=["reset"];if(n5(Z))X.push(`--${Z}`);return X.push(...Y),j1(X)}function qG(Z){if(n5(Z))return Z;switch(typeof Z){case"string":case"undefined":return"soft"}return}function n5(Z){return typeof Z==="string"&&a5.includes(Z)}var $4,a5,r5=D({"src/lib/tasks/reset.ts"(){_(),U1(),$4=((Z)=>{return Z.MIXED="mixed",Z.SOFT="soft",Z.HARD="hard",Z.MERGE="merge",Z.KEEP="keep",Z})($4||{}),a5=k9(Object.values($4))}});function UG(){return U4.default("simple-git")}function xX(Z,Y,X){if(!Y||!String(Y).replace(/\s*/,""))return!X?Z:(Q,...$)=>{Z(Q,...$),X(Q,...$)};return(Q,...$)=>{if(Z(`%s ${Q}`,Y,...$),X)X(Q,...$)}}function HG(Z,Y,{namespace:X}){if(typeof Z==="string")return Z;let Q=Y&&Y.namespace||"";if(Q.startsWith(X))return Q.substr(X.length+1);return Q||X}function kZ(Z,Y,X,Q=UG()){let $=Z&&`[${Z}]`||"",W=[],J=typeof Y==="string"?Q.extend(Y):Y,z=HG(l1(Y,D1),J,Q);return q(X);function V(U,H){return d(W,kZ(Z,z.replace(/^[^:]+/,U),H,Q))}function q(U){let H=U&&`[${U}]`||"",G=J&&xX(J,H)||U9,K=xX(Q,`${$} ${H}`,G);return Object.assign(J?G:K,{label:Z,sibling:V,info:K,step:q})}}var s5=D({"src/lib/git-logger.ts"(){_(),U4.default.formatters.L=(Z)=>String(F4(Z)?Z.length:"-"),U4.default.formatters.B=(Z)=>{if(Buffer.isBuffer(Z))return Z.toString("utf8");return P2(Z)}}}),t5,GG=D({"src/lib/runners/tasks-pending-queue.ts"(){m0(),s5(),t5=class Z{constructor(Y="GitExecutor"){this.logLabel=Y,this._queue=new Map}withProgress(Y){return this._queue.get(Y)}createProgress(Y){let X=Z.getName(Y.commands[0]),Q=kZ(this.logLabel,X);return{task:Y,logger:Q,name:X}}push(Y){let X=this.createProgress(Y);return X.logger("Adding task to the queue, commands = %o",Y.commands),this._queue.set(Y,X),X}fatal(Y){for(let[X,{logger:Q}]of Array.from(this._queue.entries())){if(X===Y.task)Q.info("Failed %o",Y),Q("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted");else Q.info("A fatal exception occurred in a previous task, the queue has been purged: %o",Y.message);this.complete(X)}if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(Y){if(this.withProgress(Y))this._queue.delete(Y)}attempt(Y){let X=this.withProgress(Y);if(!X)throw new I0(void 0,"TasksPendingQueue: attempt called for an unknown task");return X.logger("Starting task"),X}static getName(Y="empty"){return`task:${Y}:${++Z.counter}`}static{this.counter=0}}}});function V9(Z,Y){return{method:B5(Z.commands)||"",commands:Y}}function BG(Z,Y){return(X)=>{Y("[ERROR] child process exception %o",X),Z.push(Buffer.from(String(X.stack),"ascii"))}}function kX(Z,Y,X,Q){return($)=>{X("%s received %L bytes",Y,$),Q("%B",$),Z.push($)}}var NZ,LG=D({"src/lib/runners/git-executor-chain.ts"(){m0(),U1(),_(),GG(),NZ=class{constructor(Z,Y,X){this._executor=Z,this._scheduler=Y,this._plugins=X,this._chain=Promise.resolve(),this._queue=new t5}get cwd(){return this._cwd||this._executor.cwd}set cwd(Z){this._cwd=Z}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(Z){return this._queue.push(Z),this._chain=this._chain.then(()=>this.attemptTask(Z))}async attemptTask(Z){let Y=await this._scheduler.next(),X=()=>this._queue.complete(Z);try{let{logger:Q}=this._queue.attempt(Z);return await(k5(Z)?this.attemptEmptyTask(Z,Q):this.attemptRemoteTask(Z,Q))}catch(Q){throw this.onFatalException(Z,Q)}finally{X(),Y()}}onFatalException(Z,Y){let X=Y instanceof I0?Object.assign(Y,{task:Z}):new I0(Z,Y&&String(Y));return this._chain=Promise.resolve(),this._queue.fatal(X),X}async attemptRemoteTask(Z,Y){let X=this._plugins.exec("spawn.binary","",V9(Z,Z.commands)),Q=this._plugins.exec("spawn.args",[...Z.commands],V9(Z,Z.commands)),$=await this.gitResponse(Z,X,Q,this.outputHandler,Y.step("SPAWN")),W=await this.handleTaskData(Z,Q,$,Y.step("HANDLE"));if(Y("passing response to task's parser as a %s",Z.format),x5(Z))return BZ(Z.parser,W);return BZ(Z.parser,W.asStrings())}async attemptEmptyTask(Z,Y){return Y("empty task bypassing child process to call to task's parser"),Z.parser(this)}handleTaskData(Z,Y,X,Q){let{exitCode:$,rejection:W,stdOut:J,stdErr:z}=X;return new Promise((V,q)=>{Q("Preparing to handle process response exitCode=%d stdOut=",$);let{error:U}=this._plugins.exec("task.error",{error:W},{...V9(Z,Y),...X});if(U&&Z.onError)return Q.info("exitCode=%s handling with custom error handler"),Z.onError(X,U,(H)=>{Q.info("custom error handler treated as success"),Q("custom error returned a %s",P2(H)),V(new q4(Array.isArray(H)?Buffer.concat(H):H,Buffer.concat(z)))},q);if(U)return Q.info("handling as error: exitCode=%s stdErr=%s rejection=%o",$,z.length,W),q(U);Q.info("retrieving task output complete"),V(new q4(Buffer.concat(J),Buffer.concat(z)))})}async gitResponse(Z,Y,X,Q,$){let W=$.sibling("output"),J=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},V9(Z,Z.commands));return new Promise((z)=>{let V=[],q=[];$.info("%s %o",Y,X),$("%O",J);let U=this._beforeSpawn(Z,X);if(U)return z({stdOut:V,stdErr:q,exitCode:9901,rejection:U});this._plugins.exec("spawn.before",void 0,{...V9(Z,X),kill(G){U=G||U}});let H=KG(Y,X,J);if(H.stdout.on("data",kX(V,"stdOut",$,W.step("stdOut"))),H.stderr.on("data",kX(q,"stdErr",$,W.step("stdErr"))),H.on("error",BG(q,$)),Q)$("Passing child process stdOut/stdErr to custom outputHandler"),Q(Y,H.stdout,H.stderr,[...X]);this._plugins.exec("spawn.after",void 0,{...V9(Z,X),spawned:H,close(G,K){z({stdOut:V,stdErr:q,exitCode:G,rejection:U||K})},kill(G){if(H.killed)return;U=G,H.kill("SIGINT")}})})}_beforeSpawn(Z,Y){let X;return this._plugins.exec("spawn.before",void 0,{...V9(Z,Y),kill(Q){X=Q||X}}),X}}}}),e5={};H1(e5,{GitExecutor:()=>ZQ});var ZQ,MG=D({"src/lib/runners/git-executor.ts"(){LG(),ZQ=class{constructor(Z,Y,X){this.cwd=Z,this._scheduler=Y,this._plugins=X,this._chain=new NZ(this,this._scheduler,this._plugins)}chain(){return new NZ(this,this._scheduler,this._plugins)}push(Z){return this._chain.push(Z)}}}});function FG(Z,Y,X=U9){let Q=(W)=>{X(null,W)},$=(W)=>{if(W?.task===Z)X(W instanceof E2?NG(W):W,void 0)};Y.then(Q,$)}function NG(Z){let Y=(Q)=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${Q} should be GitResponseError.git.${Q}, this will no longer be available in version 3`),Y=U9};return Object.create(Z,Object.getOwnPropertyNames(Z.git).reduce(X,{}));function X(Q,$){if($ in Z)return Q;return Q[$]={enumerable:!1,configurable:!1,get(){return Y($),Z.git[$]}},Q}}var wG=D({"src/lib/task-callback.ts"(){x9(),_()}});function vX(Z,Y){return y5((X)=>{if(!IZ(Z))throw new Error(`Git.cwd: cannot change to non-directory "${Z}"`);return(Y||X).cwd=Z})}var DG=D({"src/lib/tasks/change-working-directory.ts"(){_(),U1()}});function JZ(Z){let Y=["checkout",...Z];if(Y[1]==="-b"&&Y.includes("-B"))Y[1]=B4(Y,"-B");return j1(Y)}function AG(){return{checkout(){return this._runTask(JZ(y1(arguments,1)),z1(arguments))},checkoutBranch(Z,Y){return this._runTask(JZ(["-b",Z,Y,...y1(arguments)]),z1(arguments))},checkoutLocalBranch(Z){return this._runTask(JZ(["-b",Z,...y1(arguments)]),z1(arguments))}}}var EG=D({"src/lib/tasks/checkout.ts"(){_(),U1()}});function OG(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function PG(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(Z){return x1(OG(),[YQ],Z)}})}}}var YQ,TG=D({"src/lib/tasks/count-objects.ts"(){_(),YQ=new k(/([a-z-]+): (\d+)$/,(Z,[Y,X])=>{let Q=F5(Y);if(Object.hasOwn(Z,Q))Z[Q]=a(X)})}});function IG(Z){return x1({author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}},XQ,Z)}var XQ,RG=D({"src/lib/parsers/parse-commit.ts"(){_(),XQ=[new k(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(Z,[Y,X,Q])=>{Z.branch=Y,Z.commit=Q,Z.root=!!X}),new k(/\s*Author:\s(.+)/i,(Z,[Y])=>{let X=Y.split("<"),Q=X.pop();if(!Q||!Q.includes("@"))return;Z.author={email:Q.substr(0,Q.length-1),name:X.join("<").trim()}}),new k(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(Z,[Y,X,Q])=>{Z.summary.changes=parseInt(Y,10)||0,Z.summary.insertions=parseInt(X,10)||0,Z.summary.deletions=parseInt(Q,10)||0}),new k(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(Z,[Y,X,Q])=>{Z.summary.changes=parseInt(Y,10)||0;let $=parseInt(X,10)||0;if(Q==="-")Z.summary.deletions=$;else if(Q==="+")Z.summary.insertions=$})]}});function jG(Z,Y,X){return{commands:["-c","core.abbrev=40","commit",...w2(Z,"-m"),...Y,...X],format:"utf-8",parser:IG}}function CG(){return{commit(Y,...X){let Q=z1(arguments),$=Z(Y)||jG(L0(Y),L0(l1(X[0],V4,[])),[...k9(l1(X[1],T2,[])),...y1(arguments,0,!0)]);return this._runTask($,Q)}};function Z(Y){return!V4(Y)&&b1("git.commit: requires the commit message to be supplied as a string/string[]")}}var SG=D({"src/lib/tasks/commit.ts"(){RG(),_(),U1()}});function _G(){return{firstCommit(){return this._runTask(j1(["rev-list","--max-parents=0","HEAD"],!0),z1(arguments))}}}var yG=D({"src/lib/tasks/first-commit.ts"(){_(),U1()}});function bG(Z,Y){let X=["hash-object",Z];if(Y)X.push("-w");return j1(X,!0)}var xG=D({"src/lib/tasks/hash-object.ts"(){U1()}});function kG(Z,Y,X){let Q=String(X).trim(),$;if($=QQ.exec(Q))return new W4(Z,Y,!1,$[1]);if($=$Q.exec(Q))return new W4(Z,Y,!0,$[1]);let W="",J=Q.split(" ");while(J.length)if(J.shift()==="in"){W=J.join(" ");break}return new W4(Z,Y,/^re/i.test(Q),W)}var W4,QQ,$Q,vG=D({"src/lib/responses/InitSummary.ts"(){W4=class{constructor(Z,Y,X,Q){this.bare=Z,this.path=Y,this.existing=X,this.gitDir=Q}},QQ=/^Init.+ repository in (.+)$/,$Q=/^Rein.+ in (.+)$/}});function fG(Z){return Z.includes(vZ)}function hG(Z=!1,Y,X){let Q=["init",...X];if(Z&&!fG(Q))Q.splice(1,0,vZ);return{commands:Q,format:"utf-8",parser($){return kG(Q.includes("--bare"),Y,$)}}}var vZ,gG=D({"src/lib/tasks/init.ts"(){vG(),vZ="--bare"}});function fZ(Z){for(let Y=0;Y<Z.length;Y++){let X=hZ.exec(Z[Y]);if(X)return`--${X[1]}`}return""}function uG(Z){return hZ.test(Z)}var hZ,I2=D({"src/lib/args/log-format.ts"(){hZ=/^--(stat|numstat|name-only|name-status)(=|$)/}}),WQ,mG=D({"src/lib/responses/DiffSummary.ts"(){WQ=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}});function JQ(Z=""){let Y=zQ[Z];return(X)=>x1(new WQ,Y,X,!1)}var zZ,fX,hX,gX,zQ,VQ=D({"src/lib/parsers/parse-diff-summary.ts"(){I2(),mG(),d5(),_(),zZ=[new k(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(Z,[Y,X,Q=""])=>{Z.files.push({file:Y.trim(),changes:a(X),insertions:Q.replace(/[^+]/g,"").length,deletions:Q.replace(/[^-]/g,"").length,binary:!1})}),new k(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(Z,[Y,X,Q])=>{Z.files.push({file:Y.trim(),before:a(X),after:a(Q),binary:!0})}),new k(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(Z,[Y,X])=>{let Q=/(\d+) i/.exec(X),$=/(\d+) d/.exec(X);Z.changed=a(Y),Z.insertions=a(Q?.[1]),Z.deletions=a($?.[1])})],fX=[new k(/(\d+)\t(\d+)\t(.+)$/,(Z,[Y,X,Q])=>{let $=a(Y),W=a(X);Z.changed++,Z.insertions+=$,Z.deletions+=W,Z.files.push({file:Q,changes:$+W,insertions:$,deletions:W,binary:!1})}),new k(/-\t-\t(.+)$/,(Z,[Y])=>{Z.changed++,Z.files.push({file:Y,after:0,before:0,binary:!0})})],hX=[new k(/(.+)$/,(Z,[Y])=>{Z.changed++,Z.files.push({file:Y,changes:0,insertions:0,deletions:0,binary:!1})})],gX=[new k(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(Z,[Y,X,Q,$,W])=>{Z.changed++,Z.files.push({file:W??Q,changes:0,insertions:0,deletions:0,binary:!1,status:HZ($G(Y)&&Y),from:HZ(!!W&&Q!==W&&Q),similarity:a(X)})})],zQ={[""]:zZ,["--stat"]:zZ,["--numstat"]:fX,["--name-status"]:gX,["--name-only"]:hX}}});function pG(Z,Y){return Y.reduce((X,Q,$)=>{return X[Q]=Z[$]||"",X},Object.create({diff:null}))}function qQ(Z=mZ,Y=UQ,X=""){let Q=JQ(X);return function($){let W=O2($.trim(),!1,gZ).map(function(J){let z=J.split(uZ),V=pG(z[0].split(Z),Y);if(z.length>1&&!!z[1].trim())V.diff=Q(z[1]);return V});return{all:W,latest:W.length&&W[0]||null,total:W.length}}}var gZ,uZ,mZ,UQ,HQ=D({"src/lib/parsers/parse-list-log-summary.ts"(){_(),VQ(),I2(),gZ="òòòòòò ",uZ=" òò",mZ=" ò ",UQ=["hash","date","message","refs","author_name","author_email"]}}),GQ={};H1(GQ,{diffSummaryTask:()=>dG,validateLogFormatConfig:()=>D4});function dG(Z){let Y=fZ(Z),X=["diff"];if(Y==="")Y="--stat",X.push("--stat=4096");return X.push(...Z),D4(X)||{commands:X,format:"utf-8",parser:JQ(Y)}}function D4(Z){let Y=Z.filter(uG);if(Y.length>1)return b1(`Summary flags are mutually exclusive - pick one of ${Y.join(",")}`);if(Y.length&&Z.includes("-z"))return b1(`Summary flag ${Y} parsing is not compatible with null termination option '-z'`)}var pZ=D({"src/lib/tasks/diff.ts"(){I2(),VQ(),U1()}});function cG(Z,Y){let X=[],Q=[];return Object.keys(Z).forEach(($)=>{X.push($),Q.push(String(Z[$]))}),[X,Q.join(Y)]}function lG(Z){return Object.keys(Z).reduce((Y,X)=>{if(!(X in wZ))Y[X]=Z[X];return Y},{})}function KQ(Z={},Y=[]){let X=l1(Z.splitter,D1,mZ),Q=M4(Z.format)?Z.format:{hash:"%H",date:Z.strictDate===!1?"%ai":"%aI",message:"%s",refs:"%D",body:Z.multiLine?"%B":"%b",author_name:Z.mailMap!==!1?"%aN":"%an",author_email:Z.mailMap!==!1?"%aE":"%ae"},[$,W]=cG(Q,X),J=[],z=[`--pretty=format:${gZ}${W}${uZ}`,...Y],V=Z.n||Z["max-count"]||Z.maxCount;if(V)z.push(`--max-count=${V}`);if(Z.from||Z.to){let q=Z.symmetric!==!1?"...":"..";J.push(`${Z.from||""}${q}${Z.to||""}`)}if(D1(Z.file))z.push("--follow",SH(Z.file));return jZ(lG(Z),z),{fields:$,splitter:X,commands:[...z,...J]}}function iG(Z,Y,X){let Q=qQ(Z,Y,fZ(X));return{commands:["log",...X],format:"utf-8",parser:Q}}function oG(){return{log(...X){let Q=z1(arguments),$=KQ(CZ(arguments),k9(l1(arguments[0],T2,[]))),W=Y(...X)||D4($.commands)||Z($);return this._runTask(W,Q)}};function Z(X){return iG(X.splitter,X.fields,X.commands)}function Y(X,Q){return D1(X)&&D1(Q)&&b1("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var wZ,BQ=D({"src/lib/tasks/log.ts"(){I2(),A2(),HQ(),_(),U1(),pZ(),wZ=((Z)=>{return Z[Z["--pretty"]=0]="--pretty",Z[Z["max-count"]=1]="max-count",Z[Z.maxCount=2]="maxCount",Z[Z.n=3]="n",Z[Z.file=4]="file",Z[Z.format=5]="format",Z[Z.from=6]="from",Z[Z.to=7]="to",Z[Z.splitter=8]="splitter",Z[Z.symmetric=9]="symmetric",Z[Z.mailMap=10]="mailMap",Z[Z.multiLine=11]="multiLine",Z[Z.strictDate=12]="strictDate",Z})(wZ||{})}}),J4,LQ,nG=D({"src/lib/responses/MergeSummary.ts"(){J4=class{constructor(Z,Y=null,X){this.reason=Z,this.file=Y,this.meta=X}toString(){return`${this.file}:${this.reason}`}},LQ=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){if(this.conflicts.length)return`CONFLICTS: ${this.conflicts.join(", ")}`;return"OK"}}}}),DZ,MQ,aG=D({"src/lib/responses/PullSummary.ts"(){DZ=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},MQ=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}});function VZ(Z){return Z.objects=Z.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function uX(Z){let Y=/^\s*(\d+)/.exec(Z),X=/delta (\d+)/i.exec(Z);return{count:a(Y&&Y[1]||"0"),delta:a(X&&X[1]||"0")}}var FQ,rG=D({"src/lib/parsers/parse-remote-objects.ts"(){_(),FQ=[new u0(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(Z,[Y,X])=>{let Q=Y.toLowerCase(),$=VZ(Z.remoteMessages);Object.assign($,{[Q]:a(X)})}),new u0(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(Z,[Y,X])=>{let Q=Y.toLowerCase(),$=VZ(Z.remoteMessages);Object.assign($,{[Q]:a(X)})}),new u0(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(Z,[Y,X,Q])=>{let $=VZ(Z.remoteMessages);$.total=uX(Y),$.reused=uX(X),$.packReused=a(Q)})]}});function NQ(Z,Y){return x1({remoteMessages:new DQ},wQ,Y)}var wQ,DQ,AQ=D({"src/lib/parsers/parse-remote-messages.ts"(){_(),rG(),wQ=[new u0(/^remote:\s*(.+)$/,(Z,[Y])=>{return Z.remoteMessages.all.push(Y.trim()),!1}),...FQ,new u0([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(Z,[Y])=>{Z.remoteMessages.pullRequestUrl=Y}),new u0([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(Z,[Y,X,Q])=>{Z.remoteMessages.vulnerabilities={count:a(Y),summary:X,url:Q}})],DQ=class{constructor(){this.all=[]}}}});function sG(Z,Y){let X=x1(new MQ,EQ,[Z,Y]);return X.message&&X}var mX,pX,dX,cX,EQ,lX,dZ,OQ=D({"src/lib/parsers/parse-pull.ts"(){aG(),_(),AQ(),mX=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,pX=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,dX=/^(create|delete) mode \d+ (.+)/,cX=[new k(mX,(Z,[Y,X,Q])=>{if(Z.files.push(Y),X)Z.insertions[Y]=X.length;if(Q)Z.deletions[Y]=Q.length}),new k(pX,(Z,[Y,,X,,Q])=>{if(X!==void 0||Q!==void 0)return Z.summary.changes=+Y||0,Z.summary.insertions=+X||0,Z.summary.deletions=+Q||0,!0;return!1}),new k(dX,(Z,[Y,X])=>{d(Z.files,X),d(Y==="create"?Z.created:Z.deleted,X)})],EQ=[new k(/^from\s(.+)$/i,(Z,[Y])=>void(Z.remote=Y)),new k(/^fatal:\s(.+)$/,(Z,[Y])=>void(Z.message=Y)),new k(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(Z,[Y,X,Q,$])=>{Z.branch.local=Q,Z.hash.local=Y,Z.branch.remote=$,Z.hash.remote=X})],lX=(Z,Y)=>{return x1(new DZ,cX,[Z,Y])},dZ=(Z,Y)=>{return Object.assign(new DZ,lX(Z,Y),NQ(Z,Y))}}}),iX,PQ,oX,tG=D({"src/lib/parsers/parse-merge.ts"(){nG(),_(),OQ(),iX=[new k(/^Auto-merging\s+(.+)$/,(Z,[Y])=>{Z.merges.push(Y)}),new k(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(Z,[Y,X])=>{Z.conflicts.push(new J4(Y,X))}),new k(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(Z,[Y,X,Q])=>{Z.conflicts.push(new J4(Y,X,{deleteRef:Q}))}),new k(/^CONFLICT\s+\((.+)\):/,(Z,[Y])=>{Z.conflicts.push(new J4(Y,null))}),new k(/^Automatic merge failed;\s+(.+)$/,(Z,[Y])=>{Z.result=Y})],PQ=(Z,Y)=>{return Object.assign(oX(Z,Y),dZ(Z,Y))},oX=(Z)=>{return x1(new LQ,iX,Z)}}});function nX(Z){if(!Z.length)return b1("Git.merge requires at least one option");return{commands:["merge",...Z],format:"utf-8",parser(Y,X){let Q=PQ(Y,X);if(Q.failed)throw new E2(Q);return Q}}}var eG=D({"src/lib/tasks/merge.ts"(){x9(),tG(),U1()}});function ZK(Z,Y,X){let Q=X.includes("deleted"),$=X.includes("tag")||/^refs\/tags/.test(Z),W=!X.includes("new");return{deleted:Q,tag:$,branch:!$,new:!W,alreadyUpdated:W,local:Z,remote:Y}}var aX,TQ,rX,YK=D({"src/lib/parsers/parse-push.ts"(){_(),AQ(),aX=[new k(/^Pushing to (.+)$/,(Z,[Y])=>{Z.repo=Y}),new k(/^updating local tracking ref '(.+)'/,(Z,[Y])=>{Z.ref={...Z.ref||{},local:Y}}),new k(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(Z,[Y,X,Q])=>{Z.pushed.push(ZK(Y,X,Q))}),new k(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(Z,[Y,X,Q])=>{Z.branch={...Z.branch||{},local:Y,remote:X,remoteName:Q}}),new k(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(Z,[Y,X,Q,$])=>{Z.update={head:{local:Y,remote:X},hash:{from:Q,to:$}}})],TQ=(Z,Y)=>{let X=rX(Z,Y),Q=NQ(Z,Y);return{...X,...Q}},rX=(Z,Y)=>{return x1({pushed:[]},aX,[Z,Y])}}}),IQ={};H1(IQ,{pushTagsTask:()=>XK,pushTask:()=>cZ});function XK(Z={},Y){return d(Y,"--tags"),cZ(Z,Y)}function cZ(Z={},Y){let X=["push",...Y];if(Z.branch)X.splice(1,0,Z.branch);if(Z.remote)X.splice(1,0,Z.remote);return B4(X,"-v"),d(X,"--verbose"),d(X,"--porcelain"),{commands:X,format:"utf-8",parser:TQ}}var RQ=D({"src/lib/tasks/push.ts"(){YK(),_()}});function QK(){return{showBuffer(){let Z=["show",...y1(arguments,1)];if(!Z.includes("--binary"))Z.splice(1,0,"--binary");return this._runTask(b5(Z),z1(arguments))},show(){let Z=["show",...y1(arguments,1)];return this._runTask(j1(Z),z1(arguments))}}}var $K=D({"src/lib/tasks/show.ts"(){_(),U1()}}),sX,jQ,WK=D({"src/lib/responses/FileStatusSummary.ts"(){sX=/^(.+)\0(.+)$/,jQ=class{constructor(Z,Y,X){if(this.path=Z,this.index=Y,this.working_dir=X,Y==="R"||X==="R"){let Q=sX.exec(Z)||[null,Z,Z];this.from=Q[2]||"",this.path=Q[1]||""}}}}});function tX(Z){let[Y,X]=Z.split(b9);return{from:X||Y,to:Y}}function c1(Z,Y,X){return[`${Z}${Y}`,X]}function qZ(Z,...Y){return Y.map((X)=>c1(Z,X,(Q,$)=>d(Q.conflicted,$)))}function JK(Z,Y){let X=Y.trim();switch(" "){case X.charAt(2):return Q(X.charAt(0),X.charAt(1),X.substr(3));case X.charAt(1):return Q(" ",X.charAt(0),X.substr(2));default:return}function Q($,W,J){let z=`${$}${W}`,V=CQ.get(z);if(V)V(Z,J);if(z!=="##"&&z!=="!!")Z.files.push(new jQ(J,$,W))}}var eX,CQ,SQ,zK=D({"src/lib/responses/StatusSummary.ts"(){_(),WK(),eX=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>{return!this.files.length}}},CQ=new Map([c1(" ","A",(Z,Y)=>d(Z.created,Y)),c1(" ","D",(Z,Y)=>d(Z.deleted,Y)),c1(" ","M",(Z,Y)=>d(Z.modified,Y)),c1("A"," ",(Z,Y)=>d(Z.created,Y)&&d(Z.staged,Y)),c1("A","M",(Z,Y)=>d(Z.created,Y)&&d(Z.staged,Y)&&d(Z.modified,Y)),c1("D"," ",(Z,Y)=>d(Z.deleted,Y)&&d(Z.staged,Y)),c1("M"," ",(Z,Y)=>d(Z.modified,Y)&&d(Z.staged,Y)),c1("M","M",(Z,Y)=>d(Z.modified,Y)&&d(Z.staged,Y)),c1("R"," ",(Z,Y)=>{d(Z.renamed,tX(Y))}),c1("R","M",(Z,Y)=>{let X=tX(Y);d(Z.renamed,X),d(Z.modified,X.to)}),c1("!","!",(Z,Y)=>{d(Z.ignored=Z.ignored||[],Y)}),c1("?","?",(Z,Y)=>d(Z.not_added,Y)),...qZ("A","A","U"),...qZ("D","D","U"),...qZ("U","A","D","U"),["##",(Z,Y)=>{let X=/ahead (\d+)/,Q=/behind (\d+)/,$=/^(.+?(?=(?:\.{3}|\s|$)))/,W=/\.{3}(\S*)/,J=/\son\s(\S+?)(?=\.{3}|$)/,z=X.exec(Y);if(Z.ahead=z&&+z[1]||0,z=Q.exec(Y),Z.behind=z&&+z[1]||0,z=$.exec(Y),Z.current=l1(z?.[1],D1,null),z=W.exec(Y),Z.tracking=l1(z?.[1],D1,null),z=J.exec(Y),z)Z.current=l1(z?.[1],D1,Z.current);Z.detached=/\(no branch\)/.test(Y)}]]),SQ=function(Z){let Y=Z.split(b9),X=new eX;for(let Q=0,$=Y.length;Q<$;){let W=Y[Q++].trim();if(!W)continue;if(W.charAt(0)==="R")W+=b9+(Y[Q++]||"");JK(X,W)}return X}}});function VK(Z){return{format:"utf-8",commands:["status","--porcelain","-b","-u","--null",...Z.filter((X)=>!_Q.includes(X))],parser(X){return SQ(X)}}}var _Q,qK=D({"src/lib/tasks/status.ts"(){zK(),_Q=["--null","-z"]}});function H4(Z=0,Y=0,X=0,Q="",$=!0){return Object.defineProperty({major:Z,minor:Y,patch:X,agent:Q,installed:$},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function UK(){return H4(0,0,0,"",!1)}function HK(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:GK,onError(Z,Y,X,Q){if(Z.exitCode===-2)return X(Buffer.from(lZ));Q(Y)}})}}}function GK(Z){if(Z===lZ)return UK();return x1(H4(0,0,0,Z),yQ,Z)}var lZ,yQ,KK=D({"src/lib/tasks/version.ts"(){_(),lZ="installed=false",yQ=[new k(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(Z,[Y,X,Q,$=""])=>{Object.assign(Z,H4(a(Y),a(X),a(Q),$))}),new k(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(Z,[Y,X,Q,$=""])=>{Object.assign(Z,H4(a(Y),a(X),Q,$))})]}}),bQ={};H1(bQ,{SimpleGitApi:()=>AZ});var AZ,BK=D({"src/lib/simple-git-api.ts"(){wG(),DG(),EG(),TG(),SG(),m5(),yG(),i5(),xG(),gG(),BQ(),eG(),RQ(),$K(),qK(),U1(),KK(),_(),AZ=class{constructor(Z){this._executor=Z}_runTask(Z,Y){let X=this._executor.chain(),Q=X.push(Z);if(Y)FG(Z,Q,Y);return Object.create(this,{then:{value:Q.then.bind(Q)},catch:{value:Q.catch.bind(Q)},_executor:{value:X}})}add(Z){return this._runTask(j1(["add",...L0(Z)]),z1(arguments))}cwd(Z){let Y=z1(arguments);if(typeof Z==="string")return this._runTask(vX(Z,this._executor),Y);if(typeof Z?.path==="string")return this._runTask(vX(Z.path,Z.root&&this._executor||void 0),Y);return this._runTask(b1("Git.cwd: workingDirectory must be supplied as a string"),Y)}hashObject(Z,Y){return this._runTask(bG(Z,Y===!0),z1(arguments))}init(Z){return this._runTask(hG(Z===!0,this._executor.cwd,y1(arguments)),z1(arguments))}merge(){return this._runTask(nX(y1(arguments)),z1(arguments))}mergeFromTo(Z,Y){if(!(D1(Z)&&D1(Y)))return this._runTask(b1("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"));return this._runTask(nX([Z,Y,...y1(arguments)]),z1(arguments,!1))}outputHandler(Z){return this._executor.outputHandler=Z,this}push(){let Z=cZ({remote:l1(arguments[0],D1),branch:l1(arguments[1],D1)},y1(arguments));return this._runTask(Z,z1(arguments))}stash(){return this._runTask(j1(["stash",...y1(arguments)]),z1(arguments))}status(){return this._runTask(VK(y1(arguments)),z1(arguments))}},Object.assign(AZ.prototype,AG(),CG(),QG(),PG(),_G(),zG(),oG(),QK(),HK())}}),xQ={};H1(xQ,{Scheduler:()=>vQ});var Z5,vQ,LK=D({"src/lib/runners/scheduler.ts"(){_(),s5(),Z5=(()=>{let Z=0;return()=>{Z++;let{promise:Y,done:X}=kQ.createDeferred();return{promise:Y,done:X,id:Z}}})(),vQ=class{constructor(Z=2){this.concurrency=Z,this.logger=kZ("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",Z)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let Z=d(this.running,this.pending.shift());this.logger("Attempting id=%s",Z.id),Z.done(()=>{this.logger("Completing id=",Z.id),B4(this.running,Z),this.schedule()})}next(){let{promise:Z,id:Y}=d(this.pending,Z5());return this.logger("Scheduling id=%s",Y),this.schedule(),Z}}}}),fQ={};H1(fQ,{applyPatchTask:()=>MK});function MK(Z,Y){return j1(["apply",...Y,...Z])}var FK=D({"src/lib/tasks/apply-patch.ts"(){U1()}});function NK(Z,Y){return{branch:Z,hash:Y,success:!0}}function wK(Z){return{branch:Z,hash:null,success:!1}}var hQ,DK=D({"src/lib/responses/BranchDeleteSummary.ts"(){hQ=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function gQ(Z,Y){return Y===1&&EZ.test(Z)}var Y5,EZ,X5,A4,AK=D({"src/lib/parsers/parse-branch-delete.ts"(){DK(),_(),Y5=/(\S+)\s+\(\S+\s([^)]+)\)/,EZ=/^error[^']+'([^']+)'/m,X5=[new k(Y5,(Z,[Y,X])=>{let Q=NK(Y,X);Z.all.push(Q),Z.branches[Y]=Q}),new k(EZ,(Z,[Y])=>{let X=wK(Y);Z.errors.push(X),Z.all.push(X),Z.branches[Y]=X})],A4=(Z,Y)=>{return x1(new hQ,X5,[Z,Y])}}}),uQ,EK=D({"src/lib/responses/BranchSummary.ts"(){uQ=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(Z,Y,X,Q,$){if(Z==="*")this.detached=Y,this.current=X;this.all.push(X),this.branches[X]={current:Z==="*",linkedWorkTree:Z==="+",name:X,commit:Q,label:$}}}}});function Q5(Z){return Z?Z.charAt(0):""}function mQ(Z,Y=!1){return x1(new uQ,Y?[dQ]:pQ,Z)}var pQ,dQ,OK=D({"src/lib/parsers/parse-branch.ts"(){EK(),_(),pQ=[new k(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(Z,[Y,X,Q,$])=>{Z.push(Q5(Y),!0,X,Q,$)}),new k(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(Z,[Y,X,Q,$])=>{Z.push(Q5(Y),!1,X,Q,$)})],dQ=new k(/^(\S+)$/s,(Z,[Y])=>{Z.push("*",!1,Y,"","")})}}),cQ={};H1(cQ,{branchLocalTask:()=>TK,branchTask:()=>PK,containsDeleteBranchCommand:()=>lQ,deleteBranchTask:()=>RK,deleteBranchesTask:()=>IK});function lQ(Z){let Y=["-d","-D","--delete"];return Z.some((X)=>Y.includes(X))}function PK(Z){let Y=lQ(Z),X=Z.includes("--show-current"),Q=["branch",...Z];if(Q.length===1)Q.push("-a");if(!Q.includes("-v"))Q.splice(1,0,"-v");return{format:"utf-8",commands:Q,parser($,W){if(Y)return A4($,W).all[0];return mQ($,X)}}}function TK(){return{format:"utf-8",commands:["branch","-v"],parser(Z){return mQ(Z)}}}function IK(Z,Y=!1){return{format:"utf-8",commands:["branch","-v",Y?"-D":"-d",...Z],parser(X,Q){return A4(X,Q)},onError({exitCode:X,stdOut:Q},$,W,J){if(!gQ(String($),X))return J($);W(Q)}}}function RK(Z,Y=!1){let X={format:"utf-8",commands:["branch","-v",Y?"-D":"-d",Z],parser(Q,$){return A4(Q,$).branches[Z]},onError({exitCode:Q,stdErr:$,stdOut:W},J,z,V){if(!gQ(String(J),Q))return V(J);throw new E2(X.parser(D2(W),D2($)),String(J))}};return X}var jK=D({"src/lib/tasks/branch.ts"(){x9(),AK(),OK(),_()}});function SK(Z){let Y=Z.trim().replace(/^["']|["']$/g,"");return Y&&CK(Y)}var iQ,_K=D({"src/lib/responses/CheckIgnore.ts"(){iQ=(Z)=>{return Z.split(/\n/g).map(SK).filter(Boolean)}}}),oQ={};H1(oQ,{checkIgnoreTask:()=>yK});function yK(Z){return{commands:["check-ignore",...Z],format:"utf-8",parser:iQ}}var bK=D({"src/lib/tasks/check-ignore.ts"(){_K()}}),nQ={};H1(nQ,{cloneMirrorTask:()=>kK,cloneTask:()=>aQ});function xK(Z){return/^--upload-pack(=|$)/.test(Z)}function aQ(Z,Y,X){let Q=["clone",...X];if(D1(Z)&&Q.push(Z),D1(Y)&&Q.push(Y),Q.find(xK))return b1("git.fetch: potential exploit argument blocked.");return j1(Q)}function kK(Z,Y,X){return d(X,"--mirror"),aQ(Z,Y,X)}var vK=D({"src/lib/tasks/clone.ts"(){U1(),_()}});function fK(Z,Y){return x1({raw:Z,remote:null,branches:[],tags:[],updated:[],deleted:[]},rQ,[Z,Y])}var rQ,hK=D({"src/lib/parsers/parse-fetch.ts"(){_(),rQ=[new k(/From (.+)$/,(Z,[Y])=>{Z.remote=Y}),new k(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(Z,[Y,X])=>{Z.branches.push({name:Y,tracking:X})}),new k(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(Z,[Y,X])=>{Z.tags.push({name:Y,tracking:X})}),new k(/- \[deleted]\s+\S+\s*-> (.+)$/,(Z,[Y])=>{Z.deleted.push({tracking:Y})}),new k(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(Z,[Y,X,Q,$])=>{Z.updated.push({name:Q,tracking:$,to:X,from:Y})})]}}),sQ={};H1(sQ,{fetchTask:()=>uK});function gK(Z){return/^--upload-pack(=|$)/.test(Z)}function uK(Z,Y,X){let Q=["fetch",...X];if(Z&&Y)Q.push(Z,Y);if(Q.find(gK))return b1("git.fetch: potential exploit argument blocked.");return{commands:Q,format:"utf-8",parser:fK}}var mK=D({"src/lib/tasks/fetch.ts"(){hK(),U1()}});function pK(Z){return x1({moves:[]},tQ,Z)}var tQ,dK=D({"src/lib/parsers/parse-move.ts"(){_(),tQ=[new k(/^Renaming (.+) to (.+)$/,(Z,[Y,X])=>{Z.moves.push({from:Y,to:X})})]}}),eQ={};H1(eQ,{moveTask:()=>cK});function cK(Z,Y){return{commands:["mv","-v",...L0(Z),Y],format:"utf-8",parser:pK}}var lK=D({"src/lib/tasks/move.ts"(){dK(),_()}}),Z$={};H1(Z$,{pullTask:()=>iK});function iK(Z,Y,X){let Q=["pull",...X];if(Z&&Y)Q.splice(1,0,Z,Y);return{commands:Q,format:"utf-8",parser($,W){return dZ($,W)},onError($,W,J,z){let V=sG(D2($.stdOut),D2($.stdErr));if(V)return z(new E2(V));z(W)}}}var oK=D({"src/lib/tasks/pull.ts"(){x9(),OQ(),_()}});function nK(Z){let Y={};return Y$(Z,([X])=>Y[X]={name:X}),Object.values(Y)}function aK(Z){let Y={};return Y$(Z,([X,Q,$])=>{if(!Object.hasOwn(Y,X))Y[X]={name:X,refs:{fetch:"",push:""}};if($&&Q)Y[X].refs[$.replace(/[^a-z]/g,"")]=Q}),Object.values(Y)}function Y$(Z,Y){TZ(Z,(X)=>Y(X.split(/\s+/)))}var rK=D({"src/lib/responses/GetRemoteSummary.ts"(){_()}}),X$={};H1(X$,{addRemoteTask:()=>sK,getRemotesTask:()=>tK,listRemotesTask:()=>eK,remoteTask:()=>Z3,removeRemoteTask:()=>Y3});function sK(Z,Y,X){return j1(["remote","add",...X,Z,Y])}function tK(Z){let Y=["remote"];if(Z)Y.push("-v");return{commands:Y,format:"utf-8",parser:Z?aK:nK}}function eK(Z){let Y=[...Z];if(Y[0]!=="ls-remote")Y.unshift("ls-remote");return j1(Y)}function Z3(Z){let Y=[...Z];if(Y[0]!=="remote")Y.unshift("remote");return j1(Y)}function Y3(Z){return j1(["remote","remove",Z])}var X3=D({"src/lib/tasks/remote.ts"(){rK(),U1()}}),Q$={};H1(Q$,{stashListTask:()=>Q3});function Q3(Z={},Y){let X=KQ(Z),Q=["stash","list",...X.commands,...Y],$=qQ(X.splitter,X.fields,fZ(Q));return D4(Q)||{commands:Q,format:"utf-8",parser:$}}var $3=D({"src/lib/tasks/stash-list.ts"(){I2(),HQ(),pZ(),BQ()}}),$$={};H1($$,{addSubModuleTask:()=>W3,initSubModuleTask:()=>J3,subModuleTask:()=>E4,updateSubModuleTask:()=>z3});function W3(Z,Y){return E4(["add",Z,Y])}function J3(Z){return E4(["init",...Z])}function E4(Z){let Y=[...Z];if(Y[0]!=="submodule")Y.unshift("submodule");return j1(Y)}function z3(Z){return E4(["update",...Z])}var V3=D({"src/lib/tasks/sub-module.ts"(){U1()}});function q3(Z,Y){let X=Number.isNaN(Z),Q=Number.isNaN(Y);if(X!==Q)return X?1:-1;return X?W$(Z,Y):0}function W$(Z,Y){return Z===Y?0:Z>Y?1:-1}function U3(Z){return Z.trim()}function X4(Z){if(typeof Z==="string")return parseInt(Z.replace(/^\D+/g,""),10)||0;return 0}var $5,J$,H3=D({"src/lib/responses/TagList.ts"(){$5=class{constructor(Z,Y){this.all=Z,this.latest=Y}},J$=function(Z,Y=!1){let X=Z.split(`
38
+ `).map(U3).filter(Boolean);if(!Y)X.sort(function($,W){let J=$.split("."),z=W.split(".");if(J.length===1||z.length===1)return q3(X4(J[0]),X4(z[0]));for(let V=0,q=Math.max(J.length,z.length);V<q;V++){let U=W$(X4(J[V]),X4(z[V]));if(U)return U}return 0});let Q=Y?X[0]:[...X].reverse().find(($)=>$.indexOf(".")>=0);return new $5(X,Q)}}}),z$={};H1(z$,{addAnnotatedTagTask:()=>B3,addTagTask:()=>K3,tagListTask:()=>G3});function G3(Z=[]){let Y=Z.some((X)=>/^--sort=/.test(X));return{format:"utf-8",commands:["tag","-l",...Z],parser(X){return J$(X,Y)}}}function K3(Z){return{format:"utf-8",commands:["tag",Z],parser(){return{name:Z}}}}function B3(Z,Y){return{format:"utf-8",commands:["tag","-a","-m",Y,Z],parser(){return{name:Z}}}}var L3=D({"src/lib/tasks/tag.ts"(){H3()}}),M3=jH({"src/git.js"(Z,Y){var{GitExecutor:X}=(MG(),J1(e5)),{SimpleGitApi:Q}=(BK(),J1(bQ)),{Scheduler:$}=(LK(),J1(xQ)),{configurationErrorTask:W}=(U1(),J1(MZ)),{asArray:J,filterArray:z,filterPrimitives:V,filterString:q,filterStringOrStringArray:U,filterType:H,getTrailingOptions:G,trailingFunctionArgument:K,trailingOptionsArgument:M}=(_(),J1(O5)),{applyPatchTask:E}=(FK(),J1(fQ)),{branchTask:O,branchLocalTask:T,deleteBranchesTask:i,deleteBranchTask:g}=(jK(),J1(cQ)),{checkIgnoreTask:Z1}=(bK(),J1(oQ)),{checkIsRepoTask:$1}=(R5(),J1(P5)),{cloneTask:W1,cloneMirrorTask:A0}=(vK(),J1(nQ)),{cleanWithOptionsTask:z0,isCleanOptionsArray:W9}=(h5(),J1(v5)),{diffSummaryTask:u8}=(pZ(),J1(GQ)),{fetchTask:Nq}=(mK(),J1(sQ)),{moveTask:wq}=(lK(),J1(eQ)),{pullTask:Dq}=(oK(),J1(Z$)),{pushTagsTask:Aq}=(RQ(),J1(IQ)),{addRemoteTask:Eq,getRemotesTask:Oq,listRemotesTask:Pq,remoteTask:Tq,removeRemoteTask:Iq}=(X3(),J1(X$)),{getResetMode:Rq,resetTask:jq}=(r5(),J1(o5)),{stashListTask:Cq}=($3(),J1(Q$)),{addSubModuleTask:Sq,initSubModuleTask:_q,subModuleTask:yq,updateSubModuleTask:bq}=(V3(),J1($$)),{addAnnotatedTagTask:xq,addTagTask:kq,tagListTask:vq}=(L3(),J1(z$)),{straightThroughBufferTask:fq,straightThroughStringTask:B0}=(U1(),J1(MZ));function S(N,I){this._plugins=I,this._executor=new X(N.baseDir,new $(N.maxConcurrentProcesses),I),this._trimmed=N.trimmed}(S.prototype=Object.create(Q.prototype)).constructor=S,S.prototype.customBinary=function(N){return this._plugins.reconfigure("binary",N),this},S.prototype.env=function(N,I){if(arguments.length===1&&typeof N==="object")this._executor.env=N;else(this._executor.env=this._executor.env||{})[N]=I;return this},S.prototype.stashList=function(N){return this._runTask(Cq(M(arguments)||{},z(N)&&N||[]),K(arguments))};function a7(N,I,o,R1){if(typeof o!=="string")return W(`git.${N}() requires a string 'repoPath'`);return I(o,H(R1,q),G(arguments))}S.prototype.clone=function(){return this._runTask(a7("clone",W1,...arguments),K(arguments))},S.prototype.mirror=function(){return this._runTask(a7("mirror",A0,...arguments),K(arguments))},S.prototype.mv=function(N,I){return this._runTask(wq(N,I),K(arguments))},S.prototype.checkoutLatestTag=function(N){var I=this;return this.pull(function(){I.tags(function(o,R1){I.checkout(R1.latest,N)})})},S.prototype.pull=function(N,I,o,R1){return this._runTask(Dq(H(N,q),H(I,q),G(arguments)),K(arguments))},S.prototype.fetch=function(N,I){return this._runTask(Nq(H(N,q),H(I,q),G(arguments)),K(arguments))},S.prototype.silent=function(N){return console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"),this},S.prototype.tags=function(N,I){return this._runTask(vq(G(arguments)),K(arguments))},S.prototype.rebase=function(){return this._runTask(B0(["rebase",...G(arguments)]),K(arguments))},S.prototype.reset=function(N){return this._runTask(jq(Rq(N),G(arguments)),K(arguments))},S.prototype.revert=function(N){let I=K(arguments);if(typeof N!=="string")return this._runTask(W("Commit must be a string"),I);return this._runTask(B0(["revert",...G(arguments,0,!0),N]),I)},S.prototype.addTag=function(N){let I=typeof N==="string"?kq(N):W("Git.addTag requires a tag name");return this._runTask(I,K(arguments))},S.prototype.addAnnotatedTag=function(N,I){return this._runTask(xq(N,I),K(arguments))},S.prototype.deleteLocalBranch=function(N,I,o){return this._runTask(g(N,typeof I==="boolean"?I:!1),K(arguments))},S.prototype.deleteLocalBranches=function(N,I,o){return this._runTask(i(N,typeof I==="boolean"?I:!1),K(arguments))},S.prototype.branch=function(N,I){return this._runTask(O(G(arguments)),K(arguments))},S.prototype.branchLocal=function(N){return this._runTask(T(),K(arguments))},S.prototype.raw=function(N){let I=!Array.isArray(N),o=[].slice.call(I?arguments:N,0);for(let V0=0;V0<o.length&&I;V0++)if(!V(o[V0])){o.splice(V0,o.length-V0);break}o.push(...G(arguments,0,!0));var R1=K(arguments);if(!o.length)return this._runTask(W("Raw: must supply one or more command to execute"),R1);return this._runTask(B0(o,this._trimmed),R1)},S.prototype.submoduleAdd=function(N,I,o){return this._runTask(Sq(N,I),K(arguments))},S.prototype.submoduleUpdate=function(N,I){return this._runTask(bq(G(arguments,!0)),K(arguments))},S.prototype.submoduleInit=function(N,I){return this._runTask(_q(G(arguments,!0)),K(arguments))},S.prototype.subModule=function(N,I){return this._runTask(yq(G(arguments)),K(arguments))},S.prototype.listRemote=function(){return this._runTask(Pq(G(arguments)),K(arguments))},S.prototype.addRemote=function(N,I,o){return this._runTask(Eq(N,I,G(arguments)),K(arguments))},S.prototype.removeRemote=function(N,I){return this._runTask(Iq(N),K(arguments))},S.prototype.getRemotes=function(N,I){return this._runTask(Oq(N===!0),K(arguments))},S.prototype.remote=function(N,I){return this._runTask(Tq(G(arguments)),K(arguments))},S.prototype.tag=function(N,I){let o=G(arguments);if(o[0]!=="tag")o.unshift("tag");return this._runTask(B0(o),K(arguments))},S.prototype.updateServerInfo=function(N){return this._runTask(B0(["update-server-info"]),K(arguments))},S.prototype.pushTags=function(N,I){let o=Aq({remote:H(N,q)},G(arguments));return this._runTask(o,K(arguments))},S.prototype.rm=function(N){return this._runTask(B0(["rm","-f",...J(N)]),K(arguments))},S.prototype.rmKeepLocal=function(N){return this._runTask(B0(["rm","--cached",...J(N)]),K(arguments))},S.prototype.catFile=function(N,I){return this._catFile("utf-8",arguments)},S.prototype.binaryCatFile=function(){return this._catFile("buffer",arguments)},S.prototype._catFile=function(N,I){var o=K(I),R1=["cat-file"],V0=I[0];if(typeof V0==="string")return this._runTask(W("Git.catFile: options must be supplied as an array of strings"),o);if(Array.isArray(V0))R1.push.apply(R1,V0);let m8=N==="buffer"?fq(R1):B0(R1);return this._runTask(m8,o)},S.prototype.diff=function(N,I){let o=q(N)?W("git.diff: supplying options as a single string is no longer supported, switch to an array of strings"):B0(["diff",...G(arguments)]);return this._runTask(o,K(arguments))},S.prototype.diffSummary=function(){return this._runTask(u8(G(arguments,1)),K(arguments))},S.prototype.applyPatch=function(N){let I=!U(N)?W("git.applyPatch requires one or more string patches as the first argument"):E(J(N),G([].slice.call(arguments,1)));return this._runTask(I,K(arguments))},S.prototype.revparse=function(){let N=["rev-parse",...G(arguments,!0)];return this._runTask(B0(N,!0),K(arguments))},S.prototype.clean=function(N,I,o){let R1=W9(N),V0=R1&&N.join("")||H(N,q)||"",m8=G([].slice.call(arguments,R1?1:0));return this._runTask(z0(V0,m8),K(arguments))},S.prototype.exec=function(N){let I={commands:[],format:"utf-8",parser(){if(typeof N==="function")N()}};return this._runTask(I)},S.prototype.clearQueue=function(){return this},S.prototype.checkIgnore=function(N,I){return this._runTask(Z1(J(H(N,U,[]))),K(arguments))},S.prototype.checkIsRepo=function(N,I){return this._runTask($1(H(N,q)),K(arguments))},Y.exports=S}});A2();m0();var F3=class extends I0{constructor(Z,Y){super(void 0,Y);this.config=Z}};m0();m0();var T0=class extends I0{constructor(Z,Y,X){super(Z,X);this.task=Z,this.plugin=Y,Object.setPrototypeOf(this,new.target.prototype)}};x9();U5();R5();h5();m5();d5();i5();r5();function N3(Z){if(!Z)return;return[{type:"spawn.before",action(Q,$){if(Z.aborted)$.kill(new T0(void 0,"abort","Abort already signaled"))}},{type:"spawn.after",action(Q,$){function W(){$.kill(new T0(void 0,"abort","Abort signal received"))}Z.addEventListener("abort",W),$.spawned.on("close",()=>Z.removeEventListener("abort",W))}}]}function w3(Z){return typeof Z==="string"&&Z.trim().toLowerCase()==="-c"}function D3(Z,Y){if(!w3(Z))return;if(!/^\s*protocol(.[a-z]+)?.allow/.test(Y))return;throw new T0(void 0,"unsafe","Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol")}function A3(Z,Y){if(/^\s*--(upload|receive)-pack/.test(Z))throw new T0(void 0,"unsafe","Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack");if(Y==="clone"&&/^\s*-u\b/.test(Z))throw new T0(void 0,"unsafe","Use of clone with option -u is not permitted without enabling allowUnsafePack");if(Y==="push"&&/^\s*--exec\b/.test(Z))throw new T0(void 0,"unsafe","Use of push with option --exec is not permitted without enabling allowUnsafePack")}function E3({allowUnsafeProtocolOverride:Z=!1,allowUnsafePack:Y=!1}={}){return{type:"spawn.args",action(X,Q){return X.forEach(($,W)=>{let J=W<X.length?X[W+1]:"";Z||D3($,J),Y||A3($,Q.method)}),X}}}_();function O3(Z){let Y=w2(Z,"-c");return{type:"spawn.args",action(X){return[...Y,...X]}}}_();var W5=y9.deferred().promise;function P3({onClose:Z=!0,onExit:Y=50}={}){function X(){let $=-1,W={close:y9.deferred(),closeTimeout:y9.deferred(),exit:y9.deferred(),exitTimeout:y9.deferred()},J=Promise.race([Z===!1?W5:W.closeTimeout.promise,Y===!1?W5:W.exitTimeout.promise]);return Q(Z,W.close,W.closeTimeout),Q(Y,W.exit,W.exitTimeout),{close(z){$=z,W.close.done()},exit(z){$=z,W.exit.done()},get exitCode(){return $},result:J}}function Q($,W,J){if($===!1)return;($===!0?W.promise:W.promise.then(()=>UZ($))).then(J.done)}return{type:"spawn.after",async action($,{spawned:W,close:J}){let z=X(),V=!0,q=()=>void(V=!1);W.stdout?.on("data",q),W.stderr?.on("data",q),W.on("error",q),W.on("close",(U)=>z.close(U)),W.on("exit",(U)=>z.exit(U));try{if(await z.result,V)await UZ(50);J(z.exitCode)}catch(U){J(z.exitCode,U)}}}}_();var T3="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",J5="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function I3(Z){return!Z||!/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(Z)}function z5(Z,Y){if(Z.length<1||Z.length>2)throw new T0(void 0,"binary",T3);if(Z.some(I3))if(Y)console.warn(J5);else throw new T0(void 0,"binary",J5);let[Q,$]=Z;return{binary:Q,prefix:$}}function R3(Z,Y=["git"],X=!1){let Q=z5(L0(Y),X);Z.on("binary",($)=>{Q=z5(L0($),X)}),Z.append("spawn.binary",()=>{return Q.binary}),Z.append("spawn.args",($)=>{return Q.prefix?[Q.prefix,...$]:$})}m0();function j3(Z){return!!(Z.exitCode&&Z.stdErr.length)}function C3(Z){return Buffer.concat([...Z.stdOut,...Z.stdErr])}function S3(Z=!1,Y=j3,X=C3){return(Q,$)=>{if(!Z&&Q||!Y($))return Q;return X($)}}function V5(Z){return{type:"task.error",action(Y,X){let Q=Z(Y.error,{stdErr:X.stdErr,stdOut:X.stdOut,exitCode:X.exitCode});if(Buffer.isBuffer(Q))return{error:new I0(void 0,Q.toString("utf-8"))};return{error:Q}}}}_();var y3=class{constructor(){this.plugins=new Set,this.events=new _3}on(Z,Y){this.events.on(Z,Y)}reconfigure(Z,Y){this.events.emit(Z,Y)}append(Z,Y){let X=d(this.plugins,{type:Z,action:Y});return()=>this.plugins.delete(X)}add(Z){let Y=[];return L0(Z).forEach((X)=>X&&this.plugins.add(d(Y,X))),()=>{Y.forEach((X)=>this.plugins.delete(X))}}exec(Z,Y,X){let Q=Y,$=Object.freeze(Object.create(X));for(let W of this.plugins)if(W.type===Z)Q=W.action(Q,$);return Q}};_();function b3(Z){let X=["checkout","clone","fetch","pull","push"];return[{type:"spawn.args",action(W,J){if(!X.includes(J.method))return W;return M5(W,"--progress")}},{type:"spawn.after",action(W,J){if(!J.commands.includes("--progress"))return;J.spawned.stderr?.on("data",(z)=>{let V=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(z.toString("utf8"));if(!V)return;Z({method:J.method,stage:x3(V[1]),progress:a(V[2]),processed:a(V[3]),total:a(V[4])})})}}]}function x3(Z){return String(Z.toLowerCase().split(" ",1))||"unknown"}_();function k3(Z){let Y=N5(Z,["uid","gid"]);return{type:"spawn.options",action(X){return{...Y,...X}}}}function v3({block:Z,stdErr:Y=!0,stdOut:X=!0}){if(Z>0)return{type:"spawn.after",action(Q,$){let W;function J(){W&&clearTimeout(W),W=setTimeout(V,Z)}function z(){$.spawned.stdout?.off("data",J),$.spawned.stderr?.off("data",J),$.spawned.off("exit",z),$.spawned.off("close",z),W&&clearTimeout(W)}function V(){z(),$.kill(new T0(void 0,"timeout","block timeout reached"))}X&&$.spawned.stdout?.on("data",J),Y&&$.spawned.stderr?.on("data",J),$.spawned.on("exit",z),$.spawned.on("close",z),J()}}}A2();function f3(){return{type:"spawn.args",action(Z){let Y=[],X;function Q($){(X=X||[]).push(...$)}for(let $=0;$<Z.length;$++){let W=Z[$];if(z4(W)){Q(yX(W));continue}if(W==="--"){Q(Z.slice($+1).flatMap((J)=>z4(J)&&yX(J)||J));break}Y.push(W)}return!X?Y:[...Y,"--",...X.map(String)]}}}_();var h3=M3();function g3(Z,Y){let X=new y3,Q=A5(Z&&(typeof Z==="string"?{baseDir:Z}:Z)||{},Y);if(!IZ(Q.baseDir))throw new F3(Q,"Cannot use simple-git on a directory that does not exist");if(Array.isArray(Q.config))X.add(O3(Q.config));return X.add(E3(Q.unsafe)),X.add(f3()),X.add(P3(Q.completion)),Q.abort&&X.add(N3(Q.abort)),Q.progress&&X.add(b3(Q.progress)),Q.timeout&&X.add(v3(Q.timeout)),Q.spawnOptions&&X.add(k3(Q.spawnOptions)),X.add(V5(S3(!0))),Q.errors&&X.add(V5(Q.errors)),R3(X,Q.binary,Q.unsafe?.allowUnsafeCustomBinary),new h3(Q,X)}x9();var O4=g3;class O1 extends Error{code;constructor(Z,Y){super(Z);this.code=Y;this.name="GitError"}}function u3(Z){if(Z==="staged")return{args:["--cached"],description:"staged changes"};if(Z==="unstaged")return{args:[],description:"unstaged changes"};if(Z==="HEAD")return{args:["HEAD"],description:"all uncommitted changes"};if(Z.startsWith("branch:")){let Y=Z.slice(7);if(!Y)throw new O1("Branch name required","INVALID_TARGET");return{args:[Y],description:`changes vs ${Y}`}}if(Z.startsWith("commit:")){let Y=Z.slice(7);if(!Y)throw new O1("Commit hash required","INVALID_TARGET");return{args:[`${Y}^`,Y],description:`commit ${Y}`}}if(Z.startsWith("range:")){let Y=Z.slice(6),X=Y.match(/^([^.]+)\.\.([^.]+)$/);if(!X||!X[1]||!X[2])throw new O1("Invalid range format. Use range:abc123..def456","INVALID_TARGET");return{args:[X[1],X[2]],description:`range ${Y}`}}throw new O1(`Unknown target format: ${Z}. Use staged, unstaged, HEAD, branch:name, commit:hash, or range:a..b`,"INVALID_TARGET")}async function V$(Z){let Y=O4(Z);if(!await Y.checkIsRepo())throw new O1("Not a git repository","NOT_A_REPO");return Y}async function P4(Z="staged",Y){let X=await V$(Y),{args:Q}=u3(Z);try{let $=await X.diff(Q);return{diff:$,target:Z,hasChanges:$.trim().length>0}}catch($){let W=$ instanceof Error?$.message:String($);if(W.includes("unknown revision")||W.includes("bad revision")){if(Z.startsWith("branch:"))throw new O1(`Branch not found: ${Z.slice(7)}`,"BRANCH_NOT_FOUND");if(Z.startsWith("commit:")||Z.startsWith("range:"))throw new O1(`Commit not found in: ${Z}`,"COMMIT_NOT_FOUND")}throw new O1(`Git error: ${W}`,"GIT_ERROR")}}async function q$(Z,Y){let X=await V$(Y);try{return(await X.show([Z,"--format=%s%n%n%b","-s"])).trim()}catch(Q){let $=Q instanceof Error?Q.message:String(Q);if($.includes("unknown revision")||$.includes("bad revision"))throw new O1(`Commit not found: ${Z}`,"COMMIT_NOT_FOUND");throw new O1(`Git error: ${$}`,"GIT_ERROR")}}function v9(Z){if(!Z||Z.trim().length===0)return{files:[]};let Y=[],X=Z.split(`
39
+ `),Q=0;while(Q<X.length)if(X[Q]?.startsWith("diff --git ")){let{file:W,nextIndex:J}=m3(X,Q);Y.push(W),Q=J}else Q++;return{files:Y}}function m3(Z,Y){let X=Y,Q=Z[X];if(!Q)throw new Error(`Expected diff line at index ${X}`);let{path:$,oldPath:W}=p3(Q);X++;let J,z="modified",V=!1,q=[];while(X<Z.length){let H=Z[X];if(!H||H.startsWith("diff --git "))break;if(H.startsWith("new file mode")){z="added",X++;continue}if(H.startsWith("deleted file mode")){z="deleted",X++;continue}if(H.startsWith("rename from ")){J=H.slice(12),z="renamed",X++;continue}if(H.startsWith("rename to ")){X++;continue}if(H.startsWith("similarity index ")){X++;continue}if(H.startsWith("Binary files ")||H==="GIT binary patch"){V=!0,X++;while(X<Z.length){if(Z[X]?.startsWith("diff --git "))break;X++}break}if(H.startsWith("@@")){let{hunk:G,nextIndex:K}=d3(Z,X);q.push(G),X=K;continue}X++}if(!J&&W&&W!==$){if(J=W,z==="modified")z="renamed"}let U={path:$,status:z,hunks:q,isBinary:V};if(J!==void 0)U.oldPath=J;return{file:U,nextIndex:X}}function p3(Z){let Y=Z.match(/^diff --git a\/(.+) b\/(.+)$/);if(Y){let J=Y[1],z=Y[2];if(J&&z)return{path:z,oldPath:J!==z?J:void 0}}let X=Z.slice(11),Q=X.split(" b/"),$=Q[0],W=Q[1];if($&&W){let J=$.startsWith("a/")?$.slice(2):$;return{path:W,oldPath:J!==W?J:void 0}}return{path:X,oldPath:void 0}}function d3(Z,Y){let X=Z[Y];if(!X)throw new Error(`Expected hunk header at index ${Y}`);let Q=X.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(!Q)throw new Error(`Invalid hunk header: ${X}`);let $=Q[1],W=Q[2],J=Q[3],z=Q[4];if(!$||!J)throw new Error(`Invalid hunk header numbers: ${X}`);let V=parseInt($,10),q=W!==void 0?parseInt(W,10):1,U=parseInt(J,10),H=z!==void 0?parseInt(z,10):1,G=[],K=Y+1,M=V,E=U;while(K<Z.length){let O=Z[K];if(O===void 0)break;if(O.startsWith("diff --git ")||O.startsWith("@@"))break;if(O.startsWith("\\")){K++;continue}if(O===""&&K===Z.length-1)break;let T=O[0],i=O.slice(1),g,Z1,$1;if(T==="+")g="add",$1=E,E++;else if(T==="-")g="delete",Z1=M,M++;else if(T===" "||T===void 0)g="context",Z1=M,$1=E,M++,E++;else{if(O.startsWith("index ")||O.startsWith("--- ")||O.startsWith("+++ ")||O.startsWith("new file")||O.startsWith("deleted file"))break;g="context",Z1=M,$1=E,M++,E++}G.push({type:g,content:i,oldLineNumber:Z1,newLineNumber:$1}),K++}return{hunk:{oldStart:V,oldLines:q,newStart:U,newLines:H,header:X,lines:G},nextIndex:K}}var U$=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".kt",".scala",".rb",".php",".c",".cpp",".cc",".h",".hpp",".cs",".swift",".m",".mm",".vue",".svelte"]),c3=new Set(["package.json","tsconfig.json","jsconfig.json","vite.config.ts","vite.config.js","vite.config.mjs","webpack.config.ts","webpack.config.js","webpack.config.mjs","rollup.config.ts","rollup.config.js","rollup.config.mjs","esbuild.config.ts","esbuild.config.js","next.config.ts","next.config.js","next.config.mjs","nuxt.config.ts","nuxt.config.js","svelte.config.js","astro.config.mjs","remix.config.js","vitest.config.ts","vitest.config.js","jest.config.ts","jest.config.js","playwright.config.ts","cypress.config.ts","babel.config.js","babel.config.json",".babelrc","tailwind.config.ts","tailwind.config.js","postcss.config.js","eslint.config.js","eslint.config.mjs",".eslintrc.js",".eslintrc.json","prettier.config.js",".prettierrc",".prettierrc.json","biome.json","deno.json","bun.toml","Cargo.toml","go.mod","pyproject.toml","setup.py","requirements.txt","Gemfile","Dockerfile","docker-compose.yml","docker-compose.yaml","Makefile","CMakeLists.txt"]),l3=new Set(["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lock","bun.lockb","Cargo.lock","Gemfile.lock","poetry.lock","composer.lock","go.sum"]),i3=new Set([".md",".txt",".rst",".adoc"]),o3=new Set([".json",".yaml",".yml",".toml",".ini"]);function n3(Z){let Y=Z.lastIndexOf(".");if(Y===-1||Y===Z.length-1)return"";return Z.slice(Y).toLowerCase()}function H$(Z){let Y=Math.max(Z.lastIndexOf("/"),Z.lastIndexOf("\\"));return Y===-1?Z:Z.slice(Y+1)}function a3(Z){let Y=Z.toLowerCase(),X=H$(Y);return Y.includes(".test.")||Y.includes(".spec.")||Y.includes("_test.")||Y.includes("_spec.")||Y.includes("/test/")||Y.includes("/tests/")||Y.includes("/__tests__/")||Y.startsWith("test/")||Y.startsWith("tests/")||Y.startsWith("__tests__/")||Y.endsWith("_test.go")||Y.endsWith("_test.py")||X.startsWith("test_")}function r3(Z){let Y=Z.toLowerCase();return Y.startsWith("dist/")||Y.includes("/dist/")||Y.startsWith("build/")||Y.includes("/build/")||Y.startsWith("out/")||Y.includes("/out/")||Y.startsWith(".next/")||Y.includes("/.next/")||Y.startsWith("node_modules/")||Y.includes("/node_modules/")||Y.startsWith("vendor/")||Y.includes("/vendor/")}function s3(Z){let Y=Z.toLowerCase();return Y.endsWith(".min.js")||Y.endsWith(".min.css")||Y.endsWith(".bundle.js")||Y.endsWith(".chunk.js")||Y.includes(".min.")||Y.match(/\.[a-f0-9]{8,}\.js$/)!==null}function t3(Z){return Z.startsWith(".github/workflows/")||Z.startsWith(".gitlab-ci")||Z.startsWith(".circleci/")||Z.startsWith("azure-pipelines")||Z.startsWith("Jenkinsfile")}function e3(Z){let Y=0;for(let X of Z){Y+=X.header.length;for(let Q of X.lines)Y+=Q.content.length+2}return Math.ceil(Y/4)}function ZB(Z){let{path:Y,isBinary:X}=Z,Q=H$(Y),$=n3(Y);if(X)return{tier:3,reason:"binary file"};if(l3.has(Q))return{tier:3,reason:"lock file"};if(r3(Y))return{tier:3,reason:"generated/dist directory"};if(s3(Y))return{tier:3,reason:"minified/bundled file"};if(Y.endsWith(".d.ts"))return{tier:2,reason:"type definition"};if(c3.has(Q))return{tier:1,reason:"behavior config"};if(a3(Y)&&U$.has($))return{tier:1,reason:"test file"};if(U$.has($))return{tier:1,reason:"source code"};if(t3(Y))return{tier:2,reason:"CI/CD config"};if(i3.has($))return{tier:2,reason:"documentation"};if(o3.has($))return{tier:2,reason:"config file"};return{tier:2,reason:"other"}}function f9(Z){let Y=Z.files.map((X)=>{let{tier:Q,reason:$}=ZB(X);return{file:X,tier:Q,reason:$,estimatedTokens:e3(X.hunks)}});return Y.sort((X,Q)=>{if(X.tier!==Q.tier)return X.tier-Q.tier;return X.file.path.localeCompare(Q.file.path)}),Y}import{dirname as R2,join as YB}from"path";import{readFile as XB}from"fs/promises";function iZ(Z){let Y=new Set;for(let X of Z.files){let Q=R2(X.path);if(Q&&Q!==".")Y.add(Q);if(X.oldPath){let $=R2(X.oldPath);if($&&$!==".")Y.add($)}}return[...Y].sort()}async function QB(Z,Y){if(Z.length===0)return[];let X=O4(Y),$=(await X.raw(["ls-files"])).split(`
40
+ `).filter(Boolean),J=(await X.raw(["status","--porcelain"])).split(`
41
+ `).filter(Boolean),z=new Set,V=new Set,q=new Set;for(let K of J){let M=K[0],E=K[1],O=K.slice(3);if(M==="A"||M==="?")z.add(O);else if(M==="M"||E==="M")V.add(O);else if(M==="D"||E==="D")q.add(O)}let U=new Set(Z),H=new Set;for(let K of $)if(U.has(R2(K)))H.add(K);for(let K of z)if(U.has(R2(K)))H.add(K);let G=[];for(let K of[...H].sort()){let M;if(z.has(K))M="new";else if(q.has(K))M="deleted";else if(V.has(K))M="modified";else M="existing";G.push({path:K,status:M})}return G}var $B=500,G$=2000;async function WB(Z,Y){if(Z.length===0)return[];let X=Y||process.cwd(),Q=[],$=0;for(let W of Z){if($>=G$)break;try{let J=YB(X,W),z=await XB(J,"utf-8"),V=z.split(`
42
+ `),q=V.length,U=G$-$,H=Math.min($B,U),G=q>H,K=G?V.slice(0,H).join(`
43
+ `)+`
44
+ // ... truncated`:z;Q.push({path:W,content:K,lineCount:G?H:q,truncated:G}),$+=G?H:q}catch{}}return Q}function JB(Z){if(Z.length===0)return"";let Y=["## New Files (Full Source)",""];for(let X of Z){let Q=X.path.split(".").pop()||"",$=zB(Q),W=X.truncated?` (truncated, ${X.lineCount} lines shown)`:"";Y.push(`### ${X.path}${W}`),Y.push("```"+$),Y.push(X.content),Y.push("```"),Y.push("")}return Y.join(`
45
+ `)}function zB(Z){return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",rs:"rust",go:"go",rb:"ruby",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash",bash:"bash"}[Z]||""}function oZ(Z){if(Z.length===0)return"";let Y=new Map;for(let $ of Z){let W=R2($.path),J=Y.get(W);if(J)J.push($);else Y.set(W,[$])}let X=["## Repository Context","Files in directories touched by this diff:",""],Q=[...Y.keys()].sort();for(let $ of Q){X.push(`${$}/`);let W=Y.get($)??[];W.sort((J,z)=>J.path.localeCompare(z.path));for(let J of W){let z=J.path.split("/").pop()||J.path,V=VB(J.status);X.push(`- ${z}${V}`)}X.push("")}return X.join(`
46
+ `)}function VB(Z){switch(Z){case"new":return" ← NEW";case"modified":return" ← MODIFIED";case"deleted":return" ← DELETED";case"existing":return""}}async function K$(Z,Y){let X=iZ(Z),Q=await QB(X,Y),$=Q.filter((q)=>q.status==="new").map((q)=>q.path),W=await WB($,Y),J=[],z=oZ(Q);if(z)J.push(z);let V=JB(W);if(V)J.push(V);return J.join(`
47
+ `)}class T4{#W=!0;#Y;#Z;#H;#X;#z;#Q;#V;#G=0;#B=5;#J=!1;#q=!1;#$=null;#K=()=>{this.debugLog("Connected to event bus"),this.#z=!0,this.#J=!1,this.debugLog("Emitting queued events",this.#X),this.#X.forEach((Z)=>this.emitEventToBus(Z)),this.#X=[],this.stopConnectLoop(),this.#Z().removeEventListener("tanstack-connect-success",this.#K)};#U=()=>{if(this.#G<this.#B){this.#G++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#Z().removeEventListener("tanstack-connect",this.#U),this.#q=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#L=()=>{if(this.#J)return;this.#J=!0,this.#Z().addEventListener("tanstack-connect-success",this.#K),this.#U()};constructor({pluginId:Z,debug:Y=!1,enabled:X=!0,reconnectEveryMs:Q=300}){this.#Y=Z,this.#W=X,this.#Z=this.getGlobalTarget,this.#H=Y,this.debugLog(" Initializing event subscription for plugin",this.#Y),this.#X=[],this.#z=!1,this.#q=!1,this.#Q=null,this.#V=Q}startConnectLoop(){if(this.#Q!==null||this.#z)return;this.debugLog(`Starting connect loop (every ${this.#V}ms)`),this.#Q=setInterval(this.#U,this.#V)}stopConnectLoop(){if(this.#J=!1,this.#Q===null)return;clearInterval(this.#Q),this.#Q=null,this.#X=[],this.debugLog("Stopped connect loop")}debugLog(...Z){if(this.#H)console.log(`\uD83C\uDF34 [tanstack-devtools:${this.#Y}-plugin]`,...Z)}getGlobalTarget(){if(typeof globalThis!=="undefined"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window!=="undefined"&&typeof window.addEventListener!=="undefined")return this.debugLog("Using window as event target"),window;let Z=typeof EventTarget!=="undefined"?new EventTarget:void 0;if(typeof Z==="undefined"||typeof Z.addEventListener==="undefined")return this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1};return this.debugLog("Using new EventTarget as fallback"),Z}getPluginId(){return this.#Y}dispatchCustomEventShim(Z,Y){try{let X=new Event(Z,{detail:Y});this.#Z().dispatchEvent(X)}catch(X){this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(Z,Y){try{this.#Z().dispatchEvent(new CustomEvent(Z,{detail:Y}))}catch(X){this.dispatchCustomEventShim(Z,Y)}}emitEventToBus(Z){this.debugLog("Emitting event to client bus",Z),this.dispatchCustomEvent("tanstack-dispatch-event",Z)}createEventPayload(Z,Y){return{type:`${this.#Y}:${Z}`,payload:Y,pluginId:this.#Y}}emit(Z,Y){if(!this.#W){this.debugLog("Event bus client is disabled, not emitting event",Z,Y);return}if(this.#$)this.debugLog("Emitting event to internal event target",Z,Y),this.#$.dispatchEvent(new CustomEvent(`${this.#Y}:${Z}`,{detail:this.createEventPayload(Z,Y)}));if(this.#q){this.debugLog("Previously failed to connect, not emitting to bus");return}if(!this.#z){if(this.debugLog("Bus not available, will be pushed as soon as connected"),this.#X.push(this.createEventPayload(Z,Y)),typeof CustomEvent!=="undefined"&&!this.#J)this.#L(),this.startConnectLoop();return}return this.emitEventToBus(this.createEventPayload(Z,Y))}on(Z,Y,X){let Q=X?.withEventTarget??!1,$=`${this.#Y}:${Z}`;if(Q){if(!this.#$)this.#$=new EventTarget;this.#$.addEventListener($,(J)=>{Y(J.detail)})}if(!this.#W)return this.debugLog("Event bus client is disabled, not registering event",$),()=>{};let W=(J)=>{this.debugLog("Received event from bus",J.detail),Y(J.detail)};return this.#Z().addEventListener($,W),this.debugLog("Registered event to bus",$),()=>{if(Q)this.#$?.removeEventListener($,W);this.#Z().removeEventListener($,W)}}onAll(Z){if(!this.#W)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let Y=(X)=>{let Q=X.detail;Z(Q)};return this.#Z().addEventListener("tanstack-devtools-global",Y),()=>this.#Z().removeEventListener("tanstack-devtools-global",Y)}onAllPluginEvents(Z){if(!this.#W)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let Y=(X)=>{let Q=X.detail;if(this.#Y&&Q.pluginId!==this.#Y)return;Z(Q)};return this.#Z().addEventListener("tanstack-devtools-global",Y),()=>this.#Z().removeEventListener("tanstack-devtools-global",Y)}}class B$ extends T4{constructor(){super({pluginId:"tanstack-ai-devtools"})}}var B1=new B$;async function L$(Z){let Y="";for await(let X of Z)if(X.type==="content"&&X.delta)Y+=X.delta;return Y}function qB(Z){return typeof Z==="object"&&Z!==null&&"~standard"in Z&&typeof Z["~standard"]==="object"&&Z["~standard"].version===1&&typeof Z["~standard"].jsonSchema==="object"&&typeof Z["~standard"].jsonSchema.input==="function"}function R0(Z){return typeof Z==="object"&&Z!==null&&"~standard"in Z&&typeof Z["~standard"]==="object"&&Z!==null&&Z["~standard"]!==null&&"version"in Z["~standard"]&&Z["~standard"].version===1&&"validate"in Z["~standard"]&&typeof Z["~standard"].validate==="function"}function j2(Z,Y=[]){let X={...Z};if(X.type==="object"&&X.properties){let Q={...X.properties},$=Object.keys(Q);for(let W of $){let J=Q[W],z=!Y.includes(W);if(J.type==="object"&&J.properties)Q[W]=j2(J,J.required||[]);else if(J.type==="array"&&J.items)Q[W]={...J,items:j2(J.items,J.items.required||[])};else if(z){if(J.type&&!Array.isArray(J.type))Q[W]={...J,type:[J.type,"null"]};else if(Array.isArray(J.type)&&!J.type.includes("null"))Q[W]={...J,type:[...J.type,"null"]}}}X.properties=Q,X.required=$,X.additionalProperties=!1}if(X.type==="array"&&X.items)X.items=j2(X.items,X.items.required||[]);return X}function I4(Z,Y={}){if(!Z)return;let{forStructuredOutput:X=!1}=Y;if(qB(Z)){let $=Z["~standard"].jsonSchema.input({target:"draft-07"});if(typeof $==="object"&&"$schema"in $){let{$schema:W,...J}=$;$=J}if(typeof $==="object"){if("properties"in $&&!$.type)$.type="object";if($.type==="object"&&!("properties"in $))$.properties={};if($.type==="object"&&!("required"in $))$.required=[];if(X)$=j2($,$.required||[])}return $}if(X&&typeof Z==="object")return j2(Z,Z.required||[]);return Z}function p0(Z,Y){if(!R0(Z))return Y;let X=Z["~standard"].validate(Y);if(X instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!X.issues)return X.value;let Q=X.issues.map(($)=>$.message||"Validation failed").join(", ");throw new Error(`Validation failed: ${Q}`)}class nZ{constructor(Z){this.toolCallsMap=new Map,this.tools=Z}addToolCallChunk(Z){let Y=Z.index,X=this.toolCallsMap.get(Y);if(!X){if(Z.toolCall.id&&Z.toolCall.function.name)this.toolCallsMap.set(Y,{id:Z.toolCall.id,type:"function",function:{name:Z.toolCall.function.name,arguments:Z.toolCall.function.arguments||""}})}else{if(Z.toolCall.function.name&&!X.function.name)X.function.name=Z.toolCall.function.name;if(Z.toolCall.function.arguments)X.function.arguments+=Z.toolCall.function.arguments}}hasToolCalls(){return this.getToolCalls().length>0}getToolCalls(){return Array.from(this.toolCallsMap.values()).filter((Z)=>Z.id&&Z.function.name&&Z.function.name.trim().length>0)}async*executeTools(Z){let Y=this.getToolCalls(),X=[];for(let Q of Y){let $=this.tools.find((J)=>J.name===Q.function.name),W;if($?.execute)try{let J;try{J=JSON.parse(Q.function.arguments)}catch(V){throw new Error(`Failed to parse tool arguments as JSON: ${Q.function.arguments}`)}if($.inputSchema&&R0($.inputSchema))try{J=p0($.inputSchema,J)}catch(V){let q=V instanceof Error?V.message:"Validation failed";throw new Error(`Input validation failed for tool ${$.name}: ${q}`)}let z=await $.execute(J);if($.outputSchema&&R0($.outputSchema)&&z!==void 0&&z!==null)try{z=p0($.outputSchema,z)}catch(V){let q=V instanceof Error?V.message:"Validation failed";throw new Error(`Output validation failed for tool ${$.name}: ${q}`)}W=typeof z==="string"?z:JSON.stringify(z)}catch(J){W=`Error executing tool: ${J instanceof Error?J.message:"Unknown error"}`}else W=`Tool ${Q.function.name} does not have an execute function`;yield{type:"tool_result",id:Z.id,model:Z.model,timestamp:Date.now(),toolCallId:Q.id,content:W},X.push({role:"tool",content:W,toolCallId:Q.id})}return X}clear(){this.toolCallsMap.clear()}}async function aZ(Z,Y,X=new Map,Q=new Map){let $=[],W=[],J=[],z=new Map;for(let V of Y)z.set(V.name,V);for(let V of Z){let q=z.get(V.function.name),U=V.function.name;if(!q){$.push({toolCallId:V.id,toolName:U,result:{error:`Unknown tool: ${U}`},state:"output-error"});continue}let H={},G=V.function.arguments.trim()||"{}";try{H=JSON.parse(G)}catch(M){throw new Error(`Failed to parse tool arguments as JSON: ${G}`)}if(q.inputSchema&&R0(q.inputSchema))try{H=p0(q.inputSchema,H)}catch(M){let E=M instanceof Error?M.message:"Validation failed";$.push({toolCallId:V.id,toolName:U,result:{error:`Input validation failed for tool ${q.name}: ${E}`},state:"output-error"});continue}if(!q.execute){if(q.needsApproval){let M=`approval_${V.id}`;if(X.has(M))if(X.get(M))if(Q.has(V.id))$.push({toolCallId:V.id,toolName:U,result:Q.get(V.id)});else J.push({toolCallId:V.id,toolName:U,input:H});else $.push({toolCallId:V.id,toolName:U,result:{error:"User declined tool execution"},state:"output-error"});else W.push({toolCallId:V.id,toolName:V.function.name,input:H,approvalId:M})}else if(Q.has(V.id))$.push({toolCallId:V.id,toolName:U,result:Q.get(V.id)});else J.push({toolCallId:V.id,toolName:U,input:H});continue}if(q.needsApproval){let M=`approval_${V.id}`;if(X.has(M))if(X.get(M)){let O=Date.now();try{let T=await q.execute(H),i=Date.now()-O;if(q.outputSchema&&R0(q.outputSchema)&&T!==void 0&&T!==null)T=p0(q.outputSchema,T);$.push({toolCallId:V.id,toolName:U,result:typeof T==="string"?JSON.parse(T):T||null,duration:i})}catch(T){let i=Date.now()-O,g=T instanceof Error?T.message:"Unknown error";$.push({toolCallId:V.id,toolName:U,result:{error:g},state:"output-error",duration:i})}}else $.push({toolCallId:V.id,toolName:U,result:{error:"User declined tool execution"},state:"output-error"});else W.push({toolCallId:V.id,toolName:U,input:H,approvalId:M});continue}let K=Date.now();try{let M=await q.execute(H),E=Date.now()-K;if(q.outputSchema&&R0(q.outputSchema)&&M!==void 0&&M!==null)M=p0(q.outputSchema,M);$.push({toolCallId:V.id,toolName:U,result:typeof M==="string"?JSON.parse(M):M||null,duration:E})}catch(M){let E=Date.now()-K,O=M instanceof Error?M.message:"Unknown error";$.push({toolCallId:V.id,toolName:U,result:{error:O},state:"output-error",duration:E})}}return{results:$,needsApproval:W,needsClientExecution:J}}function M$(Z){return({iterationCount:Y})=>Y<Z}class rZ{constructor(Z){this.iterationCount=0,this.lastFinishReason=null,this.streamStartTime=0,this.totalChunkCount=0,this.currentMessageId=null,this.accumulatedContent="",this.doneChunk=null,this.shouldEmitStreamEnd=!0,this.earlyTermination=!1,this.toolPhase="continue",this.cyclePhase="processText",this.adapter=Z.adapter,this.params=Z.params,this.systemPrompts=Z.params.systemPrompts||[],this.tools=Z.params.tools||[],this.loopStrategy=Z.params.agentLoopStrategy||M$(5),this.toolCallManager=new nZ(this.tools),this.initialMessageCount=Z.params.messages.length,this.messages=Z.params.messages,this.requestId=this.createId("chat"),this.streamId=this.createId("stream"),this.effectiveRequest=Z.params.abortController?{signal:Z.params.abortController.signal}:void 0,this.effectiveSignal=Z.params.abortController?.signal}getAccumulatedContent(){return this.accumulatedContent}getMessages(){return this.messages}async*run(){this.beforeRun();try{if((yield*this.checkForPendingToolCalls())==="wait")return;do{if(this.earlyTermination||this.isAborted())return;if(this.beginCycle(),this.cyclePhase==="processText")yield*this.streamModelResponse();else yield*this.processToolCalls();this.endCycle()}while(this.shouldContinue())}finally{this.afterRun()}}beforeRun(){this.streamStartTime=Date.now();let{model:Z,tools:Y,temperature:X,topP:Q,maxTokens:$,metadata:W,modelOptions:J,conversationId:z}=this.params,V={};if(X!==void 0)V.temperature=X;if(Q!==void 0)V.topP=Q;if($!==void 0)V.maxTokens=$;if(W!==void 0)V.metadata=W;B1.emit("text:started",{requestId:this.requestId,streamId:this.streamId,model:Z,provider:this.adapter.name,messageCount:this.initialMessageCount,hasTools:!!Y&&Y.length>0,streaming:!0,timestamp:Date.now(),clientId:z,toolNames:Y?.map((q)=>q.name),options:Object.keys(V).length>0?V:void 0,modelOptions:J}),B1.emit("stream:started",{streamId:this.streamId,model:Z,provider:this.adapter.name,timestamp:Date.now()})}afterRun(){if(!this.shouldEmitStreamEnd)return;let Z=Date.now();B1.emit("text:completed",{requestId:this.requestId,streamId:this.streamId,model:this.params.model,content:this.accumulatedContent,messageId:this.currentMessageId||void 0,finishReason:this.lastFinishReason||void 0,usage:this.doneChunk?.usage,timestamp:Z}),B1.emit("stream:ended",{requestId:this.requestId,streamId:this.streamId,totalChunks:this.totalChunkCount,duration:Z-this.streamStartTime,timestamp:Z})}beginCycle(){if(this.cyclePhase==="processText")this.beginIteration()}endCycle(){if(this.cyclePhase==="processText"){this.cyclePhase="executeToolCalls";return}this.cyclePhase="processText",this.iterationCount++}beginIteration(){this.currentMessageId=this.createId("msg"),this.accumulatedContent="",this.doneChunk=null}async*streamModelResponse(){let{temperature:Z,topP:Y,maxTokens:X,metadata:Q,modelOptions:$}=this.params,J=this.params.tools?.map((z)=>({...z,inputSchema:z.inputSchema?I4(z.inputSchema):void 0,outputSchema:z.outputSchema?I4(z.outputSchema):void 0}));for await(let z of this.adapter.chatStream({model:this.params.model,messages:this.messages,tools:J,temperature:Z,topP:Y,maxTokens:X,metadata:Q,request:this.effectiveRequest,modelOptions:$,systemPrompts:this.systemPrompts})){if(this.isAborted())break;if(this.totalChunkCount++,yield z,this.handleStreamChunk(z),this.earlyTermination)break}}handleStreamChunk(Z){switch(Z.type){case"content":this.handleContentChunk(Z);break;case"tool_call":this.handleToolCallChunk(Z);break;case"tool_result":this.handleToolResultChunk(Z);break;case"done":this.handleDoneChunk(Z);break;case"error":this.handleErrorChunk(Z);break;case"thinking":this.handleThinkingChunk(Z);break}}handleContentChunk(Z){this.accumulatedContent=Z.content,B1.emit("stream:chunk:content",{streamId:this.streamId,messageId:this.currentMessageId||void 0,content:Z.content,delta:Z.delta,timestamp:Date.now()})}handleToolCallChunk(Z){this.toolCallManager.addToolCallChunk(Z),B1.emit("stream:chunk:tool-call",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Z.toolCall.id,toolName:Z.toolCall.function.name,index:Z.index,arguments:Z.toolCall.function.arguments,timestamp:Date.now()})}handleToolResultChunk(Z){B1.emit("stream:chunk:tool-result",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Z.toolCallId,result:Z.content,timestamp:Date.now()})}handleDoneChunk(Z){if(this.doneChunk?.finishReason==="tool_calls"&&Z.finishReason==="stop"){if(this.lastFinishReason=Z.finishReason,B1.emit("stream:chunk:done",{streamId:this.streamId,messageId:this.currentMessageId||void 0,finishReason:Z.finishReason,usage:Z.usage,timestamp:Date.now()}),Z.usage)B1.emit("usage:tokens",{requestId:this.requestId,streamId:this.streamId,messageId:this.currentMessageId||void 0,model:this.params.model,usage:Z.usage,timestamp:Date.now()});return}if(this.doneChunk=Z,this.lastFinishReason=Z.finishReason,B1.emit("stream:chunk:done",{streamId:this.streamId,messageId:this.currentMessageId||void 0,finishReason:Z.finishReason,usage:Z.usage,timestamp:Date.now()}),Z.usage)B1.emit("usage:tokens",{requestId:this.requestId,streamId:this.streamId,messageId:this.currentMessageId||void 0,model:this.params.model,usage:Z.usage,timestamp:Date.now()})}handleErrorChunk(Z){B1.emit("stream:chunk:error",{streamId:this.streamId,messageId:this.currentMessageId||void 0,error:Z.error.message,timestamp:Date.now()}),this.earlyTermination=!0,this.shouldEmitStreamEnd=!1}handleThinkingChunk(Z){B1.emit("stream:chunk:thinking",{streamId:this.streamId,messageId:this.currentMessageId||void 0,content:Z.content,delta:Z.delta,timestamp:Date.now()})}async*checkForPendingToolCalls(){let Z=this.getPendingToolCallsFromMessages();if(Z.length===0)return"continue";let Y=this.createSyntheticDoneChunk();B1.emit("text:iteration",{requestId:this.requestId,streamId:this.streamId,iterationNumber:this.iterationCount+1,messageCount:this.messages.length,toolCallCount:Z.length,timestamp:Date.now()});let{approvals:X,clientToolResults:Q}=this.collectClientState(),$=await aZ(Z,this.tools,X,Q);if($.needsApproval.length>0||$.needsClientExecution.length>0){for(let J of this.emitApprovalRequests($.needsApproval,Y))yield J;for(let J of this.emitClientToolInputs($.needsClientExecution,Y))yield J;return this.shouldEmitStreamEnd=!1,"wait"}let W=this.emitToolResults($.results,Y);for(let J of W)yield J;return"continue"}async*processToolCalls(){if(!this.shouldExecuteToolPhase()){this.setToolPhase("stop");return}let Z=this.toolCallManager.getToolCalls(),Y=this.doneChunk;if(!Y||Z.length===0){this.setToolPhase("stop");return}B1.emit("text:iteration",{requestId:this.requestId,streamId:this.streamId,iterationNumber:this.iterationCount+1,messageCount:this.messages.length,toolCallCount:Z.length,timestamp:Date.now()}),this.addAssistantToolCallMessage(Z);let{approvals:X,clientToolResults:Q}=this.collectClientState(),$=await aZ(Z,this.tools,X,Q);if($.needsApproval.length>0||$.needsClientExecution.length>0){for(let J of this.emitApprovalRequests($.needsApproval,Y))yield J;for(let J of this.emitClientToolInputs($.needsClientExecution,Y))yield J;this.setToolPhase("wait");return}let W=this.emitToolResults($.results,Y);for(let J of W)yield J;this.toolCallManager.clear(),this.setToolPhase("continue")}shouldExecuteToolPhase(){return this.doneChunk?.finishReason==="tool_calls"&&this.tools.length>0&&this.toolCallManager.hasToolCalls()}addAssistantToolCallMessage(Z){this.messages=[...this.messages,{role:"assistant",content:this.accumulatedContent||null,toolCalls:Z}]}collectClientState(){let Z=new Map,Y=new Map;for(let X of this.messages)if(X.role==="assistant"&&X.parts){let Q=X.parts;for(let $ of Q){if($.type==="tool-call"&&$.state==="approval-responded"&&$.approval)Z.set($.approval.id,$.approval.approved);if($.type==="tool-call"&&$.output!==void 0&&!$.approval)Y.set($.id,$.output)}}return{approvals:Z,clientToolResults:Y}}emitApprovalRequests(Z,Y){let X=[];for(let Q of Z)B1.emit("stream:approval-requested",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input,approvalId:Q.approvalId,timestamp:Date.now()}),X.push({type:"approval-requested",id:Y.id,model:Y.model,timestamp:Date.now(),toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input,approval:{id:Q.approvalId,needsApproval:!0}});return X}emitClientToolInputs(Z,Y){let X=[];for(let Q of Z)B1.emit("stream:tool-input-available",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input,timestamp:Date.now()}),X.push({type:"tool-input-available",id:Y.id,model:Y.model,timestamp:Date.now(),toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input});return X}emitToolResults(Z,Y){let X=[];for(let Q of Z){B1.emit("tool:call-completed",{requestId:this.requestId,streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Q.toolCallId,toolName:Q.toolName,result:Q.result,duration:Q.duration??0,timestamp:Date.now()});let $=JSON.stringify(Q.result),W={type:"tool_result",id:Y.id,model:Y.model,timestamp:Date.now(),toolCallId:Q.toolCallId,content:$};X.push(W),this.messages=[...this.messages,{role:"tool",content:$,toolCallId:Q.toolCallId}]}return X}getPendingToolCallsFromMessages(){let Z=new Set(this.messages.filter((X)=>X.role==="tool"&&X.toolCallId).map((X)=>X.toolCallId)),Y=[];for(let X of this.messages)if(X.role==="assistant"&&X.toolCalls){for(let Q of X.toolCalls)if(!Z.has(Q.id))Y.push(Q)}return Y}createSyntheticDoneChunk(){return{type:"done",id:this.createId("pending"),model:this.params.model,timestamp:Date.now(),finishReason:"tool_calls"}}shouldContinue(){if(this.cyclePhase==="executeToolCalls")return!0;return this.loopStrategy({iterationCount:this.iterationCount,messages:this.messages,finishReason:this.lastFinishReason})&&this.toolPhase==="continue"}isAborted(){return!!this.effectiveSignal?.aborted}setToolPhase(Z){if(this.toolPhase=Z,Z==="wait")this.shouldEmitStreamEnd=!1}createId(Z){return`${Z}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}}function k1(Z){let{outputSchema:Y,stream:X}=Z;if(Y)return HB(Z);if(X===!1)return UB(Z);return F$(Z)}async function*F$(Z){let{adapter:Y,...X}=Z,Q=Y.model,$=new rZ({adapter:Y,params:{...X,model:Q}});for await(let W of $.run())yield W}function UB(Z){let Y=F$(Z);return L$(Y)}async function HB(Z){let{adapter:Y,outputSchema:X,...Q}=Z,$=Y.model;if(!X)throw new Error("outputSchema is required for structured output");let W=new rZ({adapter:Y,params:{...Q,model:$}});for await(let G of W.run());let J=W.getMessages(),{tools:z,agentLoopStrategy:V,...q}=Q,U=I4(X);if(!U)throw new Error("Failed to convert output schema to JSON Schema");let H=await Y.structuredOutput({chatOptions:{...q,model:$,messages:J},outputSchema:U});if(R0(X))return p0(X,H.data);return H.data}class R4{constructor(Z={},Y){this.kind="text",this.config=Z,this.model=Y}generateId(){return`${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`}}function N$(Z){return Z.metadata}function w$(Z){return Z.metadata}function D$(Z){return Z.metadata}function A$(Z){let Y=Z.metadata||{},X=Z.inputSchema??{properties:{},required:[]},Q={type:"object",properties:X.properties||null,required:X.required||null};return{name:Z.name,type:"custom",description:Z.description,input_schema:Q,cache_control:Y.cacheControl||null}}function E$(Z){return{type:"memory_20250818",...Z.metadata}}function O$(Z){return{...Z.metadata}}function P$(Z){return{name:"web_fetch",type:"web_fetch_20250910",...Z.metadata}}function T$(Z){let Y=Z.metadata;return{name:"web_search",type:"web_search_20250305",allowed_domains:Y.allowedDomains,blocked_domains:Y.blockedDomains,max_uses:Y.maxUses,user_location:Y.userLocation,cache_control:Y.cacheControl||null}}function sZ(Z){return Z.map((Y)=>{switch(Y.name){case"bash":return N$(Y);case"code_execution":return w$(Y);case"computer":return D$(Y);case"memory":return E$(Y);case"str_replace_editor":return O$(Y);case"web_fetch":return P$(Y);case"web_search":return T$(Y);default:return A$(Y)}})}var GB=(Z)=>{if(Z.top_p!==void 0&&Z.temperature!==void 0)throw new Error("You should either set top_p or temperature, but not both.")},KB=(Z)=>{let Y=Z.thinking;if(Y&&Y.type==="enabled"){if(Y.budget_tokens<1024)throw new Error("thinking.budget_tokens must be at least 1024.");if(Y.budget_tokens>=Z.max_tokens)throw new Error("thinking.budget_tokens must be less than max_tokens.")}},BB=(Z)=>{if(Z.max_tokens<1)throw new Error("max_tokens must be at least 1.")},I$=(Z)=>{GB(Z),KB(Z),BB(Z)};function A(Z,Y,X,Q,$){if(Q==="m")throw new TypeError("Private method is not writable");if(Q==="a"&&!$)throw new TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?Z!==Y||!$:!Y.has(Z))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?$.call(Z,X):$?$.value=X:Y.set(Z,X),X}function B(Z,Y,X,Q){if(X==="a"&&!Q)throw new TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?Z!==Y||!Q:!Y.has(Z))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Q:X==="a"?Q.call(Z):Q?Q.value:Y.get(Z)}var tZ=function(){let{crypto:Z}=globalThis;if(Z?.randomUUID)return tZ=Z.randomUUID.bind(Z),Z.randomUUID();let Y=new Uint8Array(1),X=Z?()=>Z.getRandomValues(Y)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Q)=>(+Q^X()&15>>+Q/4).toString(16))};function j0(Z){return typeof Z==="object"&&Z!==null&&(("name"in Z)&&Z.name==="AbortError"||("message"in Z)&&String(Z.message).includes("FetchRequestCanceledException"))}var C2=(Z)=>{if(Z instanceof Error)return Z;if(typeof Z==="object"&&Z!==null){try{if(Object.prototype.toString.call(Z)==="[object Error]"){let Y=new Error(Z.message,Z.cause?{cause:Z.cause}:{});if(Z.stack)Y.stack=Z.stack;if(Z.cause&&!Y.cause)Y.cause=Z.cause;if(Z.name)Y.name=Z.name;return Y}}catch{}try{return new Error(JSON.stringify(Z))}catch{}}return new Error(Z)};class R extends Error{}class L1 extends R{constructor(Z,Y,X,Q){super(`${L1.makeMessage(Z,Y,X)}`);this.status=Z,this.headers=Q,this.requestID=Q?.get("request-id"),this.error=Y}static makeMessage(Z,Y,X){let Q=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):X;if(Z&&Q)return`${Z} ${Q}`;if(Z)return`${Z} status code (no body)`;if(Q)return Q;return"(no status code or body)"}static generate(Z,Y,X,Q){if(!Z||!Q)return new H9({message:X,cause:C2(Y)});let $=Y;if(Z===400)return new _2(Z,$,X,Q);if(Z===401)return new y2(Z,$,X,Q);if(Z===403)return new b2(Z,$,X,Q);if(Z===404)return new x2(Z,$,X,Q);if(Z===409)return new k2(Z,$,X,Q);if(Z===422)return new v2(Z,$,X,Q);if(Z===429)return new f2(Z,$,X,Q);if(Z>=500)return new h2(Z,$,X,Q);return new L1(Z,$,X,Q)}}class P1 extends L1{constructor({message:Z}={}){super(void 0,void 0,Z||"Request was aborted.",void 0)}}class H9 extends L1{constructor({message:Z,cause:Y}){super(void 0,void 0,Z||"Connection error.",void 0);if(Y)this.cause=Y}}class S2 extends H9{constructor({message:Z}={}){super({message:Z??"Request timed out."})}}class _2 extends L1{}class y2 extends L1{}class b2 extends L1{}class x2 extends L1{}class k2 extends L1{}class v2 extends L1{}class f2 extends L1{}class h2 extends L1{}var MB=/^[a-z][a-z0-9+.-]*:/i,R$=(Z)=>{return MB.test(Z)},eZ=(Z)=>(eZ=Array.isArray,eZ(Z)),ZY=eZ;function j4(Z){if(typeof Z!=="object")return{};return Z??{}}function j$(Z){if(!Z)return!0;for(let Y in Z)return!1;return!0}function C$(Z,Y){return Object.prototype.hasOwnProperty.call(Z,Y)}var S$=(Z,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new R(`${Z} must be an integer`);if(Y<0)throw new R(`${Z} must be a positive integer`);return Y};var C4=(Z)=>{try{return JSON.parse(Z)}catch(Y){return}};var _$=(Z)=>new Promise((Y)=>setTimeout(Y,Z));var d0="0.71.2";var k$=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"};function FB(){if(typeof Deno!=="undefined"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime!=="undefined")return"edge";if(Object.prototype.toString.call(typeof globalThis.process!=="undefined"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var NB=()=>{let Z=FB();if(Z==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":b$(Deno.build.os),"X-Stainless-Arch":y$(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime!=="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(Z==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":b$(globalThis.process.platform??"unknown"),"X-Stainless-Arch":y$(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Y=wB();if(Y)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Y.browser}`,"X-Stainless-Runtime-Version":Y.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function wB(){if(typeof navigator==="undefined"||!navigator)return null;let Z=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Y,pattern:X}of Z){let Q=X.exec(navigator.userAgent);if(Q){let $=Q[1]||0,W=Q[2]||0,J=Q[3]||0;return{browser:Y,version:`${$}.${W}.${J}`}}}return null}var y$=(Z)=>{if(Z==="x32")return"x32";if(Z==="x86_64"||Z==="x64")return"x64";if(Z==="arm")return"arm";if(Z==="aarch64"||Z==="arm64")return"arm64";if(Z)return`other:${Z}`;return"unknown"},b$=(Z)=>{if(Z=Z.toLowerCase(),Z.includes("ios"))return"iOS";if(Z==="android")return"Android";if(Z==="darwin")return"MacOS";if(Z==="win32")return"Windows";if(Z==="freebsd")return"FreeBSD";if(Z==="openbsd")return"OpenBSD";if(Z==="linux")return"Linux";if(Z)return`Other:${Z}`;return"Unknown"},x$,v$=()=>{return x$??(x$=NB())};function f$(){if(typeof fetch!=="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function YY(...Z){let Y=globalThis.ReadableStream;if(typeof Y==="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Y(...Z)}function S4(Z){let Y=Symbol.asyncIterator in Z?Z[Symbol.asyncIterator]():Z[Symbol.iterator]();return YY({start(){},async pull(X){let{done:Q,value:$}=await Y.next();if(Q)X.close();else X.enqueue($)},async cancel(){await Y.return?.()}})}function g2(Z){if(Z[Symbol.asyncIterator])return Z;let Y=Z.getReader();return{async next(){try{let X=await Y.read();if(X?.done)Y.releaseLock();return X}catch(X){throw Y.releaseLock(),X}},async return(){let X=Y.cancel();return Y.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function h$(Z){if(Z===null||typeof Z!=="object")return;if(Z[Symbol.asyncIterator]){await Z[Symbol.asyncIterator]().return?.();return}let Y=Z.getReader(),X=Y.cancel();Y.releaseLock(),await X}var g$=({headers:Z,body:Y})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Y)}};function p$(Z){let Y=0;for(let $ of Z)Y+=$.length;let X=new Uint8Array(Y),Q=0;for(let $ of Z)X.set($,Q),Q+=$.length;return X}var u$;function u2(Z){let Y;return(u$??(Y=new globalThis.TextEncoder,u$=Y.encode.bind(Y)))(Z)}var m$;function XY(Z){let Y;return(m$??(Y=new globalThis.TextDecoder,m$=Y.decode.bind(Y)))(Z)}var i1,o1;class c0{constructor(){i1.set(this,void 0),o1.set(this,void 0),A(this,i1,new Uint8Array,"f"),A(this,o1,null,"f")}decode(Z){if(Z==null)return[];let Y=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?u2(Z):Z;A(this,i1,p$([B(this,i1,"f"),Y]),"f");let X=[],Q;while((Q=EB(B(this,i1,"f"),B(this,o1,"f")))!=null){if(Q.carriage&&B(this,o1,"f")==null){A(this,o1,Q.index,"f");continue}if(B(this,o1,"f")!=null&&(Q.index!==B(this,o1,"f")+1||Q.carriage)){X.push(XY(B(this,i1,"f").subarray(0,B(this,o1,"f")-1))),A(this,i1,B(this,i1,"f").subarray(B(this,o1,"f")),"f"),A(this,o1,null,"f");continue}let $=B(this,o1,"f")!==null?Q.preceding-1:Q.preceding,W=XY(B(this,i1,"f").subarray(0,$));X.push(W),A(this,i1,B(this,i1,"f").subarray(Q.index),"f"),A(this,o1,null,"f")}return X}flush(){if(!B(this,i1,"f").length)return[];return this.decode(`
48
+ `)}}i1=new WeakMap,o1=new WeakMap;c0.NEWLINE_CHARS=new Set([`
49
+ `,"\r"]);c0.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function EB(Z,Y){for(let $=Y??0;$<Z.length;$++){if(Z[$]===10)return{preceding:$,index:$+1,carriage:!1};if(Z[$]===13)return{preceding:$,index:$+1,carriage:!0}}return null}function d$(Z){for(let Q=0;Q<Z.length-1;Q++){if(Z[Q]===10&&Z[Q+1]===10)return Q+2;if(Z[Q]===13&&Z[Q+1]===13)return Q+2;if(Z[Q]===13&&Z[Q+1]===10&&Q+3<Z.length&&Z[Q+2]===13&&Z[Q+3]===10)return Q+4}return-1}var y4={off:0,error:200,warn:300,info:400,debug:500},QY=(Z,Y,X)=>{if(!Z)return;if(C$(y4,Z))return Z;A1(X).warn(`${Y} was set to ${JSON.stringify(Z)}, expected one of ${JSON.stringify(Object.keys(y4))}`);return};function m2(){}function _4(Z,Y,X){if(!Y||y4[Z]>y4[X])return m2;else return Y[Z].bind(Y)}var OB={error:m2,warn:m2,info:m2,debug:m2},c$=new WeakMap;function A1(Z){let Y=Z.logger,X=Z.logLevel??"off";if(!Y)return OB;let Q=c$.get(Y);if(Q&&Q[0]===X)return Q[1];let $={error:_4("error",Y,X),warn:_4("warn",Y,X),info:_4("info",Y,X),debug:_4("debug",Y,X)};return c$.set(Y,[X,$]),$}var C0=(Z)=>{if(Z.options)Z.options={...Z.options},delete Z.options.headers;if(Z.headers)Z.headers=Object.fromEntries((Z.headers instanceof Headers?[...Z.headers]:Object.entries(Z.headers)).map(([Y,X])=>[Y,Y.toLowerCase()==="x-api-key"||Y.toLowerCase()==="authorization"||Y.toLowerCase()==="cookie"||Y.toLowerCase()==="set-cookie"?"***":X]));if("retryOfRequestLogID"in Z){if(Z.retryOfRequestLogID)Z.retryOf=Z.retryOfRequestLogID;delete Z.retryOfRequestLogID}return Z};var p2;class n1{constructor(Z,Y,X){this.iterator=Z,p2.set(this,void 0),this.controller=Y,A(this,p2,X,"f")}static fromSSEResponse(Z,Y,X){let Q=!1,$=X?A1(X):console;async function*W(){if(Q)throw new R("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let J=!1;try{for await(let z of PB(Z,Y)){if(z.event==="completion")try{yield JSON.parse(z.data)}catch(V){throw $.error("Could not parse message into JSON:",z.data),$.error("From chunk:",z.raw),V}if(z.event==="message_start"||z.event==="message_delta"||z.event==="message_stop"||z.event==="content_block_start"||z.event==="content_block_delta"||z.event==="content_block_stop")try{yield JSON.parse(z.data)}catch(V){throw $.error("Could not parse message into JSON:",z.data),$.error("From chunk:",z.raw),V}if(z.event==="ping")continue;if(z.event==="error")throw new L1(void 0,C4(z.data)??z.data,void 0,Z.headers)}J=!0}catch(z){if(j0(z))return;throw z}finally{if(!J)Y.abort()}}return new n1(W,Y,X)}static fromReadableStream(Z,Y,X){let Q=!1;async function*$(){let J=new c0,z=g2(Z);for await(let V of z)for(let q of J.decode(V))yield q;for(let V of J.flush())yield V}async function*W(){if(Q)throw new R("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let J=!1;try{for await(let z of $()){if(J)continue;if(z)yield JSON.parse(z)}J=!0}catch(z){if(j0(z))return;throw z}finally{if(!J)Y.abort()}}return new n1(W,Y,X)}[(p2=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let Z=[],Y=[],X=this.iterator(),Q=($)=>{return{next:()=>{if($.length===0){let W=X.next();Z.push(W),Y.push(W)}return $.shift()}}};return[new n1(()=>Q(Z),this.controller,B(this,p2,"f")),new n1(()=>Q(Y),this.controller,B(this,p2,"f"))]}toReadableStream(){let Z=this,Y;return YY({async start(){Y=Z[Symbol.asyncIterator]()},async pull(X){try{let{value:Q,done:$}=await Y.next();if($)return X.close();let W=u2(JSON.stringify(Q)+`
50
+ `);X.enqueue(W)}catch(Q){X.error(Q)}},async cancel(){await Y.return?.()}})}}async function*PB(Z,Y){if(!Z.body){if(Y.abort(),typeof globalThis.navigator!=="undefined"&&globalThis.navigator.product==="ReactNative")throw new R("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new R("Attempted to iterate over a response with no body")}let X=new l$,Q=new c0,$=g2(Z.body);for await(let W of TB($))for(let J of Q.decode(W)){let z=X.decode(J);if(z)yield z}for(let W of Q.flush()){let J=X.decode(W);if(J)yield J}}async function*TB(Z){let Y=new Uint8Array;for await(let X of Z){if(X==null)continue;let Q=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?u2(X):X,$=new Uint8Array(Y.length+Q.length);$.set(Y),$.set(Q,Y.length),Y=$;let W;while((W=d$(Y))!==-1)yield Y.slice(0,W),Y=Y.slice(W)}if(Y.length>0)yield Y}class l${constructor(){this.event=null,this.data=[],this.chunks=[]}decode(Z){if(Z.endsWith("\r"))Z=Z.substring(0,Z.length-1);if(!Z){if(!this.event&&!this.data.length)return null;let $={event:this.event,data:this.data.join(`
51
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],$}if(this.chunks.push(Z),Z.startsWith(":"))return null;let[Y,X,Q]=IB(Z,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Y==="event")this.event=Q;else if(Y==="data")this.data.push(Q);return null}}function IB(Z,Y){let X=Z.indexOf(Y);if(X!==-1)return[Z.substring(0,X),Y,Z.substring(X+Y.length)];return[Z,"",""]}async function b4(Z,Y){let{response:X,requestLogID:Q,retryOfRequestLogID:$,startTime:W}=Y,J=await(async()=>{if(Y.options.stream){if(A1(Z).debug("response",X.status,X.url,X.headers,X.body),Y.options.__streamClass)return Y.options.__streamClass.fromSSEResponse(X,Y.controller);return n1.fromSSEResponse(X,Y.controller)}if(X.status===204)return null;if(Y.options.__binaryResponse)return X;let V=X.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){let H=await X.json();return $Y(H,X)}return await X.text()})();return A1(Z).debug(`[${Q}] response parsed`,C0({retryOfRequestLogID:$,url:X.url,status:X.status,body:J,durationMs:Date.now()-W})),J}function $Y(Z,Y){if(!Z||typeof Z!=="object"||Array.isArray(Z))return Z;return Object.defineProperty(Z,"_request_id",{value:Y.headers.get("request-id"),enumerable:!1})}var d2;class G9 extends Promise{constructor(Z,Y,X=b4){super((Q)=>{Q(null)});this.responsePromise=Y,this.parseResponse=X,d2.set(this,void 0),A(this,d2,Z,"f")}_thenUnwrap(Z){return new G9(B(this,d2,"f"),this.responsePromise,async(Y,X)=>$Y(Z(await this.parseResponse(Y,X),X),X.response))}asResponse(){return this.responsePromise.then((Z)=>Z.response)}async withResponse(){let[Z,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:Z,response:Y,request_id:Y.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((Z)=>this.parseResponse(B(this,d2,"f"),Z));return this.parsedPromise}then(Z,Y){return this.parse().then(Z,Y)}catch(Z){return this.parse().catch(Z)}finally(Z){return this.parse().finally(Z)}}d2=new WeakMap;var x4;class WY{constructor(Z,Y,X,Q){x4.set(this,void 0),A(this,x4,Z,"f"),this.options=Q,this.response=Y,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let Z=this.nextPageRequestOptions();if(!Z)throw new R("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await B(this,x4,"f").requestAPIList(this.constructor,Z)}async*iterPages(){let Z=this;yield Z;while(Z.hasNextPage())Z=await Z.getNextPage(),yield Z}async*[(x4=new WeakMap,Symbol.asyncIterator)](){for await(let Z of this.iterPages())for(let Y of Z.getPaginatedItems())yield Y}}class k4 extends G9{constructor(Z,Y,X){super(Z,Y,async(Q,$)=>new X(Q,$.response,await b4(Q,$),$.options))}async*[Symbol.asyncIterator](){let Z=await this;for await(let Y of Z)yield Y}}class q0 extends WY{constructor(Z,Y,X,Q){super(Z,Y,X,Q);this.data=X.data||[],this.has_more=X.has_more||!1,this.first_id=X.first_id||null,this.last_id=X.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let Y=this.first_id;if(!Y)return null;return{...this.options,query:{...j4(this.options.query),before_id:Y}}}let Z=this.last_id;if(!Z)return null;return{...this.options,query:{...j4(this.options.query),after_id:Z}}}}class c2 extends WY{constructor(Z,Y,X,Q){super(Z,Y,X,Q);this.data=X.data||[],this.has_more=X.has_more||!1,this.next_page=X.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let Z=this.next_page;if(!Z)return null;return{...this.options,query:{...j4(this.options.query),page:Z}}}}var zY=()=>{if(typeof File==="undefined"){let{process:Z}=globalThis,Y=typeof Z?.versions?.node==="string"&&parseInt(Z.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(Y?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function K9(Z,Y,X){return zY(),new File(Z,Y??"unknown_file",X)}function l2(Z){return(typeof Z==="object"&&Z!==null&&(("name"in Z)&&Z.name&&String(Z.name)||("url"in Z)&&Z.url&&String(Z.url)||("filename"in Z)&&Z.filename&&String(Z.filename)||("path"in Z)&&Z.path&&String(Z.path))||"").split(/[\\/]/).pop()||void 0}var VY=(Z)=>Z!=null&&typeof Z==="object"&&typeof Z[Symbol.asyncIterator]==="function";var h9=async(Z,Y)=>{return{...Z,body:await CB(Z.body,Y)}},i$=new WeakMap;function jB(Z){let Y=typeof Z==="function"?Z:Z.fetch,X=i$.get(Y);if(X)return X;let Q=(async()=>{try{let $="Response"in Y?Y.Response:(await Y("data:,")).constructor,W=new FormData;if(W.toString()===await new $(W).text())return!1;return!0}catch{return!0}})();return i$.set(Y,Q),Q}var CB=async(Z,Y)=>{if(!await jB(Y))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let X=new FormData;return await Promise.all(Object.entries(Z||{}).map(([Q,$])=>JY(X,Q,$))),X},SB=(Z)=>Z instanceof Blob&&("name"in Z);var JY=async(Z,Y,X)=>{if(X===void 0)return;if(X==null)throw new TypeError(`Received null for "${Y}"; to pass null in FormData, you must use the string 'null'`);if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")Z.append(Y,String(X));else if(X instanceof Response){let Q={},$=X.headers.get("Content-Type");if($)Q={type:$};Z.append(Y,K9([await X.blob()],l2(X),Q))}else if(VY(X))Z.append(Y,K9([await new Response(S4(X)).blob()],l2(X)));else if(SB(X))Z.append(Y,K9([X],l2(X),{type:X.type}));else if(Array.isArray(X))await Promise.all(X.map((Q)=>JY(Z,Y+"[]",Q)));else if(typeof X==="object")await Promise.all(Object.entries(X).map(([Q,$])=>JY(Z,`${Y}[${Q}]`,$)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${X} instead`)};var o$=(Z)=>Z!=null&&typeof Z==="object"&&typeof Z.size==="number"&&typeof Z.type==="string"&&typeof Z.text==="function"&&typeof Z.slice==="function"&&typeof Z.arrayBuffer==="function",_B=(Z)=>Z!=null&&typeof Z==="object"&&typeof Z.name==="string"&&typeof Z.lastModified==="number"&&o$(Z),yB=(Z)=>Z!=null&&typeof Z==="object"&&typeof Z.url==="string"&&typeof Z.blob==="function";async function v4(Z,Y,X){if(zY(),Z=await Z,Y||(Y=l2(Z)),_B(Z)){if(Z instanceof File&&Y==null&&X==null)return Z;return K9([await Z.arrayBuffer()],Y??Z.name,{type:Z.type,lastModified:Z.lastModified,...X})}if(yB(Z)){let $=await Z.blob();return Y||(Y=new URL(Z.url).pathname.split(/[\\/]/).pop()),K9(await qY($),Y,X)}let Q=await qY(Z);if(!X?.type){let $=Q.find((W)=>typeof W==="object"&&("type"in W)&&W.type);if(typeof $==="string")X={...X,type:$}}return K9(Q,Y,X)}async function qY(Z){let Y=[];if(typeof Z==="string"||ArrayBuffer.isView(Z)||Z instanceof ArrayBuffer)Y.push(Z);else if(o$(Z))Y.push(Z instanceof Blob?Z:await Z.arrayBuffer());else if(VY(Z))for await(let X of Z)Y.push(...await qY(X));else{let X=Z?.constructor?.name;throw new Error(`Unexpected data type: ${typeof Z}${X?`; constructor: ${X}`:""}${bB(Z)}`)}return Y}function bB(Z){if(typeof Z!=="object"||Z===null)return"";return`; props: [${Object.getOwnPropertyNames(Z).map((X)=>`"${X}"`).join(", ")}]`}class X1{constructor(Z){this._client=Z}}var n$=Symbol.for("brand.privateNullableHeaders");function*kB(Z){if(!Z)return;if(n$ in Z){let{values:Q,nulls:$}=Z;yield*Q.entries();for(let W of $)yield[W,null];return}let Y=!1,X;if(Z instanceof Headers)X=Z.entries();else if(ZY(Z))X=Z;else Y=!0,X=Object.entries(Z??{});for(let Q of X){let $=Q[0];if(typeof $!=="string")throw new TypeError("expected header name to be a string");let W=ZY(Q[1])?Q[1]:[Q[1]],J=!1;for(let z of W){if(z===void 0)continue;if(Y&&!J)J=!0,yield[$,null];yield[$,z]}}}var y=(Z)=>{let Y=new Headers,X=new Set;for(let Q of Z){let $=new Set;for(let[W,J]of kB(Q)){let z=W.toLowerCase();if(!$.has(z))Y.delete(W),$.add(z);if(J===null)Y.delete(W),X.add(z);else Y.append(W,J),X.delete(z)}}return{[n$]:!0,values:Y,nulls:X}};function r$(Z){return Z.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var a$=Object.freeze(Object.create(null)),vB=(Z=r$)=>function Y(X,...Q){if(X.length===1)return X[0];let $=!1,W=[],J=X.reduce((U,H,G)=>{if(/[?#]/.test(H))$=!0;let K=Q[G],M=($?encodeURIComponent:Z)(""+K);if(G!==Q.length&&(K==null||typeof K==="object"&&K.toString===Object.getPrototypeOf(Object.getPrototypeOf(K.hasOwnProperty??a$)??a$)?.toString))M=K+"",W.push({start:U.length+H.length,length:M.length,error:`Value of type ${Object.prototype.toString.call(K).slice(8,-1)} is not a valid path parameter`});return U+H+(G===Q.length?"":M)},""),z=J.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,q;while((q=V.exec(z))!==null)W.push({start:q.index,length:q[0].length,error:`Value "${q[0]}" can't be safely passed as a path parameter`});if(W.sort((U,H)=>U.start-H.start),W.length>0){let U=0,H=W.reduce((G,K)=>{let M=" ".repeat(K.start-U),E="^".repeat(K.length);return U=K.start+K.length,G+M+E},"");throw new R(`Path parameters result in path with invalid segments:
52
+ ${W.map((G)=>G.error).join(`
53
+ `)}
54
+ ${J}
55
+ ${H}`)}return J},Y1=vB(r$);class i2 extends X1{list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/files",q0,{query:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"files-api-2025-04-14"].toString()},Y?.headers])})}delete(Z,Y={},X){let{betas:Q}=Y??{};return this._client.delete(Y1`/v1/files/${Z}`,{...X,headers:y([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},X?.headers])})}download(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/files/${Z}/content`,{...X,headers:y([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},X?.headers]),__binaryResponse:!0})}retrieveMetadata(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/files/${Z}`,{...X,headers:y([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},X?.headers])})}upload(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/files",h9({body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"files-api-2025-04-14"].toString()},Y?.headers])},this._client))}}class o2 extends X1{retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/models/${Z}?beta=true`,{...X,headers:y([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/models?beta=true",q0,{query:Q,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers])})}}var f4={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function UY(Z,Y,X){if(!Y||!("parse"in(Y.output_format??{})))return{...Z,content:Z.content.map((Q)=>{if(Q.type==="text"){let $=Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty($,"parsed",{get(){return X.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Q}),parsed_output:null};return HY(Z,Y,X)}function HY(Z,Y,X){let Q=null,$=Z.content.map((W)=>{if(W.type==="text"){let J=gB(Y,W.text);if(Q===null)Q=J;let z=Object.defineProperty({...W},"parsed_output",{value:J,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return X.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),J},enumerable:!1})}return W});return{...Z,content:$,parsed_output:Q}}function gB(Z,Y){if(Z.output_format?.type!=="json_schema")return null;try{if("parse"in Z.output_format)return Z.output_format.parse(Y);return JSON.parse(Y)}catch(X){throw new R(`Failed to parse structured output: ${X}`)}}var uB=(Z)=>{let Y=0,X=[];while(Y<Z.length){let Q=Z[Y];if(Q==="\\"){Y++;continue}if(Q==="{"){X.push({type:"brace",value:"{"}),Y++;continue}if(Q==="}"){X.push({type:"brace",value:"}"}),Y++;continue}if(Q==="["){X.push({type:"paren",value:"["}),Y++;continue}if(Q==="]"){X.push({type:"paren",value:"]"}),Y++;continue}if(Q===":"){X.push({type:"separator",value:":"}),Y++;continue}if(Q===","){X.push({type:"delimiter",value:","}),Y++;continue}if(Q==='"'){let z="",V=!1;Q=Z[++Y];while(Q!=='"'){if(Y===Z.length){V=!0;break}if(Q==="\\"){if(Y++,Y===Z.length){V=!0;break}z+=Q+Z[Y],Q=Z[++Y]}else z+=Q,Q=Z[++Y]}if(Q=Z[++Y],!V)X.push({type:"string",value:z});continue}if(Q&&/\s/.test(Q)){Y++;continue}let W=/[0-9]/;if(Q&&W.test(Q)||Q==="-"||Q==="."){let z="";if(Q==="-")z+=Q,Q=Z[++Y];while(Q&&W.test(Q)||Q===".")z+=Q,Q=Z[++Y];X.push({type:"number",value:z});continue}let J=/[a-z]/i;if(Q&&J.test(Q)){let z="";while(Q&&J.test(Q)){if(Y===Z.length)break;z+=Q,Q=Z[++Y]}if(z=="true"||z=="false"||z==="null")X.push({type:"name",value:z});else{Y++;continue}continue}Y++}return X},g9=(Z)=>{if(Z.length===0)return Z;let Y=Z[Z.length-1];switch(Y.type){case"separator":return Z=Z.slice(0,Z.length-1),g9(Z);break;case"number":let X=Y.value[Y.value.length-1];if(X==="."||X==="-")return Z=Z.slice(0,Z.length-1),g9(Z);case"string":let Q=Z[Z.length-2];if(Q?.type==="delimiter")return Z=Z.slice(0,Z.length-1),g9(Z);else if(Q?.type==="brace"&&Q.value==="{")return Z=Z.slice(0,Z.length-1),g9(Z);break;case"delimiter":return Z=Z.slice(0,Z.length-1),g9(Z);break}return Z},mB=(Z)=>{let Y=[];if(Z.map((X)=>{if(X.type==="brace")if(X.value==="{")Y.push("}");else Y.splice(Y.lastIndexOf("}"),1);if(X.type==="paren")if(X.value==="[")Y.push("]");else Y.splice(Y.lastIndexOf("]"),1)}),Y.length>0)Y.reverse().map((X)=>{if(X==="}")Z.push({type:"brace",value:"}"});else if(X==="]")Z.push({type:"paren",value:"]"})});return Z},pB=(Z)=>{let Y="";return Z.map((X)=>{switch(X.type){case"string":Y+='"'+X.value+'"';break;default:Y+=X.value;break}}),Y},h4=(Z)=>JSON.parse(pB(mB(g9(uB(Z)))));var Z0,l0,u9,n2,g4,a2,r2,u4,s2,S0,t2,m4,p4,B9,d4,c4,e2,GY,s$,l4,KY,BY,LY,t$,e$="__json_buf";function ZW(Z){return Z.type==="tool_use"||Z.type==="server_tool_use"||Z.type==="mcp_tool_use"}class Z6{constructor(Z,Y){Z0.add(this),this.messages=[],this.receivedMessages=[],l0.set(this,void 0),u9.set(this,null),this.controller=new AbortController,n2.set(this,void 0),g4.set(this,()=>{}),a2.set(this,()=>{}),r2.set(this,void 0),u4.set(this,()=>{}),s2.set(this,()=>{}),S0.set(this,{}),t2.set(this,!1),m4.set(this,!1),p4.set(this,!1),B9.set(this,!1),d4.set(this,void 0),c4.set(this,void 0),e2.set(this,void 0),l4.set(this,(X)=>{if(A(this,m4,!0,"f"),j0(X))X=new P1;if(X instanceof P1)return A(this,p4,!0,"f"),this._emit("abort",X);if(X instanceof R)return this._emit("error",X);if(X instanceof Error){let Q=new R(X.message);return Q.cause=X,this._emit("error",Q)}return this._emit("error",new R(String(X)))}),A(this,n2,new Promise((X,Q)=>{A(this,g4,X,"f"),A(this,a2,Q,"f")}),"f"),A(this,r2,new Promise((X,Q)=>{A(this,u4,X,"f"),A(this,s2,Q,"f")}),"f"),B(this,n2,"f").catch(()=>{}),B(this,r2,"f").catch(()=>{}),A(this,u9,Z,"f"),A(this,e2,Y?.logger??console,"f")}get response(){return B(this,d4,"f")}get request_id(){return B(this,c4,"f")}async withResponse(){A(this,B9,!0,"f");let Z=await B(this,n2,"f");if(!Z)throw new Error("Could not resolve a `Response` object");return{data:this,response:Z,request_id:Z.headers.get("request-id")}}static fromReadableStream(Z){let Y=new Z6(null);return Y._run(()=>Y._fromReadableStream(Z)),Y}static createMessage(Z,Y,X,{logger:Q}={}){let $=new Z6(Y,{logger:Q});for(let W of Y.messages)$._addMessageParam(W);return A($,u9,{...Y,stream:!0},"f"),$._run(()=>$._createMessage(Z,{...Y,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),$}_run(Z){Z().then(()=>{this._emitFinal(),this._emit("end")},B(this,l4,"f"))}_addMessageParam(Z){this.messages.push(Z)}_addMessage(Z,Y=!0){if(this.receivedMessages.push(Z),Y)this._emit("message",Z)}async _createMessage(Z,Y,X){let Q=X?.signal,$;if(Q){if(Q.aborted)this.controller.abort();$=this.controller.abort.bind(this.controller),Q.addEventListener("abort",$)}try{B(this,Z0,"m",KY).call(this);let{response:W,data:J}=await Z.create({...Y,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(W);for await(let z of J)B(this,Z0,"m",BY).call(this,z);if(J.controller.signal?.aborted)throw new P1;B(this,Z0,"m",LY).call(this)}finally{if(Q&&$)Q.removeEventListener("abort",$)}}_connected(Z){if(this.ended)return;A(this,d4,Z,"f"),A(this,c4,Z?.headers.get("request-id"),"f"),B(this,g4,"f").call(this,Z),this._emit("connect")}get ended(){return B(this,t2,"f")}get errored(){return B(this,m4,"f")}get aborted(){return B(this,p4,"f")}abort(){this.controller.abort()}on(Z,Y){return(B(this,S0,"f")[Z]||(B(this,S0,"f")[Z]=[])).push({listener:Y}),this}off(Z,Y){let X=B(this,S0,"f")[Z];if(!X)return this;let Q=X.findIndex(($)=>$.listener===Y);if(Q>=0)X.splice(Q,1);return this}once(Z,Y){return(B(this,S0,"f")[Z]||(B(this,S0,"f")[Z]=[])).push({listener:Y,once:!0}),this}emitted(Z){return new Promise((Y,X)=>{if(A(this,B9,!0,"f"),Z!=="error")this.once("error",X);this.once(Z,Y)})}async done(){A(this,B9,!0,"f"),await B(this,r2,"f")}get currentMessage(){return B(this,l0,"f")}async finalMessage(){return await this.done(),B(this,Z0,"m",GY).call(this)}async finalText(){return await this.done(),B(this,Z0,"m",s$).call(this)}_emit(Z,...Y){if(B(this,t2,"f"))return;if(Z==="end")A(this,t2,!0,"f"),B(this,u4,"f").call(this);let X=B(this,S0,"f")[Z];if(X)B(this,S0,"f")[Z]=X.filter((Q)=>!Q.once),X.forEach(({listener:Q})=>Q(...Y));if(Z==="abort"){let Q=Y[0];if(!B(this,B9,"f")&&!X?.length)Promise.reject(Q);B(this,a2,"f").call(this,Q),B(this,s2,"f").call(this,Q),this._emit("end");return}if(Z==="error"){let Q=Y[0];if(!B(this,B9,"f")&&!X?.length)Promise.reject(Q);B(this,a2,"f").call(this,Q),B(this,s2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",B(this,Z0,"m",GY).call(this))}async _fromReadableStream(Z,Y){let X=Y?.signal,Q;if(X){if(X.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),X.addEventListener("abort",Q)}try{B(this,Z0,"m",KY).call(this),this._connected(null);let $=n1.fromReadableStream(Z,this.controller);for await(let W of $)B(this,Z0,"m",BY).call(this,W);if($.controller.signal?.aborted)throw new P1;B(this,Z0,"m",LY).call(this)}finally{if(X&&Q)X.removeEventListener("abort",Q)}}[(l0=new WeakMap,u9=new WeakMap,n2=new WeakMap,g4=new WeakMap,a2=new WeakMap,r2=new WeakMap,u4=new WeakMap,s2=new WeakMap,S0=new WeakMap,t2=new WeakMap,m4=new WeakMap,p4=new WeakMap,B9=new WeakMap,d4=new WeakMap,c4=new WeakMap,e2=new WeakMap,l4=new WeakMap,Z0=new WeakSet,GY=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},s$=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Y.length===0)throw new R("stream ended without producing a content block with type=text");return Y.join(" ")},KY=function Z(){if(this.ended)return;A(this,l0,void 0,"f")},BY=function Z(Y){if(this.ended)return;let X=B(this,Z0,"m",t$).call(this,Y);switch(this._emit("streamEvent",Y,X),Y.type){case"content_block_delta":{let Q=X.content.at(-1);switch(Y.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Y.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Y.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(ZW(Q)&&Q.input)this._emit("inputJson",Y.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Y.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:YW(Y.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(UY(X,B(this,u9,"f"),{logger:B(this,e2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{A(this,l0,X,"f");break}case"content_block_start":case"message_delta":break}},LY=function Z(){if(this.ended)throw new R("stream has ended, this shouldn't happen");let Y=B(this,l0,"f");if(!Y)throw new R("request ended without sending any chunks");return A(this,l0,void 0,"f"),UY(Y,B(this,u9,"f"),{logger:B(this,e2,"f")})},t$=function Z(Y){let X=B(this,l0,"f");if(Y.type==="message_start"){if(X)throw new R(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!X)throw new R(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return X;case"message_delta":if(X.container=Y.delta.container,X.stop_reason=Y.delta.stop_reason,X.stop_sequence=Y.delta.stop_sequence,X.usage.output_tokens=Y.usage.output_tokens,X.context_management=Y.context_management,Y.usage.input_tokens!=null)X.usage.input_tokens=Y.usage.input_tokens;if(Y.usage.cache_creation_input_tokens!=null)X.usage.cache_creation_input_tokens=Y.usage.cache_creation_input_tokens;if(Y.usage.cache_read_input_tokens!=null)X.usage.cache_read_input_tokens=Y.usage.cache_read_input_tokens;if(Y.usage.server_tool_use!=null)X.usage.server_tool_use=Y.usage.server_tool_use;return X;case"content_block_start":return X.content.push(Y.content_block),X;case"content_block_delta":{let Q=X.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,text:(Q.text||"")+Y.delta.text};break}case"citations_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,citations:[...Q.citations??[],Y.delta.citation]};break}case"input_json_delta":{if(Q&&ZW(Q)){let $=Q[e$]||"";$+=Y.delta.partial_json;let W={...Q};if(Object.defineProperty(W,e$,{value:$,enumerable:!1,writable:!0}),$)try{W.input=h4($)}catch(J){let z=new R(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${J}. JSON: ${$}`);B(this,l4,"f").call(this,z)}X.content[Y.index]=W}break}case"thinking_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,thinking:Q.thinking+Y.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,signature:Y.delta.signature};break}default:YW(Y.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let Z=[],Y=[],X=!1;return this.on("streamEvent",(Q)=>{let $=Y.shift();if($)$.resolve(Q);else Z.push(Q)}),this.on("end",()=>{X=!0;for(let Q of Y)Q.resolve(void 0);Y.length=0}),this.on("abort",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),this.on("error",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),{next:async()=>{if(!Z.length){if(X)return{value:void 0,done:!0};return new Promise(($,W)=>Y.push({resolve:$,reject:W})).then(($)=>$?{value:$,done:!1}:{value:void 0,done:!0})}return{value:Z.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new n1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function YW(Z){}var XW=1e5,QW=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
56
+ 1. Task Overview
57
+ The user's core request and success criteria
58
+ Any clarifications or constraints they specified
59
+ 2. Current State
60
+ What has been completed so far
61
+ Files created, modified, or analyzed (with paths if relevant)
62
+ Key outputs or artifacts produced
63
+ 3. Important Discoveries
64
+ Technical constraints or requirements uncovered
65
+ Decisions made and their rationale
66
+ Errors encountered and how they were resolved
67
+ What approaches were tried that didn't work (and why)
68
+ 4. Next Steps
69
+ Specific actions needed to complete the task
70
+ Any blockers or open questions to resolve
71
+ Priority order if multiple steps remain
72
+ 5. Context to Preserve
73
+ User preferences or style requirements
74
+ Domain-specific details that aren't obvious
75
+ Any promises made to the user
76
+ Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
77
+ Wrap your summary in <summary></summary> tags.`;var Y6,m9,L9,M1,X6,a1,_0,i0,Q6,$W,MY;function WW(){let Z,Y;return{promise:new Promise((Q,$)=>{Z=Q,Y=$}),resolve:Z,reject:Y}}class $6{constructor(Z,Y,X){Y6.add(this),this.client=Z,m9.set(this,!1),L9.set(this,!1),M1.set(this,void 0),X6.set(this,void 0),a1.set(this,void 0),_0.set(this,void 0),i0.set(this,void 0),Q6.set(this,0),A(this,M1,{params:{...Y,messages:structuredClone(Y.messages)}},"f"),A(this,X6,{...X,headers:y([{"x-stainless-helper":"BetaToolRunner"},X?.headers])},"f"),A(this,i0,WW(),"f")}async*[(m9=new WeakMap,L9=new WeakMap,M1=new WeakMap,X6=new WeakMap,a1=new WeakMap,_0=new WeakMap,i0=new WeakMap,Q6=new WeakMap,Y6=new WeakSet,$W=async function Z(){let Y=B(this,M1,"f").params.compactionControl;if(!Y||!Y.enabled)return!1;let X=0;if(B(this,a1,"f")!==void 0)try{let V=await B(this,a1,"f");X=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Q=Y.contextTokenThreshold??XW;if(X<Q)return!1;let $=Y.model??B(this,M1,"f").params.model,W=Y.summaryPrompt??QW,J=B(this,M1,"f").params.messages;if(J[J.length-1].role==="assistant"){let V=J[J.length-1];if(Array.isArray(V.content)){let q=V.content.filter((U)=>U.type!=="tool_use");if(q.length===0)J.pop();else V.content=q}}let z=await this.client.beta.messages.create({model:$,messages:[...J,{role:"user",content:[{type:"text",text:W}]}],max_tokens:B(this,M1,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(z.content[0]?.type!=="text")throw new R("Expected text response for compaction");return B(this,M1,"f").params.messages=[{role:"user",content:z.content}],!0},Symbol.asyncIterator)](){var Z;if(B(this,m9,"f"))throw new R("Cannot iterate over a consumed stream");A(this,m9,!0,"f"),A(this,L9,!0,"f"),A(this,_0,void 0,"f");try{while(!0){let Y;try{if(B(this,M1,"f").params.max_iterations&&B(this,Q6,"f")>=B(this,M1,"f").params.max_iterations)break;A(this,L9,!1,"f"),A(this,_0,void 0,"f"),A(this,Q6,(Z=B(this,Q6,"f"),Z++,Z),"f"),A(this,a1,void 0,"f");let{max_iterations:X,compactionControl:Q,...$}=B(this,M1,"f").params;if($.stream)Y=this.client.beta.messages.stream({...$},B(this,X6,"f")),A(this,a1,Y.finalMessage(),"f"),B(this,a1,"f").catch(()=>{}),yield Y;else A(this,a1,this.client.beta.messages.create({...$,stream:!1},B(this,X6,"f")),"f"),yield B(this,a1,"f");if(!await B(this,Y6,"m",$W).call(this)){if(!B(this,L9,"f")){let{role:z,content:V}=await B(this,a1,"f");B(this,M1,"f").params.messages.push({role:z,content:V})}let J=await B(this,Y6,"m",MY).call(this,B(this,M1,"f").params.messages.at(-1));if(J)B(this,M1,"f").params.messages.push(J);else if(!B(this,L9,"f"))break}}finally{if(Y)Y.abort()}}if(!B(this,a1,"f"))throw new R("ToolRunner concluded without a message from the server");B(this,i0,"f").resolve(await B(this,a1,"f"))}catch(Y){throw A(this,m9,!1,"f"),B(this,i0,"f").promise.catch(()=>{}),B(this,i0,"f").reject(Y),A(this,i0,WW(),"f"),Y}}setMessagesParams(Z){if(typeof Z==="function")B(this,M1,"f").params=Z(B(this,M1,"f").params);else B(this,M1,"f").params=Z;A(this,L9,!0,"f"),A(this,_0,void 0,"f")}async generateToolResponse(){let Z=await B(this,a1,"f")??this.params.messages.at(-1);if(!Z)return null;return B(this,Y6,"m",MY).call(this,Z)}done(){return B(this,i0,"f").promise}async runUntilDone(){if(!B(this,m9,"f"))for await(let Z of this);return this.done()}get params(){return B(this,M1,"f").params}pushMessages(...Z){this.setMessagesParams((Y)=>({...Y,messages:[...Y.messages,...Z]}))}then(Z,Y){return this.runUntilDone().then(Z,Y)}}MY=async function Z(Y){if(B(this,_0,"f")!==void 0)return B(this,_0,"f");return A(this,_0,dB(B(this,M1,"f").params,Y),"f"),B(this,_0,"f")};async function dB(Z,Y=Z.messages.at(-1)){if(!Y||Y.role!=="assistant"||!Y.content||typeof Y.content==="string")return null;let X=Y.content.filter(($)=>$.type==="tool_use");if(X.length===0)return null;return{role:"user",content:await Promise.all(X.map(async($)=>{let W=Z.tools.find((J)=>("name"in J?J.name:J.mcp_server_name)===$.name);if(!W||!("run"in W))return{type:"tool_result",tool_use_id:$.id,content:`Error: Tool '${$.name}' not found`,is_error:!0};try{let J=$.input;if("parse"in W&&W.parse)J=W.parse(J);let z=await W.run(J);return{type:"tool_result",tool_use_id:$.id,content:z}}catch(J){return{type:"tool_result",tool_use_id:$.id,content:`Error: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}))}}class p9{constructor(Z,Y){this.iterator=Z,this.controller=Y}async*decoder(){let Z=new c0;for await(let Y of this.iterator)for(let X of Z.decode(Y))yield JSON.parse(X);for(let Y of Z.flush())yield JSON.parse(Y)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(Z,Y){if(!Z.body){if(Y.abort(),typeof globalThis.navigator!=="undefined"&&globalThis.navigator.product==="ReactNative")throw new R("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new R("Attempted to iterate over a response with no body")}return new p9(g2(Z.body),Y)}}class W6 extends X1{create(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/messages/batches/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/messages/batches?beta=true",q0,{query:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}delete(Z,Y={},X){let{betas:Q}=Y??{};return this._client.delete(Y1`/v1/messages/batches/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},X?.headers])})}cancel(Z,Y={},X){let{betas:Q}=Y??{};return this._client.post(Y1`/v1/messages/batches/${Z}/cancel?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},X?.headers])})}async results(Z,Y={},X){let Q=await this.retrieve(Z);if(!Q.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);let{betas:$}=Y??{};return this._client.get(Q.results_url,{...X,headers:y([{"anthropic-beta":[...$??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},X?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((W,J)=>p9.fromResponse(J.response,J.controller))}}var JW={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};class M9 extends X1{constructor(){super(...arguments);this.batches=new W6(this._client)}create(Z,Y){let{betas:X,...Q}=Z;if(Q.model in JW)console.warn(`The model '${Q.model}' is deprecated and will reach end-of-life on ${JW[Q.model]}
78
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let $=this._client._options.timeout;if(!Q.stream&&$==null){let W=f4[Q.model]??void 0;$=this._client.calculateNonstreamingTimeout(Q.max_tokens,W)}return this._client.post("/v1/messages?beta=true",{body:Q,timeout:$??600000,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers]),stream:Z.stream??!1})}parse(Z,Y){return Y={...Y,headers:y([{"anthropic-beta":[...Z.betas??[],"structured-outputs-2025-11-13"].toString()},Y?.headers])},this.create(Z,Y).then((X)=>HY(X,Z,{logger:this._client.logger??console}))}stream(Z,Y){return Z6.createMessage(this,Z,Y)}countTokens(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"token-counting-2024-11-01"].toString()},Y?.headers])})}toolRunner(Z,Y){return new $6(this._client,Z,Y)}}M9.Batches=W6;M9.BetaToolRunner=$6;class J6 extends X1{create(Z,Y={},X){let{betas:Q,...$}=Y??{};return this._client.post(Y1`/v1/skills/${Z}/versions?beta=true`,h9({body:$,...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])},this._client))}retrieve(Z,Y,X){let{skill_id:Q,betas:$}=Y;return this._client.get(Y1`/v1/skills/${Q}/versions/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...$??[],"skills-2025-10-02"].toString()},X?.headers])})}list(Z,Y={},X){let{betas:Q,...$}=Y??{};return this._client.getAPIList(Y1`/v1/skills/${Z}/versions?beta=true`,c2,{query:$,...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])})}delete(Z,Y,X){let{skill_id:Q,betas:$}=Y;return this._client.delete(Y1`/v1/skills/${Q}/versions/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...$??[],"skills-2025-10-02"].toString()},X?.headers])})}}class d9 extends X1{constructor(){super(...arguments);this.versions=new J6(this._client)}create(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.post("/v1/skills?beta=true",h9({body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/skills/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/skills?beta=true",c2,{query:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete(Z,Y={},X){let{betas:Q}=Y??{};return this._client.delete(Y1`/v1/skills/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])})}}d9.Versions=J6;class M0 extends X1{constructor(){super(...arguments);this.models=new o2(this._client),this.messages=new M9(this._client),this.files=new i2(this._client),this.skills=new d9(this._client)}}M0.Models=o2;M0.Messages=M9;M0.Files=i2;M0.Skills=d9;class c9 extends X1{create(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers]),stream:Z.stream??!1})}}var Y0,o0,z6,i4,V6,q6,o4,U6,y0,H6,n4,a4,F9,r4,s4,FY,zW,NY,wY,DY,AY,VW,qW="__json_buf";function UW(Z){return Z.type==="tool_use"||Z.type==="server_tool_use"}class G6{constructor(){Y0.add(this),this.messages=[],this.receivedMessages=[],o0.set(this,void 0),this.controller=new AbortController,z6.set(this,void 0),i4.set(this,()=>{}),V6.set(this,()=>{}),q6.set(this,void 0),o4.set(this,()=>{}),U6.set(this,()=>{}),y0.set(this,{}),H6.set(this,!1),n4.set(this,!1),a4.set(this,!1),F9.set(this,!1),r4.set(this,void 0),s4.set(this,void 0),NY.set(this,(Z)=>{if(A(this,n4,!0,"f"),j0(Z))Z=new P1;if(Z instanceof P1)return A(this,a4,!0,"f"),this._emit("abort",Z);if(Z instanceof R)return this._emit("error",Z);if(Z instanceof Error){let Y=new R(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new R(String(Z)))}),A(this,z6,new Promise((Z,Y)=>{A(this,i4,Z,"f"),A(this,V6,Y,"f")}),"f"),A(this,q6,new Promise((Z,Y)=>{A(this,o4,Z,"f"),A(this,U6,Y,"f")}),"f"),B(this,z6,"f").catch(()=>{}),B(this,q6,"f").catch(()=>{})}get response(){return B(this,r4,"f")}get request_id(){return B(this,s4,"f")}async withResponse(){A(this,F9,!0,"f");let Z=await B(this,z6,"f");if(!Z)throw new Error("Could not resolve a `Response` object");return{data:this,response:Z,request_id:Z.headers.get("request-id")}}static fromReadableStream(Z){let Y=new G6;return Y._run(()=>Y._fromReadableStream(Z)),Y}static createMessage(Z,Y,X){let Q=new G6;for(let $ of Y.messages)Q._addMessageParam($);return Q._run(()=>Q._createMessage(Z,{...Y,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run(Z){Z().then(()=>{this._emitFinal(),this._emit("end")},B(this,NY,"f"))}_addMessageParam(Z){this.messages.push(Z)}_addMessage(Z,Y=!0){if(this.receivedMessages.push(Z),Y)this._emit("message",Z)}async _createMessage(Z,Y,X){let Q=X?.signal,$;if(Q){if(Q.aborted)this.controller.abort();$=this.controller.abort.bind(this.controller),Q.addEventListener("abort",$)}try{B(this,Y0,"m",wY).call(this);let{response:W,data:J}=await Z.create({...Y,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(W);for await(let z of J)B(this,Y0,"m",DY).call(this,z);if(J.controller.signal?.aborted)throw new P1;B(this,Y0,"m",AY).call(this)}finally{if(Q&&$)Q.removeEventListener("abort",$)}}_connected(Z){if(this.ended)return;A(this,r4,Z,"f"),A(this,s4,Z?.headers.get("request-id"),"f"),B(this,i4,"f").call(this,Z),this._emit("connect")}get ended(){return B(this,H6,"f")}get errored(){return B(this,n4,"f")}get aborted(){return B(this,a4,"f")}abort(){this.controller.abort()}on(Z,Y){return(B(this,y0,"f")[Z]||(B(this,y0,"f")[Z]=[])).push({listener:Y}),this}off(Z,Y){let X=B(this,y0,"f")[Z];if(!X)return this;let Q=X.findIndex(($)=>$.listener===Y);if(Q>=0)X.splice(Q,1);return this}once(Z,Y){return(B(this,y0,"f")[Z]||(B(this,y0,"f")[Z]=[])).push({listener:Y,once:!0}),this}emitted(Z){return new Promise((Y,X)=>{if(A(this,F9,!0,"f"),Z!=="error")this.once("error",X);this.once(Z,Y)})}async done(){A(this,F9,!0,"f"),await B(this,q6,"f")}get currentMessage(){return B(this,o0,"f")}async finalMessage(){return await this.done(),B(this,Y0,"m",FY).call(this)}async finalText(){return await this.done(),B(this,Y0,"m",zW).call(this)}_emit(Z,...Y){if(B(this,H6,"f"))return;if(Z==="end")A(this,H6,!0,"f"),B(this,o4,"f").call(this);let X=B(this,y0,"f")[Z];if(X)B(this,y0,"f")[Z]=X.filter((Q)=>!Q.once),X.forEach(({listener:Q})=>Q(...Y));if(Z==="abort"){let Q=Y[0];if(!B(this,F9,"f")&&!X?.length)Promise.reject(Q);B(this,V6,"f").call(this,Q),B(this,U6,"f").call(this,Q),this._emit("end");return}if(Z==="error"){let Q=Y[0];if(!B(this,F9,"f")&&!X?.length)Promise.reject(Q);B(this,V6,"f").call(this,Q),B(this,U6,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",B(this,Y0,"m",FY).call(this))}async _fromReadableStream(Z,Y){let X=Y?.signal,Q;if(X){if(X.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),X.addEventListener("abort",Q)}try{B(this,Y0,"m",wY).call(this),this._connected(null);let $=n1.fromReadableStream(Z,this.controller);for await(let W of $)B(this,Y0,"m",DY).call(this,W);if($.controller.signal?.aborted)throw new P1;B(this,Y0,"m",AY).call(this)}finally{if(X&&Q)X.removeEventListener("abort",Q)}}[(o0=new WeakMap,z6=new WeakMap,i4=new WeakMap,V6=new WeakMap,q6=new WeakMap,o4=new WeakMap,U6=new WeakMap,y0=new WeakMap,H6=new WeakMap,n4=new WeakMap,a4=new WeakMap,F9=new WeakMap,r4=new WeakMap,s4=new WeakMap,NY=new WeakMap,Y0=new WeakSet,FY=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},zW=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Y.length===0)throw new R("stream ended without producing a content block with type=text");return Y.join(" ")},wY=function Z(){if(this.ended)return;A(this,o0,void 0,"f")},DY=function Z(Y){if(this.ended)return;let X=B(this,Y0,"m",VW).call(this,Y);switch(this._emit("streamEvent",Y,X),Y.type){case"content_block_delta":{let Q=X.content.at(-1);switch(Y.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Y.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Y.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(UW(Q)&&Q.input)this._emit("inputJson",Y.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Y.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:HW(Y.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{A(this,o0,X,"f");break}case"content_block_start":case"message_delta":break}},AY=function Z(){if(this.ended)throw new R("stream has ended, this shouldn't happen");let Y=B(this,o0,"f");if(!Y)throw new R("request ended without sending any chunks");return A(this,o0,void 0,"f"),Y},VW=function Z(Y){let X=B(this,o0,"f");if(Y.type==="message_start"){if(X)throw new R(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!X)throw new R(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return X;case"message_delta":if(X.stop_reason=Y.delta.stop_reason,X.stop_sequence=Y.delta.stop_sequence,X.usage.output_tokens=Y.usage.output_tokens,Y.usage.input_tokens!=null)X.usage.input_tokens=Y.usage.input_tokens;if(Y.usage.cache_creation_input_tokens!=null)X.usage.cache_creation_input_tokens=Y.usage.cache_creation_input_tokens;if(Y.usage.cache_read_input_tokens!=null)X.usage.cache_read_input_tokens=Y.usage.cache_read_input_tokens;if(Y.usage.server_tool_use!=null)X.usage.server_tool_use=Y.usage.server_tool_use;return X;case"content_block_start":return X.content.push({...Y.content_block}),X;case"content_block_delta":{let Q=X.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,text:(Q.text||"")+Y.delta.text};break}case"citations_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,citations:[...Q.citations??[],Y.delta.citation]};break}case"input_json_delta":{if(Q&&UW(Q)){let $=Q[qW]||"";$+=Y.delta.partial_json;let W={...Q};if(Object.defineProperty(W,qW,{value:$,enumerable:!1,writable:!0}),$)W.input=h4($);X.content[Y.index]=W}break}case"thinking_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,thinking:Q.thinking+Y.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,signature:Y.delta.signature};break}default:HW(Y.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let Z=[],Y=[],X=!1;return this.on("streamEvent",(Q)=>{let $=Y.shift();if($)$.resolve(Q);else Z.push(Q)}),this.on("end",()=>{X=!0;for(let Q of Y)Q.resolve(void 0);Y.length=0}),this.on("abort",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),this.on("error",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),{next:async()=>{if(!Z.length){if(X)return{value:void 0,done:!0};return new Promise(($,W)=>Y.push({resolve:$,reject:W})).then(($)=>$?{value:$,done:!1}:{value:void 0,done:!0})}return{value:Z.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new n1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function HW(Z){}class K6 extends X1{create(Z,Y){return this._client.post("/v1/messages/batches",{body:Z,...Y})}retrieve(Z,Y){return this._client.get(Y1`/v1/messages/batches/${Z}`,Y)}list(Z={},Y){return this._client.getAPIList("/v1/messages/batches",q0,{query:Z,...Y})}delete(Z,Y){return this._client.delete(Y1`/v1/messages/batches/${Z}`,Y)}cancel(Z,Y){return this._client.post(Y1`/v1/messages/batches/${Z}/cancel`,Y)}async results(Z,Y){let X=await this.retrieve(Z);if(!X.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);return this._client.get(X.results_url,{...Y,headers:y([{Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,$)=>p9.fromResponse($.response,$.controller))}}class N9 extends X1{constructor(){super(...arguments);this.batches=new K6(this._client)}create(Z,Y){if(Z.model in GW)console.warn(`The model '${Z.model}' is deprecated and will reach end-of-life on ${GW[Z.model]}
79
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let X=this._client._options.timeout;if(!Z.stream&&X==null){let Q=f4[Z.model]??void 0;X=this._client.calculateNonstreamingTimeout(Z.max_tokens,Q)}return this._client.post("/v1/messages",{body:Z,timeout:X??600000,...Y,stream:Z.stream??!1})}stream(Z,Y){return G6.createMessage(this,Z,Y)}countTokens(Z,Y){return this._client.post("/v1/messages/count_tokens",{body:Z,...Y})}}var GW={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};N9.Batches=K6;class l9 extends X1{retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/models/${Z}`,{...X,headers:y([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/models",q0,{query:Q,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers])})}}var B6=(Z)=>{if(typeof globalThis.process!=="undefined")return globalThis.process.env?.[Z]?.trim()??void 0;if(typeof globalThis.Deno!=="undefined")return globalThis.Deno.env?.get?.(Z)?.trim();return};var EY,OY,t4,KW,BW="\\n\\nHuman:",LW="\\n\\nAssistant:";class V1{constructor({baseURL:Z=B6("ANTHROPIC_BASE_URL"),apiKey:Y=B6("ANTHROPIC_API_KEY")??null,authToken:X=B6("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){EY.add(this),t4.set(this,void 0);let $={apiKey:Y,authToken:X,...Q,baseURL:Z||"https://api.anthropic.com"};if(!$.dangerouslyAllowBrowser&&k$())throw new R(`It looks like you're running in a browser-like environment.
80
+
81
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
82
+ If you understand the risks and have appropriate mitigations in place,
83
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
84
+
85
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
86
+ `);this.baseURL=$.baseURL,this.timeout=$.timeout??OY.DEFAULT_TIMEOUT,this.logger=$.logger??console;let W="warn";this.logLevel=W,this.logLevel=QY($.logLevel,"ClientOptions.logLevel",this)??QY(B6("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??W,this.fetchOptions=$.fetchOptions,this.maxRetries=$.maxRetries??2,this.fetch=$.fetch??f$(),A(this,t4,g$,"f"),this._options=$,this.apiKey=typeof Y==="string"?Y:null,this.authToken=X}withOptions(Z){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...Z})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:Z,nulls:Y}){if(Z.get("x-api-key")||Z.get("authorization"))return;if(this.apiKey&&Z.get("x-api-key"))return;if(Y.has("x-api-key"))return;if(this.authToken&&Z.get("authorization"))return;if(Y.has("authorization"))return;throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(Z){return y([await this.apiKeyAuth(Z),await this.bearerAuth(Z)])}async apiKeyAuth(Z){if(this.apiKey==null)return;return y([{"X-Api-Key":this.apiKey}])}async bearerAuth(Z){if(this.authToken==null)return;return y([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(Z){return Object.entries(Z).filter(([Y,X])=>typeof X!=="undefined").map(([Y,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent(Y)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent(Y)}=`;throw new R(`Cannot stringify type ${typeof X}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${d0}`}defaultIdempotencyKey(){return`stainless-node-retry-${tZ()}`}makeStatusError(Z,Y,X,Q){return L1.generate(Z,Y,X,Q)}buildURL(Z,Y,X){let Q=!B(this,EY,"m",KW).call(this)&&X||this.baseURL,$=R$(Z)?new URL(Z):new URL(Q+(Q.endsWith("/")&&Z.startsWith("/")?Z.slice(1):Z)),W=this.defaultQuery();if(!j$(W))Y={...W,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))$.search=this.stringifyQuery(Y);return $.toString()}_calculateNonstreamingTimeout(Z){if(3600*Z/128000>600)throw new R("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(Z){}async prepareRequest(Z,{url:Y,options:X}){}get(Z,Y){return this.methodRequest("get",Z,Y)}post(Z,Y){return this.methodRequest("post",Z,Y)}patch(Z,Y){return this.methodRequest("patch",Z,Y)}put(Z,Y){return this.methodRequest("put",Z,Y)}delete(Z,Y){return this.methodRequest("delete",Z,Y)}methodRequest(Z,Y,X){return this.request(Promise.resolve(X).then((Q)=>{return{method:Z,path:Y,...Q}}))}request(Z,Y=null){return new G9(this,this.makeRequest(Z,Y,void 0))}async makeRequest(Z,Y,X){let Q=await Z,$=Q.maxRetries??this.maxRetries;if(Y==null)Y=$;await this.prepareOptions(Q);let{req:W,url:J,timeout:z}=await this.buildRequest(Q,{retryCount:$-Y});await this.prepareRequest(W,{url:J,options:Q});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),q=X===void 0?"":`, retryOf: ${X}`,U=Date.now();if(A1(this).debug(`[${V}] sending request`,C0({retryOfRequestLogID:X,method:Q.method,url:J,options:Q,headers:W.headers})),Q.signal?.aborted)throw new P1;let H=new AbortController,G=await this.fetchWithTimeout(J,W,z,H).catch(C2),K=Date.now();if(G instanceof globalThis.Error){let O=`retrying, ${Y} attempts remaining`;if(Q.signal?.aborted)throw new P1;let T=j0(G)||/timed? ?out/i.test(String(G)+("cause"in G?String(G.cause):""));if(Y)return A1(this).info(`[${V}] connection ${T?"timed out":"failed"} - ${O}`),A1(this).debug(`[${V}] connection ${T?"timed out":"failed"} (${O})`,C0({retryOfRequestLogID:X,url:J,durationMs:K-U,message:G.message})),this.retryRequest(Q,Y,X??V);if(A1(this).info(`[${V}] connection ${T?"timed out":"failed"} - error; no more retries left`),A1(this).debug(`[${V}] connection ${T?"timed out":"failed"} (error; no more retries left)`,C0({retryOfRequestLogID:X,url:J,durationMs:K-U,message:G.message})),T)throw new S2;throw new H9({cause:G})}let M=[...G.headers.entries()].filter(([O])=>O==="request-id").map(([O,T])=>", "+O+": "+JSON.stringify(T)).join(""),E=`[${V}${q}${M}] ${W.method} ${J} ${G.ok?"succeeded":"failed"} with status ${G.status} in ${K-U}ms`;if(!G.ok){let O=await this.shouldRetry(G);if(Y&&O){let W1=`retrying, ${Y} attempts remaining`;return await h$(G.body),A1(this).info(`${E} - ${W1}`),A1(this).debug(`[${V}] response error (${W1})`,C0({retryOfRequestLogID:X,url:G.url,status:G.status,headers:G.headers,durationMs:K-U})),this.retryRequest(Q,Y,X??V,G.headers)}let T=O?"error; no more retries left":"error; not retryable";A1(this).info(`${E} - ${T}`);let i=await G.text().catch((W1)=>C2(W1).message),g=C4(i),Z1=g?void 0:i;throw A1(this).debug(`[${V}] response error (${T})`,C0({retryOfRequestLogID:X,url:G.url,status:G.status,headers:G.headers,message:Z1,durationMs:Date.now()-U})),this.makeStatusError(G.status,g,Z1,G.headers)}return A1(this).info(E),A1(this).debug(`[${V}] response start`,C0({retryOfRequestLogID:X,url:G.url,status:G.status,headers:G.headers,durationMs:K-U})),{response:G,options:Q,controller:H,requestLogID:V,retryOfRequestLogID:X,startTime:U}}getAPIList(Z,Y,X){return this.requestAPIList(Y,{method:"get",path:Z,...X})}requestAPIList(Z,Y){let X=this.makeRequest(Y,null,void 0);return new k4(this,X,Z)}async fetchWithTimeout(Z,Y,X,Q){let{signal:$,method:W,...J}=Y||{};if($)$.addEventListener("abort",()=>Q.abort());let z=setTimeout(()=>Q.abort(),X),V=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,q={signal:Q.signal,...V?{duplex:"half"}:{},method:"GET",...J};if(W)q.method=W.toUpperCase();try{return await this.fetch.call(void 0,Z,q)}finally{clearTimeout(z)}}async shouldRetry(Z){let Y=Z.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="false")return!1;if(Z.status===408)return!0;if(Z.status===409)return!0;if(Z.status===429)return!0;if(Z.status>=500)return!0;return!1}async retryRequest(Z,Y,X,Q){let $,W=Q?.get("retry-after-ms");if(W){let z=parseFloat(W);if(!Number.isNaN(z))$=z}let J=Q?.get("retry-after");if(J&&!$){let z=parseFloat(J);if(!Number.isNaN(z))$=z*1000;else $=Date.parse(J)-Date.now()}if(!($&&0<=$&&$<60000)){let z=Z.maxRetries??this.maxRetries;$=this.calculateDefaultRetryTimeoutMillis(Y,z)}return await _$($),this.makeRequest(Z,Y-1,X)}calculateDefaultRetryTimeoutMillis(Z,Y){let $=Y-Z,W=Math.min(0.5*Math.pow(2,$),8),J=1-Math.random()*0.25;return W*J*1000}calculateNonstreamingTimeout(Z,Y){if(3600000*Z/128000>600000||Y!=null&&Z>Y)throw new R("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(Z,{retryCount:Y=0}={}){let X={...Z},{method:Q,path:$,query:W,defaultBaseURL:J}=X,z=this.buildURL($,W,J);if("timeout"in X)S$("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let{bodyHeaders:V,body:q}=this.buildBody({options:X}),U=await this.buildHeaders({options:Z,method:Q,bodyHeaders:V,retryCount:Y});return{req:{method:Q,headers:U,...X.signal&&{signal:X.signal},...globalThis.ReadableStream&&q instanceof globalThis.ReadableStream&&{duplex:"half"},...q&&{body:q},...this.fetchOptions??{},...X.fetchOptions??{}},url:z,timeout:X.timeout}}async buildHeaders({options:Z,method:Y,bodyHeaders:X,retryCount:Q}){let $={};if(this.idempotencyHeader&&Y!=="get"){if(!Z.idempotencyKey)Z.idempotencyKey=this.defaultIdempotencyKey();$[this.idempotencyHeader]=Z.idempotencyKey}let W=y([$,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...Z.timeout?{"X-Stainless-Timeout":String(Math.trunc(Z.timeout/1000))}:{},...v$(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(Z),this._options.defaultHeaders,X,Z.headers]);return this.validateHeaders(W),W.values}buildBody({options:{body:Z,headers:Y}}){if(!Z)return{bodyHeaders:void 0,body:void 0};let X=y([Y]);if(ArrayBuffer.isView(Z)||Z instanceof ArrayBuffer||Z instanceof DataView||typeof Z==="string"&&X.values.has("content-type")||globalThis.Blob&&Z instanceof globalThis.Blob||Z instanceof FormData||Z instanceof URLSearchParams||globalThis.ReadableStream&&Z instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:Z};else if(typeof Z==="object"&&((Symbol.asyncIterator in Z)||(Symbol.iterator in Z)&&("next"in Z)&&typeof Z.next==="function"))return{bodyHeaders:void 0,body:S4(Z)};else return B(this,t4,"f").call(this,{body:Z,headers:X})}}OY=V1,t4=new WeakMap,EY=new WeakSet,KW=function Z(){return this.baseURL!=="https://api.anthropic.com"};V1.Anthropic=OY;V1.HUMAN_PROMPT=BW;V1.AI_PROMPT=LW;V1.DEFAULT_TIMEOUT=600000;V1.AnthropicError=R;V1.APIError=L1;V1.APIConnectionError=H9;V1.APIConnectionTimeoutError=S2;V1.APIUserAbortError=P1;V1.NotFoundError=x2;V1.ConflictError=k2;V1.RateLimitError=f2;V1.BadRequestError=_2;V1.AuthenticationError=y2;V1.InternalServerError=h2;V1.PermissionDeniedError=b2;V1.UnprocessableEntityError=v2;V1.toFile=v4;class b0 extends V1{constructor(){super(...arguments);this.completions=new c9(this),this.messages=new N9(this),this.models=new l9(this),this.beta=new M0(this)}}b0.Completions=c9;b0.Messages=N9;b0.Models=l9;b0.Beta=M0;function PY(Z){return new b0({apiKey:Z.apiKey})}function TY(){let Y=(typeof globalThis!=="undefined"&&globalThis.window?.env?globalThis.window.env:typeof process!=="undefined"?process.env:void 0)?.ANTHROPIC_API_KEY;if(!Y)throw new Error("ANTHROPIC_API_KEY is required. Please set it in your environment variables or use the factory function with an explicit API key.");return Y}function e4(Z){return`${Z}-${Date.now()}-${Math.random().toString(36).substring(7)}`}class IY extends R4{constructor(Z,Y){super({},Y);this.kind="text",this.name="anthropic",this.client=PY(Z)}async*chatStream(Z){try{let Y=this.mapCommonOptionsToAnthropic(Z),X=await this.client.beta.messages.create({...Y,stream:!0},{signal:Z.request?.signal,headers:Z.request?.headers});yield*this.processAnthropicStream(X,Z.model,()=>e4(this.name))}catch(Y){let X=Y;yield{type:"error",id:e4(this.name),model:Z.model,timestamp:Date.now(),error:{message:X.message||"Unknown error occurred",code:X.code||String(X.status)}}}}async structuredOutput(Z){let{chatOptions:Y,outputSchema:X}=Z,Q=this.mapCommonOptionsToAnthropic(Y),$={name:"structured_output",description:"Use this tool to provide your response in the required structured format.",input_schema:{type:"object",properties:X.properties??{},required:X.required??[]}};try{let W=await this.client.messages.create({...Q,stream:!1,tools:[$],tool_choice:{type:"tool",name:"structured_output"}},{signal:Y.request?.signal,headers:Y.request?.headers}),J=null,z="";for(let V of W.content)if(V.type==="tool_use"&&V.name==="structured_output"){J=V.input,z=JSON.stringify(V.input);break}if(J===null){z=W.content.map((V)=>{if(V.type==="text")return V.text;return""}).join("");try{J=JSON.parse(z)}catch{throw new Error(`Failed to extract structured output from response. Content: ${z.slice(0,200)}${z.length>200?"...":""}`)}}return{data:J,rawText:z}}catch(W){throw new Error(`Structured output generation failed: ${W.message||"Unknown error occurred"}`)}}mapCommonOptionsToAnthropic(Z){let Y=Z.modelOptions,X=this.formatMessages(Z.messages),Q=Z.tools?sZ(Z.tools):void 0,$={};if(Y){let q=["container","context_management","mcp_servers","service_tier","stop_sequences","system","thinking","tool_choice","top_k"];for(let U of q)if(U in Y){let H=Y[U];if(U==="tool_choice"&&typeof H==="string")$[U]={type:H};else $[U]=H}}let W=$.thinking?.type==="enabled"?$.thinking.budget_tokens:void 0,J=Z.maxTokens||1024,z=W&&W>=J?W+1:J,V={model:Z.model,max_tokens:z,temperature:Z.temperature,top_p:Z.topP,messages:X,system:Z.systemPrompts?.join(`
87
+ `),tools:Q,...$};return I$(V),V}convertContentPartToAnthropic(Z){switch(Z.type){case"text":{let Y=Z.metadata;return{type:"text",text:Z.content,...Y}}case"image":{let Y=Z.metadata,X=Z.source.type==="data"?{type:"base64",data:Z.source.value,media_type:Y?.mediaType??"image/jpeg"}:{type:"url",url:Z.source.value},{mediaType:Q,...$}=Y||{};return{type:"image",source:X,...$}}case"document":{let Y=Z.metadata;return{type:"document",source:Z.source.type==="data"?{type:"base64",data:Z.source.value,media_type:"application/pdf"}:{type:"url",url:Z.source.value},...Y}}case"audio":case"video":throw new Error(`Anthropic does not support ${Z.type} content directly`);default:throw new Error(`Unsupported content part type: ${Z.type}`)}}formatMessages(Z){let Y=[];for(let X of Z){let Q=X.role;if(Q==="tool"&&X.toolCallId){Y.push({role:"user",content:[{type:"tool_result",tool_use_id:X.toolCallId,content:typeof X.content==="string"?X.content:""}]});continue}if(Q==="assistant"&&X.toolCalls?.length){let $=[];if(X.content){let J={type:"text",text:typeof X.content==="string"?X.content:""};$.push(J)}for(let W of X.toolCalls){let J={};try{J=W.function.arguments?JSON.parse(W.function.arguments):{}}catch{J=W.function.arguments}let z={type:"tool_use",id:W.id,name:W.function.name,input:J};$.push(z)}Y.push({role:"assistant",content:$});continue}if(Q==="user"&&Array.isArray(X.content)){let $=X.content.map((W)=>this.convertContentPartToAnthropic(W));Y.push({role:"user",content:$});continue}Y.push({role:Q==="assistant"?"assistant":"user",content:typeof X.content==="string"?X.content:X.content?X.content.map(($)=>this.convertContentPartToAnthropic($)):""})}return Y}async*processAnthropicStream(Z,Y,X){let Q="",$="",W=Date.now(),J=new Map,z=-1;try{for await(let V of Z)if(V.type==="content_block_start"){if(V.content_block.type==="tool_use")z++,J.set(z,{id:V.content_block.id,name:V.content_block.name,input:""});else if(V.content_block.type==="thinking")$=""}else if(V.type==="content_block_delta"){if(V.delta.type==="text_delta"){let q=V.delta.text;Q+=q,yield{type:"content",id:X(),model:Y,timestamp:W,delta:q,content:Q,role:"assistant"}}else if(V.delta.type==="thinking_delta"){let q=V.delta.thinking;$+=q,yield{type:"thinking",id:X(),model:Y,timestamp:W,delta:q,content:$}}else if(V.delta.type==="input_json_delta"){let q=J.get(z);if(q)q.input+=V.delta.partial_json,yield{type:"tool_call",id:X(),model:Y,timestamp:W,toolCall:{id:q.id,type:"function",function:{name:q.name,arguments:V.delta.partial_json}},index:z}}}else if(V.type==="content_block_stop"){let q=J.get(z);if(q&&q.input==="")yield{type:"tool_call",id:X(),model:Y,timestamp:W,toolCall:{id:q.id,type:"function",function:{name:q.name,arguments:"{}"}},index:z}}else if(V.type==="message_stop")yield{type:"done",id:X(),model:Y,timestamp:W,finishReason:"stop"};else if(V.type==="message_delta"){if(V.delta.stop_reason)switch(V.delta.stop_reason){case"tool_use":{yield{type:"done",id:X(),model:Y,timestamp:W,finishReason:"tool_calls",usage:{promptTokens:V.usage.input_tokens||0,completionTokens:V.usage.output_tokens||0,totalTokens:(V.usage.input_tokens||0)+(V.usage.output_tokens||0)}};break}case"max_tokens":{yield{type:"error",id:X(),model:Y,timestamp:W,error:{message:"The response was cut off because the maximum token limit was reached.",code:"max_tokens"}};break}default:yield{type:"done",id:X(),model:Y,timestamp:W,finishReason:"stop",usage:{promptTokens:V.usage.input_tokens||0,completionTokens:V.usage.output_tokens||0,totalTokens:(V.usage.input_tokens||0)+(V.usage.output_tokens||0)}}}}}catch(V){let q=V;yield{type:"error",id:X(),model:Y,timestamp:W,error:{message:q.message||"Unknown error occurred",code:q.code||String(q.status)}}}}}function MW(Z,Y,X){return new IY({apiKey:Y,...X},Z)}function C1(Z,Y){let X=TY();return MW(Z,X,Y)}var n0=(Z)=>Array.isArray(Z)?Z:[Z],FW=(Z,Y)=>{let X=[[],[]];for(let Q of Z)if(Y(Q))X[0].push(Q);else X[1].push(Q);return X},Z8=Array,X0=(Z,Y)=>Z.includes(Y),NW=(Z,Y=0)=>[...new Array(Z)].map((X,Q)=>Q+Y),h=(Z,Y,X)=>{if(Z===void 0)return Y===void 0?[]:Array.isArray(Y)?Y:[Y];if(X?.prepend)if(Array.isArray(Y))Z.unshift(...Y);else Z.unshift(Y);else if(Array.isArray(Y))Z.push(...Y);else Z.push(Y);return Z},x0=(Z,Y)=>{if(Y===void 0||Y===null)return Z??[];if(Z===void 0||Z===null)return n0(Y);return Z.concat(Y)},wW=(...Z)=>Z.reduce(x0,[]),F0=(Z,Y,X)=>{if(Z===void 0)return Array.isArray(Y)?Y:[Y];let Q=X?.isEqual??(($,W)=>$===W);for(let $ of n0(Y))if(!Z.some((W)=>Q(W,$)))Z.push($);return Z},DW=(Z,Y)=>Z.reduce((X,Q)=>{let $=Q[Y];return X[$]=h(X[$],Q),X},{}),k0=(Z,Y,X)=>Z.length===Y.length&&Z.every(X?.isEqual?(Q,$)=>X.isEqual(Q,Y[$]):(Q,$)=>Q===Y[$]);var v1=(Z,Y)=>F1(Z)===Y,F1=(Z)=>{let Y=typeof Z;return Y==="object"?Z===null?"null":"object":Y==="function"?"object":Y},f1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},AW={...f1,function:"a function"};class EW extends Error{}var u=(Z)=>w9(Z,EW),w9=(Z,Y=Error)=>{throw new Y(Z)};class L6 extends Error{name="ParseError"}var L=(Z)=>w9(Z,L6),U0=(Z)=>` ${Z}`,OW="​";var b=(Z,Y)=>{let X={},Q=Array.isArray(Z),$=!1;for(let[W,J]of Object.entries(Z).entries()){let z=Q?Y(W,J[1]):Y(...J,W);$||=typeof z[0]==="number";let V=Array.isArray(z[0])||z.length===0?z:[z];for(let[q,U]of V)if(typeof q==="object")X[q.group]=h(X[q.group],U);else X[q]=U}return $?Object.values(X):X};var RY=Object.entries;var N1=(Z,Y)=>(Z in Y),i9=(Z,Y)=>(Y in Z);class jY{constructor(Z){Object.assign(this,Z)}}var PW=class{};class M6 extends PW{}var rB=(Z,Y)=>{let X={},Q={},$;for($ in Z)if($ in Y)X[$]=Z[$];else Q[$]=Z[$];return[X,Q]};var Y8=(Z,Y)=>rB(Z,Y)[1],N0=(Z)=>Object.keys(Z).length===0,D9=(Z)=>[...Object.entries(Z),...Object.getOwnPropertySymbols(Z).map((Y)=>[Y,Z[Y]])],TW=(Z,Y)=>Object.defineProperties(Z,Object.getOwnPropertyDescriptors(Y)),IW=(Z)=>{let Y=Object.keys(Z).sort(),X={};for(let Q=0;Q<Y.length;Q++)X[Y[Q]]=Z[Y[Q]];return X};var h1=U0(`unset${OW}`),RW=(Z)=>Object.values(Z).filter((Y)=>{if(typeof Y==="number")return!0;return typeof Z[Y]!=="number"});var CY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},SY=globalThis.File??Blob,_Y={ArrayBuffer,Blob,File:SY,FormData,Headers,Request,Response,URL},sB={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},A9={...CY,..._Y,...sB,String,Number,Boolean},F6=(Z)=>{let Y=Object.getPrototypeOf(Z);while(Y?.constructor&&(!N1(Y.constructor.name,A9)||!(Z instanceof A9[Y.constructor.name])))Y=Object.getPrototypeOf(Y);let X=Y?.constructor?.name;if(X===void 0||X==="Object")return;return X},N6=(Z)=>typeof Z==="object"&&Z!==null?F6(Z)??"object":F1(Z);var n=Array.isArray,tB={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},eB={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},ZL={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},jW={...tB,...eB,...ZL},w6=(Z)=>{let Y=Object(Z).name??null;return Y&&N1(Y,A9)&&A9[Y]===Z?Y:null};var yY=(Z,Y)=>{let X=Z.prototype;while(X!==null){if(X===Y.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var CW=(Z)=>SW(Z,new Map),SW=(Z,Y)=>{if(typeof Z!=="object"||Z===null)return Z;if(Y?.has(Z))return Y.get(Z);let X=w6(Z.constructor);if(X==="Date")return new Date(Z.getTime());if(X&&X!=="Array")return Z;let Q=Array.isArray(Z)?Z.slice():Object.create(Object.getPrototypeOf(Z)),$=Object.getOwnPropertyDescriptors(Z);if(Y){Y.set(Z,Q);for(let W in $){let J=$[W];if("get"in J||"set"in J)continue;J.value=SW(J.value,Y)}}return Object.defineProperties(Q,$),Q};var YL=(Z)=>{let Y=h1;return()=>Y===h1?Y=Z():Y},a0=(Z)=>typeof Z==="function"&&Z.length===0;var _W=class extends Function{constructor(...Z){let Y=Z.slice(0,-1),X=Z[Z.length-1];try{super(...Y,X)}catch(Q){return u(`Encountered an unexpected error while compiling your definition:
88
+ Message: ${Q}
89
+ Source: (${Z.slice(0,-1)}) => {
90
+ ${Z[Z.length-1]}
91
+ }`)}}};class g1{constructor(Z,...[Y]){return Object.assign(Object.setPrototypeOf(Z.bind(Y?.bind??this),this.constructor.prototype),Y?.attach)}}var yW=YL(()=>{try{return new Function("return false")()}catch{return!0}});var FI=U0("brand");var bW=U0("arkInferred");var DI=U0("args");class T1{constructor(){}}var XL=()=>{try{return((new Error().stack?.split(`
92
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},QL=globalThis.process?.env??{},xW={fileName:XL,env:QL};var kW=(Z)=>Z[0].toUpperCase()+Z.slice(1),vW=(Z)=>Z[0].toLowerCase()+Z.slice(1),bY=(Z)=>new RegExp($L(Z),typeof Z==="string"?"":Z.flags);var $L=(Z)=>{return`^(?:${typeof Z==="string"?Z:Z.source})$`};var v0={negativeLookahead:(Z)=>`(?!${Z})`,nonCapturingGroup:(Z)=>`(?:${Z})`},E9="\\",r0={" ":1,"\n":1,"\t":1};var WL=/^-0\.?0*$/.source,hW=/[1-9]\d*/.source,JL=/\.\d+/.source,zL=/\.\d*[1-9]/.source,gW=(Z)=>bY(v0.negativeLookahead(WL)+v0.nonCapturingGroup("-?"+v0.nonCapturingGroup(v0.nonCapturingGroup("0|"+hW)+v0.nonCapturingGroup(Z.decimalPattern)+"?")+(Z.allowDecimalOnly?"|"+Z.decimalPattern:"")+"?")),fW=gW({decimalPattern:zL,allowDecimalOnly:!1}),VL=fW.test.bind(fW),X8=gW({decimalPattern:JL,allowDecimalOnly:!0}),RI=X8.test.bind(X8),qL=/^-?\d*\.?\d*$/,UL=(Z)=>Z.length!==0&&qL.test(Z),D6=bY(v0.negativeLookahead("^-0$")+"-?"+v0.nonCapturingGroup(v0.nonCapturingGroup("0|"+hW))),HL=D6.test.bind(D6),xY=/^-?\d+$/,GL=xY.test.bind(xY),uW={number:"a number",bigint:"a bigint",integer:"an integer"},mW=(Z,Y)=>`'${Z}' was parsed as ${uW[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,KL=(Z,Y)=>Y==="number"?VL(Z):HL(Z),BL=(Z,Y)=>Y==="number"?Number(Z):Number.parseInt(Z),LL=(Z,Y)=>Y==="number"?UL(Z):GL(Z),pW=(Z,Y)=>kY(Z,"number",Y),dW=(Z,Y)=>kY(Z,"number",{...Y,strict:!0}),cW=(Z,Y)=>kY(Z,"integer",Y),kY=(Z,Y,X)=>{let Q=BL(Z,Y);if(!Number.isNaN(Q)){if(LL(Z,Y)){if(X?.strict)return KL(Z,Y)?Q:L(mW(Z,Y));return Q}}return X?.errorOnFail?L(X?.errorOnFail===!0?`Failed to parse ${uW[Y]} from '${Z}'`:X?.errorOnFail):void 0},lW=(Z)=>{if(Z[Z.length-1]!=="n")return;let Y=Z.slice(0,-1),X;try{X=BigInt(Y)}catch{return}if(D6.test(Y))return X;if(xY.test(Y))return L(mW(Z,"bigint"))};var ML="0.56.0",FL={version:ML,filename:xW.fileName(),FileConstructor:SY},O9=FL,iW=new Map,vY=Object.create(null),A6=(Z)=>{let Y=iW.get(Z);if(Y)return Y;let X=NL(Z);if(vY[X])X=`${X}${vY[X]++}`;else vY[X]=1;return O9[X]=Z,iW.set(Z,X),X},s0=(Z)=>/^[$A-Z_a-z][\w$]*$/.test(Z),NL=(Z)=>{switch(typeof Z){case"object":{if(Z===null)break;let Y=F6(Z)??"object";return Y[0].toLowerCase()+Y.slice(1)}case"function":return s0(Z.name)?Z.name:"fn";case"symbol":return Z.description&&s0(Z.description)?Z.description:"symbol"}return u(`Unexpected attempt to register serializable value of type ${F1(Z)}`)};var E6=(Z)=>typeof Z==="string"?JSON.stringify(Z):typeof Z==="bigint"?`${Z}n`:`${Z}`;var oW=(Z,Y={})=>O6(Z,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Y},[]);var x=(Z,Y)=>{switch(F1(Z)){case"object":let X=Z,Q=X.constructor?.name??"Object";return Q==="Object"||Q==="Array"?Y?.quoteKeys===!1?Q8(X,Y?.indent??0,""):JSON.stringify(O6(X,o9,[]),null,Y?.indent):Q8(X,Y?.indent??0,"");case"symbol":return o9.onSymbol(Z);default:return E6(Z)}},Q8=(Z,Y,X)=>{if(typeof Z==="function")return o9.onFunction(Z);if(typeof Z!=="object"||Z===null)return E6(Z);let Q=X+" ".repeat(Y);if(Array.isArray(Z)){if(Z.length===0)return"[]";let W=Z.map((J)=>Q8(J,Y,Q)).join(`,
93
+ `+Q);return Y?`[
94
+ ${Q}${W}
95
+ ${X}]`:`[${W}]`}let $=Z.constructor?.name??"Object";if($==="Object"){let W=D9(Z).map(([J,z])=>{let V=typeof J==="symbol"?o9.onSymbol(J):s0(J)?J:JSON.stringify(J),q=Q8(z,Y,Q);return`${Q}${V}: ${q}`});if(W.length===0)return"{}";return Y?`{
96
+ ${W.join(`,
97
+ `)}
98
+ ${X}}`:`{${W.join(", ")}}`}if(Z instanceof Date)return P9(Z);if("expression"in Z&&typeof Z.expression==="string")return Z.expression;return $},o9={onCycle:()=>"(cycle)",onSymbol:(Z)=>`Symbol(${A6(Z)})`,onFunction:(Z)=>`Function(${A6(Z)})`},O6=(Z,Y,X)=>{switch(F1(Z)){case"object":{let Q=Z;if("toJSON"in Q&&typeof Q.toJSON==="function")return Q.toJSON();if(typeof Q==="function")return o9.onFunction(Q);if(X.includes(Q))return"(cycle)";let $=[...X,Q];if(Array.isArray(Q))return Q.map((J)=>O6(J,Y,$));if(Q instanceof Date)return Q.toDateString();let W={};for(let J in Q)W[J]=O6(Q[J],Y,$);for(let J of Object.getOwnPropertySymbols(Q))W[Y.onSymbol?.(J)??J.toString()]=O6(Q[J],Y,$);return W}case"symbol":return o9.onSymbol(Z);case"bigint":return Y.onBigInt?.(Z)??`${Z}n`;case"undefined":return Y.onUndefined??"undefined";case"string":return Z.replace(/\\/g,"\\\\");default:return Z}},P9=(Z)=>{let Y=Z.getFullYear(),X=Z.getMonth(),Q=Z.getDate(),$=Z.getHours(),W=Z.getMinutes(),J=Z.getSeconds(),z=Z.getMilliseconds();if(X===0&&Q===1&&$===0&&W===0&&J===0&&z===0)return`${Y}`;let V=`${wL[X]} ${Q}, ${Y}`;if($===0&&W===0&&J===0&&z===0)return V;let q=Z.toLocaleTimeString(),U=q.endsWith(" AM")||q.endsWith(" PM")?q.slice(-3):"";if(U)q=q.slice(0,-U.length);if(z)q+=`.${AL(z,3)}`;else if(DL.test(q))q=q.slice(0,-3);return`${q+U}, ${V}`},wL=["January","February","March","April","May","June","July","August","September","October","November","December"],DL=/:\d\d:00$/,AL=(Z,Y)=>String(Z).padStart(Y,"0");var nW=(Z,Y,...[X])=>{let Q=X?.stringifySymbol??x,$=Z;switch(typeof Y){case"string":$=s0(Y)?Z===""?Y:`${Z}.${Y}`:`${Z}[${JSON.stringify(Y)}]`;break;case"number":$=`${Z}[${Y}]`;break;case"symbol":$=`${Z}[${Q(Y)}]`;break;default:if(X?.stringifyNonKey)$=`${Z}[${X.stringifyNonKey(Y)}]`;else L(`${x(Y)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return $},f0=(Z,...Y)=>Z.reduce((X,Q)=>nW(X,Q,...Y),"");class P6 extends Z8{cache={};constructor(...Z){super();this.push(...Z)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Z=0;Z<this.length;Z++)this.cache.json.push(typeof this[Z]==="symbol"?x(this[Z]):this[Z]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=f0(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Z="",Y=[Z];for(let X of this)Z=nW(Z,X),Y.push(Z);return this.cache.stringifyAncestors=Y}}class T6{chars;i;def;constructor(Z){this.def=Z,this.chars=[...Z],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(Z){let Y="";while(this.lookahead)if(Z(this,Y))break;else Y+=this.shift();return Y}shiftUntilEscapable(Z){let Y="";while(this.lookahead)if(this.lookahead===E9)if(this.shift(),Z(this,Y))Y+=this.shift();else if(this.lookahead===E9)Y+=this.shift();else Y+=`${E9}${this.shift()}`;else if(Z(this,Y))break;else Y+=this.shift();return Y}shiftUntilLookahead(Z){return typeof Z==="string"?this.shiftUntil((Y)=>Y.lookahead===Z):this.shiftUntil((Y)=>(Y.lookahead in Z))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in r0))}jumpToIndex(Z){this.i=Z<0?this.length+Z:Z}jumpForward(Z){this.i+=Z}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(Z,Y){return this.chars.slice(Z,Y).join("")}lookaheadIs(Z){return this.lookahead===Z}lookaheadIsIn(Z){return this.lookahead in Z}}var aW=(Z,Y)=>`Unmatched ${Z}${Y===""?"":` before ${Y}`}`,$8=(Z)=>`Missing ${Z}`;var tI=U0("implementedTraits");var fY="$ark",EL=2;while(fY in globalThis)fY=`$ark${EL++}`;var rW=fY;globalThis[rW]=O9;var F=O9,OL=(Z)=>`${rW}.${Z}`,Q1=(Z)=>OL(A6(Z));class W8 extends M6{argNames;body="";constructor(...Z){super();this.argNames=Z;for(let Y of Z){if(Y in this)throw new Error(`Arg name '${Y}' would overwrite an existing property on FunctionBody`);this[Y]=Y}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Z,Y=!1){return hY(Z,Y)}index(Z,Y=!1){return sW(`${Z}`,Y)}line(Z){return this.body+=`${" ".repeat(this.indentation)}${Z}
99
+ `,this}const(Z,Y){return this.line(`const ${Z} = ${Y}`),this}let(Z,Y){return this.line(`let ${Z} = ${Y}`)}set(Z,Y){return this.line(`${Z} = ${Y}`)}if(Z,Y){return this.block(`if (${Z})`,Y)}elseIf(Z,Y){return this.block(`else if (${Z})`,Y)}else(Z){return this.block("else",Z)}for(Z,Y,X=0){return this.block(`for (let i = ${X}; ${Z}; i++)`,Y)}forIn(Z,Y){return this.block(`for (const k in ${Z})`,Y)}block(Z,Y,X=""){return this.line(`${Z} {`),this.indent(),Y(this),this.dedent(),this.line(`}${X}`)}return(Z=""){return this.line(`return ${Z}`)}write(Z="anonymous",Y=0){return`${Z}(${this.argNames.join(", ")}) { ${Y?this.body.split(`
100
+ `).map((X)=>" ".repeat(Y)+`${X}`).join(`
101
+ `):this.body} }`}compile(){return new _W(...this.argNames,this.body)}}var H0=(Z)=>v1(Z,"object")||typeof Z==="symbol"?Q1(Z):E6(Z),hY=(Z,Y=!1)=>{if(typeof Z==="string"&&s0(Z))return`${Y?"?":""}.${Z}`;return sW(PL(Z),Y)},PL=(Z)=>typeof Z==="symbol"?Q1(Z):JSON.stringify(Z),sW=(Z,Y=!1)=>`${Y?"?.":""}[${Z}]`;class I6 extends W8{traversalKind;optimistic;constructor(Z){super("data","ctx");this.traversalKind=Z.kind,this.optimistic=Z.optimistic===!0}invoke(Z,Y){let X=Y?.arg??this.data,Q=typeof Z==="string"?!0:this.requiresContextFor(Z),$=typeof Z==="string"?Z:Z.id;if(Q)return`${this.referenceToId($,Y)}(${X}, ${this.ctx})`;return`${this.referenceToId($,Y)}(${X})`}referenceToId(Z,Y){let X=Y?.kind??this.traversalKind,Q=`this.${Z}${X}`;return Y?.bind?`${Q}.bind(${Y?.bind})`:Q}requiresContextFor(Z){return this.traversalKind==="Apply"||Z.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(Z,Y,X){let Q=this.requiresContextFor(X);if(Q)this.line(`${this.ctx}.path.push(${Z})`);if(this.check(X,{arg:Y}),Q)this.line(`${this.ctx}.path.pop()`);return this}check(Z,Y){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Z,Y)}`,()=>this.return(!1)):this.line(this.invoke(Z,Y))}}var J8=(Z)=>b(Z,(Y,X)=>[Y,n(X)?[...X]:X]),S1=U0("arkKind"),P=(Z,Y)=>Z?.[S1]===Y,r=(Z)=>P(Z,"root")||P(Z,"constraint");var tW=["unit","proto","domain"],n9=["required","optional","index","sequence"],gY=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],uY=[...gY,"structure","predicate"],z8=[...uY,...n9],a9=["alias","union","morph","unit","intersection","proto","domain"],TL=[...a9,...z8],V8=b(z8,(Z,Y)=>[Y,1]),eW=b([...n9,"undeclared"],(Z,Y)=>[Y,1]),ZJ=b(TL,(Z,Y)=>[Y,Z]),r9=(Z)=>typeof Z==="string"&&(Z in ZJ);var s9=(Z)=>ZJ[Z],q8=(Z)=>a9.slice(s9(Z)+1),kR=[...q8("union"),"alias"],vR=[...q8("morph"),"alias"],Q0=(Z)=>{if(typeof Z==="string"||typeof Z==="boolean"||Z===null)return Z;if(typeof Z==="number"){if(Number.isNaN(Z))return"NaN";if(Z===Number.POSITIVE_INFINITY)return"Infinity";if(Z===Number.NEGATIVE_INFINITY)return"-Infinity";return Z}return H0(Z)},t0=(Z)=>{let Y="{ ";for(let[X,Q]of Object.entries(Z))Y+=`${X}: ${H0(Q)}, `;return Y+" }"},v=(Z)=>{let Y=Z;if(Y.hasAssociatedError)Y.defaults.expected??=(X)=>("description"in X)?X.description:Y.defaults.description(X),Y.defaults.actual??=(X)=>x(X),Y.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Y.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let Q=`${X.propString} ${X.problem}`;if(Q[0]==="[")return`value at ${Q}`;return Q};return Y};class YJ extends Error{name="ToJsonSchemaError";code;context;constructor(Z,Y){super(x(Y,{quoteKeys:!1,indent:4}));this.code=Z,this.context=Y}hasCode(Z){return this.code===Z}}var IL={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Z)=>t.throw("arrayObject",Z),arrayPostfix:(Z)=>t.throw("arrayPostfix",Z),defaultValue:(Z)=>t.throw("defaultValue",Z),domain:(Z)=>t.throw("domain",Z),morph:(Z)=>t.throw("morph",Z),patternIntersection:(Z)=>t.throw("patternIntersection",Z),predicate:(Z)=>t.throw("predicate",Z),proto:(Z)=>t.throw("proto",Z),symbolKey:(Z)=>t.throw("symbolKey",Z),unit:(Z)=>t.throw("unit",Z),date:(Z)=>t.throw("date",Z)}},t={Error:YJ,throw:(...Z)=>{throw new t.Error(...Z)},throwInternalOperandError:(Z,Y)=>u(`Unexpected JSON Schema input for ${Z}: ${x(Y)}`),defaultConfig:IL};F.config??={};var R6=(Z,Y)=>{if(!Y)return Z;let X={...Z},Q;for(Q in Y){let $={...Z.keywords};if(Q==="keywords"){for(let W in Y[Q]){let J=Y.keywords[W];if(J===void 0)continue;$[W]=typeof J==="string"?{description:J}:J}X.keywords=$}else if(Q==="toJsonSchema")X[Q]=mY(Z.toJsonSchema,Y.toJsonSchema);else if(r9(Q))X[Q]={...Z[Q],...Y[Q]};else X[Q]=Y[Q]}return X},RL={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},mY=(Z,Y)=>{if(!Z)return XJ(Y??{},void 0);if(!Y)return Z;let X={...Z},Q;for(Q in Y)if(Q==="fallback")X.fallback=jL(Z.fallback,Y.fallback);else X[Q]=Y[Q];return XJ(X,Y)},XJ=(Z,Y)=>{if(Y?.dialect!==void 0)return Z;if(Y?.target!==void 0)return{...Z,dialect:RL[Y.target]};return Z},jL=(Z,Y)=>{Z=QJ(Z),Y=QJ(Y);let X={},Q;for(Q in t.defaultConfig.fallback)X[Q]=Y[Q]??Y.default??Z[Q]??Z.default??t.defaultConfig.fallback[Q];return X},QJ=(Z)=>typeof Z==="function"?{default:Z}:Z??{};class e0 extends M6{[S1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Z,relativePath:Y,...X},Q){super();this.input=X,this.ctx=Q,TW(this,X);let $=Q.data;if(X.code==="union")X.errors=X.errors.flatMap((J)=>{let z=J.hasCode("union")?J.errors:[J];if(!Z&&!Y)return z;return z.map((V)=>V.transform((q)=>({...q,path:wW(Z,q.path,Y)})))});this.nodeConfig=Q.config[this.code];let W=[...X.path??Q.path];if(Y)W.push(...Y);if(Z)W.unshift(...Z);this.path=new P6(...W),this.data="data"in X?X.data:$}transform(Z){return new e0(Z({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Z){return this.code===Z}get propString(){return f0(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Z=this.meta?.expected??this.nodeConfig.expected;return typeof Z==="function"?Z(this.input):Z}get actual(){if(this.input.actual)return this.input.actual;let Z=this.meta?.actual??this.nodeConfig.actual;return typeof Z==="function"?Z(this.data):Z}get problem(){if(this.input.problem)return this.input.problem;let Z=this.meta?.problem??this.nodeConfig.problem;return typeof Z==="function"?Z(this):Z}get message(){if(this.input.message)return this.input.message;let Z=this.meta?.message??this.nodeConfig.message;return typeof Z==="function"?Z(this):Z}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class u1 extends Z8{[S1]="errors";ctx;constructor(Z){super();this.ctx=Z}byPath=Object.create(null);get flatByPath(){return b(this.byPath,(Z,Y)=>[Z,Y.flat])}get flatProblemsByPath(){return b(this.byPath,(Z,Y)=>[Z,Y.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new pY(this)}add(Z){let Y=this.byPath[Z.propString];if(Y){if(Z===Y)return;if(Y.hasCode("union")&&Y.errors.length===0)return;let X=Z.hasCode("union")&&Z.errors.length===0?Z:new e0({code:"intersection",errors:Y.hasCode("intersection")?[...Y.errors,Z]:[Y,Z]},this.ctx),Q=this.indexOf(Y);this.mutable[Q===-1?this.length:Q]=X,this.byPath[Z.propString]=X,this.addAncestorPaths(Z)}else this.byPath[Z.propString]=Z,this.addAncestorPaths(Z),this.mutable.push(Z);this.count++}transform(Z){let Y=new u1(this.ctx);for(let X of this)Y.add(Z(X));return Y}merge(Z){for(let Y of Z)this.add(new e0({...Y,path:[...this.ctx.path,...Y.path]},this.ctx))}affectsPath(Z){if(this.length===0)return!1;return Z.stringifyAncestors().some((Y)=>(Y in this.byPath))||Z.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Z)=>Z.toJSON())]}toString(){return this.join(`
102
+ `)}addAncestorPaths(Z){for(let Y of Z.path.stringifyAncestors())this.byAncestorPath[Y]=h(this.byAncestorPath[Y],Z)}}class pY extends Error{name="TraversalError";constructor(Z){if(Z.length===1)super(Z.summary);else super(`
103
+ `+Z.map((Y)=>` • ${CL(Y)}`).join(`
104
+ `));Object.defineProperty(this,"arkErrors",{value:Z,enumerable:!1})}}var CL=(Z)=>Z.toString().split(`
105
+ `).join(`
106
+ `);class G0{path=[];errors=new u1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Z,Y){this.root=Z,this.config=Y}get data(){let Z=this.root;for(let Y of this.path)Z=Z?.[Y];return Z}get propString(){return f0(this.path)}reject(Z){return this.error(Z),!1}mustBe(Z){return this.error(Z),!1}error(Z){let Y=typeof Z==="object"?Z.code?Z:{...Z,code:"predicate"}:{code:"predicate",expected:Z};return this.errorFromContext(Y)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Z){let Y={path:new P6(...this.path),morphs:Z};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Y);else this.queuedMorphs.push(Y)}finalize(Z){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return Z?Z(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(Z){return this.errorFromContext(Z)}errorFromContext(Z){let Y=new e0(Z,this);if(this.currentBranch)this.currentBranch.error=Y;else this.errors.add(Y);return Y}applyQueuedMorphs(){while(this.queuedMorphs.length){let Z=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Y,morphs:X}of Z){if(this.errors.affectsPath(Y))continue;this.applyMorphsAtPath(Y,X)}}}applyMorphsAtPath(Z,Y){let X=Z[Z.length-1],Q;if(X!==void 0){Q=this.root;for(let $=0;$<Z.length-1;$++)Q=Q[Z[$]]}for(let $ of Y){this.path=[...Z];let W=r($),J=$(Q===void 0?this.root:Q[X],this);if(J instanceof e0){if(!this.errors.includes(J))this.errors.add(J);break}if(J instanceof u1){if(!W)this.errors.merge(J);this.queuedMorphs=[];break}if(Q===void 0)this.root=J;else Q[X]=J;this.applyQueuedMorphs()}}}var m1=(Z,Y,X)=>{if(!X)return Y();X.path.push(Z);let Q=Y();return X.path.pop(),Q};class C6 extends g1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Z,Y){super((Q,$,W=this.onFail)=>{if($)return this.traverseApply(Q,$),$.hasError()?$.errors:$.data;return this.rootApply(Q,W)},{attach:Z});this.attachments=Z,this.$=Y,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((Q,$)=>bL(Q,$.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let Q=0;Q<this.children.length;Q++){if(this.includesTransform||=this.children[Q].includesTransform,this.includesContextualPredicate||=this.children[Q].includesContextualPredicate,this.isCyclic||=this.children[Q].isCyclic,!X){let $=this.children[Q].flatRefs;for(let W=0;W<$.length;W++){let J=$[W];if(!this.flatRefs.some((z)=>WJ(z,J))){this.flatRefs.push(J);for(let z of J.node.branches)if(z.hasKind("morph")||z.hasKind("intersection")&&z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:J.path,propString:J.propString,node:z})}}}Object.assign(this.referencesById,this.children[Q].referencesById)}this.flatRefs.sort((Q,$)=>Q.path.length>$.path.length?1:Q.path.length<$.path.length?-1:Q.propString>$.propString?1:Q.propString<$.propString?-1:Q.node.expression<$.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((Q)=>Q.length===1||Q.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((Q)=>Q.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(Q)=>this.traverseAllows(Q,new G0(Q,this.$.resolvedConfig)):(Q)=>this.traverseAllows(Q)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Y,X)=>{if(this.allows(Y))return Y;let Q=new G0(Y,this.$.resolvedConfig);return this.traverseApply(Y,Q),Q.finalize(X)};case"contextual":return(Y,X)=>{let Q=new G0(Y,this.$.resolvedConfig);return this.traverseApply(Y,Q),Q.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Z=this.$.resolvedConfig.clone;return(Y,X)=>{if(this.allows(Y))return this.contextFreeMorph(Z&&(typeof Y==="object"&&Y!==null||typeof Y==="function")?Z(Y):Y);let Q=new G0(Y,this.$.resolvedConfig);return this.traverseApply(Y,Q),Q.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,u(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=yL(this.metaJson);cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=s9(this.kind);precompilation;assert=(Z,Y)=>this(Z,Y,(X)=>X.throw());traverse(Z,Y){return this(Z,Y,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(Z){if(!this.includesTransform)return this;let Y={};for(let[X,Q]of this.innerEntries){let $=this.impl.keys[X];if($.reduceIo)$.reduceIo(Z,Y,Q);else if($.child){let W=Q;Y[X]=n(W)?W.map((J)=>Z==="in"?J.rawIn:J.rawOut):Z==="in"?W.rawIn:W.rawOut}else Y[X]=Q}return this.$.node(this.kind,Y)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Z){let Y=r(Z)?Z:this.$.parseDefinition(Z);return this.innerHash===Y.innerHash}ifEquals(Z){return this.equals(Z)?this:void 0}hasKind(Z){return this.kind===Z}assertHasKind(Z){if(this.kind!==Z)w9(`${this.kind} node was not of asserted kind ${Z}`);return this}hasKindIn(...Z){return Z.includes(this.kind)}assertHasKindIn(...Z){if(!X0(Z,this.kind))w9(`${this.kind} node was not one of asserted kinds ${Z}`);return this}isBasis(){return X0(tW,this.kind)}isConstraint(){return X0(z8,this.kind)}isStructural(){return X0(n9,this.kind)}isRefinement(){return X0(uY,this.kind)}isRoot(){return X0(a9,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Z){return this.hasKind("unit")&&this.allows(Z)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Z){let Y=j6.normalize(Z);return this._select(Y)}_select(Z){let Y=j6.applyBoundary[Z.boundary??"references"](this);if(Z.kind)Y=Y.filter((X)=>X.kind===Z.kind);if(Z.where)Y=Y.filter(Z.where);return j6.applyMethod[Z.method??"filter"](Y,this,Z)}transform(Z,Y){return this._transform(Z,this._createTransformContext(Y))}_createTransformContext(Z){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Z?.prereduced??!1},undeclaredKeyHandling:void 0,...Z}}_transform(Z,Y){let X=Y.bindScope??this.$;if(Y.seen[this.id])return this.$.lazilyResolve(Y.seen[this.id]);if(Y.shouldTransform?.(this,Y)===!1)return this;let Q;if(Y.seen[this.id]=()=>Q,this.hasKind("structure")&&this.undeclared!==Y.undeclaredKeyHandling)Y={...Y,undeclaredKeyHandling:this.undeclared};let $=b(this.inner,(q,U)=>{if(!this.impl.keys[q].child)return[q,U];let H=U;if(!n(H)){let K=H._transform(Z,Y);return K?[q,K]:[]}if(H.length===0)return[q,U];let G=H.flatMap((K)=>{return K._transform(Z,Y)??[]});return G.length?[q,G]:[]});delete Y.seen[this.id];let W=Object.assign($,{meta:this.meta}),J=Y.selected&&!Y.selected.includes(this)?W:Z(this.kind,W,Y);if(J===null)return null;if(r(J))return Q=J;let z=Object.keys(J);if((z.length===0||z.length===1&&z[0]==="meta")&&!N0(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in J))return Y.undeclaredKeyHandling?{...J,value:F.intrinsic.unknown}:null;if(this.kind==="morph")J.in??=F.intrinsic.unknown;return Q=X.node(this.kind,J,Y.parseOptions)}configureReferences(Z,Y="references"){let X=j6.normalize(Y),Q=typeof Z==="string"?(z,V)=>({...V,meta:{...V.meta,description:Z}}):typeof Z==="function"?(z,V)=>({...V,meta:Z(V.meta)}):(z,V)=>({...V,meta:{...V.meta,...Z}});if(X.boundary==="self")return this.$.node(this.kind,Q(this.kind,{...this.inner,meta:this.meta}));let $=this._select(X),W=$&&n0($),J=X.boundary==="child"?(z,V)=>V.root.children.includes(z):X.boundary==="shallow"?(z)=>z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(Q,{shouldTransform:J,selected:W}))}}var j6={applyBoundary:{self:(Z)=>[Z],child:(Z)=>[...Z.children],shallow:(Z)=>[...Z.shallowReferences],references:(Z)=>[...Z.references]},applyMethod:{filter:(Z)=>Z,assertFilter:(Z,Y,X)=>{if(Z.length===0)w9($J(Y,X));return Z},find:(Z)=>Z[0],assertFind:(Z,Y,X)=>{if(Z.length===0)w9($J(Y,X));return Z[0]}},normalize:(Z)=>typeof Z==="function"?{boundary:"references",method:"filter",where:Z}:typeof Z==="string"?N1(Z,j6.applyBoundary)?{method:"filter",boundary:Z}:{boundary:"references",method:"filter",kind:Z}:{boundary:"references",method:"filter",...Z}},$J=(Z,Y)=>`${Z} had no references matching ${x(Y)}.`,SL=(Z)=>f0(Z,{stringifyNonKey:(Y)=>Y.expression}),_L=/"(\$ark\.[^"]+)"/g,yL=(Z)=>JSON.stringify(Z).replace(_L,"$1"),K0=(Z,Y)=>({path:Z,node:Y,propString:SL(Z)}),WJ=(Z,Y)=>Z.propString===Y.propString&&Z.node.equals(Y.node),dY=(Z,Y)=>F0(Z,Y,{isEqual:WJ}),bL=(Z,Y)=>F0(Z,Y,{isEqual:(X,Q)=>X.equals(Q)});class w extends Array{static init(Z,Y,X,Q){return new w({kind:Z,l:Y,r:X,path:Q?.path??[],optional:Q?.optional??!1})}add(Z,Y,X,Q){return this.push({kind:Z,l:Y,r:X,path:Q?.path??[],optional:Q?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Z,l:Y,r:X}=this[0],Q=f0(Z);return lY(`Intersection${Q&&` at ${Q}`} of ${JJ(Y,X)}`)}return`The following intersections result in unsatisfiable types:
107
+ • ${this.map(({path:Z,l:Y,r:X})=>`${Z}: ${JJ(Y,X)}`).join(`
108
+ • `)}`}throw(){return L(this.describeReasons())}invert(){let Z=this.map((Y)=>({...Y,l:Y.r,r:Y.l}));if(!(Z instanceof w))return new w(...Z);return Z}withPrefixKey(Z,Y){return this.map((X)=>({...X,path:[Z,...X.path],optional:X.optional||Y==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var JJ=(Z,Y)=>`${cY(Z)} and ${cY(Y)}`,cY=(Z)=>r(Z)?Z.expression:n(Z)?Z.map(cY).join(" | ")||"never":String(Z),lY=(Z)=>`${Z} results in an unsatisfiable type`;var t9={},p1=(Z,Y,X)=>s(Z,Y,{$:X,invert:!1,pipe:!1}),S6=(Z,Y,X)=>s(Z,Y,{$:X,invert:!1,pipe:!0}),s=(Z,Y,X)=>{let Q=X.pipe?"|>":"&",$=`${Z.hash}${Q}${Y.hash}`;if(t9[$]!==void 0)return t9[$];if(!X.pipe){let z=`${Y.hash}${Q}${Z.hash}`;if(t9[z]!==void 0){let V=t9[z],q=V instanceof w?V.invert():V;return t9[$]=q,q}}let W=!X.pipe||!Z.includesTransform&&!Y.includesTransform;if(W&&Z.equals(Y))return Z;let J=W?iY(Z,Y,X):Z.hasKindIn(...a9)?xL(Z,Y,X):iY(Z,Y,X);if(r(J)){if(Z.equals(J))J=Z;else if(Y.equals(J))J=Y}return t9[$]=J,J},iY=(Z,Y,X)=>{let Q=Z.precedence<Y.precedence?Z.kind:Y.kind,$=Z.impl.intersections[Y.kind]??Y.impl.intersections[Z.kind];if($===void 0)return null;else if(Q===Z.kind)return $(Z,Y,X);else{let W=$(Y,Z,{...X,invert:!X.invert});if(W instanceof w)W=W.invert();return W}},xL=(Z,Y,X)=>Z.includesTransform||Y.includesTransform?X.invert?zJ(Y,Z,X):zJ(Z,Y,X):iY(Z,Y,X),zJ=(Z,Y,X)=>Z.distribute((Q)=>kL(Q,Y,X),(Q)=>{let $=Q.filter(r);if($.length===0)return w.init("union",Z.branches,Y.branches);if($.length<Z.branches.length||!Z.branches.every((z,V)=>z.rawIn.equals($[V].rawIn)))return X.$.parseSchema($);let W;if($.length===1){let z=$[0];if(!W)return z;return X.$.node("morph",{...z.inner,in:z.rawIn.configure(W,"self")})}let J={branches:$};if(W)J.meta=W;return X.$.parseSchema(J)}),kL=(Z,Y,X)=>{if(Z.hasKind("morph")){let $=[...Z.morphs];if(Z.lastMorphIfNode){let W=s(Z.lastMorphIfNode,Y,X);if(W instanceof w)return W;$[$.length-1]=W}else $.push(Y);return X.$.node("morph",{morphs:$,in:Z.inner.in})}if(Y.hasKind("morph")){let $=s(Z,Y.rawIn,X);if($ instanceof w)return $;return X.$.node("morph",{morphs:[Y],in:$})}return X.$.node("morph",{morphs:[Y],in:Z})};class $0 extends C6{constructor(Z,Y){super(Z,Y);Object.defineProperty(this,S1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Z){return p1(this,Z,this.$)}}class h0 extends $0{traverseApply=(Z,Y)=>{if(!this.traverseAllows(Z,Y))Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return t0(this.errorContext)}}var I1=(Z)=>(Y,X)=>{if(n(Y)){if(Y.length===0)return;let $=Y.map((W)=>X.$.node(Z,W));if(Z==="predicate")return $;return $.sort((W,J)=>W.hash<J.hash?-1:1)}let Q=X.$.node(Z,Y);return Q.hasOpenIntersection()?[Q]:Q},e9=(Z)=>{let Y=Z.r.shift();if(!Y){let Q=Z.l.length===0&&Z.kind==="structure"?F.intrinsic.unknown.internal:Z.ctx.$.node(Z.kind,Object.assign(Z.baseInner,vL(Z.l)),{prereduced:!0});for(let $ of Z.roots){if(Q instanceof w)return Q;Q=s($,Q,Z.ctx)}return Q}let X=!1;for(let Q=0;Q<Z.l.length;Q++){let $=s(Z.l[Q],Y,Z.ctx);if($===null)continue;if($ instanceof w)return $;if($.isRoot())return Z.roots.push($),Z.l.splice(Q),e9(Z);if(!X)Z.l[Q]=$,X=!0;else if(!Z.l.includes($))return u(`Unexpectedly encountered multiple distinct intersection results for refinement ${Y}`)}if(!X)Z.l.push(Y);if(Z.kind==="intersection"){if(Y.impliedSiblings)for(let Q of Y.impliedSiblings)F0(Z.r,Q)}return e9(Z)},Z2=(Z)=>{return Object.entries(Z).flatMap(([X,Q])=>(X in V8)?Q:[]).sort((X,Q)=>X.precedence<Q.precedence?-1:X.precedence>Q.precedence?1:X.kind==="predicate"&&Q.kind==="predicate"?0:X.hash<Q.hash?-1:1)},vL=(Z)=>{let Y={};for(let X of Z)if(X.hasOpenIntersection())Y[X.kind]=h(Y[X.kind],X);else{if(Y[X.kind])return u(`Unexpected intersection of closed refinements of kind ${X.kind}`);Y[X.kind]=X}return Y},VJ=(...Z)=>L(qJ(...Z)),qJ=(Z,Y,X)=>{let Q=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Y).defaultShortDescription;return`${kW(Z)} operand must be ${Y.description} (was ${Q})`};var UJ=(Z,Y,X)=>new Z9(Z,Y,X,X,null);class U8 extends g1{}class Z9 extends g1{[S1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Z,Y,X,Q,$){super((...W)=>{let J=b(this.names,(z,V)=>{let q=this.arg$.parse(W[z]);if(!q.extends(this.constraints[z]))L(fL(V,this.constraints[z].expression,q.expression));return[V,q]});if(this.defIsLazy()){let z=this.bodyDef(J);return this.$.parse(z)}return this.$.parse(Y,{args:J})});this.paramDefs=Z,this.bodyDef=Y,this.$=X,this.arg$=Q,this.hkt=$,this.description=$?new $().description??`a generic type for ${$.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof U8}cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get json(){return this.cacheGetter("json",{params:this.params.map((Z)=>Z[1].isUnknown()?Z[0]:[Z[0],Z[1].json]),body:oW(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Z)=>typeof Z==="string"?[Z,F.intrinsic.unknown]:[Z[0],this.$.parse(Z[1])]))}get names(){return this.cacheGetter("names",this.params.map((Z)=>Z[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Z)=>Z[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var fL=(Z,Y,X)=>`${Z} must be assignable to ${Y} (was ${X})`;var hL=v({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Z)=>typeof Z==="function"?{predicate:Z}:Z,defaults:{description:(Z)=>`valid according to ${Z.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class HJ extends $0{serializedPredicate=Q1(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=t0(this.errorContext);traverseApply=(Z,Y)=>{let X=Y.currentErrorCount;if(!this.predicate(Z,Y.external)&&Y.currentErrorCount===X)Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows"){Z.return(this.compiledCondition);return}Z.initializeErrorCount(),Z.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Z,Y){return Y.fallback.predicate({code:"predicate",base:Z,predicate:this.predicate})}}var oY={implementation:hL,Node:HJ};var gL=v({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Z)=>Number.isInteger(Z)?Z:L(uL(Z))}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>Z.rule===1?"an integer":Z.rule===2?"even":`a multiple of ${Z.rule}`},intersections:{divisor:(Z,Y,X)=>X.$.node("divisor",{rule:Math.abs(Z.rule*Y.rule/mL(Z.rule,Y.rule))})},obviatesBasisDescription:!0});class GJ extends h0{traverseAllows=(Z)=>Z%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Z){if(Z.type="integer",this.rule===1)return Z;return Z.multipleOf=this.rule,Z}}var nY={implementation:gL,Node:GJ};var uL=(Z)=>`divisor must be an integer (was ${Z})`,mL=(Z,Y)=>{let X,Q=Z,$=Y;while($!==0)X=$,$=Q%$,Q=X;return Q};class r1 extends h0{boundOperandKind=lL[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=iL(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${pL[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?oL(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Z){return(this.limitKind==="upper"?this.numericLimit<Z.numericLimit:this.numericLimit>Z.numericLimit)||this.numericLimit===Z.numericLimit&&this.exclusive===!0&&!Z.exclusive}overlapsRange(Z){if(this.isStricterThan(Z))return!1;if(this.numericLimit===Z.numericLimit&&(this.exclusive||Z.exclusive))return!1;return!0}overlapIsUnit(Z){return this.numericLimit===Z.numericLimit&&!this.exclusive&&!Z.exclusive}}var pL={"<":">=","<=":">",">":"<=",">=":"<"},dL={min:"max",minLength:"maxLength",after:"before"},H8={parse:(Z)=>Z||void 0},G8=(Z)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:X,...Q}=Y;return X?{...Q,rule:Z==="minLength"?Q.rule+1:Q.rule-1}:Q},K8=(Z)=>(Y)=>{if(typeof Y==="number"||typeof Y==="string"||Y instanceof Date)return{rule:Y};let{exclusive:X,...Q}=Y;if(!X)return Q;let $=typeof Q.rule==="number"?Q.rule:typeof Q.rule==="string"?new Date(Q.rule).valueOf():Q.rule.valueOf();return X?{...Q,rule:Z==="after"?$+1:$-1}:Q},B8=(Z)=>typeof Z==="string"||typeof Z==="number"?new Date(Z):Z,cL=(Z,Y)=>`${Z} bound must be a positive integer (was ${Y})`,Y2=(Z)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)L(cL(Z,Y));return Y},lL={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},iL=(Z,Y)=>`${N1(Z,dL)?">":"<"}${Y?"":"="}`,oL=(Z)=>typeof Z==="string"?Z:new Date(Z).toLocaleString(),KJ=(Z)=>`Bounded expression ${Z} must be exactly one of number, string, Array, or Date`;var nL=v({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:B8,serialize:(Z)=>Z.toISOString()}},normalize:K8("after"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or later`,actual:P9},intersections:{after:(Z,Y)=>Z.isStricterThan(Y)?Z:Y}});class BJ extends r1{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=P9(this.rule);traverseAllows=(Z)=>Z>=this.rule;reduceJsonSchema(Z,Y){return Y.fallback.date({code:"date",base:Z,after:this.rule})}}var aY={implementation:nL,Node:BJ};var aL=v({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:B8,serialize:(Z)=>Z.toISOString()}},normalize:K8("before"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or earlier`,actual:P9},intersections:{before:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,after:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("unit",{unit:Z.rule}):null:w.init("range",Z,Y)}});class LJ extends r1{collapsibleLimitString=P9(this.rule);traverseAllows=(Z)=>Z<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(Z,Y){return Y.fallback.date({code:"date",base:Z,before:this.rule})}}var rY={implementation:aL,Node:LJ};var rL=v({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Y2("exactLength")}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>`exactly length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{exactLength:(Z,Y,X)=>w.init("unit",X.$.node("unit",{unit:Z.rule}),X.$.node("unit",{unit:Y.rule}),{path:["length"]}),minLength:(Z,Y)=>Z.rule>=Y.rule?Z:w.init("range",Z,Y),maxLength:(Z,Y)=>Z.rule<=Y.rule?Z:w.init("range",Z,Y)}});class MJ extends h0{traverseAllows=(Z)=>Z.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z.maxLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z.maxItems=this.rule,Z;default:return t.throwInternalOperandError("exactLength",Z)}}}var sY={implementation:rL,Node:MJ};var sL=v({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:H8},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"negative":"non-positive";return`${Z.exclusive?"less than":"at most"} ${Z.rule}`}},intersections:{max:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,min:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("unit",{unit:Z.rule}):null:w.init("range",Z,Y)},obviatesBasisDescription:!0});class FJ extends r1{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z<this.rule:(Z)=>Z<=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMaximum=this.rule;else Z.maximum=this.rule;return Z}}var tY={implementation:sL,Node:FJ};var tL=v({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y2("maxLength")}},reduce:(Z,Y)=>Z.rule===0?Y.node("exactLength",Z):void 0,normalize:G8("maxLength"),defaults:{description:(Z)=>`at most length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{maxLength:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,minLength:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("exactLength",{rule:Z.rule}):null:w.init("range",Z,Y)}});class NJ extends r1{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length<=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.maxLength=this.rule,Z;case"array":return Z.maxItems=this.rule,Z;default:return t.throwInternalOperandError("maxLength",Z)}}}var eY={implementation:tL,Node:NJ};var eL=v({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:H8},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"positive":"non-negative";return`${Z.exclusive?"more than":"at least"} ${Z.rule}`}},intersections:{min:(Z,Y)=>Z.isStricterThan(Y)?Z:Y},obviatesBasisDescription:!0});class wJ extends r1{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z>this.rule:(Z)=>Z>=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMinimum=this.rule;else Z.minimum=this.rule;return Z}}var Z7={implementation:eL,Node:wJ};var ZM=v({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y2("minLength")}},reduce:(Z)=>Z.rule===0?F.intrinsic.unknown:void 0,normalize:G8("minLength"),defaults:{description:(Z)=>Z.rule===1?"non-empty":`at least length ${Z.rule}`,actual:(Z)=>Z.length===0?"":`${Z.length}`},intersections:{minLength:(Z,Y)=>Z.isStricterThan(Y)?Z:Y}});class DJ extends r1{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length>=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z;default:return t.throwInternalOperandError("minLength",Z)}}}var Y7={implementation:ZM,Node:DJ};var AJ={min:Z7.implementation,max:tY.implementation,minLength:Y7.implementation,maxLength:eY.implementation,exactLength:sY.implementation,after:aY.implementation,before:rY.implementation},EJ={min:Z7.Node,max:tY.Node,minLength:Y7.Node,maxLength:eY.Node,exactLength:sY.Node,after:aY.Node,before:rY.Node};var YM=v({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Z)=>typeof Z==="string"?{rule:Z}:Z instanceof RegExp?Z.flags?{rule:Z.source,flags:Z.flags}:{rule:Z.source}:Z,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Z)=>`matched by ${Z.rule}`},intersections:{pattern:()=>null}});class OJ extends h0{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=F.intrinsic.string.internal;reduceJsonSchema(Z,Y){if(Z.pattern)return Y.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:this.rule});return Z.pattern=this.rule,Z}}var X7={implementation:YM,Node:OJ};var _6=(Z,Y)=>{let X=XM(Z);if(Y&&!Y.includes(X))return L(`Root of kind ${X} should be one of ${Y}`);return X},XM=(Z)=>{if(P(Z,"root"))return Z.kind;if(typeof Z==="string")return Z[0]==="$"?"alias":(Z in f1)?"domain":"proto";if(typeof Z==="function")return"proto";if(typeof Z!=="object"||Z===null)return L(PJ(Z));if("morphs"in Z)return"morph";if("branches"in Z||n(Z))return"union";if("unit"in Z)return"unit";if("reference"in Z)return"alias";let Y=Object.keys(Z);if(Y.length===0||Y.some((X)=>(X in V8)))return"intersection";if("proto"in Z)return"proto";if("domain"in Z)return"domain";return L(PJ(Z))},PJ=(Z)=>`${x(Z)} is not a valid type schema`,TJ={},QM=(Z)=>n(Z)?Z.map((Y)=>Y.collapsibleJson):Z.collapsibleJson,_1={};F.nodesByRegisteredId=_1;var Q7=(Z)=>{return TJ[Z]??=0,`${Z}${++TJ[Z]}`},$7=(Z)=>{let Y=X2[Z.kind],X=Y.applyConfig?.(Z.def,Z.$.resolvedConfig)??Z.def,Q={},{meta:$,...W}=X,J=$===void 0?{}:typeof $==="string"?{description:$}:$,z=RY(W).sort(([q],[U])=>r9(q)?r9(U)?s9(q)-s9(U):1:r9(U)?-1:q<U?-1:1).filter(([q,U])=>{if(q.startsWith("meta.")){let H=q.slice(5);return J[H]=U,!1}return!0});for(let q of z){let U=q[0],H=Y.keys[U];if(!H)return L(`Key ${U} is not valid on ${Z.kind} schema`);let G=H.parse?H.parse(q[1],Z):q[1];if(G!==h1&&(G!==void 0||H.preserveUndefined))Q[U]=G}if(Y.reduce&&!Z.prereduced){let q=Y.reduce(Q,Z.$);if(q){if(q instanceof w)return q.throw();return $M(q,J)}}return W7({id:Z.id,kind:Z.kind,inner:Q,meta:J,$:Z.$})},W7=({id:Z,kind:Y,inner:X,meta:Q,$,ignoreCache:W})=>{let J=X2[Y],z=RY(X),V=[],q={};for(let[T,i]of z){let g=J.keys[T],Z1=g.serialize??(g.child?QM:Q0);if(q[T]=Z1(i),g.child===!0){let $1=i;if(n($1))V.push(...$1);else V.push($1)}else if(typeof g.child==="function")V.push(...g.child(i))}if(J.finalizeInnerJson)q=J.finalizeInnerJson(q);let U={...q},H={};if(!N0(Q))H=b(Q,(T,i)=>[T,T==="examples"?i:Q0(i)]),U.meta=L8(H,"description",!0);q=L8(q,J.collapsibleKey,!1);let G=JSON.stringify({kind:Y,...q});U=L8(U,J.collapsibleKey,!1);let K=L8(U,J.collapsibleKey,!0),M=JSON.stringify({kind:Y,...U});if($.nodesByHash[M]&&!W)return $.nodesByHash[M];let E={id:Z,kind:Y,impl:J,inner:X,innerEntries:z,innerJson:q,innerHash:G,meta:Q,metaJson:H,json:U,hash:M,collapsibleJson:K,children:V};if(Y!=="intersection"){for(let T in X)if(T!=="in"&&T!=="out")E[T]=X[T]}let O=new RJ[Y](E,$);return $.nodesByHash[M]=O},IJ=(Z,Y)=>{if(Z.id===Y)return Z;if(r(_1[Y]))u(`Unexpected attempt to overwrite node id ${Y}`);return W7({id:Y,kind:Z.kind,inner:Z.inner,meta:Z.meta,$:Z.$,ignoreCache:!0})},$M=(Z,Y,X)=>{if(X&&r(_1[X]))u(`Unexpected attempt to overwrite node id ${X}`);return W7({id:X??Q7(Y.alias??Z.kind),kind:Z.kind,inner:Z.inner,meta:Y,$:Z.$})},L8=(Z,Y,X)=>{let Q=Object.keys(Z);if(Q.length===1&&Q[0]===Y){let $=Z[Y];if(X)return $;if(v1($,"object")&&(Object.keys($).length===1||Array.isArray($)))return $}return Z};var y6=(Z,Y,X)=>{if(Z.key!==Y.key)return null;let Q=Z.key,$=s(Z.value,Y.value,X),W=Z.required||Y.required?"required":"optional";if($ instanceof w)if(W==="optional")$=F.intrinsic.never.internal;else return $.withPrefixKey(Z.key,Z.required&&Y.required?"required":"optional");if(W==="required")return X.$.node("required",{key:Q,value:$});let J=Z.hasDefault()?Y.hasDefault()?Z.default===Y.default?Z.default:L(J7(Z.default,Y.default)):Z.default:Y.hasDefault()?Y.default:h1;return X.$.node("optional",{key:Q,value:$,default:J})};class b6 extends $0{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=H0(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=h(this.value.flatRefs.map((Z)=>K0([this.key,...Z.path],Z.node)),K0([this.key],this.value));_transform(Z,Y){Y.path.push(this.key);let X=super._transform(Z,Y);return Y.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Z,Y)=>{if(this.key in Z)return m1(this.key,()=>this.value.traverseAllows(Z[this.key],Y),Y);return this.optional};traverseApply=(Z,Y)=>{if(this.key in Z)m1(this.key,()=>this.value.traverseApply(Z[this.key],Y),Y);else if(this.hasKind("required"))Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.if(`${this.serializedKey} in data`,()=>Z.traverseKey(this.serializedKey,`data${Z.prop(this.key)}`,this.value)),this.hasKind("required"))Z.else(()=>Z.traversalKind==="Apply"?Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Z.return(!1));if(Z.traversalKind==="Allows")Z.return(!0)}}var J7=(Z,Y)=>`Invalid intersection of default values ${x(Z)} & ${x(Y)}`;var WM=v({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)},default:{preserveUndefined:!0}},normalize:(Z)=>Z,reduce:(Z,Y)=>{if(Y.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Z.value.allows(void 0))return Y.node("optional",{...Z,value:Z.value.or(C.undefined)},{prereduced:!0})}},defaults:{description:(Z)=>`${Z.compiledKey}?: ${Z.value.description}`},intersections:{optional:y6}});class jJ extends b6{constructor(...Z){super(...Z);if("default"in this.inner)k6(this.value,this.inner.default,this.key)}get rawIn(){let Z=super.rawIn;if(!this.hasDefault())return Z;return this.$.node("optional",Y8(Z.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Z,...Y}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Y,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${x(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=zM(this);defaultValueMorphRef=this.defaultValueMorph&&Q1(this.defaultValueMorph)}var x6={implementation:WM,Node:jJ},JM={},zM=(Z)=>{if(!Z.hasDefault())return;let Y=`{${Z.compiledKey}: ${Z.value.id} = ${Q0(Z.default)}}`;return JM[Y]??=z7(Z.key,Z.value,Z.default)},z7=(Z,Y,X)=>{if(typeof X==="function")return Y.includesTransform?($,W)=>{return m1(Z,()=>Y($[Z]=X(),W),W),$}:($)=>{return $[Z]=X(),$};let Q=Y.includesTransform?Y.assert(X):X;return v1(Q,"object")?($,W)=>{return m1(Z,()=>Y($[Z]=X,W),W),$}:($)=>{return $[Z]=Q,$}},k6=(Z,Y,X)=>{let Q=a0(Y);if(v1(Y,"object")&&!Q)L(VM(X));let $=Z.in(Q?Y():Y);if($ instanceof u1){if(X===null)L(`Default ${$.summary}`);let W=$.transform((J)=>J.transform((z)=>({...z,prefixPath:[X]})));L(`Default for ${W.summary}`)}return Y},VM=(Z)=>{return`Non-primitive default ${Z===null?"":typeof Z==="number"?`for value at [${Z}] `:`for ${H0(Z)} `}must be specified as a function like () => ({my: 'object'})`};class W0 extends C6{constructor(Z,Y){super(Z,Y);Object.defineProperty(this,S1,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Z)=>{let Y=this(Z);if(Y instanceof u1)return Y;return{value:Y}},jsonSchema:{input:(Z)=>this.rawIn.toJsonSchema({target:CJ(Z.target),...Z.libraryOptions}),output:(Z)=>this.rawOut.toJsonSchema({target:CJ(Z.target),...Z.libraryOptions})}}}as(){return this}brand(Z){if(Z==="")return L(qM);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Z,Y){let X=this.branches.map(Z);return Y?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Z={}){let Y=mY(this.$.resolvedConfig.toJsonSchema,Z);Y.useRefs||=this.isCyclic;let X=typeof Y.dialect==="string"?{$schema:Y.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Y)),Y.useRefs){let Q=b(this.references,($,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(Y)]:[]);if(Y.target==="draft-07")Object.assign(X,{definitions:Q});else X.$defs=Q}return X}toJsonSchemaRecurse(Z){if(Z.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Z.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Z)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Z){let Y=this.innerToJsonSchema(Z);return Object.assign(Y,this.metaJson)}intersect(Z){let Y=this.$.parseDefinition(Z),X=this.rawIntersect(Y);if(X instanceof w)return X;return this.$.finalize(X)}rawIntersect(Z){return p1(this,Z,this.$)}toNeverIfDisjoint(){return this}and(Z){let Y=this.intersect(Z);return Y instanceof w?Y.throw():Y}rawAnd(Z){let Y=this.rawIntersect(Z);return Y instanceof w?Y.throw():Y}or(Z){let Y=this.$.parseDefinition(Z);return this.$.finalize(this.rawOr(Y))}rawOr(Z){let Y=[...this.branches,...Z.branches];return this.$.node("union",Y)}map(Z){return this.$.schema(this.applyStructuralOperation("map",[Z]))}pick(...Z){return this.$.schema(this.applyStructuralOperation("pick",Z))}omit(...Z){return this.$.schema(this.applyStructuralOperation("omit",Z))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.applyStructuralOperation("keyof",[]).reduce((Y,X)=>Y.intersect(X).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Z.branches.length===0)L(lY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Z)}get props(){if(this.branches.length!==1)return L(HM(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(Y.distribute((X)=>this.applyStructuralOperation("merge",[SJ(X)??L(_J("merge",X.expression))])))}applyStructuralOperation(Z,Y){return this.distribute((X)=>{if(X.equals(F.intrinsic.object)&&Z!=="merge")return X;let Q=SJ(X);if(!Q)L(_J(Z,X.expression));if(Z==="keyof")return Q.keyof();if(Z==="get")return Q.get(...Y);if(Z==="props")return Q.props;let $=Z==="required"?"require":Z==="partial"?"optionalize":Z;return this.$.node("intersection",{domain:"object",structure:Q[$](...Y)})})}get(...Z){if(Z[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Z))}extract(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((X)=>X.extends(Y)))}exclude(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((X)=>!X.extends(Y)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Z){return!(this.intersect(Z)instanceof w)}extends(Z){if(this.isNever())return!0;let Y=this.intersect(Z);return!(Y instanceof w)&&this.equals(Y)}ifExtends(Z){return this.extends(Z)?this:void 0}subsumes(Z){return this.$.parseDefinition(Z).extends(this)}configure(Z,Y="shallow"){return this.configureReferences(Z,Y)}describe(Z,Y="shallow"){return this.configure({description:Z},Y)}optional(){return[this,"?"]}default(Z){return k6(this,Z,null),[this,"=",Z]}from(Z){return this.assert(Z)}_pipe(...Z){let Y=Z.reduce((X,Q)=>X.rawPipeOnce(Q),this);return this.$.finalize(Y)}tryPipe(...Z){let Y=Z.reduce((X,Q)=>X.rawPipeOnce(P(Q,"root")?Q:($,W)=>{try{return Q($,W)}catch(J){return W.error({code:"predicate",predicate:Q,actual:`aborted due to error:
109
+ ${J}
110
+ `})}}),this);return this.$.finalize(Y)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Z){return this.$.finalize(this.toNode(this.$.parseDefinition(Z)))}toNode(Z){let Y=S6(this,Z,this.$);if(Y instanceof w)return Y.throw();return Y}rawPipeOnce(Z){if(P(Z,"root"))return this.toNode(Z);return this.distribute((Y)=>Y.hasKind("morph")?this.$.node("morph",{in:Y.inner.in,morphs:[...Y.morphs,Z]}):this.$.node("morph",{in:Y,morphs:[Z]}),this.$.parseSchema)}narrow(Z){return this.constrainOut("predicate",Z)}constrain(Z,Y){return this._constrain("root",Z,Y)}constrainIn(Z,Y){return this._constrain("in",Z,Y)}constrainOut(Z,Y){return this._constrain("out",Z,Y)}_constrain(Z,Y,X){let Q=this.$.node(Y,X);if(Q.isRoot())return Q.isUnknown()?this:u(`Unexpected constraint node ${Q}`);let $=Z==="root"?this:Z==="in"?this.rawIn:this.rawOut;if($.hasKind("morph")||Q.impliedBasis&&!$.extends(Q.impliedBasis))return VJ(Y,Q.impliedBasis,this);let W=this.$.node("intersection",{[Q.kind]:Q}),J=Z==="out"?S6(this,W,this.$):p1(this,W,this.$);if(J instanceof w)J.throw();return this.$.finalize(J)}onUndeclaredKey(Z){let Y=typeof Z==="string"?Z:Z.rule,X=typeof Z==="string"?!1:Z.deep;return this.$.finalize(this.transform((Q,$)=>Q==="structure"?Y==="ignore"?Y8($,{undeclared:1}):{...$,undeclared:Y}:$,X?void 0:{shouldTransform:(Q)=>!X0(n9,Q.kind)}))}hasEqualMorphs(Z){if(!this.includesTransform&&!Z.includesTransform)return!0;if(!k0(this.shallowMorphs,Z.shallowMorphs))return!1;if(!k0(this.flatMorphs,Z.flatMorphs,{isEqual:(Y,X)=>Y.propString===X.propString&&(Y.node.hasKind("morph")&&X.node.hasKind("morph")?Y.node.hasEqualMorphs(X.node):Y.node.hasKind("intersection")&&X.node.hasKind("intersection")?Y.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Z){return this.onUndeclaredKey({rule:Z,deep:!0})}filter(Z){return this.constrainIn("predicate",Z)}divisibleBy(Z){return this.constrain("divisor",Z)}matching(Z){return this.constrain("pattern",Z)}atLeast(Z){return this.constrain("min",Z)}atMost(Z){return this.constrain("max",Z)}moreThan(Z){return this.constrain("min",Q2(Z))}lessThan(Z){return this.constrain("max",Q2(Z))}atLeastLength(Z){return this.constrain("minLength",Z)}atMostLength(Z){return this.constrain("maxLength",Z)}moreThanLength(Z){return this.constrain("minLength",Q2(Z))}lessThanLength(Z){return this.constrain("maxLength",Q2(Z))}exactlyLength(Z){return this.constrain("exactLength",Z)}atOrAfter(Z){return this.constrain("after",Z)}atOrBefore(Z){return this.constrain("before",Z)}laterThan(Z){return this.constrain("after",Q2(Z))}earlierThan(Z){return this.constrain("before",Q2(Z))}}var qM="Expected a non-empty brand name after #",yJ=["draft-2020-12","draft-07"],UM=(Z)=>`JSONSchema target '${Z}' is not supported (must be ${yJ.map((Y)=>`"${Y}"`).join(" or ")})`,CJ=(Z)=>{if(!X0(yJ,Z))L(UM(Z));return Z},Q2=(Z)=>typeof Z==="object"&&!(Z instanceof Date)?{...Z,exclusive:!0}:{rule:Z,exclusive:!0},v6=(Z,Y)=>P(Y,"root")?P(Z,"root")?Z.extends(Y):Y.allows(Z):P(Z,"root")?Z.hasUnit(Y):Y===Z,SJ=(Z)=>{if(Z.hasKind("morph"))return null;if(Z.hasKind("intersection"))return Z.inner.structure??(Z.basis?.domain==="object"?Z.$.bindReference(F.intrinsic.emptyStructure):null);if(Z.isBasis()&&Z.domain==="object")return Z.$.bindReference(F.intrinsic.emptyStructure);return null},HM=(Z)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
111
+ ${Z}`,_J=(Z,Y)=>`${Z} operand must be an object (was ${Y})`;var w0=(Z,Y)=>b(q8(Z),(X,Q)=>[Q,Y]);var GM=(Z)=>typeof Z==="string"?{reference:Z}:Z,bJ=(Z)=>Z instanceof w?F.intrinsic.never.internal:Z,KM=v({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Z)=>Z.startsWith("$")?Z:`$ark.${Z}`},resolve:{}},normalize:GM,defaults:{description:(Z)=>Z.reference},intersections:{alias:(Z,Y,X)=>X.$.lazilyResolve(()=>bJ(s(Z.resolution,Y.resolution,X)),`${Z.reference}${X.pipe?"=>":"&"}${Y.reference}`),...w0("alias",(Z,Y,X)=>{if(Y.isUnknown())return Z;if(Y.isNever())return Y;if(Y.isBasis()&&!Y.overlaps(F.intrinsic.object))return w.init("assignability",F.intrinsic.object,Y);return X.$.lazilyResolve(()=>bJ(s(Z.resolution,Y,X)),`${Z.reference}${X.pipe?"=>":"&"}${Y.id}`)})}});class xJ extends W0{expression=this.reference;structure=void 0;get resolution(){let Z=this._resolve();return _1[this.id]=Z}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Z=this.reference,Y=_1[Z],X=[];while(P(Y,"context")){if(X.includes(Y.id))return L(BM(Y.id,X));X.push(Y.id),Y=_1[Y.id]}if(!P(Y,"root"))return u(`Unexpected resolution for reference ${this.reference}
112
+ Seen: [${X.join("->")}]
113
+ Resolution: ${x(Y)}`);return Y}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Z=this.reference.slice(1),Y=this.$.resolutions[Z];if(typeof Y==="string")return Y;if(P(Y,"root"))return Y.id;return u(`Unexpected resolution for reference ${this.reference}: ${x(Y)}`)}get defaultShortDescription(){return f1.object}innerToJsonSchema(Z){return this.resolution.toJsonSchemaRecurse(Z)}traverseAllows=(Z,Y)=>{let X=Y.seen[this.reference];if(X?.includes(Z))return!0;return Y.seen[this.reference]=h(X,Z),this.resolution.traverseAllows(Z,Y)};traverseApply=(Z,Y)=>{let X=Y.seen[this.reference];if(X?.includes(Z))return;Y.seen[this.reference]=h(X,Z),this.resolution.traverseApply(Z,Y)};compile(Z){let Y=this.resolutionId;Z.if(`ctx.seen.${Y} && ctx.seen.${Y}.includes(data)`,()=>Z.return(!0)),Z.if(`!ctx.seen.${Y}`,()=>Z.line(`ctx.seen.${Y} = []`)),Z.line(`ctx.seen.${Y}.push(data)`),Z.return(Z.invoke(Y))}}var BM=(Z,Y)=>`Alias '${Z}' has a shallow resolution cycle: ${[...Y,Z].join("->")}`,f6={implementation:KM,Node:xJ};class T9 extends W0{traverseApply=(Z,Y)=>{if(!this.traverseAllows(Z,Y))Y.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return t0(this.errorContext)}compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var LM=v({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Z)=>typeof Z==="string"?{domain:Z}:i9(Z,"numberAllowsNaN")&&Z.domain!=="number"?L(M8.writeBadAllowNanMessage(Z.domain)):Z,applyConfig:(Z,Y)=>Z.numberAllowsNaN===void 0&&Z.domain==="number"&&Y.numberAllowsNaN?{...Z,numberAllowsNaN:!0}:Z,defaults:{description:(Z)=>f1[Z.domain],actual:(Z)=>Number.isNaN(Z)?"NaN":f1[F1(Z)]},intersections:{domain:(Z,Y)=>Z.domain==="number"&&Y.domain==="number"?Z.numberAllowsNaN?Y:Z:w.init("domain",Z,Y)}});class kJ extends T9{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Z)=>typeof Z==="number"&&!Number.isNaN(Z):(Z)=>F1(Z)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return f1[this.domain]}innerToJsonSchema(Z){if(this.domain==="bigint"||this.domain==="symbol")return Z.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var M8={implementation:LM,Node:kJ,writeBadAllowNanMessage:(Z)=>`numberAllowsNaN may only be specified with domain "number" (was ${Z})`};var MM=v({kind:"intersection",hasAssociatedError:!0,normalize:(Z)=>{if(r(Z))return Z;let{structure:Y,...X}=Z,Q=!!Y,$=Y??{},W=b(X,(J,z)=>{if(N1(J,eW)){if(Q)L(`Flattened structure key ${J} cannot be specified alongside a root 'structure' key.`);return $[J]=z,[]}return[J,z]});if(P($,"constraint")||!N0($))W.structure=$;return W},finalizeInnerJson:({structure:Z,...Y})=>v1(Z,"object")?{...Z,...Y}:Y,keys:{domain:{child:!0,parse:(Z,Y)=>Y.$.node("domain",Z)},proto:{child:!0,parse:(Z,Y)=>Y.$.node("proto",Z)},structure:{child:!0,parse:(Z,Y)=>Y.$.node("structure",Z),serialize:(Z)=>{if(!Z.sequence?.minLength)return Z.collapsibleJson;let{sequence:Y,...X}=Z.collapsibleJson,{minVariadicLength:Q,...$}=Y,W=$.variadic&&Object.keys($).length===1?$.variadic:$;return{...X,sequence:W}}},divisor:{child:!0,parse:I1("divisor")},max:{child:!0,parse:I1("max")},min:{child:!0,parse:I1("min")},maxLength:{child:!0,parse:I1("maxLength")},minLength:{child:!0,parse:I1("minLength")},exactLength:{child:!0,parse:I1("exactLength")},before:{child:!0,parse:I1("before")},after:{child:!0,parse:I1("after")},pattern:{child:!0,parse:I1("pattern")},predicate:{child:!0,parse:I1("predicate")}},reduce:(Z,Y)=>vJ({},Z,{$:Y,invert:!1,pipe:!1}),defaults:{description:(Z)=>{if(Z.children.length===0)return"unknown";if(Z.structure)return Z.structure.description;let Y=[];if(Z.basis&&!Z.prestructurals.some((X)=>X.impl.obviatesBasisDescription))Y.push(Z.basis.description);if(Z.prestructurals.length){let X=Z.prestructurals.slice().sort((Q,$)=>Q.kind==="min"&&$.kind==="max"?-1:0).map((Q)=>Q.description);Y.push(...X)}if(Z.inner.predicate)Y.push(...Z.inner.predicate.map((X)=>X.description));return Y.join(" and ")},expected:(Z)=>` ◦ ${Z.errors.map((Y)=>Y.expected).join(`
114
+ ◦ `)}`,problem:(Z)=>`(${Z.actual}) must be...
115
+ ${Z.expected}`},intersections:{intersection:(Z,Y,X)=>vJ(Z.inner,Y.inner,X),...w0("intersection",(Z,Y,X)=>{if(Z.children.length===0)return Y;let{domain:Q,proto:$,...W}=Z.inner,J=$??Q,z=J?s(J,Y,X):Y;return z instanceof w?z:Z?.basis?.equals(z)?Z:Z.$.node("intersection",{...W,[z.kind]:z},{prereduced:!0})})}});class fJ extends W0{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((Z)=>{if(!Z.isRefinement())return!1;if(X0(gY,Z.kind))this.prestructurals.push(Z);return!0});structure=this.inner.structure;expression=FM(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Z){return this.children.reduce((Y,X)=>X.isBasis()?X.toJsonSchemaRecurse(Z):X.reduceJsonSchema(Y,Z),{})}traverseAllows=(Z,Y)=>this.children.every((X)=>X.traverseAllows(Z,Y));traverseApply=(Z,Y)=>{let X=Y.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Z,Y),Y.currentErrorCount>X)return}if(this.prestructurals.length){for(let Q=0;Q<this.prestructurals.length-1;Q++)if(this.prestructurals[Q].traverseApply(Z,Y),Y.failFast&&Y.currentErrorCount>X)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(Z,Y),Y.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Z,Y),Y.currentErrorCount>X)return}if(this.inner.predicate){for(let Q=0;Q<this.inner.predicate.length-1;Q++)if(this.inner.predicate[Q].traverseApply(Z,Y),Y.failFast&&Y.currentErrorCount>X)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(Z,Y)}};compile(Z){if(Z.traversalKind==="Allows"){for(let Y of this.children)Z.check(Y);Z.return(!0);return}if(Z.initializeErrorCount(),this.basis){if(Z.check(this.basis),this.children.length>1)Z.returnIfFail()}if(this.prestructurals.length){for(let Y=0;Y<this.prestructurals.length-1;Y++)Z.check(this.prestructurals[Y]),Z.returnIfFailFast();if(Z.check(this.prestructurals[this.prestructurals.length-1]),this.structure||this.inner.predicate)Z.returnIfFail()}if(this.structure){if(Z.check(this.structure),this.inner.predicate)Z.returnIfFail()}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)Z.check(this.inner.predicate[Y]),Z.returnIfFail();Z.check(this.inner.predicate[this.inner.predicate.length-1])}}}var V7={implementation:MM,Node:fJ},FM=(Z)=>{if(Z.structure?.expression)return Z.structure.expression;let Y=Z.basis&&!Z.prestructurals.some(($)=>$.impl.obviatesBasisExpression)?Z.basis.nestableExpression:"",X=Z.prestructurals.map(($)=>$.expression).join(" & "),Q=`${Y}${Y?" ":""}${X}`;if(Q==="Array == 0")return"[]";return Q||"unknown"},vJ=(Z,Y,X)=>{let Q={},$=Z.proto??Z.domain,W=Y.proto??Y.domain,J=$?W?s($,W,X):$:W;if(J instanceof w)return J;if(J)Q[J.kind]=J;return e9({kind:"intersection",baseInner:Q,l:Z2(Z),r:Z2(Y),roots:[],ctx:X})};var NM=v({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)},morphs:{parse:n0,serialize:(Z)=>Z.map((Y)=>P(Y,"root")?Y.json:Q1(Y))},declaredIn:{child:!1,serialize:(Z)=>Z.json},declaredOut:{child:!1,serialize:(Z)=>Z.json}},normalize:(Z)=>Z,defaults:{description:(Z)=>`a morph from ${Z.rawIn.description} to ${Z.rawOut?.description??"unknown"}`},intersections:{morph:(Z,Y,X)=>{if(!Z.hasEqualMorphs(Y))return L(wM(Z.expression,Y.expression));let Q=s(Z.rawIn,Y.rawIn,X);if(Q instanceof w)return Q;let $={morphs:Z.morphs};if(Z.declaredIn||Y.declaredIn){let W=s(Z.rawIn,Y.rawIn,X);if(W instanceof w)return W.throw();else $.declaredIn=W}if(Z.declaredOut||Y.declaredOut){let W=s(Z.rawOut,Y.rawOut,X);if(W instanceof w)return W.throw();else $.declaredOut=W}return Q.distribute((W)=>X.$.node("morph",{...$,in:W}),X.$.parseSchema)},...w0("morph",(Z,Y,X)=>{let Q=Z.inner.in?s(Z.inner.in,Y,X):Y;return Q instanceof w?Q:Q.equals(Z.inner.in)?Z:X.$.node("morph",{...Z.inner,in:Q})})}});class hJ extends W0{serializedMorphs=this.morphs.map(Q1);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=P(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??F.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??F.intrinsic.unknown.internal}declareIn(Z){return this.$.node("morph",{...this.inner,declaredIn:Z})}declareOut(Z){return this.$.node("morph",{...this.inner,declaredOut:Z})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(Z){return Z.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(Z),out:this.introspectableOut?.toJsonSchemaRecurse(Z)??null})}compile(Z){if(Z.traversalKind==="Allows"){if(!this.introspectableIn)return;Z.return(Z.invoke(this.introspectableIn));return}if(this.introspectableIn)Z.line(Z.invoke(this.introspectableIn));Z.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Z,Y)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Z,Y);traverseApply=(Z,Y)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Z,Y);Y.queueMorphs(this.morphs)};hasEqualMorphs(Z){return k0(this.morphs,Z.morphs,{isEqual:(Y,X)=>Y===X||P(Y,"root")&&P(X,"root")&&Y.equals(X)})}}var q7={implementation:NM,Node:hJ},wM=(Z,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
116
+ Left: ${Z}
117
+ Right: ${Y}`;var DM=v({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Z)=>w6(Z)??Q0(Z)},dateAllowsInvalid:{}},normalize:(Z)=>{let Y=typeof Z==="string"?{proto:A9[Z]}:typeof Z==="function"?r(Z)?Z:{proto:Z}:typeof Z.proto==="string"?{...Z,proto:A9[Z.proto]}:Z;if(typeof Y.proto!=="function")L(h6.writeInvalidSchemaMessage(Y.proto));if(i9(Y,"dateAllowsInvalid")&&Y.proto!==Date)L(h6.writeBadInvalidDateMessage(Y.proto));return Y},applyConfig:(Z,Y)=>{if(Z.dateAllowsInvalid===void 0&&Z.proto===Date&&Y.dateAllowsInvalid)return{...Z,dateAllowsInvalid:!0};return Z},defaults:{description:(Z)=>Z.builtinName?jW[Z.builtinName]:`an instance of ${Z.proto.name}`,actual:(Z)=>Z instanceof Date&&Z.toString()==="Invalid Date"?"an invalid Date":N6(Z)},intersections:{proto:(Z,Y)=>Z.proto===Date&&Y.proto===Date?Z.dateAllowsInvalid?Y:Z:yY(Z.proto,Y.proto)?Z:yY(Y.proto,Z.proto)?Y:w.init("proto",Z,Y),domain:(Z,Y)=>Y.domain==="object"?Z:w.init("domain",F.intrinsic.object.internal,Y)}});class gJ extends T9{builtinName=w6(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Z)=>Z instanceof Date&&Z.toString()!=="Invalid Date":(Z)=>Z instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Z){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Z.fallback.date?.({code:"date",base:{}})??Z.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Z.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var h6={implementation:DM,Node:gJ,writeBadInvalidDateMessage:(Z)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Z.name})`,writeInvalidSchemaMessage:(Z)=>`instanceOf operand must be a function (was ${F1(Z)})`};var AM=v({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Z,Y)=>{let X=[];for(let Q of Z){let $=P(Q,"root")?Q.branches:Y.$.parseSchema(Q).branches;for(let W of $)if(W.hasKind("morph")){let J=X.findIndex((z)=>z.hasKind("morph")&&z.hasEqualMorphs(W));if(J===-1)X.push(W);else{let z=X[J];X[J]=Y.$.node("morph",{...z.inner,in:z.rawIn.rawOr(W.rawIn)})}}else X.push(W)}if(!Y.def.ordered)X.sort((Q,$)=>Q.hash<$.hash?-1:1);return X}}},normalize:(Z)=>n(Z)?{branches:Z}:Z,reduce:(Z,Y)=>{let X=_M(Z);if(X.length===1)return X[0];if(X.length===Z.branches.length)return;return Y.node("union",{...Z,branches:X},{prereduced:!0})},defaults:{description:(Z)=>Z.distribute((Y)=>Y.description,$2),expected:(Z)=>{let Y=DW(Z.errors,"propString"),X=Object.entries(Y).map(([Q,$])=>{let W=[];for(let V of $)F0(W,V.expected);let J=$2(W),z=$.every((V)=>V.actual===$[0].actual)?$[0].actual:x($[0].data);return`${Q&&`${Q} `}must be ${J}${z&&` (was ${z})`}`});return $2(X)},problem:(Z)=>Z.expected,message:(Z)=>{if(Z.problem[0]==="[")return`value at ${Z.problem}`;return Z.problem}},intersections:{union:(Z,Y,X)=>{if(Z.isNever!==Y.isNever)return w.init("presence",Z,Y);let Q;if(Z.ordered){if(Y.ordered)L(bM(Z.expression,Y.expression));if(Q=U7(Y.branches,Z.branches,X),Q instanceof w)Q.invert()}else Q=U7(Z.branches,Y.branches,X);if(Q instanceof w)return Q;return X.$.parseSchema(Z.ordered||Y.ordered?{branches:Q,ordered:!0}:{branches:Q})},...w0("union",(Z,Y,X)=>{let Q=U7(Z.branches,[Y],X);if(Q instanceof w)return Q;if(Q.length===1)return Q[0];return X.$.parseSchema(Z.ordered?{branches:Q,ordered:!0}:{branches:Q})})}});class pJ extends W0{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Z=[],Y=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Y===-1)Y=Z.length,Z.push(X);else Z[Y]=F.intrinsic.boolean;continue}Z.push(X)}return Z}unitBranches=this.branches.filter((Z)=>Z.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?jM(this.discriminant):null;expression=this.distribute((Z)=>Z.nestableExpression,SM);createBranchedOptimisticRootApply(){return(Z,Y)=>{let X=this.traverseOptimistic(Z);if(X!==h1)return X;let Q=new G0(Z,this.$.resolvedConfig);return this.traverseApply(Z,Q),Q.finalize(Y)}}get shallowMorphs(){return this.branches.reduce((Z,Y)=>F0(Z,Y.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Z)=>Z.defaultShortDescription,$2)}innerToJsonSchema(Z){if(this.branchGroups.length===1&&this.branchGroups[0].equals(F.intrinsic.boolean))return{type:"boolean"};let Y=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Z));if(Y.every((X)=>Object.keys(X).length===1&&i9(X,"const")))return{enum:Y.map((X)=>X.const)};return{anyOf:Y}}traverseAllows=(Z,Y)=>this.branches.some((X)=>X.traverseAllows(Z,Y));traverseApply=(Z,Y)=>{let X=[];for(let Q=0;Q<this.branches.length;Q++){if(Y.pushBranch(),this.branches[Q].traverseApply(Z,Y),!Y.hasError()){if(this.branches[Q].includesTransform)return Y.queuedMorphs.push(...Y.popBranch().queuedMorphs);return Y.popBranch()}X.push(Y.popBranch().error)}Y.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Z)=>{for(let Y=0;Y<this.branches.length;Y++){let X=this.branches[Y];if(X.traverseAllows(Z)){if(X.contextFreeMorph)return X.contextFreeMorph(Z);return Z}}return h1};compile(Z){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Z);let Y=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Y=`typeof ${Y} === "object" ? ${Y} === null ? "null" : "object" : typeof ${Y} === "function" ? "object" : typeof ${Y}`;let X=this.discriminant.cases,Q=Object.keys(X),{optimistic:$}=Z;if(Z.optimistic=!1,Z.block(`switch(${Y})`,()=>{for(let q in X){let U=X[q],H=q==="default"?q:`case ${q}`,G;if(U===!0)G=$?"data":"true";else if($)if(U.rootApplyStrategy==="branchedOptimistic")G=Z.invoke(U,{kind:"Optimistic"});else if(U.contextFreeMorph)G=`${Z.invoke(U)} ? ${Q1(U.contextFreeMorph)}(data) : "${h1}"`;else G=`${Z.invoke(U)} ? data : "${h1}"`;else G=Z.invoke(U);Z.line(`${H}: return ${G}`)}return Z}),Z.traversalKind==="Allows"){Z.return($?`"${h1}"`:!1);return}let W=$2(this.discriminant.kind==="domain"?Q.map((q)=>{let U=q.slice(1,-1);return U==="function"?f1.object:f1[U]}):Q),J=this.discriminant.path.map((q)=>typeof q==="symbol"?Q1(q):JSON.stringify(q)),z=JSON.stringify(W),V=this.discriminant.kind==="domain"?`${IM}[${Y}]`:`${RM}(${Y})`;Z.line(`ctx.errorFromNodeContext({
118
+ code: "predicate",
119
+ expected: ${z},
120
+ actual: ${V},
121
+ relativePath: [${J}],
122
+ meta: ${this.compiledMeta}
123
+ })`)}compileIndiscriminable(Z){if(Z.traversalKind==="Apply"){Z.const("errors","[]");for(let Y of this.branches)Z.line("ctx.pushBranch()").line(Z.invoke(Y)).if("!ctx.hasError()",()=>Z.return(Y.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Z.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Y}=Z;Z.optimistic=!1;for(let X of this.branches)Z.if(`${Z.invoke(X)}`,()=>Z.return(Y?X.contextFreeMorph?`${Q1(X.contextFreeMorph)}(data)`:"data":!0));Z.return(Y?`"${h1}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let $=b(this.unitBranches,(W,J)=>[`${J.rawIn.serializedValue}`,J.hasKind("morph")?J:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:$}}let Z=[];for(let $=0;$<this.branches.length-1;$++){let W=this.branches[$];for(let J=$+1;J<this.branches.length;J++){let z=this.branches[J],V=p1(W.rawIn,z.rawIn,W.$);if(!(V instanceof w))continue;for(let q of V){if(!q.kind||q.optional)continue;let U,H;if(q.kind==="domain"){let{l:K,r:M}=q;U=`"${typeof K==="string"?K:K.domain}"`,H=`"${typeof M==="string"?M:M.domain}"`}else if(q.kind==="unit")U=q.l.serializedValue,H=q.r.serializedValue;else continue;let G=Z.find((K)=>k0(K.path,q.path)&&K.kind===q.kind);if(!G)Z.push({kind:q.kind,cases:{[U]:{branchIndices:[$],condition:q.l},[H]:{branchIndices:[J],condition:q.r}},path:q.path});else{if(G.cases[U])G.cases[U].branchIndices=F0(G.cases[U].branchIndices,$);else G.cases[U]??={branchIndices:[$],condition:q.l};if(G.cases[H])G.cases[H].branchIndices=F0(G.cases[H].branchIndices,J);else G.cases[H]??={branchIndices:[J],condition:q.r}}}}}let Y=this.ordered?PM(Z,this.branches):Z;if(!Y.length)return null;let X=EM(Y,this),Q={};for(let $ in X.best.cases){let W=OM(X,$);if(W===null){Q[$]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((V,q)=>V.originalIndex-q.originalIndex);let J=W.map((V)=>V.branch),z=J.length===1?J[0]:this.$.node("union",this.ordered?{branches:J,ordered:!0}:J);Object.assign(this.referencesById,z.referencesById),Q[$]=z}if(X.defaultEntries.length){let $=X.defaultEntries.map((W)=>W.branch);Q.default=this.$.node("union",this.ordered?{branches:$,ordered:!0}:$,{prereduced:!0}),Object.assign(this.referencesById,Q.default.referencesById)}return Object.assign(X.location,{cases:Q})}}var EM=(Z,Y)=>{let Q=Z.sort((J,z)=>J.path.length===z.path.length?Object.keys(z.cases).length-Object.keys(J.cases).length:J.path.length-z.path.length)[0],$={kind:Q.kind,path:Q.path,optionallyChainedPropString:dJ(Q.path)},W=Y.branches.map((J,z)=>({originalIndex:z,branch:J}));return{best:Q,location:$,defaultEntries:W,node:Y}},OM=(Z,Y)=>{let X=Z.best.cases[Y],Q=TM(X.condition,Z.location.path,Z.node.$),$=[],W=[];for(let J=0;J<Z.defaultEntries.length;J++){let z=Z.defaultEntries[J];if(X.branchIndices.includes(z.originalIndex)){let V=uJ(Z.node.branches[z.originalIndex],Z.location);if(V===null)$=null;else $?.push({originalIndex:z.originalIndex,branch:V})}else if(z.branch.hasKind("alias")&&Q.hasKind("domain")&&Q.domain==="object")$?.push(z);else{if(z.branch.rawIn.overlaps(Q)){let V=uJ(z.branch,Z.location);$?.push({originalIndex:z.originalIndex,branch:V})}W.push(z)}}return Z.defaultEntries=W,$},PM=(Z,Y)=>{return Z.filter((Q)=>{let $=Object.values(Q.cases).map((W)=>W.branchIndices);for(let W=0;W<$.length-1;W++){let J=$[W];for(let z=W+1;z<$.length;z++){let V=$[z];for(let q of J)for(let U of V)if(q>U){if(Y[q].overlaps(Y[U]))return!1}}}return!0})},TM=(Z,Y,X)=>{let Q=Z==="undefined"?X.node("unit",{unit:void 0}):Z==="null"?X.node("unit",{unit:null}):Z==="boolean"?X.units([!0,!1]):Z;for(let $=Y.length-1;$>=0;$--){let W=Y[$];Q=X.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...NW(W).map((J)=>({})),Q]}:{domain:"object",required:[{key:W,value:Q}]})}return Q},dJ=(Z)=>Z.reduce((Y,X)=>Y+hY(X,!0),"data"),IM=Q1(AW),RM=Q1(x),H7={implementation:AM,Node:pJ},jM=(Z)=>({kind:Z.kind,path:Z.path.map((Y)=>typeof Y==="string"?Y:H0(Y)),cases:b(Z.cases,(Y,X)=>[Y,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),CM={delimiter:" | ",finalDelimiter:" | "},SM=(Z)=>$2(Z,CM),$2=(Z,Y)=>{let X=Y?.delimiter??", ",Q=Y?.finalDelimiter??" or ";if(Z.length===0)return"never";if(Z.length===1)return Z[0];if(Z.length===2&&Z[0]==="false"&&Z[1]==="true"||Z[0]==="true"&&Z[1]==="false")return"boolean";let $={},W=Z.filter((z)=>$[z]?!1:$[z]=!0),J=W.pop();return`${W.join(X)}${W.length?Q:""}${J}`},U7=(Z,Y,X)=>{let Q=Y.map(()=>[]);for(let W=0;W<Z.length;W++){let J={};for(let z=0;z<Y.length;z++){if(Q[z]===null)continue;if(Z[W].equals(Y[z])){Q[z]=null,J={};break}let V=s(Z[W],Y[z],X);if(V instanceof w)continue;if(V.equals(Z[W])){Q[z].push(Z[W]),J={};break}if(V.equals(Y[z]))Q[z]=null;else J[z]=V}for(let z in J)Q[z][W]=J[z]}let $=Q.flatMap((W,J)=>W?.flatMap((z)=>z.branches)??Y[J]);return $.length===0?w.init("union",Z,Y):$},_M=({branches:Z,ordered:Y})=>{if(Z.length<2)return Z;let X=Z.map(()=>!0);for(let Q=0;Q<Z.length;Q++)for(let $=Q+1;$<Z.length&&X[Q]&&X[$];$++){if(Z[Q].equals(Z[$])){X[$]=!1;continue}let W=p1(Z[Q].rawIn,Z[$].rawIn,Z[0].$);if(W instanceof w)continue;if(!Y)yM(Z[Q],Z[$]);if(W.equals(Z[Q].rawIn))X[Q]=!!Y;else if(W.equals(Z[$].rawIn))X[$]=!1}return Z.filter((Q,$)=>X[$])},yM=(Z,Y)=>{if(!Z.includesTransform&&!Y.includesTransform)return;if(!k0(Z.shallowMorphs,Y.shallowMorphs))L(mJ(Z.expression,Y.expression));if(!k0(Z.flatMorphs,Y.flatMorphs,{isEqual:(X,Q)=>X.propString===Q.propString&&(X.node.hasKind("morph")&&Q.node.hasKind("morph")?X.node.hasEqualMorphs(Q.node):X.node.hasKind("intersection")&&Q.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===Q.node.structure?.structuralMorphRef:!1)}))L(mJ(Z.expression,Y.expression))},uJ=(Z,Y)=>Z.transform((X,Q)=>{if(X==="domain"||X==="unit")return null;return Q},{shouldTransform:(X,Q)=>{let $=dJ(Q.path);if(!Y.optionallyChainedPropString.startsWith($))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Y.kind==="unit")&&$===Y.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),mJ=(Z,Y)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
124
+ Left: ${Z}
125
+ Right: ${Y}`,bM=(Z,Y)=>`The intersection of two ordered unions is indeterminate:
126
+ Left: ${Z}
127
+ Right: ${Y}`;var xM=v({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Z)=>Z instanceof Date?Z.toISOString():Q0(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>x(Z.unit),problem:({expected:Z,actual:Y})=>`${Z===Y?`must be reference equal to ${Z} (serialized to the same value)`:`must be ${Z} (was ${Y})`}`},intersections:{unit:(Z,Y)=>w.init("unit",Z,Y),...w0("unit",(Z,Y)=>{if(Y.allows(Z.unit))return Z;let X=Y.hasKind("intersection")?Y.basis:Y;if(X){let Q=X.hasKind("domain")?X:F.intrinsic.object;if(Z.domain!==Q.domain){let $=Z.domain==="undefined"||Z.domain==="null"||Z.domain==="boolean"?Z.domain:F.intrinsic[Z.domain];return w.init("domain",$,Q)}}return w.init("assignability",Z,Y.hasKind("intersection")?Y.children.find((Q)=>!Q.allows(Z.unit)):Y)})}});class lJ extends T9{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=cJ(this.unit,this.serializedValue);compiledNegation=cJ(this.unit,this.serializedValue,"negated");expression=x(this.unit);domain=F1(this.unit);get defaultShortDescription(){return this.domain==="object"?f1.object:this.description}innerToJsonSchema(Z){return this.unit===null?{type:"null"}:F.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Z.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Z)=>Z instanceof Date&&Z.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Z)=>Number.isNaN(Z):(Z)=>Z===this.unit}var G7={implementation:xM,Node:lJ},cJ=(Z,Y,X)=>{if(Z instanceof Date){let Q=`data instanceof Date && data.toISOString() === ${Y}`;return X?`!(${Q})`:Q}if(Number.isNaN(Z))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Y}`};var kM=v({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Z,Y)=>{let X=Y.$.parseSchema(Z);if(!X.extends(F.intrinsic.key))return L(fM(X.expression));let Q=X.branches.filter(($)=>$.hasKind("unit"));if(Q.length)return L(vM(Q.map(($)=>x($.unit))));return X}},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`[${Z.signature.expression}]: ${Z.value.description}`},intersections:{index:(Z,Y,X)=>{if(Z.signature.equals(Y.signature)){let Q=s(Z.value,Y.value,X),$=Q instanceof w?F.intrinsic.never.internal:Q;return X.$.node("index",{signature:Z.signature,value:$})}if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;return null}}});class iJ extends $0{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=h(this.value.flatRefs.map((Z)=>K0([this.signature,...Z.path],Z.node)),K0([this.signature],this.value));traverseAllows=(Z,Y)=>D9(Z).every((X)=>{if(this.signature.traverseAllows(X[0],Y))return m1(X[0],()=>this.value.traverseAllows(X[1],Y),Y);return!0});traverseApply=(Z,Y)=>{for(let X of D9(Z))if(this.signature.traverseAllows(X[0],Y))m1(X[0],()=>this.value.traverseApply(X[1],Y),Y)};_transform(Z,Y){Y.path.push(this.signature);let X=super._transform(Z,Y);return Y.path.pop(),X}compile(){}}var K7={implementation:kM,Node:iJ},vM=(Z)=>`Index keys ${Z.join(", ")} should be specified as named props.`,fM=(Z)=>`Indexed key definition '${Z}' must be a string or symbol`;var hM=v({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`${Z.compiledKey}: ${Z.value.description}`,expected:(Z)=>Z.missingValueDescription,actual:()=>"missing"},intersections:{required:y6,optional:y6}});class oJ extends b6{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=t0(this.errorContext)}var B7={implementation:hM,Node:oJ};var gM=v({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}},optionals:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}},defaultables:{child:(Z)=>Z.map((Y)=>Y[0]),parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>{let Q=Y.$.parseSchema(X[0]);return k6(Q,X[1],null),[Q,X[1]]})},serialize:(Z)=>Z.map((Y)=>[Y[0].collapsibleJson,Q0(Y[1])]),reduceIo:(Z,Y,X)=>{if(Z==="in"){Y.optionals=X.map((Q)=>Q[0].rawIn);return}Y.prefix=X.map((Q)=>Q[0].rawOut);return}},variadic:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z,Y)},minVariadicLength:{parse:(Z)=>Z===0?void 0:Z},postfix:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}}},normalize:(Z)=>{if(typeof Z==="string")return{variadic:Z};if("variadic"in Z||"prefix"in Z||"defaultables"in Z||"optionals"in Z||"postfix"in Z||"minVariadicLength"in Z){if(Z.postfix?.length){if(!Z.variadic)return L(dM);if(Z.optionals?.length||Z.defaultables?.length)return L(M7)}if(Z.minVariadicLength&&!Z.variadic)return L("minVariadicLength may not be specified without a variadic element");return Z}return{variadic:Z}},reduce:(Z,Y)=>{let X=Z.minVariadicLength??0,Q=Z.prefix?.slice()??[],$=Z.defaultables?.slice()??[],W=Z.optionals?.slice()??[],J=Z.postfix?.slice()??[];if(Z.variadic){while(W[W.length-1]?.equals(Z.variadic))W.pop();if(W.length===0&&$.length===0)while(Q[Q.length-1]?.equals(Z.variadic))Q.pop(),X++;while(J[0]?.equals(Z.variadic))J.shift(),X++}else if(W.length===0&&$.length===0)Q.push(...J.splice(0));if(X!==Z.minVariadicLength||Z.prefix&&Z.prefix.length!==Q.length)return Y.node("sequence",{...Z,prefix:Q,defaultables:$,optionals:W,postfix:J,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Z)=>{if(Z.isVariadicOnly)return`${Z.variadic.nestableExpression}[]`;return`[${Z.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${x(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Z,Y,X)=>{let Q=g6({l:Z.tuple,r:Y.tuple,disjoint:new w,result:[],fixedVariants:[],ctx:X}),$=Q.disjoint.length===0?[Q,...Q.fixedVariants]:Q.fixedVariants;return $.length===0?Q.disjoint:$.length===1?X.$.node("sequence",nJ($[0].result)):X.$.node("union",$.map((W)=>({proto:Array,sequence:nJ(W.result)})))}}});class rJ extends $0{impliedBasis=F.intrinsic.Array.internal;tuple=pM(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((Z)=>{if(Z.kind==="defaultables"||Z.kind==="optionals")return this.defaultablesAndOptionals.push(Z.node),!0;return Z.kind==="prefix"});variadicOrPostfix=x0(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return dY(this.flatRefs,this.prevariadic.flatMap((Z,Y)=>h(Z.node.flatRefs.map((X)=>K0([`${Y}`,...X.path],X.node)),K0([`${Y}`],Z.node)))),dY(this.flatRefs,this.variadicOrPostfix.flatMap((Z)=>h(Z.flatRefs.map((Y)=>K0([F.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),K0([F.intrinsic.nonNegativeIntegerString.internal],Z)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=mM(this);defaultValueMorphsReference=this.defaultValueMorphs.length?Q1(this.defaultValueMorphs):void 0;elementAtIndex(Z,Y){if(Y<this.prevariadic.length)return this.tuple[Y];let X=Z.length-this.postfixLength;if(Y>=X)return{kind:"postfix",node:this.postfix[Y-X]};return{kind:"variadic",node:this.variadic??u(`Unexpected attempt to access index ${Y} on ${this}`)}}traverseAllows=(Z,Y)=>{for(let X=0;X<Z.length;X++)if(!this.elementAtIndex(Z,X).node.traverseAllows(Z[X],Y))return!1;return!0};traverseApply=(Z,Y)=>{let X=0;for(;X<Z.length;X++)m1(X,()=>this.elementAtIndex(Z,X).node.traverseApply(Z[X],Y),Y)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Z){if(this.prefix)for(let[Y,X]of this.prefix.entries())Z.traverseKey(`${Y}`,`data[${Y}]`,X);for(let[Y,X]of this.defaultablesAndOptionals.entries()){let Q=`${Y+this.prefixLength}`;Z.if(`${Q} >= data.length`,()=>Z.traversalKind==="Allows"?Z.return(!0):Z.return()),Z.traverseKey(Q,`data[${Q}]`,X)}if(this.variadic){if(this.postfix)Z.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Z.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Z.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Y,X]of this.postfix.entries()){let Q=`firstPostfixIndex + ${Y}`;Z.traverseKey(Q,`data[${Q}]`,X)}}if(Z.traversalKind==="Allows")Z.return(!0)}_transform(Z,Y){Y.path.push(F.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Z,Y);return Y.path.pop(),X}expression=this.description;reduceJsonSchema(Z,Y){let X=Y.target==="draft-07";if(this.prevariadic.length){let Q=this.prevariadic.map(($)=>{let W=$.node.toJsonSchemaRecurse(Y);if($.kind==="defaultables"){let J=typeof $.default==="function"?$.default():$.default;W.default=F.intrinsic.jsonData.allows(J)?J:Y.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(X)Z.items=Q;else Z.prefixItems=Q}if(this.minLength)Z.minItems=this.minLength;if(this.variadic){let Q=this.variadic.toJsonSchemaRecurse(Y);if(X&&this.prevariadic.length)Z.additionalItems=Q;else Z.items=Q;if(this.maxLength)Z.maxItems=this.maxLength;if(this.postfix){let $=this.postfix.map((W)=>W.toJsonSchemaRecurse(Y));Z=Y.fallback.arrayPostfix({code:"arrayPostfix",base:Z,elements:$})}}else{if(X)Z.additionalItems=!1;else Z.items=!1;delete Z.maxItems}return Z}}var uM={},mM=(Z)=>{if(!Z.defaultables)return[];let Y=[],X="[",Q=Z.prefixLength+Z.defaultablesLength-1;for(let $=Z.prefixLength;$<=Q;$++){let[W,J]=Z.defaultables[$-Z.prefixLength];Y.push(z7($,W,J)),X+=`${$}: ${W.id} = ${Q0(J)}, `}return X+="]",uM[X]??=Y},L7={implementation:gM,Node:rJ},pM=(Z)=>{let Y=[];if(Z.prefix)for(let X of Z.prefix)Y.push({kind:"prefix",node:X});if(Z.defaultables)for(let[X,Q]of Z.defaultables)Y.push({kind:"defaultables",node:X,default:Q});if(Z.optionals)for(let X of Z.optionals)Y.push({kind:"optionals",node:X});if(Z.variadic)Y.push({kind:"variadic",node:Z.variadic});if(Z.postfix)for(let X of Z.postfix)Y.push({kind:"postfix",node:X});return Y},nJ=(Z)=>Z.reduce((Y,X)=>{if(X.kind==="variadic")Y.variadic=X.node;else if(X.kind==="defaultables")Y.defaultables=h(Y.defaultables,[[X.node,X.default]]);else Y[X.kind]=h(Y[X.kind],X.node);return Y},{}),M7="A postfix required element cannot follow an optional or defaultable element",dM="A postfix element requires a variadic element",g6=(Z)=>{let[Y,...X]=Z.l,[Q,...$]=Z.r;if(!Y||!Q)return Z;let W=X[X.length-1]?.kind==="postfix",J=$[$.length-1]?.kind==="postfix",z=Y.kind==="prefix"||Q.kind==="prefix"?"prefix":Y.kind==="postfix"||Q.kind==="postfix"?"postfix":Y.kind==="variadic"&&Q.kind==="variadic"?"variadic":W||J?"prefix":Y.kind==="defaultables"||Q.kind==="defaultables"?"defaultables":"optionals";if(Y.kind==="prefix"&&Q.kind==="variadic"&&J){let H=g6({...Z,fixedVariants:[],r:$.map((G)=>({...G,kind:"prefix"}))});if(H.disjoint.length===0)Z.fixedVariants.push(H)}else if(Q.kind==="prefix"&&Y.kind==="variadic"&&W){let H=g6({...Z,fixedVariants:[],l:X.map((G)=>({...G,kind:"prefix"}))});if(H.disjoint.length===0)Z.fixedVariants.push(H)}let V=s(Y.node,Q.node,Z.ctx);if(V instanceof w)if(z==="prefix"||z==="postfix")Z.disjoint.push(...V.withPrefixKey(z==="prefix"?Z.result.length:`-${X.length+1}`,aJ(Y)&&aJ(Q)?"required":"optional")),Z.result=[...Z.result,{kind:z,node:F.intrinsic.never.internal}];else if(z==="optionals"||z==="defaultables")return Z;else return g6({...Z,fixedVariants:[],l:X.map((H)=>({...H,kind:"prefix"})),r:X.map((H)=>({...H,kind:"prefix"}))});else if(z==="defaultables"){if(Y.kind==="defaultables"&&Q.kind==="defaultables"&&Y.default!==Q.default)L(J7(Y.default,Q.default));Z.result=[...Z.result,{kind:z,node:V,default:Y.kind==="defaultables"?Y.default:Q.kind==="defaultables"?Q.default:u(`Unexpected defaultable intersection from ${Y.kind} and ${Q.kind} elements.`)}]}else Z.result=[...Z.result,{kind:z,node:V}];let q=Z.l.length,U=Z.r.length;if(Y.kind!=="variadic"||q>=U&&(Q.kind==="variadic"||U===1))Z.l=X;if(Q.kind!=="variadic"||U>=q&&(Y.kind==="variadic"||q===1))Z.r=$;return g6(Z)},aJ=(Z)=>Z.kind==="prefix"||Z.kind==="postfix";var Zz=(Z)=>(Y)=>{if(Y.props.length||Y.index){let X=Y.index?.map(($)=>$[Z])??[];for(let $ of Y.props)X.push($[Z]);if(Y.undeclared)X.push(`+ (undeclared): ${Y.undeclared}`);let Q=`{ ${X.join(", ")} }`;return Y.sequence?`${Q} & ${Y.sequence.description}`:Q}return Y.sequence?.description??"{}"},cM=Zz("description"),lM=Zz("expression"),sJ=(Z,Y,X)=>{let Q=Z.required?"required":"optional";if(!Y.signature.allows(Z.key))return null;let $=p1(Z.value,Y.value,X);if($ instanceof w)return Q==="optional"?X.node("optional",{key:Z.key,value:F.intrinsic.never.internal}):$.withPrefixKey(Z.key,Z.kind);return null},iM=v({kind:"structure",hasAssociatedError:!1,normalize:(Z)=>Z,applyConfig:(Z,Y)=>{if(!Z.undeclared&&Y.onUndeclaredKey!=="ignore")return{...Z,undeclared:Y.onUndeclaredKey};return Z},keys:{required:{child:!0,parse:I1("required"),reduceIo:(Z,Y,X)=>{Y.required=h(Y.required,X.map((Q)=>Z==="in"?Q.rawIn:Q.rawOut));return}},optional:{child:!0,parse:I1("optional"),reduceIo:(Z,Y,X)=>{if(Z==="in"){Y.optional=X.map((Q)=>Q.rawIn);return}for(let Q of X)Y[Q.outProp.kind]=h(Y[Q.outProp.kind],Q.outProp.rawOut)}},index:{child:!0,parse:I1("index")},sequence:{child:!0,parse:I1("sequence")},undeclared:{parse:(Z)=>Z==="ignore"?void 0:Z,reduceIo:(Z,Y,X)=>{if(X==="reject"){Y.undeclared="reject";return}if(Z==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:cM},intersections:{structure:(Z,Y,X)=>{let Q={...Z.inner},$={...Y.inner},W=new w;if(Z.undeclared){let V=Z.keyof();for(let q of Y.requiredKeys)if(!V.allows(q))W.add("presence",F.intrinsic.never.internal,Y.propsByKey[q].value,{path:[q]});if($.optional)$.optional=$.optional.filter((q)=>V.allows(q.key));if($.index)$.index=$.index.flatMap((q)=>{if(q.signature.extends(V))return q;let U=p1(V,q.signature,X.$);if(U instanceof w)return[];let H=F8(U,q.value,X.$);if(H.required)$.required=x0($.required,H.required);if(H.optional)$.optional=x0($.optional,H.optional);return H.index??[]})}if(Y.undeclared){let V=Y.keyof();for(let q of Z.requiredKeys)if(!V.allows(q))W.add("presence",Z.propsByKey[q].value,F.intrinsic.never.internal,{path:[q]});if(Q.optional)Q.optional=Q.optional.filter((q)=>V.allows(q.key));if(Q.index)Q.index=Q.index.flatMap((q)=>{if(q.signature.extends(V))return q;let U=p1(V,q.signature,X.$);if(U instanceof w)return[];let H=F8(U,q.value,X.$);if(H.required)Q.required=x0(Q.required,H.required);if(H.optional)Q.optional=x0(Q.optional,H.optional);return H.index??[]})}let J={};if(Z.undeclared||Y.undeclared)J.undeclared=Z.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let z=e9({kind:"structure",baseInner:J,l:Z2(Q),r:Z2($),roots:[],ctx:X});if(z instanceof w)W.push(...z);if(W.length)return W;return z}},reduce:(Z,Y)=>{if(!Z.required&&!Z.optional)return;let X={},Q=!1,$=Z.optional?[...Z.optional]:[];if(Z.required)for(let W=0;W<Z.required.length;W++){let J=Z.required[W];if(J.key in X)L(eJ(J.key));if(X[J.key]=!0,Z.index)for(let z of Z.index){let V=sJ(J,z,Y);if(V instanceof w)return V}}if(Z.optional)for(let W=0;W<Z.optional.length;W++){let J=Z.optional[W];if(J.key in X)L(eJ(J.key));if(X[J.key]=!0,Z.index)for(let z of Z.index){let V=sJ(J,z,Y);if(V instanceof w)return V;if(V!==null)$[W]=V,Q=!0}}if(Q)return Y.node("structure",{...Z,optional:$},{prereduced:!0})}});class Yz extends $0{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Z)=>Z.impliedSiblings??[]);props=x0(this.required,this.optional);propsByKey=b(this.props,(Z,Y)=>[Y.key,Y]);propsByKeyReference=Q1(this.propsByKey);expression=lM(this);requiredKeys=this.required?.map((Z)=>Z.key)??[];optionalKeys=this.optional?.map((Z)=>Z.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Y}of this.index)Z=Z.concat(Y.branches);return this._keyof=this.$.node("union",Z)}map(Z){return this.$.node("structure",this.props.flatMap(Z).reduce((Y,X)=>{let Q=this.propsByKey[X.key];if(r(X)){if(X.kind!=="required"&&X.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Y[X.kind]=h(Y[X.kind],X),Y}let $=X.kind??Q?.kind??"required",W=b(X,(J,z)=>(J in x6.implementation.keys)?[J,z]:[]);return Y[$]=h(Y[$],this.$.node($,W)),Y},{}))}assertHasKeys(Z){let Y=Z.filter((X)=>!v6(X,this.keyof()));if(Y.length)return L(tJ(this.expression,Y))}get(Z,...Y){let X,Q=!1,$=rM(Z);if((typeof $==="string"||typeof $==="symbol")&&this.propsByKey[$])X=this.propsByKey[$].value,Q=this.propsByKey[$].required;if(this.index){for(let J of this.index)if(v6($,J.signature))X=X?.and(J.value)??J.value}if(this.sequence&&v6($,F.intrinsic.nonNegativeIntegerString))if(P($,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let J=Number.parseInt($);if(J<this.sequence.prevariadic.length){let z=this.sequence.prevariadic[J].node;X=X?.and(z)??z,Q||=J<this.sequence.prefixLength}else if(this.sequence.variadic){let z=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(z)??z}}if(!X){if(this.sequence?.variadic&&P($,"root")&&$.extends(F.intrinsic.number))return L(sM($.expression,this.sequence.expression));return L(tJ(this.expression,[$]))}let W=X.get(...Y);return Q?W:W.or(F.intrinsic.undefined)}pick(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("pick",Z))}omit(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("omit",Z))}optionalize(){let{required:Z,...Y}=this.inner;return this.$.node("structure",{...Y,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Z,...Y}=this.inner;return this.$.node("structure",{...Y,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Z){let Y=this.filterKeys("omit",[Z.keyof()]);if(Z.required)Y.required=h(Y.required,Z.required);if(Z.optional)Y.optional=h(Y.optional,Z.optional);if(Z.index)Y.index=h(Y.index,Z.index);if(Z.sequence)Y.sequence=Z.sequence;if(Z.undeclared)Y.undeclared=Z.undeclared;else delete Y.undeclared;return this.$.node("structure",Y)}filterKeys(Z,Y){let X=J8(this.inner),Q=($)=>{let W=Y.some((J)=>v6($,J));return Z==="pick"?W:!W};if(X.required)X.required=X.required.filter(($)=>Q($.key));if(X.optional)X.optional=X.optional.filter(($)=>Q($.key));if(X.index)X.index=X.index.filter(($)=>Q($.signature));return X}traverseAllows=(Z,Y)=>this._traverse("Allows",Z,Y);traverseApply=(Z,Y)=>this._traverse("Apply",Z,Y);_traverse=(Z,Y,X)=>{let Q=X?.currentErrorCount??0;for(let $=0;$<this.props.length;$++)if(Z==="Allows"){if(!this.props[$].traverseAllows(Y,X))return!1}else if(this.props[$].traverseApply(Y,X),X.failFast&&X.currentErrorCount>Q)return!1;if(this.sequence){if(Z==="Allows"){if(!this.sequence.traverseAllows(Y,X))return!1}else if(this.sequence.traverseApply(Y,X),X.failFast&&X.currentErrorCount>Q)return!1}if(this.index||this.undeclared==="reject"){let $=Object.keys(Y);$.push(...Object.getOwnPropertySymbols(Y));for(let W=0;W<$.length;W++){let J=$[W];if(this.index){for(let z of this.index)if(z.signature.traverseAllows(J,X)){if(Z==="Allows"){if(!m1(J,()=>z.value.traverseAllows(Y[J],X),X))return!1}else if(m1(J,()=>z.value.traverseApply(Y[J],X),X),X.failFast&&X.currentErrorCount>Q)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(J)){if(Z==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[J],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Z)=>Z.hasDefault())??[])}declaresKey=(Z)=>(Z in this.propsByKey)||this.index?.some((Y)=>Y.signature.allows(Z))||this.sequence!==void 0&&F.intrinsic.nonNegativeIntegerString.allows(Z);_compileDeclaresKey(Z){let Y=[];if(this.props.length)Y.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Y.push(Z.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Y.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Y.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",nM(this))}structuralMorphRef=this.structuralMorph&&Q1(this.structuralMorph);compile(Z){if(Z.traversalKind==="Apply")Z.initializeErrorCount();for(let Y of this.props)if(Z.check(Y),Z.traversalKind==="Apply")Z.returnIfFailFast();if(this.sequence){if(Z.check(this.sequence),Z.traversalKind==="Apply")Z.returnIfFailFast()}if(this.index||this.undeclared==="reject")Z.const("keys","Object.keys(data)"),Z.line("keys.push(...Object.getOwnPropertySymbols(data))"),Z.for("i < keys.length",()=>this.compileExhaustiveEntry(Z));if(Z.traversalKind==="Allows")return Z.return(!0);if(this.structuralMorphRef)Z.if("ctx && !ctx.hasError()",()=>{return Z.line("ctx.queueMorphs(["),aM(Z,this),Z.line("])")})}compileExhaustiveEntry(Z){if(Z.const("k","keys[i]"),this.index)for(let Y of this.index)Z.if(`${Z.invoke(Y.signature,{arg:"k",kind:"Allows"})}`,()=>Z.traverseKey("k","data[k]",Y.value));if(this.undeclared==="reject")Z.if(`!(${this._compileDeclaresKey(Z)})`,()=>{if(Z.traversalKind==="Allows")return Z.return(!1);return Z.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Z.return())});return Z}reduceJsonSchema(Z,Y){switch(Z.type){case"object":return this.reduceObjectJsonSchema(Z,Y);case"array":let X=this.sequence?.reduceJsonSchema(Z,Y)??Z;if(this.props.length||this.index)return Y.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Y)});return X;default:return t.throwInternalOperandError("structure",Z)}}reduceObjectJsonSchema(Z,Y){if(this.props.length){Z.properties={};for(let X of this.props){let Q=X.value.toJsonSchemaRecurse(Y);if(typeof X.key==="symbol"){Y.fallback.symbolKey({code:"symbolKey",base:Z,key:X.key,value:Q,optional:X.optional});continue}if(X.hasDefault()){let $=typeof X.default==="function"?X.default():X.default;Q.default=F.intrinsic.jsonData.allows($)?$:Y.fallback.defaultValue({code:"defaultValue",base:Q,value:$})}Z.properties[X.key]=Q}if(this.requiredKeys.length&&Z.properties)Z.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Z.properties))}if(this.index)for(let X of this.index){let Q=X.value.toJsonSchemaRecurse(Y);if(X.signature.equals(F.intrinsic.string)){Z.additionalProperties=Q;continue}for(let $ of X.signature.branches){if(!$.extends(F.intrinsic.string)){Z=Y.fallback.symbolKey({code:"symbolKey",base:Z,key:null,value:Q,optional:!1});continue}let W={type:"string"};if($.hasKind("morph"))W=Y.fallback.morph({code:"morph",base:$.rawIn.toJsonSchemaRecurse(Y),out:$.rawOut.toJsonSchemaRecurse(Y)});if(!$.hasKind("intersection"))return u(`Unexpected index branch kind ${$.kind}.`);let{pattern:J}=$.inner;if(J){let z=Object.assign(W,{pattern:J[0].rule});for(let V=1;V<J.length;V++)W=Y.fallback.patternIntersection({code:"patternIntersection",base:z,pattern:J[V].rule});Z.patternProperties??={},Z.patternProperties[z.pattern]=Q}}}if(this.undeclared&&!Z.additionalProperties)Z.additionalProperties=!1;return Z}}var F7={},oM=(Z)=>{let Y="";for(let X=0;X<Z.defaultable.length;X++)Y+=Z.defaultable[X].defaultValueMorphRef;if(Z.sequence?.defaultValueMorphsReference)Y+=Z.sequence?.defaultValueMorphsReference;if(Z.undeclared==="delete"){if(Y+="delete !(",Z.required)for(let X of Z.required)Y+=X.compiledKey+" | ";if(Z.optional)for(let X of Z.optional)Y+=X.compiledKey+" | ";if(Z.index)for(let X of Z.index)Y+=X.signature.id+" | ";if(Z.sequence)if(Z.sequence.maxLength===null)Y+=C.nonNegativeIntegerString.id;else for(let X=0;X<Z.sequence.tuple.length;X++)Y+=X+" | ";Y+=")"}return Y},nM=(Z)=>{let Y=oM(Z);if(!Y)return;if(F7[Y])return F7[Y];let X=(Q,$)=>{for(let W=0;W<Z.defaultable.length;W++)if(!(Z.defaultable[W].key in Q))Z.defaultable[W].defaultValueMorph(Q,$);if(Z.sequence?.defaultables)for(let W=Q.length-Z.sequence.prefixLength;W<Z.sequence.defaultables.length;W++)Z.sequence.defaultValueMorphs[W](Q,$);if(Z.undeclared==="delete"){for(let W in Q)if(!Z.declaresKey(W))delete Q[W]}return Q};return F7[Y]=X},aM=(Z,Y)=>{let Q=`(data${Y.defaultable.some(($)=>$.defaultValueMorph.length===2)||Y.sequence?.defaultValueMorphs.some(($)=>$.length===2)?", ctx":""})`;return Z.block(`${Q} => `,($)=>{for(let W=0;W<Y.defaultable.length;W++){let{serializedKey:J,defaultValueMorphRef:z}=Y.defaultable[W];$.if(`!(${J} in data)`,(V)=>V.line(`${z}${Q}`))}if(Y.sequence?.defaultables)$.for(`i < ${Y.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Y.sequence.prefixLength}`);if(Y.undeclared==="delete")$.forIn("data",(W)=>W.if(`!(${Y._compileDeclaresKey(W)})`,(J)=>J.line("delete data[k]")));return $.return("data")})},N7={implementation:iM,Node:Yz},rM=(Z)=>{if(P(Z,"root")&&Z.hasKind("unit"))Z=Z.unit;if(typeof Z==="number")Z=`${Z}`;return Z},sM=(Z,Y)=>`${Z} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,F8=(Z,Y,X)=>{let[Q,$]=FW(Z.branches,(J)=>J.hasKind("unit"));if(!Q.length)return{index:X.node("index",{signature:Z,value:Y})};let W={};for(let J of Q){let z=X.node("required",{key:J.unit,value:Y});W[z.kind]=h(W[z.kind],z)}if($.length)W.index=X.node("index",{signature:$,value:Y});return W},tM=(Z)=>P(Z,"root")?Z.expression:x(Z),tJ=(Z,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(tM).join(", ")} ${Y.length===1?"does":"do"} not exist on ${Z}`,eJ=(Z)=>`Duplicate key ${H0(Z)}`;var X2={...AJ,alias:f6.implementation,domain:M8.implementation,unit:G7.implementation,proto:h6.implementation,union:H7.implementation,morph:q7.implementation,intersection:V7.implementation,divisor:nY.implementation,pattern:X7.implementation,predicate:oY.implementation,required:B7.implementation,optional:x6.implementation,index:K7.implementation,sequence:L7.implementation,structure:N7.implementation};F.defaultConfig=IW(Object.assign(b(X2,(Z,Y)=>[Z,Y.defaults]),{jitless:yW(),clone:CW,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:t.defaultConfig}));F.resolvedConfig=R6(F.defaultConfig,F.config);var RJ={...EJ,alias:f6.Node,domain:M8.Node,unit:G7.Node,proto:h6.Node,union:H7.Node,morph:q7.Node,intersection:V7.Node,divisor:nY.Node,pattern:X7.Node,predicate:oY.Node,required:B7.Node,optional:x6.Node,index:K7.Node,sequence:L7.Node,structure:N7.Node};class W2 extends jY{get[S1](){return"module"}}var w7=(Z,Y)=>new W2(b(Z,(X,Q)=>[X,P(Q,"module")?w7(Q,Y):Y.bindReference(Q)]));var eM=(Z)=>n(Z)?Z:("branches"in Z)&&n(Z.branches)?Z.branches:void 0,ZF=(Z,Y)=>L(`Node of kind ${Y} is not valid as a ${Z} definition`),Xz=(Z)=>`#${Z} duplicates public alias ${Z}`,D7={};F.ambient??={};var Qz,Wz="function $",YF=(Z)=>Jz(Z,zz(Z)),Jz=(Z,Y)=>{let X=Y.write(Wz,4),Q=Y.compile()();for(let $ of Z){if($.precompilation)continue;if($.traverseAllows=Q[`${$.id}Allows`].bind(Q),$.isRoot()&&!$.allowsRequiresContext)$.allows=$.traverseAllows;if($.traverseApply=Q[`${$.id}Apply`].bind(Q),Q[`${$.id}Optimistic`])$.traverseOptimistic=Q[`${$.id}Optimistic`].bind(Q);$.precompilation=X}},zz=(Z)=>new W8().return(Z.reduce((Y,X)=>{let Q=new I6({kind:"Allows"}).indent();X.compile(Q);let $=Q.write(`${X.id}Allows`),W=new I6({kind:"Apply"}).indent();X.compile(W);let J=W.write(`${X.id}Apply`),z=`${Y}${$},
128
+ ${J},
129
+ `;if(!X.hasKind("union"))return z;let V=new I6({kind:"Allows",optimistic:!0}).indent();X.compile(V);let q=V.write(`${X.id}Optimistic`);return`${z}${q},
130
+ `},`{
131
+ `)+"}");class N8{config;resolvedConfig;name;get[S1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Z,Y){if(this.config=R6(F.config,Y),this.resolvedConfig=R6(F.resolvedConfig,Y),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(D7).length}`,this.name in D7)L(`A Scope already named ${this.name} already exists`);D7[this.name]=this;let X=Object.entries(Z).map((Q)=>this.preparseOwnAliasEntry(...Q));for(let[Q,$]of X){let W=Q;if(Q[0]==="#"){if(W=Q.slice(1),W in this.aliases)L(Xz(W));this.aliases[W]=$}else{if(W in this.aliases)L(Xz(Q));this.aliases[W]=$,this.exportedNames.push(W)}if(!P($,"module")&&!P($,"generic")&&!a0($)){let J=this.preparseOwnDefinitionFormat($,{alias:W});this.resolutions[W]=P(J,"root")?this.bindReference(J):this.createParseContext(J).id}}Qz??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Qz.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?b(F.intrinsic,(Q,$)=>Q.startsWith("json")?[]:[Q,this.bindReference($)]):{}}cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Z){return Z}generic=(...Z)=>{let Y=this;return(X,Q)=>new Z9(Z,Q?new U8(X):X,Y,Y,Q??null)};units=(Z,Y)=>{let X=[];for(let $ of Z)if(!X.includes($))X.push($);let Q=X.map(($)=>this.node("unit",{unit:$},Y));return this.node("union",Q,{...Y,prereduced:!0})};lazyResolutions=[];lazilyResolve(Z,Y){let X=this.node("alias",{reference:Y??"synthetic",resolve:Z},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Z,Y)=>this.finalize(this.parseSchema(Z,Y));parseSchema=(Z,Y)=>this.node(_6(Z),Z,Y);preparseNode(Z,Y,X){let Q=typeof Z==="string"?Z:_6(Y,Z);if(r(Y)&&Y.kind===Q)return Y;if(Q==="alias"&&!X?.prereduced){let{reference:J}=f6.implementation.normalize(Y,this);if(J.startsWith("$")){let z=this.resolveRoot(J.slice(1));Y=z,Q=z.kind}}else if(Q==="union"&&v1(Y,"object")){let J=eM(Y);if(J?.length===1)Y=J[0],Q=_6(Y)}if(r(Y)&&Y.kind===Q)return Y;let W=X2[Q].normalize?.(Y,this)??Y;if(r(W))return W.kind===Q?W:ZF(Q,W.kind);return{...X,$:this,kind:Q,def:W,prefix:X.alias??Q}}bindReference(Z){let Y;if(r(Z))Y=Z.$===this?Z:new Z.constructor(Z.attachments,this);else Y=Z.$===this?Z:new Z9(Z.params,Z.bodyDef,Z.$,this,Z.hkt);if(!this.resolved)Object.assign(this.referencesById,Y.referencesById);return Y}resolveRoot(Z){return this.maybeResolveRoot(Z)??L(O7(Z))}maybeResolveRoot(Z){let Y=this.maybeResolve(Z);if(P(Y,"generic"))return;return Y}maybeResolveSubalias(Z){return A7(this.aliases,Z)??A7(this.ambient,Z)}get ambient(){return F.ambient}maybeResolve(Z){let Y=this.resolutions[Z];if(Y){if(typeof Y!=="string")return this.bindReference(Y);let Q=_1[Y];if(P(Q,"root"))return this.resolutions[Z]=Q;if(P(Q,"context")){if(Q.phase==="resolving")return this.node("alias",{reference:`$${Z}`},{prereduced:!0});if(Q.phase==="resolved")return u(`Unexpected resolved context for was uncached by its scope: ${x(Q)}`);Q.phase="resolving";let $=this.bindReference(this.parseOwnDefinitionFormat(Q.def,Q));return Q.phase="resolved",_1[$.id]=$,_1[Q.id]=$,this.resolutions[Z]=$}return u(`Unexpected nodesById entry for ${Y}: ${x(Q)}`)}let X=this.aliases[Z]??this.ambient?.[Z];if(!X)return this.maybeResolveSubalias(Z);if(X=this.normalizeRootScopeValue(X),P(X,"generic"))return this.resolutions[Z]=this.bindReference(X);if(P(X,"module")){if(!X.root)L(Uz(Z));return this.resolutions[Z]=this.bindReference(X.root)}return this.resolutions[Z]=this.parse(X,{alias:Z})}createParseContext(Z){let Y=Z.id??Q7(Z.prefix);return _1[Y]=Object.assign(Z,{[S1]:"context",$:this,id:Y,phase:"unresolved"})}traversal(Z){return new G0(Z,this.resolvedConfig)}import(...Z){return new W2(b(this.export(...Z),(Y,X)=>[`#${Y}`,X]))}precompilation;_exportedResolutions;_exports;export(...Z){if(!this._exports){this._exports={};for(let X of this.exportedNames){let Q=this.aliases[X];this._exports[X]=P(Q,"module")?w7(Q,this):$z(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=qz(this,this._exports),this._json=Vz(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=zz(this.references);this.precompilation=X.write(Wz,4),Jz(this.references,X)}this.resolved=!0}let Y=Z.length?Z:this.exportedNames;return new W2(b(Y,(X,Q)=>[Q,this._exports[Q]]))}resolve(Z){return this.export()[Z]}node=(Z,Y,X={})=>{let Q=this.preparseNode(Z,Y,X);if(r(Q))return this.bindReference(Q);let $=this.createParseContext(Q),W=$7($),J=this.bindReference(W);return _1[$.id]=J};parse=(Z,Y={})=>this.finalize(this.parseDefinition(Z,Y));parseDefinition(Z,Y={}){if(P(Z,"root"))return this.bindReference(Z);let X=this.preparseOwnDefinitionFormat(Z,Y);if(P(X,"root"))return this.bindReference(X);let Q=this.createParseContext(X);_1[Q.id]=Q;let $=this.bindReference(this.parseOwnDefinitionFormat(Z,Q));if($.isCyclic)$=IJ($,Q.id);return _1[Q.id]=$,$}finalize(Z){if($z(Z),!Z.precompilation&&!this.resolvedConfig.jitless)YF(Z.references);return Z}}class E7 extends N8{parseOwnDefinitionFormat(Z,Y){return $7(Y)}preparseOwnDefinitionFormat(Z,Y){return this.preparseNode(_6(Z),Z,Y)}preparseOwnAliasEntry(Z,Y){return[Z,Y]}normalizeRootScopeValue(Z){return Z}}var $z=(Z)=>{let Y=Z.references.filter((X)=>X.hasKind("alias"));for(let X of Y){Object.assign(X.referencesById,X.resolution.referencesById);for(let Q of Z.references)if(X.id in Q.referencesById)Object.assign(Q.referencesById,X.referencesById)}return Z},Vz=(Z)=>b(Z,(Y,X)=>[Y,P(X,"root")||P(X,"generic")?X.json:P(X,"module")?Vz(X):u(`Unexpected resolution ${x(X)}`)]),A7=(Z,Y)=>{let X=Y.indexOf(".");if(X===-1)return;let Q=Y.slice(0,X),$=Z[Q];if($===void 0)return;if(!P($,"module"))return L(XF(Q));let W=Y.slice(X+1),J=$[W];if(J===void 0)return A7($,W);if(P(J,"root")||P(J,"generic"))return J;if(P(J,"module"))return J.root??L(Uz(Y));u(`Unexpected resolution for alias '${Y}': ${x(J)}`)},w8=(Z,Y)=>new E7(Z,Y),u6=new E7({});var qz=(Z,Y)=>{let X={};for(let Q in Y){let $=Y[Q];if(P($,"module")){let W=qz(Z,$),J=b(W,(z,V)=>[`${Q}.${z}`,V]);Object.assign(X,J)}else if(P($,"root")||P($,"generic"))X[Q]=$;else u(`Unexpected scope resolution ${x($)}`)}return X},O7=(Z)=>`'${Z}' is unresolvable`,XF=(Z)=>`'${Z}' must reference a module to be accessed using dot syntax`,Uz=(Z)=>`Reference to submodule '${Z}' must specify an alias`;u6.export();var{schema:c,node:J2,defineSchema:py,generic:J0}=u6;var P7="^(?:0|[1-9]\\d*)$",QF=new RegExp(P7),ly=Q1(QF);var Hz=w8({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();F.intrinsic={...Hz};var Gz=w8({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:P7}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,Gz);var $F=w8({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),C={...Hz,...Gz,...$F,emptyStructure:J2("structure",{},{prereduced:!0})};F.intrinsic={...C};var D8=(Z,Y)=>new RegExp(Z,Y);Object.assign(D8,{as:D8});var Bz=(Z)=>typeof Z==="string"&&Z[0]==="d"&&(Z[1]==="'"||Z[1]==='"')&&Z[Z.length-1]===Z[1],Kz=(Z)=>Z.toString()!=="Invalid Date",Lz=(Z)=>Z.slice(2,-1),T7=(Z)=>`'${Z}' could not be parsed by the Date constructor`,Mz=(Z,Y)=>WF(Z,Y),WF=(Z,Y)=>{let X=new Date(Z);if(Kz(X))return X;let Q=pW(Z);if(Q!==void 0){let $=new Date(Q);if(Kz($))return $}return Y?L(Y===!0?T7(Z):Y):void 0};var JF=c({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),A8=(Z,Y)=>{let X=Z.scanner.shiftUntilEscapable(VF[wz[Y]]);if(Z.scanner.lookahead==="")return Z.error(UF(X,Y));if(Z.scanner.shift(),Y in Nz){let Q;try{Q=new RegExp(X)}catch($){L(String($))}if(Z.root=Z.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0}),Y==="x/")Z.root=Z.ctx.$.node("morph",{in:Z.root,morphs:($)=>Q.exec($),declaredOut:JF})}else if(N1(Y,I7))Z.root=Z.ctx.$.node("unit",{unit:X});else{let Q=Mz(X,T7(X));Z.root=Z.ctx.$.node("unit",{meta:X,unit:Q})}},I7={"'":1,'"':1},Fz={"/":1,"'":1,'"':1},zF={"d'":"'",'d"':'"',"'":"'",'"':'"'},Nz={"/":"/","x/":"/"},wz={...zF,...Nz},VF={"'":(Z)=>Z.lookahead==="'",'"':(Z)=>Z.lookahead==='"',"/":(Z)=>Z.lookahead==="/"},qF={'"':"double-quote","'":"single-quote","/":"forward slash"},UF=(Z,Y)=>`${Y}${Z} requires a closing ${qF[wz[Y]]}`;var Dz=(Z)=>`Private type references should not include '#'. Use '${Z}' instead.`,E8="Optional definitions like 'string?' are only valid as properties in an object or tuple",O8="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var D0={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...r0};var Az=(Z,Y)=>Z===">"?Y[0]==="="?Y[1]==="=":Y.trimStart()===""||N1(Y.trimStart()[0],D0):Z==="="?Y[0]!=="=":Z===","||Z==="?";var Ez=(Z,Y,X)=>Oz(Z,Y,X,[]),Oz=(Z,Y,X,Q)=>{let $=X.parseUntilFinalizer();if(Q.push($.root),$.finalizer===">"){if(Q.length!==Y.params.length)return X.error(R7(Z,Y.names,Q.map((W)=>W.expression)));return Q}if($.finalizer===",")return Oz(Z,Y,X,Q);return $.error($8(">"))},R7=(Z,Y,X)=>`${Z}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var P8=(Z)=>{let Y=Z.scanner.shiftUntilLookahead(D0);if(Y==="keyof")Z.addPrefix("keyof");else Z.root=GF(Z,Y)},HF=(Z,Y,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(R7(Z,Y.names,[]));let $=Ez(Z,Y,X);return Y(...$)},GF=(Z,Y)=>KF(Z,Y)??BF(Z,Y)??Z.error(Y===""?Z.scanner.lookahead==="#"?Dz(Z.shiftedBy(1).scanner.shiftUntilLookahead(D0)):j7(Z):O7(Y)),KF=(Z,Y)=>{if(Z.ctx.args?.[Y]){let Q=Z.ctx.args[Y];if(typeof Q!=="string")return Q;return Z.ctx.$.node("alias",{reference:Q},{prereduced:!0})}let X=Z.ctx.$.maybeResolve(Y);if(P(X,"root"))return X;if(X===void 0)return;if(P(X,"generic"))return HF(Y,X,Z);return L(`Unexpected resolution ${x(X)}`)},BF=(Z,Y)=>{let X=dW(Y);if(X!==void 0)return Z.ctx.$.node("unit",{unit:X});let Q=lW(Y);if(Q!==void 0)return Z.ctx.$.node("unit",{unit:Q})},j7=(Z)=>{let Y=Z.previousOperator();return Y?C7(Y,Z.scanner.unscanned):LF(Z.scanner.unscanned)},C7=(Z,Y="")=>`Token '${Z}' requires a right operand${Y?` before '${Y}'`:""}`,LF=(Z)=>`Expected an expression${Z?` before '${Z}'`:""}`;var S7=(Z)=>Z.scanner.lookahead===""?Z.error(j7(Z)):Z.scanner.lookahead==="("?Z.shiftedBy(1).reduceGroupOpen():Z.scanner.lookaheadIsIn(Fz)?A8(Z,Z.scanner.shift()):Z.scanner.lookaheadIsIn(r0)?S7(Z.shiftedBy(1)):Z.scanner.lookahead==="d"?Z.scanner.nextLookahead in I7?A8(Z,`${Z.scanner.shift()}${Z.scanner.shift()}`):P8(Z):Z.scanner.lookahead==="x"?Z.scanner.nextLookahead==="/"?Z.shiftedBy(2)&&A8(Z,"x/"):P8(Z):P8(Z);var Pz={">":!0,">=":!0},Tz={"<":!0,"<=":!0};var z2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Iz=(Z,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${Z})`,T8=(Z)=>`Left-bounded expressions must specify their limits using < or <= (was ${Z})`,Rz=(Z,Y,X,Q)=>`An expression may have at most one left bound (parsed ${Z}${z2[Y]}, ${X}${z2[Q]})`;var Cz=(Z,Y)=>{let X=MF(Z,Y);if(Z.root.hasKind("unit")){if(typeof Z.root.unit==="number"){Z.reduceLeftBound(Z.root.unit,X),Z.unsetRoot();return}if(Z.root.unit instanceof Date){let Q=`d'${Z.root.description??Z.root.unit.toISOString()}'`;Z.unsetRoot(),Z.reduceLeftBound(Q,X);return}}return NF(Z,X)},Sz={"<":1,">":1,"=":1},MF=(Z,Y)=>Z.scanner.lookaheadIs("=")?`${Y}${Z.scanner.shift()}`:Y;var jz=(Z,Y,X,Q)=>{if(X.extends(F.intrinsic.number)){if(typeof Y!=="number")return L(_7(Z,Y,Q));return Z==="=="?["min","max"]:Z[0]===">"?["min"]:["max"]}if(X.extends(F.intrinsic.lengthBoundable)){if(typeof Y!=="number")return L(_7(Z,Y,Q));return Z==="=="?["exactLength"]:Z[0]===">"?["minLength"]:["maxLength"]}if(X.extends(F.intrinsic.Date))return Z==="=="?["after","before"]:Z[0]===">"?["after"]:["before"];return L(KJ(X.expression))},FF=(Z)=>({rule:Bz(Z.limit)?Lz(Z.limit):Z.limit,exclusive:Z.comparator.length===1}),NF=(Z,Y)=>{let X=Z.unsetRoot(),Q=Z.scanner.location;Z.parseOperand();let $=Z.unsetRoot(),W=Z.scanner.sliceChars(Q,Z.scanner.location);if(Z.root=X,!$.hasKind("unit")||typeof $.unit!=="number"&&!($.unit instanceof Date))return Z.error(_7(Y,W,"right"));let J=$.unit,z=Y.length===1,V=jz(Y,typeof J==="number"?J:W,X,"right");for(let U of V)Z.constrainRoot(U,Y==="=="?{rule:J}:{rule:J,exclusive:z});if(!Z.branches.leftBound)return;if(!N1(Y,Tz))return Z.error(T8(Y));let q=jz(Z.branches.leftBound.comparator,Z.branches.leftBound.limit,X,"left");Z.constrainRoot(q[0],FF(Z.branches.leftBound)),Z.branches.leftBound=null},_7=(Z,Y,X)=>`Comparator ${X==="left"?z2[Z]:Z} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var _z=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let Y=Z.scanner.shiftUntilLookahead(D0);Z.root=Z.root.brand(Y)};var bz=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let Y=Z.scanner.shiftUntilLookahead(D0),X=cW(Y,{errorOnFail:yz(Y)});if(X===0)Z.error(yz(0));Z.root=Z.root.constrain("divisor",X)},yz=(Z)=>`% operator must be followed by a non-zero integer literal (was ${Z})`;var y7=(Z)=>{let Y=Z.scanner.shift();return Y===""?Z.finalize(""):Y==="["?Z.scanner.shift()==="]"?Z.setRoot(Z.root.array()):Z.error(wF):Y==="|"?Z.scanner.lookahead===">"?Z.shiftedBy(1).pushRootToBranch("|>"):Z.pushRootToBranch(Y):Y==="&"?Z.pushRootToBranch(Y):Y===")"?Z.finalizeGroup():Az(Y,Z.scanner.unscanned)?Z.finalize(Y):N1(Y,Sz)?Cz(Z,Y):Y==="%"?bz(Z):Y==="#"?_z(Z):(Y in r0)?y7(Z):Z.error(I8(Y))},I8=(Z,Y="")=>`'${Z}' is not allowed here${Y&&` (should be ${Y})`}`,wF="Missing expected ']'";var xz=(Z)=>{let Y=Z.unsetRoot();Z.parseOperand();let X=Z.unsetRoot();if(!X.hasKind("unit"))return Z.error(DF(X.expression));let Q=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Y,"=",Q]},DF=(Z)=>`Default value '${Z}' must be a literal value`;var b7=(Z,Y)=>{let X=Y.$.maybeResolveRoot(Z);if(X)return X;if(Z.endsWith("[]")){let W=Y.$.maybeResolveRoot(Z.slice(0,-2));if(W)return W.array()}let Q=new V2(new T6(Z),Y),$=AF(Q);if(Q.finalizer===">")L(I8(">"));return $},AF=(Z)=>{Z.parseOperand();let Y=m6(Z).root;if(!Y)return u(`Root was unexpectedly unset after parsing string '${Z.scanner.scanned}'`);if(Z.finalizer==="=")Y=xz(Z);else if(Z.finalizer==="?")Y=[Y,"?"];if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.lookahead)L(I8(Z.scanner.lookahead));return Y},m6=(Z)=>{while(Z.finalizer===void 0)EF(Z);return Z},EF=(Z)=>Z.hasRoot()?Z.parseOperator():Z.parseOperand();class V2{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Z,Y){this.scanner=Z,this.ctx=Y}error(Z){return L(Z)}hasRoot(){return this.root!==void 0}setRoot(Z){this.root=Z}unsetRoot(){let Z=this.root;return this.root=void 0,Z}constrainRoot(...Z){this.root=this.root.constrain(Z[0],Z[1])}finalize(Z){if(this.groups.length)return this.error($8(")"));this.finalizeBranches(),this.finalizer=Z}reduceLeftBound(Z,Y){let X=z2[Y];if(!N1(X,Pz))return this.error(T8(Y));if(this.branches.leftBound)return this.error(Rz(this.branches.leftBound.limit,this.branches.leftBound.comparator,Z,X));this.branches.leftBound={comparator:X,limit:Z}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Z=this.groups.pop();if(!Z)return this.error(aW(")",this.scanner.unscanned));this.branches=Z}addPrefix(Z){this.branches.prefixes.push(Z)}applyPrefixes(){while(this.branches.prefixes.length){let Z=this.branches.prefixes.pop();this.root=Z==="keyof"?this.root.keyof():u(`Unexpected prefix '${Z}'`)}}pushRootToBranch(Z){this.assertRangeUnset(),this.applyPrefixes();let Y=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Y)??Y,Z==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Z==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return m6(new V2(this.scanner,this.ctx))}parseOperator(){return y7(this)}parseOperand(){return S7(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Iz(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(Z){return this.scanner.jumpForward(Z),this}}var OF="An empty string is not a valid generic parameter name",R8=(Z,Y,X)=>{Z.shiftUntilNonWhitespace();let Q=Z.shiftUntilLookahead(D0);if(Q===""){if(Z.lookahead===""&&Y.length)return Y;return L(OF)}return Z.shiftUntilNonWhitespace(),PF(Z,Q,Y,X)},kz="extends ",PF=(Z,Y,X,Q)=>{if(Z.shiftUntilNonWhitespace(),Z.unscanned.startsWith(kz))Z.jumpForward(kz.length);else{if(Z.lookahead===",")Z.shift();return X.push(Y),R8(Z,X,Q)}let $=m6(new V2(Z,Q));return X.push([Y,$.root]),R8(Z,X,Q)};class x7 extends g1{constructor(Z){let Y={$:Z,raw:Z.fn};super((...X)=>{let Q=X.indexOf(":"),$=Q===-1?X.length-1:Q-1,W=X.slice(0,$+1),J=Z.parse(W).assertHasKind("intersection"),z=Z.intrinsic.unknown;if(Q!==-1){if(Q!==X.length-2)return L(TF);z=Z.parse(X[Q+1])}return(V)=>new vz(V,J,z)},{attach:Y})}}class vz extends g1{raw;params;returns;expression;constructor(Z,Y,X){let Q=`typed ${Z.name}`,$={[Q]:(...J)=>{let z=Y.assert(J),V=Z(...z);return X.assert(V)}}[Q];super($);this.raw=Z,this.params=Y,this.returns=X;let W=Y.expression;if(W[0]==="["&&W[W.length-1]==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${X?.expression??"unknown"}`}}var TF=`":" must be followed by exactly one return type e.g:
132
+ fn("string", ":", "number")(s => s.length)`;class k7 extends g1{$;constructor(Z){super((...Y)=>new p6(Z)(...Y),{bind:Z});this.$=Z}in(Z){return new p6(this.$,Z===void 0?void 0:this.$.parse(Z))}at(Z,Y){return new p6(this.$).at(Z,Y)}case(Z,Y){return new p6(this.$).case(Z,Y)}}class p6 extends g1{$;in;key;branches=[];constructor(Z,Y){super((X)=>this.caseEntries(Object.entries(X).map(([Q,$])=>Q==="default"?[Q,$]:[this.$.parse(Q),$])));this.$=Z,this.in=Y}at(Z,Y){if(this.key)L(RF);if(this.branches.length)L(IF);return this.key=Z,Y?this.match(Y):this}case(Z,Y){return this.caseEntry(this.$.parse(Z),Y)}caseEntry(Z,Y){let Q=(this.key?this.$.parse({[this.key]:Z}):Z).pipe(Y);return this.branches.push(Q),this}match(Z){return this(Z)}strings(Z){return this.caseEntries(Object.entries(Z).map(([Y,X])=>Y==="default"?[Y,X]:[this.$.node("unit",{unit:Y}),X]))}caseEntries(Z){for(let Y=0;Y<Z.length;Y++){let[X,Q]=Z[Y];if(X==="default"){if(Y!==Z.length-1)L("default may only be specified as the last key of a switch definition");return this.default(Q)}if(typeof Q!=="function")return L(`Value for case "${X}" must be a function (was ${F1(Q)})`);this.caseEntry(X,Q)}return this}default(Z){if(typeof Z==="function")this.case(C.unknown,Z);let Y={branches:this.branches,ordered:!0};if(Z==="never"||Z==="assert")Y.meta={onFail:fz};let X=this.$.node("union",Y);if(!this.in)return this.$.finalize(X);let Q=this.in.pipe(X);if(Z==="never"||Z==="assert")Q=Q.configureReferences({onFail:fz},"self");return this.$.finalize(Q)}}var fz=(Z)=>Z.throw(),IF="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",RF="At most one key matcher may be specified per expression";var j8=(Z,Y)=>{if(n(Z)){if(Z[1]==="=")return[Y.$.parseOwnDefinitionFormat(Z[0],Y),"=",Z[2]];if(Z[1]==="?")return[Y.$.parseOwnDefinitionFormat(Z[0],Y),"?"]}return C8(Z,Y)},hz="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",gz="Only required keys may specify default values, e.g. { value: 'number = 0' }";var uz=(Z,Y)=>{let X,Q={},$=D9(Z);for(let[J,z]of $){let V=SF(J);if(V.kind==="spread"){if(!N0(Q))return L(CF);let K=Y.$.parseOwnDefinitionFormat(z,Y);if(K.equals(C.object))continue;if(!K.hasKind("intersection")||!K.basis?.equals(C.object))return L(_F(K.expression));X=K.structure;continue}if(V.kind==="undeclared"){if(z!=="reject"&&z!=="delete"&&z!=="ignore")L(jF(z));Q.undeclared=z;continue}let q=j8(z,Y),U=V;if(V.kind==="required"){if(!n(q))v7(Q,"required",{key:V.normalized,value:q},Y);else v7(Q,"optional",q[1]==="="?{key:V.normalized,value:q[0],default:q[2]}:{key:V.normalized,value:q[0]},Y);continue}if(n(q)){if(q[1]==="?")L(hz);if(q[1]==="=")L(gz)}if(V.kind==="optional"){v7(Q,"optional",{key:V.normalized,value:q},Y);continue}let H=Y.$.parseOwnDefinitionFormat(U.normalized,Y),G=F8(H,q,Y.$);if(G.index)Q.index=h(Q.index,G.index);if(G.required)Q.required=h(Q.required,G.required)}let W=Y.$.node("structure",Q);return Y.$.parseSchema({domain:"object",structure:X?.merge(W)??W})},v7=(Z,Y,X,Q)=>{Z[Y]=h(Z[Y],Q.$.node(Y,X))},jF=(Z)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${x(Z)})`,CF="Spread operator may only be used as the first key in an object",SF=(Z)=>typeof Z==="symbol"?{kind:"required",normalized:Z}:Z[Z.length-1]==="?"?Z[Z.length-2]===E9?{kind:"required",normalized:`${Z.slice(0,-2)}?`}:{kind:"optional",normalized:Z.slice(0,-1)}:Z[0]==="["&&Z[Z.length-1]==="]"?{kind:"index",normalized:Z.slice(1,-1)}:Z[0]===E9&&Z[1]==="["&&Z[Z.length-1]==="]"?{kind:"required",normalized:Z.slice(1)}:Z==="..."?{kind:"spread"}:Z==="+"?{kind:"undeclared"}:{kind:"required",normalized:Z==="\\..."?"...":Z==="\\+"?"+":Z},_F=(Z)=>`Spread operand must resolve to an object literal type (was ${Z})`;var pz=(Z,Y)=>mF(Z)?iz[Z[0]](Z,Y):gF(Z)?lz[Z[1]](Z,Y):null,yF=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[1],Y).keyof(),f7=(Z,Y)=>{if(Z[2]===void 0)return L(C7(Z[1],""));let X=Y.$.parseOwnDefinitionFormat(Z[0],Y),Q=Y.$.parseOwnDefinitionFormat(Z[2],Y);if(Z[1]==="|")return Y.$.node("union",{branches:[X,Q]});let $=Z[1]==="&"?p1(X,Q,Y.$):S6(X,Q,Y.$);if($ instanceof w)return $.throw();return $},bF=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[0],Y).array(),xF=(Z,Y)=>{if(typeof Z[2]!=="function")return L(dz("=>",Z[2]));return Y.$.parseOwnDefinitionFormat(Z[0],Y).pipe(Z[2])},dz=(Z,Y)=>`${Z===":"?"Narrow":"Morph"} expression requires a function following '${Z}' (was ${typeof Y})`,kF=(Z,Y)=>{if(typeof Z[2]!=="function")return L(dz(":",Z[2]));return Y.$.parseOwnDefinitionFormat(Z[0],Y).constrain("predicate",Z[2])},vF=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[0],Y).configure(Z[2],Z[3]),cz=(Z)=>Z,fF=cz({"[]":bF,"?":()=>L(E8)}),hF=cz({"|":f7,"&":f7,":":kF,"=>":xF,"|>":f7,"@":vF,"=":()=>L(O8)}),lz={...fF,...hF},gF=(Z)=>lz[Z[1]]!==void 0,uF=(Z)=>Z,iz=uF({keyof:yF,instanceof:(Z,Y)=>{if(typeof Z[1]!=="function")return L(mz(N6(Z[1])));let X=Z.slice(1).map((Q)=>typeof Q==="function"?Y.$.node("proto",{proto:Q}):L(mz(N6(Q))));return X.length===1?X[0]:Y.$.node("union",{branches:X})},"===":(Z,Y)=>Y.$.units(Z.slice(1))}),mF=(Z)=>iz[Z[0]]!==void 0,mz=(Z)=>`Expected a constructor following 'instanceof' operator (was ${Z})`;var az=(Z,Y)=>{let X=[{}],Q=0;while(Q<Z.length){let $=!1;if(Z[Q]==="..."&&Q<Z.length-1)$=!0,Q++;let W=j8(Z[Q],Y),[J,z,V]=!n(W)?[W]:W;if(Q++,$){if(!J.extends(F.intrinsic.Array))return L(cF(J.expression));X=X.flatMap((q)=>J.distribute((U)=>dF(J8(q),U)))}else X=X.map((q)=>{if(z==="?")return rz(q,J);if(z==="=")return pF(q,J,V);return h7(q,J)})}return Y.$.parseSchema(X.map(($)=>N0($)?{proto:Array,exactLength:0}:{proto:Array,sequence:$}))},h7=(Z,Y)=>{if(Z.defaultables||Z.optionals)return L(Z.variadic?M7:lF);if(Z.variadic)Z.postfix=h(Z.postfix,Y);else Z.prefix=h(Z.prefix,Y);return Z},rz=(Z,Y)=>{if(Z.variadic)return L(sz);return Z.optionals=h(Z.optionals,Y),Z},pF=(Z,Y,X)=>{if(Z.variadic)return L(sz);if(Z.optionals)return L(iF);return Z.defaultables=h(Z.defaultables,[[Y,X]]),Z},oz=(Z,Y)=>{if(Z.postfix)L(nz);if(Z.variadic){if(!Z.variadic.equals(Y))L(nz)}else Z.variadic=Y.internal;return Z},dF=(Z,Y)=>{let X=Y.select({method:"find",kind:"sequence"});if(!X)return oz(Z,F.intrinsic.unknown);if(X.prefix)for(let Q of X.prefix)h7(Z,Q);if(X.optionals)for(let Q of X.optionals)rz(Z,Q);if(X.variadic)oz(Z,X.variadic);if(X.postfix)for(let Q of X.postfix)h7(Z,Q);return Z},cF=(Z)=>`Spread element must be an array (was ${Z})`,nz="A tuple may have at most one variadic element",lF="A required element may not follow an optional element",sz="An optional element may not follow a variadic element";var iF="A defaultable element may not follow an optional element without a default";var oF={},C8=(Z,Y)=>{if(typeof Z==="string"){if(Y.args&&Object.keys(Y.args).some((Q)=>Z.includes(Q)))return b7(Z,Y);let X=oF[Y.$.name]??={};return X[Z]??=b7(Z,Y)}return v1(Z,"object")?nF(Z,Y):L(g7(F1(Z)))},nF=(Z,Y)=>{let X=F6(Z);switch(X){case void 0:if(P(Z,"root"))return Z;if("~standard"in Z)return aF(Z,Y);return uz(Z,Y);case"Array":return rF(Z,Y);case"RegExp":return Y.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0});case"Function":{let Q=a0(Z)?Z():Z;if(P(Q,"root"))return Q;return L(g7("Function"))}default:return L(g7(X??x(Z)))}},aF=(Z,Y)=>Y.$.intrinsic.unknown.pipe((X,Q)=>{let $=Z["~standard"].validate(X);if(!$.issues)return $.value;for(let{message:W,path:J}of $.issues)if(J)if(J.length)Q.error({problem:vW(W),relativePath:J.map((z)=>typeof z==="object"?z.key:z)});else Q.error({message:W});else Q.error({message:W})}),rF=(Z,Y)=>pz(Z,Y)??az(Z,Y),g7=(Z)=>`Type definitions must be strings or objects (was ${Z})`;class u7 extends g1{constructor(Z){let Y=Object.assign({errors:u1,hkt:T1,$:Z,raw:Z.parse,module:Z.constructor.module,scope:Z.constructor.scope,declare:Z.declare,define:Z.define,match:Z.match,generic:Z.generic,schema:Z.schema,keywords:Z.ambient,unit:Z.unit,enumerated:Z.enumerated,instanceOf:Z.instanceOf,valueOf:Z.valueOf,or:Z.or,and:Z.and,merge:Z.merge,pipe:Z.pipe,fn:Z.fn},Z.ambientAttachments);super((...X)=>{if(X.length===1)return Z.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0][X[0].length-1]===">"){let Q=X[0].slice(1,-1),$=Z.parseGenericParams(Q,{});return new Z9($,X[1],Z,Z,null)}return Z.parse(X)},{attach:Y})}}var q2=F;class S8 extends N8{get ambientAttachments(){if(!q2.typeAttachments)return;return this.cacheGetter("ambientAttachments",b(q2.typeAttachments,(Z,Y)=>[Z,this.bindReference(Y)]))}preparseOwnAliasEntry(Z,Y){let X=Z.indexOf("<");if(X===-1){if(P(Y,"module")||P(Y,"generic"))return[Z,Y];let W=this.name==="ark"?Z:Z==="root"?this.name:`${this.name}.${Z}`,J=this.resolvedConfig.keywords?.[W];if(J)Y=[Y,"@",J];return[Z,Y]}if(Z[Z.length-1]!==">")L("'>' must be the last character of a generic declaration in a scope");let Q=Z.slice(0,X),$=Z.slice(X+1,-1);return[Q,()=>{let W=this.parseGenericParams($,{alias:Q});return UJ(W,Y,this)}]}parseGenericParams(Z,Y){return R8(new T6(Z),[],this.createParseContext({...Y,def:Z,prefix:"generic"}))}normalizeRootScopeValue(Z){if(a0(Z)&&!P(Z,"generic"))return Z();return Z}preparseOwnDefinitionFormat(Z,Y){return{...Y,def:Z,prefix:Y.alias??"type"}}parseOwnDefinitionFormat(Z,Y){if(!(Y.alias&&(Y.alias in this.aliases))&&!Y.args)Y.args={this:Y.id};let Q=C8(Z,Y);if(n(Q)){if(Q[1]==="=")return L(O8);if(Q[1]==="?")return L(E8)}return Q}unit=(Z)=>this.units([Z]);valueOf=(Z)=>this.units(RW(Z));enumerated=(...Z)=>this.units(Z);instanceOf=(Z)=>this.node("proto",{proto:Z},{prereduced:!0});or=(...Z)=>this.schema(Z.map((Y)=>this.parse(Y)));and=(...Z)=>Z.reduce((Y,X)=>Y.and(this.parse(X)),this.intrinsic.unknown);merge=(...Z)=>Z.reduce((Y,X)=>Y.merge(this.parse(X)),this.intrinsic.object);pipe=(...Z)=>this.intrinsic.unknown.pipe(...Z);fn=new x7(this);match=new k7(this);declare=()=>({type:this.type});define(Z){return Z}type=new u7(this);static scope=(Z,Y={})=>new S8(Z,Y);static module=(Z,Y={})=>this.scope(Z,Y).export()}var m7=Object.assign(S8.scope,{define:(Z)=>Z}),f=S8;class tz extends T1{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var sF=J0(["base",C.object],["props",C.object])((Z)=>Z.base.merge(Z.props),tz),ez=f.module({Key:C.key,Merge:sF});class ZV extends T1{}var tF=J0("element")((Z)=>{let Y=Z.element.exclude(C.Array),X=Y.array();return Y.rawOr(X).pipe(n0).distribute((Q)=>Q.assertHasKind("morph").declareOut(X),c)},ZV),YV=f.module({root:C.Array,readonly:"root",index:C.nonNegativeIntegerString,liftFrom:tF},{name:"Array"});var p7=c(["string",O9.FileConstructor]),eF=p7.rawOr(p7.array()),XV=c({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:eF}}),QV=f.module({root:["instanceof",FormData],value:p7,parsed:XV,parse:c({in:FormData,morphs:(Z)=>{let Y={};for(let[X,Q]of Z)if(X in Y){let $=Y[X];if(typeof $==="string"||$ instanceof O9.FileConstructor)Y[X]=[$,Q];else $.push(Q)}else Y[X]=Q;return Y},declaredOut:XV})},{name:"FormData"});var $V=f.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var ZN={Boolean:1,Number:1,String:1},WV=f.module({...b({...CY,..._Y},(Z,Y)=>(Z in ZN)?[]:[Z,["instanceof",Y]]),Array:YV,TypedArray:$V,FormData:QV});var YN=c({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),XN=c({domain:"number",divisor:1}),_8=f.module({root:C.number,integer:XN,epoch:YN,safe:c({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var e=(Z,Y,X)=>{let Q={domain:"string",pattern:{rule:Z.source,flags:Z.flags,meta:Y}};if(X)Q.meta={format:X};return J2("intersection",Q)},JV=e(D6,"a well-formed integer string"),NV=f.module({root:JV,parse:c({in:JV,morphs:(Z,Y)=>{let X=Number.parseInt(Z);return Number.isSafeInteger(X)?X:Y.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:C.integer})},{name:"string.integer"}),QN=e(/^[\dA-Fa-f]+$/,"hex characters only"),$N=f.module({root:e(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:e(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),zV=e(/^[A-Z].*$/,"capitalized"),WN=f.module({root:c({in:"string",morphs:(Z)=>Z.charAt(0).toUpperCase()+Z.slice(1),declaredOut:zV}),preformatted:zV},{name:"string.capitalize"}),JN=(Z)=>{let Y=Z.replace(/[ -]+/g,""),X=0,Q,$,W=!1;for(let J=Y.length-1;J>=0;J--){if(Q=Y.substring(J,J+1),$=Number.parseInt(Q,10),W)$*=2,X+=$>=10?$%10+1:$;else X+=$;W=!W}return!!(X%10===0?Y:!1)},zN=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,VN=c({domain:"string",pattern:{meta:"a credit card number",rule:zN.source},predicate:{meta:"a credit card number",predicate:JN}});var qN=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var UN=(Z)=>!Number.isNaN(new Date(Z).valueOf()),VV=c({domain:"string",predicate:{meta:"a parsable date",predicate:UN}}).assertHasKind("intersection"),qV=NV.root.internal.narrow((Z,Y)=>{let X=Number.parseInt(Z),Q=_8.epoch(X);if(Q instanceof u1)return Y.errors.merge(Q),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),HN=f.module({root:qV,parse:c({in:qV,morphs:(Z)=>new Date(Z),declaredOut:C.Date})},{name:"string.date.epoch"}),UV=e(qN,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),GN=f.module({root:UV,parse:c({in:UV,morphs:(Z)=>new Date(Z),declaredOut:C.Date})},{name:"string.date.iso"}),KN=f.module({root:VV,parse:c({declaredIn:VV,in:"string",morphs:(Z,Y)=>{let X=new Date(Z);if(Number.isNaN(X.valueOf()))return Y.error("a parsable date");return X},declaredOut:C.Date}),iso:GN,epoch:HN},{name:"string.date"}),BN=e(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),HV="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Y9=`(${HV}[.]){3}${HV}`,LN=new RegExp(`^${Y9}$`),G1="(?:[0-9a-fA-F]{1,4})",MN=new RegExp(`^((?:${G1}:){7}(?:${G1}|:)|(?:${G1}:){6}(?:${Y9}|:${G1}|:)|(?:${G1}:){5}(?::${Y9}|(:${G1}){1,2}|:)|(?:${G1}:){4}(?:(:${G1}){0,1}:${Y9}|(:${G1}){1,3}|:)|(?:${G1}:){3}(?:(:${G1}){0,2}:${Y9}|(:${G1}){1,4}|:)|(?:${G1}:){2}(?:(:${G1}){0,3}:${Y9}|(:${G1}){1,5}|:)|(?:${G1}:){1}(?:(:${G1}){0,4}:${Y9}|(:${G1}){1,6}|:)|(?::((?::${G1}){0,5}:${Y9}|(?::${G1}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),FN=f.module({root:["v4 | v6","@","an IP address"],v4:e(LN,"an IPv4 address","ipv4"),v6:e(MN,"an IPv6 address","ipv6")},{name:"string.ip"}),U2="a JSON string",wV=(Z)=>{if(!(Z instanceof SyntaxError))throw Z;return`must be ${U2} (${Z})`},NN=c({meta:U2,domain:"string",predicate:{meta:U2,predicate:(Z,Y)=>{try{return JSON.parse(Z),!0}catch(X){return Y.reject({code:"predicate",expected:U2,problem:wV(X)})}}}}),wN=(Z,Y)=>{if(Z.length===0)return Y.error({code:"predicate",expected:U2,actual:"empty"});try{return JSON.parse(Z)}catch(X){return Y.error({code:"predicate",expected:U2,problem:wV(X)})}},DN=f.module({root:NN,parse:c({meta:"safe JSON string parser",in:"string",morphs:wN,declaredOut:C.jsonObject})},{name:"string.json"}),GV=e(/^[a-z]*$/,"only lowercase letters"),AN=f.module({root:c({in:"string",morphs:(Z)=>Z.toLowerCase(),declaredOut:GV}),preformatted:GV},{name:"string.lower"}),DV=["NFC","NFD","NFKC","NFKD"],d6=b(DV,(Z,Y)=>[Y,c({domain:"string",predicate:(X)=>X.normalize(Y)===X,meta:`${Y}-normalized unicode`})]),y8=b(DV,(Z,Y)=>[Y,c({in:"string",morphs:(X)=>X.normalize(Y),declaredOut:d6[Y]})]),EN=f.module({root:y8.NFC,preformatted:d6.NFC},{name:"string.normalize.NFC"}),ON=f.module({root:y8.NFD,preformatted:d6.NFD},{name:"string.normalize.NFD"}),PN=f.module({root:y8.NFKC,preformatted:d6.NFKC},{name:"string.normalize.NFKC"}),TN=f.module({root:y8.NFKD,preformatted:d6.NFKD},{name:"string.normalize.NFKD"}),IN=f.module({root:"NFC",NFC:EN,NFD:ON,NFKC:PN,NFKD:TN},{name:"string.normalize"}),KV=e(X8,"a well-formed numeric string"),RN=f.module({root:KV,parse:c({in:KV,morphs:(Z)=>Number.parseFloat(Z),declaredOut:C.number})},{name:"string.numeric"}),BV="a regex pattern",jN=c({domain:"string",predicate:{meta:BV,predicate:(Z,Y)=>{try{return new RegExp(Z),!0}catch(X){return Y.reject({code:"predicate",expected:BV,problem:String(X)})}}},meta:{format:"regex"}}),CN=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,SN=e(CN,"a semantic version (see https://semver.org/)"),LV=e(/^\S.*\S$|^\S?$/,"trimmed"),_N=f.module({root:c({in:"string",morphs:(Z)=>Z.trim(),declaredOut:LV}),preformatted:LV},{name:"string.trim"}),MV=e(/^[A-Z]*$/,"only uppercase letters"),yN=f.module({root:c({in:"string",morphs:(Z)=>Z.toUpperCase(),declaredOut:MV}),preformatted:MV},{name:"string.upper"}),bN=(Z)=>URL.canParse(Z),FV=c({domain:"string",predicate:{meta:"a URL string",predicate:bN},meta:{format:"uri"}}),xN=f.module({root:FV,parse:c({declaredIn:FV,in:"string",morphs:(Z,Y)=>{try{return new URL(Z)}catch{return Y.error("a URL string")}},declaredOut:c(URL)})},{name:"string.url"}),kN=f.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:e(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:e(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:e(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:e(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:e(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:e(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:e(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:e(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),AV=f.module({root:C.string,alpha:e(/^[A-Za-z]*$/,"only letters"),alphanumeric:e(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:QN,base64:$N,capitalize:WN,creditCard:VN,date:KN,digits:e(/^\d*$/,"only digits 0-9"),email:BN,integer:NV,ip:FN,json:DN,lower:AN,normalize:IN,numeric:RN,regex:jN,semver:SN,trim:_N,upper:yN,url:xN,uuid:kN},{name:"string"});var EV=f.module({bigint:C.bigint,boolean:C.boolean,false:C.false,never:C.never,null:C.null,number:C.number,object:C.object,string:C.string,symbol:C.symbol,true:C.true,unknown:C.unknown,undefined:C.undefined}),OV=f.module({root:C.unknown,any:C.unknown},{name:"unknown"}),vN=f.module({root:C.jsonObject,stringify:J2("morph",{in:C.jsonObject,morphs:(Z)=>JSON.stringify(Z),declaredOut:C.string})},{name:"object.json"}),PV=f.module({root:C.object,json:vN},{name:"object"});class TV extends T1{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var fN=J0(["K",C.key],"V")((Z)=>({domain:"object",index:{signature:Z.K,value:Z.V}}),TV);class IV extends T1{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var hN=J0(["T",C.object],["K",C.key])((Z)=>Z.T.pick(Z.K),IV);class RV extends T1{description='omit a set of properties from an object like `Omit(User, "age")`'}var gN=J0(["T",C.object],["K",C.key])((Z)=>Z.T.omit(Z.K),RV);class jV extends T1{description="make all named properties of an object optional like `Partial(User)`"}var uN=J0(["T",C.object])((Z)=>Z.T.partial(),jV);class CV extends T1{description="make all named properties of an object required like `Required(User)`"}var mN=J0(["T",C.object])((Z)=>Z.T.required(),CV);class SV extends T1{description='exclude branches of a union like `Exclude("boolean", "true")`'}var pN=J0("T","U")((Z)=>Z.T.exclude(Z.U),SV);class _V extends T1{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var dN=J0("T","U")((Z)=>Z.T.extract(Z.U),_V),yV=f.module({Exclude:pN,Extract:dN,Omit:gN,Partial:uN,Pick:hN,Record:fN,Required:mN});var g0=m7({...EV,...yV,...WV,...ez,string:AV,number:_8,object:PV,unknown:OV},{prereducedAliases:!0,name:"ark"}),w1=g0.export();Object.assign(q2.ambient,w1);q2.typeAttachments={string:w1.string.root,number:w1.number.root,bigint:w1.bigint,boolean:w1.boolean,symbol:w1.symbol,undefined:w1.undefined,null:w1.null,object:w1.object.root,unknown:w1.unknown.root,false:w1.false,true:w1.true,never:w1.never,arrayIndex:w1.Array.index,Key:w1.Key,Record:w1.Record,Array:w1.Array.root,Date:w1.Date};var K1=Object.assign(g0.type,q2.typeAttachments),cN=g0.match,lN=g0.fn,iN=g0.generic,Ov=g0.schema,oN=g0.define,nN=g0.declare;var mv=K1("'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'"),bV=K1({summary:"string",purpose:"string",scope:"'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'",affectedAreas:"string[]","suggestedReviewOrder?":"string[]"}),pv=K1("'low' | 'medium' | 'high' | 'critical'"),dv=K1("'high' | 'medium' | 'low'"),aN=K1({severity:"'low' | 'medium' | 'high' | 'critical'",category:"string",description:"string",evidence:"string","file?":"string","mitigation?":"string"}),b8=K1({overallRisk:"'low' | 'medium' | 'high' | 'critical'",summary:"string",risks:aN.array(),confidence:"'high' | 'medium' | 'low'"}),xV=K1({alignment:"'aligned' | 'partial' | 'misaligned'",confidence:"'high' | 'medium' | 'low'",summary:"string",matches:"string[]",mismatches:"string[]",missing:"string[]",unstated:"string[]"}),rN=K1({name:"string",description:"string",files:"string[]",priority:"number"}),cv=K1({flows:rN.array(),uncategorized:"string[]"});function s1(Z){let Y=Z["~standard"];if(!Y)throw new Error("Schema does not have ~standard property. Is this an ArkType schema?");return{"~standard":Y}}function I9(Z){if(Z.status!=="deleted")return!1;return Z.hunks.reduce((X,Q)=>X+Q.lines.filter(($)=>$.type==="delete").length,0)>100}function sN(Z,Y){let X=[];if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(Y)){let Q=Z.matchAll(/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)/gm);for(let q of Q)X.push(`class ${q[1]}`);let $=Z.matchAll(/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+(\w+)/gm);for(let q of $)X.push(`function ${q[1]}()`);let W=Z.matchAll(/^export\s+const\s+(\w+)\s*=/gm);for(let q of W)X.push(`const ${q[1]}`);let J=Z.matchAll(/^(?:export\s+)?interface\s+(\w+)/gm);for(let q of J)X.push(`interface ${q[1]}`);let z=Z.matchAll(/^(?:export\s+)?type\s+(\w+)\s*=/gm);for(let q of z)X.push(`type ${q[1]}`);let V=Z.matchAll(/^export\s+\{([^}]+)\}/gm);for(let q of V){let U=q[1];if(U){let H=U.split(",").map((G)=>G.trim().split(/\s+as\s+/)[0]?.trim()).filter(Boolean);if(H.length>0)X.push(`export { ${H.join(", ")} }`)}}}if(Y===".py"){let Q=Z.matchAll(/^class\s+(\w+)/gm);for(let W of Q)X.push(`class ${W[1]}`);let $=Z.matchAll(/^(?:async\s+)?def\s+(\w+)/gm);for(let W of $)X.push(`def ${W[1]}()`)}return X}function x8(Z){let Y=Z.hunks.flatMap((Q)=>Q.lines.filter(($)=>$.type==="delete").map(($)=>$.content)),X=kV(Z.path);return{headerLines:Y.slice(0,15),signatures:sN(Y.join(`
133
+ `),X),totalLines:Y.length}}function k8(Z,Y){let X=kV(Z.path),Q=tN(X),$=[`DELETED FILE: ${Z.path} (${Y.totalLines} lines)`,"",`First ${Y.headerLines.length} lines (header/imports):`,"```"+Q,...Y.headerLines,"```"];if(Y.signatures.length>0){$.push(""),$.push("Extracted signatures:");for(let W of Y.signatures)$.push(`- ${W}`)}return $.join(`
134
+ `)}function kV(Z){let Y=Z.lastIndexOf(".");if(Y===-1)return"";return Z.slice(Y).toLowerCase()}function tN(Z){return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".rs":"rust",".go":"go",".java":"java",".rb":"ruby",".css":"css",".scss":"scss",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown"}[Z]||""}function eN(Z){let Y=[Z.header];for(let X of Z.lines){let Q=X.type==="add"?"+":X.type==="delete"?"-":" ";Y.push(`${Q}${X.content}`)}return Y.join(`
135
+ `)}function X9(Z){if(I9(Z)){let Q=x8(Z);return k8(Z,Q)}let Y=[],X=Z.status.toUpperCase();if(Z.status==="renamed"&&Z.oldPath)Y.push(`=== ${Z.oldPath} → ${Z.path} (${X}) ===`);else Y.push(`=== ${Z.path} (${X}) ===`);if(Z.isBinary)return Y.push("[binary file]"),Y.join(`
136
+ `);for(let Q of Z.hunks)Y.push(eN(Q));return Y.join(`
137
+ `)}var Zw=`You are an experienced code reviewer analyzing a diff to understand its intent.
138
+
139
+ Your goal is to determine:
140
+ 1. WHAT the change does (summary)
141
+ 2. WHY it's being made (purpose)
142
+ 3. What category it falls into (scope)
143
+ 4. What parts of the codebase are affected
144
+
145
+ ## Key Principles
146
+
147
+ - **Explain WHY, not just WHAT**: Don't just describe the changes - explain their purpose
148
+ - **Be specific and concrete**: "Adds rate limiting to /api/users" is better than "improves API"
149
+ - **Consider the reviewer**: What would help someone understand this change quickly?
150
+ - **Suggest reading order**: Which files should a reviewer look at first?
151
+
152
+ ## When Stated Intent is Provided
153
+
154
+ If the author has provided their stated intent, use it as additional context:
155
+ - It may clarify ambiguous changes
156
+ - It may reveal the "why" behind the change
157
+ - But derive intent from the CODE, not just the stated intent
158
+ - The stated intent could be incomplete or misleading
159
+
160
+ ## Scope Definitions
161
+
162
+ - **feature**: New functionality or capability
163
+ - **bugfix**: Fixing incorrect behavior
164
+ - **refactor**: Code restructuring without behavior change
165
+ - **config**: Build, tooling, CI/CD, or environment changes
166
+ - **docs**: Documentation updates only
167
+ - **test**: Test additions or modifications only
168
+ - **mixed**: Combines multiple categories (common in real changes)
169
+
170
+ ## Context Limitations
171
+
172
+ You are analyzing a diff, not the complete codebase. This means:
173
+ - Imports may reference files that exist but aren't shown in the diff
174
+ - Functions may be defined in files you can't see
175
+ - Types may be declared elsewhere
176
+ - New files created in this change may appear as imports but not as full file contents
177
+
178
+ Focus on understanding the intent from what IS visible in the diff. Don't flag concerns about code you can't see - assume referenced files and symbols exist unless there's clear evidence otherwise.`;function Yw(Z,Y,X,Q){let $=Y.filter((z)=>z.tier<=2),W=[];W.push("## Diff Overview"),W.push(`Total files changed: ${Z.files.length}`),W.push(`Files included for analysis: ${$.length}`);let J=Y.filter((z)=>z.tier===3).length;if(J>0)W.push(`(${J} files excluded: lock files, generated code, binaries)`);if(W.push(""),Q)W.push(Q),W.push("");W.push("## Files Changed");for(let z of $){let V=z.file.status;W.push(`- ${z.file.path} (${V})`)}W.push(""),W.push("## Diff Content"),W.push("");for(let z of $)W.push(X9(z.file)),W.push("");if(X)W.push("## Author's Stated Intent"),W.push(""),W.push(X),W.push(""),W.push("Use this as context for understanding the change, but derive intent from the actual code changes."),W.push("");return W.push("---"),W.push(`Analyze this diff and provide the intent analysis. Focus on WHY, not just WHAT.
179
+
180
+ REQUIRED OUTPUT FIELDS (all are mandatory):
181
+ - summary: string - 1-2 sentence summary of what the change does
182
+ - purpose: string - the WHY behind this change
183
+ - scope: "feature" | "bugfix" | "refactor" | "config" | "docs" | "test" | "mixed"
184
+ - affectedAreas: string[] - high-level areas of the codebase touched
185
+
186
+ OPTIONAL FIELDS:
187
+ - suggestedReviewOrder: string[] - suggested order to review files`),W.join(`
188
+ `)}async function H2(Z,Y,X,Q){let $=Yw(Z,Y,X,Q);try{return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[Zw],messages:[{role:"user",content:$}],outputSchema:s1(bV),temperature:0.3,stream:!1,maxTokens:4096})}catch(W){if(W instanceof Error&&W.message.includes("Validation failed")){let J=new Error(`${W.message}
189
+
190
+ This usually means the LLM response was missing required fields. Check that the diff wasn't too large (${Z.files.length} files, ${Y.filter((z)=>z.tier<=2).length} analyzed).`);throw J.cause=W,J}throw W}}var Xw=`You are a security-minded senior code reviewer analyzing a diff for potential risks.
191
+
192
+ Your goal is to identify concrete risks in this change - things that could go wrong in production, security vulnerabilities, breaking changes, or issues that could cause problems for users or the codebase.
193
+
194
+ ## Key Principles
195
+
196
+ - **Cite specific evidence**: Every risk MUST reference specific code from the diff. "Line 45 removes the null check before calling .toLowerCase()" is good. "Error handling could be better" is useless.
197
+
198
+ - **Don't cry wolf**: Not every change is risky. If the code looks fine, say so. Flagging non-issues creates alert fatigue and makes real issues harder to spot.
199
+
200
+ - **Be calibrated on severity**:
201
+ - **critical**: Must fix before merge. Security vulnerabilities, data loss, auth bypass.
202
+ Example: "Removed password hashing - passwords will be stored in plaintext"
203
+ - **high**: Likely to cause production issues if not addressed.
204
+ Example: "Missing null check will throw NPE when optional field is absent"
205
+ - **medium**: Should be reviewed carefully, may need changes.
206
+ Example: "API response format changed - clients may need updates"
207
+ - **low**: Worth noting but unlikely to cause problems.
208
+ Example: "New dependency added - should verify it's actively maintained"
209
+
210
+ - **Consider the full picture**: Think about:
211
+ - Breaking changes (API signatures, removed exports, changed behavior)
212
+ - Security (auth, input validation, secrets, injection)
213
+ - Error handling (uncaught exceptions, missing error paths)
214
+ - Performance (N+1 queries, unbounded loops, missing pagination)
215
+ - Backwards compatibility (migrations, protocol changes)
216
+ - Test coverage (removed tests, untested paths)
217
+
218
+ ## Risk Categories
219
+
220
+ Use these categories for consistency:
221
+ - security: Auth, secrets, injection, validation
222
+ - breaking-change: API changes, removed exports, changed contracts
223
+ - performance: N+1, unbounded operations, missing indexes
224
+ - error-handling: Missing catches, unhandled cases, error propagation
225
+ - backwards-compatibility: Migrations, protocol changes, data format changes
226
+ - test-coverage: Removed tests, untested risky paths
227
+ - data-integrity: Race conditions, partial updates, validation gaps
228
+ - maintainability: Complexity, coupling, undocumented behavior (use sparingly)
229
+
230
+ ## When Stated Intent is Provided
231
+
232
+ If the author has stated their intent, consider whether risks relate to:
233
+ - Gaps between stated intent and actual implementation
234
+ - Security/safety issues in how the stated goal is achieved
235
+ - Missing validation or error handling for the stated use case
236
+
237
+ ## Context Limitations
238
+
239
+ You are analyzing a diff, not the complete codebase. This means:
240
+ - Imports may reference files that exist but aren't shown in the diff
241
+ - Functions may be defined in files you can't see
242
+ - Types may be declared elsewhere
243
+ - New files created in this change may appear as imports but not as full file contents
244
+
245
+ When you see something that MIGHT be an issue but could be fine with full context:
246
+ - Don't flag it as critical/high severity
247
+ - Either skip it entirely, or note it as low severity with "may be resolved by unseen context"
248
+ - Focus on issues that are clearly evident FROM the diff itself
249
+
250
+ ## Output Quality
251
+
252
+ - Order risks by severity (critical first)
253
+ - Keep descriptions concise but specific
254
+ - If a risk has a clear mitigation, include it
255
+ - If you're uncertain, reflect that in confidence level`;function Qw(Z,Y,X,Q){let $=Y.filter((z)=>z.tier<=2),W=[];W.push("## Diff Overview"),W.push(`Total files changed: ${Z.files.length}`),W.push(`Files included for analysis: ${$.length}`);let J=Y.filter((z)=>z.tier===3);if(J.length>0){W.push(`(${J.length} files excluded from analysis: lock files, generated code, binaries)`);let z=J.filter((V)=>V.file.path.includes(".test.")||V.file.path.includes(".spec."));if(z.length>0)W.push(`Note: ${z.length} test file(s) were in excluded category`)}if(W.push(""),Q)W.push(Q),W.push("");W.push("## Files Changed");for(let z of $){let V=z.file.status;W.push(`- ${z.file.path} (${V})`)}W.push(""),W.push("## Diff Content"),W.push("");for(let z of $)W.push(X9(z.file)),W.push("");if(X)W.push("## Author's Stated Intent"),W.push(""),W.push(X),W.push(""),W.push("Consider whether any risks relate to gaps between this stated intent and the actual implementation."),W.push("");return W.push("---"),W.push(`Analyze this diff for potential risks.
256
+
257
+ Requirements:
258
+ 1. For each risk, cite SPECIFIC evidence from the diff (file, line, code snippet)
259
+ 2. Only flag issues that have concrete evidence - no generic warnings
260
+ 3. If the change looks safe, it's okay to return an empty risks array
261
+ 4. Order risks by severity (critical/high first)
262
+ 5. Set confidence based on how much context you have
263
+
264
+ REQUIRED OUTPUT FIELDS (all are mandatory):
265
+ - overallRisk: "low" | "medium" | "high" | "critical" - the highest severity among all risks (use "low" if no risks)
266
+ - summary: string - 1-2 sentence actionable summary
267
+ - risks: array of risk objects (can be empty array [] if no risks found)
268
+ - confidence: "high" | "medium" | "low" - how confident you are in this assessment
269
+
270
+ Each risk object MUST have:
271
+ - severity: "low" | "medium" | "high" | "critical"
272
+ - category: string (e.g., "security", "breaking-change", "performance")
273
+ - description: string - what the risk is
274
+ - evidence: string - specific code/line from the diff`),W.join(`
275
+ `)}async function G2(Z,Y,X,Q){let $=Qw(Z,Y,X,Q);try{return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[Xw],messages:[{role:"user",content:$}],outputSchema:s1(b8),temperature:0.4,stream:!1,maxTokens:8192})}catch(W){if(W instanceof Error&&W.message.includes("Validation failed")){let J=new Error(`${W.message}
276
+
277
+ This usually means the LLM response was missing required fields. Check that the diff wasn't too large (${Z.files.length} files, ${Y.filter((z)=>z.tier<=2).length} analyzed).`);throw J.cause=W,J}throw W}}var $w=`You are comparing what an author claims their code change does (stated intent) against what it actually does (derived intent).
278
+
279
+ Your goal is to identify:
280
+ 1. Do the stated and derived intents align?
281
+ 2. What matches between claimed and actual behavior?
282
+ 3. What mismatches - where the code does something different than stated?
283
+ 4. What's missing - stated but not implemented?
284
+ 5. What's unstated - implemented but not mentioned (scope creep)?
285
+
286
+ ## Alignment Levels
287
+
288
+ - **aligned**: The code does what the author says, with no significant extra or missing pieces.
289
+ Use this when the stated intent accurately describes the changes.
290
+
291
+ - **partial**: Some aspects match, but there are notable gaps or additions.
292
+ Use when: core intent is correct but scope differs, or some stated items are missing.
293
+
294
+ - **misaligned**: The code does something substantially different than claimed.
295
+ Use when: stated intent is misleading, or changes don't match the stated goal.
296
+
297
+ ## Calibration Guidelines
298
+
299
+ - Be generous with "aligned" - minor wording differences don't matter
300
+ - "partial" is common - real changes often include cleanup/related fixes not mentioned
301
+ - "misaligned" should be rare - only when there's genuine mismatch of stated vs actual
302
+ - Vague stated intent ("misc fixes", "updates") should get medium/low confidence
303
+ - If stated intent is just a feature name with no details, focus on whether the feature exists
304
+
305
+ ## Evidence Requirements
306
+
307
+ For each item in matches/mismatches/missing/unstated, cite specific evidence:
308
+ - Good: "Added null check in UserService.ts:45 as stated"
309
+ - Good: "Error refactoring not mentioned but present in 3 files"
310
+ - Bad: "Some things match"
311
+ - Bad: "There might be missing features"
312
+
313
+ ## Context Limitations
314
+
315
+ You are comparing stated intent against a diff, not the complete codebase. This means:
316
+ - New files created in this change may not appear in the diff hunks
317
+ - Imports may reference files that exist but aren't shown
318
+ - If an import references a file that isn't visible, assume it likely exists
319
+
320
+ Don't flag "missing implementation" if the code imports from a file you can't see - it's probably implemented there. Focus on alignment issues evident from what IS visible.
321
+
322
+ ## Output Quality
323
+
324
+ - Keep summary to 1-2 sentences - the key finding
325
+ - Order matches/mismatches/missing/unstated by importance
326
+ - Empty arrays are fine - not every analysis will have all categories
327
+ - Set confidence based on how clear the comparison is`;function Ww(Z){let Y=[],X=Z.status.toUpperCase();if(Z.status==="renamed"&&Z.oldPath)Y.push(`=== ${Z.oldPath} → ${Z.path} (${X}) ===`);else Y.push(`=== ${Z.path} (${X}) ===`);if(Z.isBinary)return Y.push("[binary file]"),Y.join(`
328
+ `);for(let Q of Z.hunks)Y.push(Jw(Q));return Y.join(`
329
+ `)}function Jw(Z){let Y=[Z.header];for(let X of Z.lines){let Q=X.type==="add"?"+":X.type==="delete"?"-":" ";Y.push(`${Q}${X.content}`)}return Y.join(`
330
+ `)}function zw(Z,Y,X,Q,$){let W=[];if(W.push("## Author's Stated Intent"),W.push(""),W.push(Z),W.push(""),W.push("## Derived Intent (from diff analysis)"),W.push(""),W.push(`**Summary:** ${Y.summary}`),W.push(`**Purpose:** ${Y.purpose}`),W.push(`**Scope:** ${Y.scope}`),W.push(`**Affected Areas:** ${Y.affectedAreas.join(", ")}`),W.push(""),$)W.push($),W.push("");W.push("## Diff Content (for evidence)"),W.push("");let J=Q.filter((z)=>z.tier<=2);for(let z of J)W.push(Ww(z.file)),W.push("");return W.push("---"),W.push(""),W.push(`Compare the stated intent against the derived intent and the actual diff.
331
+
332
+ For each finding, cite specific evidence from the diff.
333
+
334
+ If the stated intent is vague, note that in the summary and set confidence accordingly.`),W.join(`
335
+ `)}async function v8(Z,Y,X,Q,$){let W=zw(Z,Y,X,Q,$);return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[$w],messages:[{role:"user",content:W}],outputSchema:s1(xV),temperature:0.3,stream:!1,maxTokens:4096})}class K2 extends Error{constructor(){super("ANTHROPIC_API_KEY environment variable is not set. Please set it to your Anthropic API key.");this.name="LLMAPIKeyError"}}class B2 extends Error{cause;constructor(Z,Y){super(Z);this.cause=Y;this.name="LLMGenerationError"}}function f8(){return!!process.env.ANTHROPIC_API_KEY}var m=E0(M2(),1);class t1 extends Error{code;constructor(Z,Y){super(Z);this.code=Y;this.name="GitHubError"}}import{dirname as rw}from"path";import{createRequire as Vw}from"module";import{spawn as qw}from"node:child_process";import{delimiter as vV,dirname as Uw,normalize as Hw,resolve as Gw}from"node:path";import{cwd as Kw}from"node:process";import{PassThrough as Bw}from"node:stream";import Lw from"node:readline";var{create:Mw,defineProperty:uV,getOwnPropertyDescriptor:Fw,getOwnPropertyNames:Nw,getPrototypeOf:ww}=Object,Dw=Object.prototype.hasOwnProperty,e1=(Z,Y)=>()=>(Y||Z((Y={exports:{}}).exports,Y),Y.exports),Aw=(Z,Y,X,Q)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(var $=Nw(Y),W=0,J=$.length,z;W<J;W++)if(z=$[W],!Dw.call(Z,z)&&z!==X)uV(Z,z,{get:((V)=>Y[V]).bind(null,z),enumerable:!(Q=Fw(Y,z))||Q.enumerable})}return Z},Ew=(Z,Y,X)=>(X=Z!=null?Mw(ww(Z)):{},Aw(Y||!Z||!Z.__esModule?uV(X,"default",{value:Z,enumerable:!0}):X,Z)),Q9=Vw(import.meta.url),Ow=/^path$/i,fV={key:"PATH",value:""};function Pw(Z){for(let Y in Z){if(!Object.prototype.hasOwnProperty.call(Z,Y)||!Ow.test(Y))continue;let X=Z[Y];if(!X)return fV;return{key:Y,value:X}}return fV}function Tw(Z,Y){let X=Y.value.split(vV),Q=Z,$;do X.push(Gw(Q,"node_modules",".bin")),$=Q,Q=Uw(Q);while(Q!==$);return{key:Y.key,value:X.join(vV)}}function Iw(Z,Y){let X={...process.env,...Y},Q=Tw(Z,Pw(X));return X[Q.key]=Q.value,X}var Rw=(Z)=>{let Y=Z.length,X=new Bw,Q=()=>{if(--Y===0)X.emit("end")};for(let $ of Z)$.pipe(X,{end:!1}),$.on("end",Q);return X},jw=e1((Z,Y)=>{Y.exports=W,W.sync=J;var X=Q9("fs");function Q(z,V){var q=V.pathExt!==void 0?V.pathExt:process.env.PATHEXT;if(!q)return!0;if(q=q.split(";"),q.indexOf("")!==-1)return!0;for(var U=0;U<q.length;U++){var H=q[U].toLowerCase();if(H&&z.substr(-H.length).toLowerCase()===H)return!0}return!1}function $(z,V,q){if(!z.isSymbolicLink()&&!z.isFile())return!1;return Q(V,q)}function W(z,V,q){X.stat(z,function(U,H){q(U,U?!1:$(H,z,V))})}function J(z,V){return $(X.statSync(z),z,V)}}),Cw=e1((Z,Y)=>{Y.exports=Q,Q.sync=$;var X=Q9("fs");function Q(z,V,q){X.stat(z,function(U,H){q(U,U?!1:W(H,V))})}function $(z,V){return W(X.statSync(z),V)}function W(z,V){return z.isFile()&&J(z,V)}function J(z,V){var{mode:q,uid:U,gid:H}=z,G=V.uid!==void 0?V.uid:process.getuid&&process.getuid(),K=V.gid!==void 0?V.gid:process.getgid&&process.getgid(),M=parseInt("100",8),E=parseInt("010",8),O=parseInt("001",8),T=M|E,i=q&O||q&E&&H===K||q&M&&U===G||q&T&&G===0;return i}}),Sw=e1((Z,Y)=>{var X=Q9("fs"),Q;if(process.platform==="win32"||global.TESTING_WINDOWS)Q=jw();else Q=Cw();Y.exports=$,$.sync=W;function $(J,z,V){if(typeof z==="function")V=z,z={};if(!V){if(typeof Promise!=="function")throw new TypeError("callback not provided");return new Promise(function(q,U){$(J,z||{},function(H,G){if(H)U(H);else q(G)})})}Q(J,z||{},function(q,U){if(q){if(q.code==="EACCES"||z&&z.ignoreErrors)q=null,U=!1}V(q,U)})}function W(J,z){try{return Q.sync(J,z||{})}catch(V){if(z&&z.ignoreErrors||V.code==="EACCES")return!1;else throw V}}}),_w=e1((Z,Y)=>{let X=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Q=Q9("path"),$=X?";":":",W=Sw(),J=(U)=>Object.assign(new Error(`not found: ${U}`),{code:"ENOENT"}),z=(U,H)=>{let G=H.colon||$,K=U.match(/\//)||X&&U.match(/\\/)?[""]:[...X?[process.cwd()]:[],...(H.path||process.env.PATH||"").split(G)],M=X?H.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",E=X?M.split(G):[""];if(X){if(U.indexOf(".")!==-1&&E[0]!=="")E.unshift("")}return{pathEnv:K,pathExt:E,pathExtExe:M}},V=(U,H,G)=>{if(typeof H==="function")G=H,H={};if(!H)H={};let{pathEnv:K,pathExt:M,pathExtExe:E}=z(U,H),O=[],T=(g)=>new Promise((Z1,$1)=>{if(g===K.length)return H.all&&O.length?Z1(O):$1(J(U));let W1=K[g],A0=/^".*"$/.test(W1)?W1.slice(1,-1):W1,z0=Q.join(A0,U),W9=!A0&&/^\.[\\\/]/.test(U)?U.slice(0,2)+z0:z0;Z1(i(W9,g,0))}),i=(g,Z1,$1)=>new Promise((W1,A0)=>{if($1===M.length)return W1(T(Z1+1));let z0=M[$1];W(g+z0,{pathExt:E},(W9,u8)=>{if(!W9&&u8)if(H.all)O.push(g+z0);else return W1(g+z0);return W1(i(g,Z1,$1+1))})});return G?T(0).then((g)=>G(null,g),G):T(0)},q=(U,H)=>{H=H||{};let{pathEnv:G,pathExt:K,pathExtExe:M}=z(U,H),E=[];for(let O=0;O<G.length;O++){let T=G[O],i=/^".*"$/.test(T)?T.slice(1,-1):T,g=Q.join(i,U),Z1=!i&&/^\.[\\\/]/.test(U)?U.slice(0,2)+g:g;for(let $1=0;$1<K.length;$1++){let W1=Z1+K[$1];try{if(W.sync(W1,{pathExt:M}))if(H.all)E.push(W1);else return W1}catch(A0){}}}if(H.all&&E.length)return E;if(H.nothrow)return null;throw J(U)};Y.exports=V,V.sync=q}),yw=e1((Z,Y)=>{let X=(Q={})=>{let $=Q.env||process.env;if((Q.platform||process.platform)!=="win32")return"PATH";return Object.keys($).reverse().find((J)=>J.toUpperCase()==="PATH")||"Path"};Y.exports=X,Y.exports.default=X}),bw=e1((Z,Y)=>{let X=Q9("path"),Q=_w(),$=yw();function W(z,V){let q=z.options.env||process.env,U=process.cwd(),H=z.options.cwd!=null,G=H&&process.chdir!==void 0&&!process.chdir.disabled;if(G)try{process.chdir(z.options.cwd)}catch(M){}let K;try{K=Q.sync(z.command,{path:q[$({env:q})],pathExt:V?X.delimiter:void 0})}catch(M){}finally{if(G)process.chdir(U)}if(K)K=X.resolve(H?z.options.cwd:"",K);return K}function J(z){return W(z)||W(z,!0)}Y.exports=J}),xw=e1((Z,Y)=>{let X=/([()\][%!^"`<>&|;, *?])/g;function Q(W){return W=W.replace(X,"^$1"),W}function $(W,J){if(W=`${W}`,W=W.replace(/(\\*)"/g,"$1$1\\\""),W=W.replace(/(\\*)$/,"$1$1"),W=`"${W}"`,W=W.replace(X,"^$1"),J)W=W.replace(X,"^$1");return W}Y.exports.command=Q,Y.exports.argument=$}),kw=e1((Z,Y)=>{Y.exports=/^#!(.*)/}),vw=e1((Z,Y)=>{let X=kw();Y.exports=(Q="")=>{let $=Q.match(X);if(!$)return null;let[W,J]=$[0].replace(/#! ?/,"").split(" "),z=W.split("/").pop();if(z==="env")return J;return J?`${z} ${J}`:z}}),fw=e1((Z,Y)=>{let X=Q9("fs"),Q=vw();function $(W){let z=Buffer.alloc(150),V;try{V=X.openSync(W,"r"),X.readSync(V,z,0,150,0),X.closeSync(V)}catch(q){}return Q(z.toString())}Y.exports=$}),hw=e1((Z,Y)=>{let X=Q9("path"),Q=bw(),$=xw(),W=fw(),J=process.platform==="win32",z=/\.(?:com|exe)$/i,V=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function q(G){G.file=Q(G);let K=G.file&&W(G.file);if(K)return G.args.unshift(G.file),G.command=K,Q(G);return G.file}function U(G){if(!J)return G;let K=q(G),M=!z.test(K);if(G.options.forceShell||M){let E=V.test(K);G.command=X.normalize(G.command),G.command=$.command(G.command),G.args=G.args.map((T)=>$.argument(T,E));let O=[G.command].concat(G.args).join(" ");G.args=["/d","/s","/c",`"${O}"`],G.command=process.env.comspec||"cmd.exe",G.options.windowsVerbatimArguments=!0}return G}function H(G,K,M){if(K&&!Array.isArray(K))M=K,K=null;K=K?K.slice(0):[],M=Object.assign({},M);let E={command:G,args:K,options:M,file:void 0,original:{command:G,args:K}};return M.shell?E:U(E)}Y.exports=H}),gw=e1((Z,Y)=>{let X=process.platform==="win32";function Q(z,V){return Object.assign(new Error(`${V} ${z.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${V} ${z.command}`,path:z.command,spawnargs:z.args})}function $(z,V){if(!X)return;let q=z.emit;z.emit=function(U,H){if(U==="exit"){let G=W(H,V,"spawn");if(G)return q.call(z,"error",G)}return q.apply(z,arguments)}}function W(z,V){if(X&&z===1&&!V.file)return Q(V.original,"spawn");return null}function J(z,V){if(X&&z===1&&!V.file)return Q(V.original,"spawnSync");return null}Y.exports={hookChildProcess:$,verifyENOENT:W,verifyENOENTSync:J,notFoundError:Q}}),uw=e1((Z,Y)=>{let X=Q9("child_process"),Q=hw(),$=gw();function W(z,V,q){let U=Q(z,V,q),H=X.spawn(U.command,U.args,U.options);return $.hookChildProcess(H,U),H}function J(z,V,q){let U=Q(z,V,q),H=X.spawnSync(U.command,U.args,U.options);return H.error=H.error||$.verifyENOENTSync(H.status,U),H}Y.exports=W,Y.exports.spawn=W,Y.exports.sync=J,Y.exports._parse=Q,Y.exports._enoent=$}),mw=Ew(uw(),1),hV=class extends Error{result;output;get exitCode(){if(this.result.exitCode!==null)return this.result.exitCode;return}constructor(Z,Y){super(`Process exited with non-zero status (${Z.exitCode})`);this.result=Z,this.output=Y}},pw={timeout:void 0,persist:!1},dw={windowsHide:!0};function cw(Z,Y){return{command:Hw(Z),args:Y??[]}}function lw(Z){let Y=new AbortController;for(let X of Z){if(X.aborted)return Y.abort(),X;let Q=()=>{Y.abort(X.reason)};X.addEventListener("abort",Q,{signal:Y.signal})}return Y.signal}async function gV(Z){let Y="";for await(let X of Z)Y+=X.toString();return Y}var iw=class{_process;_aborted=!1;_options;_command;_args;_resolveClose;_processClosed;_thrownError;get process(){return this._process}get pid(){return this._process?.pid}get exitCode(){if(this._process&&this._process.exitCode!==null)return this._process.exitCode;return}constructor(Z,Y,X){this._options={...pw,...X},this._command=Z,this._args=Y??[],this._processClosed=new Promise((Q)=>{this._resolveClose=Q})}kill(Z){return this._process?.kill(Z)===!0}get aborted(){return this._aborted}get killed(){return this._process?.killed===!0}pipe(Z,Y,X){return ow(Z,Y,{...X,stdin:this})}async*[Symbol.asyncIterator](){let Z=this._process;if(!Z)return;let Y=[];if(this._streamErr)Y.push(this._streamErr);if(this._streamOut)Y.push(this._streamOut);let X=Rw(Y),Q=Lw.createInterface({input:X});for await(let $ of Q)yield $.toString();if(await this._processClosed,Z.removeAllListeners(),this._thrownError)throw this._thrownError;if(this._options?.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new hV(this)}async _waitForOutput(){let Z=this._process;if(!Z)throw new Error("No process was started");let[Y,X]=await Promise.all([this._streamOut?gV(this._streamOut):"",this._streamErr?gV(this._streamErr):""]);if(await this._processClosed,this._options?.stdin)await this._options.stdin;if(Z.removeAllListeners(),this._thrownError)throw this._thrownError;let Q={stderr:X,stdout:Y,exitCode:this.exitCode};if(this._options.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new hV(this,Q);return Q}then(Z,Y){return this._waitForOutput().then(Z,Y)}_streamOut;_streamErr;spawn(){let Z=Kw(),Y=this._options,X={...dw,...Y.nodeOptions},Q=[];if(this._resetState(),Y.timeout!==void 0)Q.push(AbortSignal.timeout(Y.timeout));if(Y.signal!==void 0)Q.push(Y.signal);if(Y.persist===!0)X.detached=!0;if(Q.length>0)X.signal=lw(Q);X.env=Iw(Z,X.env);let{command:$,args:W}=cw(this._command,this._args),J=(0,mw._parse)($,W,X),z=qw(J.command,J.args,J.options);if(z.stderr)this._streamErr=z.stderr;if(z.stdout)this._streamOut=z.stdout;if(this._process=z,z.once("error",this._onError),z.once("close",this._onClose),Y.stdin!==void 0&&z.stdin&&Y.stdin.process){let{stdout:V}=Y.stdin.process;if(V)V.pipe(z.stdin)}}_resetState(){this._aborted=!1,this._processClosed=new Promise((Z)=>{this._resolveClose=Z}),this._thrownError=void 0}_onError=(Z)=>{if(Z.name==="AbortError"&&(!(Z.cause instanceof Error)||Z.cause.name!=="TimeoutError")){this._aborted=!0;return}this._thrownError=Z};_onClose=()=>{if(this._resolveClose)this._resolveClose()}},d7=(Z,Y,X)=>{let Q=new iw(Z,Y,X);return Q.spawn(),Q},ow=d7;import{readFile as nw,access as aw}from"node:fs/promises";var h8=typeof Bun!=="undefined";async function mV(Z){if(h8)return Bun.file(Z).text();return nw(Z,"utf-8")}async function pV(Z){if(h8)return Bun.file(Z).exists();try{return await aw(Z),!0}catch{return!1}}async function dV(){if(h8)return Bun.stdin.text();let Z=[];for await(let Y of process.stdin)Z.push(Y);return Buffer.concat(Z).toString("utf-8")}async function $9(Z,Y,X){if(h8){let $={stdout:"pipe",stderr:"pipe"};if(X?.cwd)$.cwd=X.cwd;let W=Bun.spawn([Z,...Y],$),[J,z,V]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);return{stdout:J,stderr:z,exitCode:V}}let Q=await d7(Z,Y,{nodeOptions:{cwd:X?.cwd},throwOnError:!1});return{stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode??0}}async function cV(){if((await $9("gh",["--version"])).exitCode!==0)throw new t1("gh CLI is not installed. Install it from https://cli.github.com/","GH_NOT_INSTALLED");if((await $9("gh",["auth","status"])).exitCode!==0)throw new t1("Not authenticated with GitHub. Run `gh auth login` to authenticate.","NOT_AUTHENTICATED")}async function lV(Z,Y){let X=["pr","diff",String(Z)];if(Y)X.push("-R",Y);let{stdout:Q,stderr:$,exitCode:W}=await $9("gh",X);if(W!==0)oV($,Z,Y);return Q}async function iV(Z,Y){let X=["title","body","author","commits","baseRefName","headRefName","state","number","url"].join(","),Q=["pr","view",String(Z),"--json",X];if(Y)Q.push("-R",Y);let{stdout:$,stderr:W,exitCode:J}=await $9("gh",Q);if(J!==0)oV(W,Z,Y);try{return JSON.parse($)}catch{throw new t1(`Failed to parse PR metadata: ${$.slice(0,200)}`,"GH_ERROR")}}function oV(Z,Y,X){let Q=Z.toLowerCase(),$=X?` in ${X}`:"";if(Q.includes("could not resolve to a pullrequest")||Q.includes("no pull requests found")||Q.includes("http 404"))throw new t1(`PR #${Y} not found${$}`,"PR_NOT_FOUND");if(Q.includes("could not resolve to a repository")||Q.includes("repository not found"))throw new t1(`Repository not found: ${X||"(current)"}`,"REPO_NOT_FOUND");if(Q.includes("not logged in")||Q.includes("authentication"))throw new t1("Not authenticated with GitHub. Run `gh auth login` to authenticate.","NOT_AUTHENTICATED");if(Q.includes("not a git repository")||Q.includes("could not determine current repository"))throw new t1("Not in a git repository. Use -R owner/repo to specify the repository.","NOT_IN_REPO");throw new t1(`gh error: ${Z.trim()}`,"GH_ERROR")}function nV(Z){let Y=[];if(Y.push(`PR Title: ${Z.title}`),Y.push(`Author: ${Z.author.name||Z.author.login}`),Y.push(`Branch: ${Z.headRefName} → ${Z.baseRefName}`),Z.body?.trim())Y.push(""),Y.push("PR Description:"),Y.push(Z.body.trim());if(Z.commits.length>1){Y.push(""),Y.push(`Commits (${Z.commits.length}):`);for(let X of Z.commits)if(Y.push(` - ${X.messageHeadline}`),X.messageBody?.trim()){let Q=X.messageBody.trim().split(`
336
+ `).map(($)=>` ${$}`).join(`
337
+ `);Y.push(Q)}}return Y.join(`
338
+ `)}async function aV(Z,Y,X){if(Z.length===0)return[];let Q=["api",`repos/${X}/git/trees/${Y}?recursive=1`,"--jq",".tree[].path"],{stdout:$,stderr:W,exitCode:J}=await $9("gh",Q);if(J!==0){let U=[];return U.warning=`Could not fetch repository context from GitHub: ${W.trim()}`,U}let z=$.split(`
339
+ `).filter(Boolean),V=new Set(Z),q=[];for(let U of z){let H=rw(U);if(V.has(H))q.push({path:U,status:"existing"})}return q.sort((U,H)=>U.path.localeCompare(H.path))}function sw(Z){let Y=[],X=m.default.dim("─".repeat(60));return Y.push(X),Y.push(m.default.bold(m.default.cyan(`PR #${Z.number}: ${Z.title}`))),Y.push(X),Y.push(""),Y.push(`${m.default.bold("Author:")} ${Z.author.name||Z.author.login}`),Y.push(`${m.default.bold("URL:")} ${m.default.blue(Z.url)}`),Y.push(`${m.default.bold("Branch:")} ${Z.headRefName} → ${Z.baseRefName}`),Y.push(`${m.default.bold("State:")} ${tw(Z.state)}`),Y.push(""),Y.join(`
340
+ `)}function tw(Z){switch(Z){case"OPEN":return m.default.green(Z);case"MERGED":return m.default.magenta(Z);case"CLOSED":return m.default.red(Z)}}function ew(Z,Y,X,Q,$,W){if(W.json)console.log(JSON.stringify({pr:{number:Z.number,title:Z.title,author:Z.author,url:Z.url,state:Z.state,branch:{head:Z.headRefName,base:Z.baseRefName}},statedIntent:Q,intent:Y,risks:X,alignment:$},null,2));else if(console.log(sw(Z)),W.verbose)console.log(s6(Y,X,Q,$));else console.log(r6(Y,X,Q,$))}async function ZD(){let{stdout:Z,exitCode:Y}=await $9("gh",["repo","view","--json","nameWithOwner","--jq",".nameWithOwner"]);if(Y!==0)throw new t1("Could not determine current repository. Use -R owner/repo to specify.","NOT_IN_REPO");return Z.trim()}function YD(Z){let Y=Z;if(!Y.startsWith("http://")&&!Y.startsWith("https://"))Y=`https://${Y}`;let X;try{X=new URL(Y)}catch{return null}if(X.hostname!=="github.com")return null;let Q=X.pathname.slice(1).split("/");if(Q.length<4||Q[2]!=="pull")return null;let $=Q[0],W=Q[1],J=Q[3];if(!$||!W||!J)return null;let z=parseInt(J,10);if(isNaN(z))return null;return{owner:$,repo:W,prNumber:z}}function XD(Z,Y){let X=YD(Z);if(X)return{repo:`${X.owner}/${X.repo}`,prNumber:X.prNumber};let Q=Z.match(/^([^#]+)#(\d+)$/);if(Q&&Q[1]&&Q[2])return{repo:Q[1],prNumber:parseInt(Q[2],10)};let $=parseInt(Z,10);if(isNaN($))throw new Error(`Invalid PR identifier: ${Z}. Use a number, owner/repo#number, or GitHub URL.`);return{prNumber:$,repo:Y}}function rV(){return new R9("pr").description("Analyze a GitHub PR").argument("<identifier>","PR number, owner/repo#number, or GitHub URL").option("-R, --repo <repo>","Repository in owner/repo format").option("-v, --verbose","Show detailed output",!1).option("--json","Output results as JSON",!1).action(async(Z,Y)=>{try{let{prNumber:X,repo:Q}=XD(Z,Y.repo),$={...Y,prNumber:X,repo:Q};if(console.log(m.default.dim("Checking gh CLI...")),await cV(),!f8())console.error(m.default.red(`Error: ANTHROPIC_API_KEY environment variable is not set.
341
+ `)+m.default.dim(`Set it in your .env file or export it in your shell:
342
+ `)+m.default.dim(" export ANTHROPIC_API_KEY=sk-ant-...")),process.exit(1);console.log(m.default.dim(`Fetching PR #${X}...`));let[W,J]=await Promise.all([iV(X,Q),lV(X,Q)]);if(!J.trim()){console.log(m.default.yellow(`
343
+ PR has no file changes.`)),console.log(m.default.dim(`URL: ${W.url}`));return}console.log(m.default.dim("Parsing diff..."));let z=v9(J),V=f9(z);console.log(m.default.dim(`Found ${z.files.length} file(s), analyzing with AI...`));let q=nV(W),U=iZ(z),H=Q||await ZD(),G=await aV(U,W.baseRefName,H),K=G.warning;if(K)console.log(m.default.yellow(`⚠ ${K}`)),console.log(m.default.dim(" Analysis will continue but may flag false positives about missing files."));let M=oZ(G),[E,O]=await Promise.all([H2(z,V,q,M),G2(z,V,q,M)]);console.log(m.default.dim("Analyzing intent alignment..."));let T=await v8(q,E,z,V,M);console.log(""),ew(W,E,O,q,T,$)}catch(X){if(X instanceof t1){if(console.error(m.default.red(`GitHub error: ${X.message}`)),X.code==="GH_NOT_INSTALLED")console.error(m.default.dim("Install gh from https://cli.github.com/"));else if(X.code==="NOT_AUTHENTICATED")console.error(m.default.dim("Run `gh auth login` to authenticate."));else if(X.code==="NOT_IN_REPO")console.error(m.default.dim("Specify the repository with -R owner/repo"));process.exit(1)}if(X instanceof K2)console.error(m.default.red(`Error: Invalid or missing API key.
344
+ `)+m.default.dim("Check that your ANTHROPIC_API_KEY is correct.")),process.exit(1);if(X instanceof B2)console.error(m.default.red(`Error: AI analysis failed.
345
+ `)+m.default.dim(X.message)),process.exit(1);let Q=X instanceof Error?X.message:String(X);console.error(m.default.red(`Error: ${Q}`)),process.exit(1)}})}var q1=E0(M2(),1);function sV(Z){return Math.ceil(Z.length/4)}function QD(Z){let Y=Z.hunks.flatMap((Q)=>Q.lines.map(($)=>$.content)).join(`
346
+ `),X=sV(Y);if(I9(Z)){let Q=x8(Z),$=k8(Z,Q);return{original:X,withSummarization:sV($),summarized:!0}}return{original:X,withSummarization:X,summarized:!1}}function tV(Z){let Y=Z.map((W)=>({path:W.path,estimate:QD(W)})),X=Y.reduce((W,J)=>W+J.estimate.original,0),Q=Y.reduce((W,J)=>W+J.estimate.withSummarization,0),$=X-Q;return{files:Y,totals:{original:X,withSummarization:Q,savings:$,savingsPercent:X>0?Math.round($/X*100):0}}}function eV(Z){if(Z.status==="deleted")return Z.hunks.reduce((Y,X)=>Y+X.lines.filter((Q)=>Q.type==="delete").length,0);return Z.hunks.reduce((Y,X)=>Y+X.lines.filter((Q)=>Q.type==="add"||Q.type==="delete").length,0)}function $D(Z,Y){let X=[],Q=Z.filter((z)=>z.tier===1).length,$=Z.filter((z)=>z.tier===2).length,W=Z.filter((z)=>z.tier===3).length;X.push(q1.default.bold(`Files (${Z.length} total: ${Q} Tier 1, ${$} Tier 2, ${W} excluded):`));let J=[...Z].sort((z,V)=>{if(z.tier!==V.tier)return z.tier-V.tier;return z.file.path.localeCompare(V.file.path)});for(let z of J){let V=z.file,q=eV(V),U=V.status.toUpperCase().padEnd(8),H=I9(V),G;switch(V.status){case"added":G=q1.default.green(U);break;case"deleted":G=q1.default.red(U);break;case"renamed":G=q1.default.yellow(U);break;default:G=q1.default.blue(U)}let K=z.tier===3?q1.default.dim(" [excluded]"):"",M=H?q1.default.cyan(" [summarized]"):"";X.push(` ${G} ${V.path} (${q} lines)${M}${K}`)}return X.join(`
347
+ `)}function WD(Z){let Y=[],{totals:X}=Z;if(Y.push(q1.default.bold("Token Estimate:")),Y.push(` Original: ${X.original.toLocaleString()} tokens`),Y.push(` Summarized: ${X.withSummarization.toLocaleString()} tokens`),X.savings>0)Y.push(q1.default.green(` Savings: ${X.savings.toLocaleString()} tokens (${X.savingsPercent}%)`));return Y.join(`
348
+ `)}function Zq(Z){let Y=[],X=Z.filter((Q)=>Q.tier<=2);for(let Q of X)Y.push(X9(Q.file)),Y.push("");return Y.join(`
349
+ `)}function JD(Z,Y,X){let $={files:Z.map((W)=>{let J=W.file,z=Y.files.find((V)=>V.path===J.path);return{path:J.path,status:J.status,tier:W.tier,lines:eV(J),summarized:I9(J),tokens:z?{original:z.estimate.original,withSummarization:z.estimate.withSummarization}:{original:0,withSummarization:0}}}),totals:{files:Z.length,tier1:Z.filter((W)=>W.tier===1).length,tier2:Z.filter((W)=>W.tier===2).length,excluded:Z.filter((W)=>W.tier===3).length,tokens:Y.totals}};if(!X.stats&&!X.filesOnly)$.content=Zq(Z);return $}async function zD(Z,Y){let X={target:Z,...Y};try{console.error(q1.default.dim(`Fetching ${X.target} diff...`));let Q=await P4(X.target,X.cwd);if(!Q.hasChanges){if(X.json)console.log(JSON.stringify({files:[],totals:{files:0,tier1:0,tier2:0,excluded:0,tokens:{original:0,withSummarization:0,savings:0,savingsPercent:0}}},null,2));else if(console.log(q1.default.yellow(`
350
+ No changes found.`)),X.target==="unstaged")console.log(q1.default.dim(`Make some changes first, or try:
351
+ `)+q1.default.dim(` diffloupe summarize --staged
352
+ `)+q1.default.dim(" diffloupe summarize HEAD~1"));return}let $=v9(Q.diff),W=f9($),J=W.filter((q)=>q.tier<=2).map((q)=>q.file),z=tV(J);if(X.json){let q=JD(W,z,X);console.log(JSON.stringify(q,null,2));return}let V=[];if(V.push(q1.default.bold(q1.default.cyan("=== DIFF SUMMARY ==="))),V.push(""),V.push($D(W,z)),V.push(""),!X.noTokens)V.push(WD(z)),V.push("");if(!X.stats&&!X.filesOnly)V.push(q1.default.bold(q1.default.cyan("=== DIFF CONTENT ==="))),V.push(""),V.push(Zq(W));console.log(V.join(`
353
+ `))}catch(Q){if(Q instanceof O1){if(console.error(q1.default.red(`Git error: ${Q.message}`)),Q.code==="NOT_A_REPO")console.error(q1.default.dim("Run this command from within a git repository."));process.exit(1)}let $=Q instanceof Error?Q.message:String(Q);console.error(q1.default.red(`Error: ${$}`)),process.exit(1)}}function Yq(){return new R9("summarize").description("Preview diff formatting without running LLM analysis").argument("[target]","What to diff: unstaged, staged, HEAD, branch:name, commit:hash, or range:a..b","unstaged").option("--stats","Show only file list and token estimates",!1).option("--full","Include system prompt framing (not yet implemented)",!1).option("--json","Output as JSON",!1).option("--no-tokens","Skip token estimates").option("--files-only","Show only file list",!1).option("-C, --cwd <path>","Run as if started in <path>").action(zD)}function VD(Z){let Y=0;for(let X of Z.files)for(let Q of X.hunks)for(let $ of Q.lines)if($.type==="add"||$.type==="delete")Y++;return Y}function c7(Z,Y){let X=Y.length,Q=VD(Z),$=Y.reduce((J,z)=>J+z.estimatedTokens,0),W=Y.filter((J)=>J.tier===1).length;return{fileCount:X,totalLines:Q,estimatedTokens:$,tier1FileCount:W}}function l7(Z){let{fileCount:Y,estimatedTokens:X}=Z;if(Y<=15||X<=8000)return{strategy:"direct",reason:Y<=15?`Small diff (${Y} files ≤ ${"15"})`:`Low token count (${X} ≤ ${"8000"})`,metrics:Z};if(Y<=40)return{strategy:"two-pass",reason:`Medium diff (${Y} files, 16-40 range)`,metrics:Z};if(Y<=80)return{strategy:"flow-based",reason:`Large diff (${Y} files, 41-80 range)`,metrics:Z};return{strategy:"hierarchical",reason:`Huge diff (${Y} files > 80)`,metrics:Z}}var qD=K1({summary:"string",purpose:"string",scope:"'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'",affectedAreas:"string[]",flaggedFiles:K1({path:"string",reason:"string"}).array(),initialRisks:K1({severity:"'low' | 'medium' | 'high' | 'critical'",category:"string",description:"string",evidence:"string","file?":"string"}).array()}),Xq=20,UD=`You are an experienced code reviewer doing a quick scan of a diff to identify areas needing detailed review.
354
+
355
+ Your goal in this OVERVIEW pass is to:
356
+ 1. Understand the overall intent of the change
357
+ 2. Identify which files need careful, detailed review
358
+ 3. Flag any immediately obvious risks
359
+
360
+ ## Key Principles
361
+
362
+ - This is a QUICK SCAN, not a detailed review
363
+ - Flag files that have:
364
+ - Security-sensitive changes (auth, validation, secrets)
365
+ - Complex logic changes
366
+ - API/interface changes that could break things
367
+ - Error handling modifications
368
+ - Database/data layer changes
369
+ - Don't flag routine files:
370
+ - Pure test files (unless testing critical paths)
371
+ - Config files with minor changes
372
+ - Formatting/style changes
373
+ - Simple type additions
374
+
375
+ ## Scope Definitions
376
+
377
+ - **feature**: New functionality
378
+ - **bugfix**: Fixing incorrect behavior
379
+ - **refactor**: Code restructuring without behavior change
380
+ - **config**: Build, tooling, CI/CD changes
381
+ - **docs**: Documentation only
382
+ - **test**: Test additions/modifications only
383
+ - **mixed**: Multiple categories
384
+
385
+ ## Output Quality
386
+
387
+ - Be selective: flag 20-50% of files, not everything
388
+ - Order flagged files by importance
389
+ - Keep reasons concise but specific`;function HD(Z){let Y=[],X=Z.hunks.reduce((J,z)=>J+z.lines.filter((V)=>V.type==="add").length,0),Q=Z.hunks.reduce((J,z)=>J+z.lines.filter((V)=>V.type==="delete").length,0),$=Z.status.toUpperCase();if(Z.status==="renamed"&&Z.oldPath)Y.push(`=== ${Z.oldPath} → ${Z.path} (${$}) [+${X}/-${Q}] ===`);else Y.push(`=== ${Z.path} (${$}) [+${X}/-${Q}] ===`);if(Z.isBinary)return Y.push("[binary file]"),Y.join(`
390
+ `);let W=0;for(let J of Z.hunks){if(W>=Xq)break;Y.push(J.header);for(let z of J.lines){if(W>=Xq){Y.push(`... (${X+Q-W} more changed lines)`);break}if(z.type==="add"||z.type==="delete"){let V=z.type==="add"?"+":"-";Y.push(`${V}${z.content}`),W++}}}return Y.join(`
391
+ `)}function Qq(Z,Y,X,Q){let $=Y.filter((z)=>z.tier<=2),W=[];W.push("## Diff Overview"),W.push(`Total files changed: ${Z.files.length}`),W.push(`Files for overview: ${$.length}`);let J=Y.filter((z)=>z.tier===3).length;if(J>0)W.push(`(${J} files excluded: lock files, generated code, binaries)`);if(W.push(""),Q)W.push(Q),W.push("");W.push("## Files Changed (with stats)");for(let z of $){let V=z.file,q=V.hunks.reduce((H,G)=>H+G.lines.filter((K)=>K.type==="add").length,0),U=V.hunks.reduce((H,G)=>H+G.lines.filter((K)=>K.type==="delete").length,0);W.push(`- ${V.path} (${V.status}) [+${q}/-${U}]`)}W.push(""),W.push("## Diff Preview (first ~20 changed lines per file)"),W.push("");for(let z of $)W.push(HD(z.file)),W.push("");if(X)W.push("## Author's Stated Intent"),W.push(""),W.push(X),W.push("");return W.push("---"),W.push(`Analyze this diff OVERVIEW and identify which files need detailed review.
392
+
393
+ REQUIRED OUTPUT:
394
+ - summary: string - 1-2 sentence summary of what this diff does
395
+ - purpose: string - why this change is being made
396
+ - scope: "feature" | "bugfix" | "refactor" | "config" | "docs" | "test" | "mixed"
397
+ - affectedAreas: string[] - high-level areas touched
398
+ - flaggedFiles: array of { path: string, reason: string } - files needing detailed review
399
+ - initialRisks: array of any immediately obvious risks (can be empty)
400
+
401
+ Be SELECTIVE with flaggedFiles - flag 20-50% of files, not everything.`),W.join(`
402
+ `)}async function $q(Z,Y,X,Q){let $=Qq(Z,Y,X,Q),W=await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[UD],messages:[{role:"user",content:$}],outputSchema:s1(qD),temperature:0.3,stream:!1,maxTokens:4096});return{summary:W.summary,flaggedFiles:W.flaggedFiles.map((J)=>J.path),initialRisks:W.initialRisks.map((J)=>({severity:J.severity,category:J.category,description:J.description,evidence:J.evidence,file:J.file})),overviewIntent:{summary:W.summary,purpose:W.purpose,scope:W.scope,affectedAreas:W.affectedAreas}}}var GD=`You are an experienced code reviewer doing a DETAILED analysis of specific files that were flagged for careful review.
403
+
404
+ This is a DEEP-DIVE pass. You've already done a quick overview and now need to:
405
+ 1. Thoroughly analyze the flagged files
406
+ 2. Identify all risks in these files
407
+ 3. Provide detailed, specific findings
408
+
409
+ ## Key Principles
410
+
411
+ - Every risk MUST cite specific evidence from the diff
412
+ - Don't repeat findings already noted in the overview - focus on NEW details
413
+ - Be thorough - these files were flagged for a reason
414
+
415
+ ## Risk Categories
416
+
417
+ - security: Auth, secrets, injection, validation
418
+ - breaking-change: API changes, removed exports
419
+ - performance: N+1, unbounded operations
420
+ - error-handling: Missing catches, unhandled cases
421
+ - backwards-compatibility: Migrations, protocol changes
422
+ - data-integrity: Race conditions, partial updates
423
+ - test-coverage: Removed tests, untested risky paths
424
+
425
+ ## Severity Calibration
426
+
427
+ - **critical**: Must fix before merge (security vulns, data loss)
428
+ - **high**: Likely production issues if not addressed
429
+ - **medium**: Should review carefully
430
+ - **low**: Worth noting but unlikely to cause problems`;function Wq(Z,Y,X,Q,$,W){let J=Y.filter((H)=>H.tier<=2),z=new Set(X),V=J.filter((H)=>z.has(H.file.path)),q=J.filter((H)=>!z.has(H.file.path)),U=[];if(U.push("## Context from Overview Pass"),U.push(""),U.push(`Overall change: ${Q}`),U.push(`Files flagged for detailed review: ${V.length}`),U.push(`Files not flagged (already reviewed): ${q.length}`),U.push(""),W)U.push(W),U.push("");if(q.length>0){U.push("## Files NOT Flagged (for reference only)");for(let H of q)U.push(`- ${H.file.path} (${H.file.status})`);U.push("")}U.push("## Flagged Files (FULL DIFF - analyze in detail)"),U.push("");for(let H of V)U.push(X9(H.file)),U.push("");if($)U.push("## Author's Stated Intent"),U.push(""),U.push($),U.push("");return U.push("---"),U.push(`Analyze these FLAGGED files in detail for risks.
431
+
432
+ REQUIRED OUTPUT:
433
+ - overallRisk: "low" | "medium" | "high" | "critical" - highest severity found
434
+ - summary: string - actionable summary of findings
435
+ - risks: array of detailed risk objects (can be empty)
436
+ - confidence: "high" | "medium" | "low"
437
+
438
+ Each risk MUST have:
439
+ - severity, category, description, evidence
440
+ - Be SPECIFIC - cite actual code and line numbers`),U.join(`
441
+ `)}async function Jq(Z,Y,X,Q,$,W){if(X.length===0)return{overallRisk:"low",summary:"No files required detailed review - change appears safe.",risks:[],confidence:"high"};let J=Wq(Z,Y,X,Q,$,W);return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[GD],messages:[{role:"user",content:J}],outputSchema:s1(b8),temperature:0.4,stream:!1,maxTokens:8192})}function zq(Z,Y){let X={summary:Z.overviewIntent.summary||Z.summary,purpose:Z.overviewIntent.purpose||Z.summary,scope:Z.overviewIntent.scope||"mixed",affectedAreas:Z.overviewIntent.affectedAreas||[]};if(Z.flaggedFiles.length>0)X.suggestedReviewOrder=Z.flaggedFiles;let Q=[...Z.initialRisks,...Y.risks],$=new Set,W=Q.filter((H)=>{let G=`${H.category}:${H.description.slice(0,50)}`;if($.has(G))return!1;return $.add(G),!0}),J={critical:0,high:1,medium:2,low:3};W.sort((H,G)=>J[H.severity]-J[G.severity]);let z=W[0],V=z?z.severity:"low",q;if(W.length===0)q="No significant risks identified in detailed review.";else{let H=W.filter((K)=>K.severity==="critical").length,G=W.filter((K)=>K.severity==="high").length;if(H>0)q=`${H} critical risk(s) found. ${Y.summary}`;else if(G>0)q=`${G} high-severity risk(s) found. ${Y.summary}`;else q=Y.summary}let U={overallRisk:V,summary:q,risks:W,confidence:Y.confidence};return{intent:X,risks:U}}async function i7(Z,Y,X,Q){let $=Y.filter((q)=>q.tier<=2),W=await $q(Z,Y,X,Q),J=await Jq(Z,Y,W.flaggedFiles,W.summary,X,Q),{intent:z,risks:V}=zq(W,J);return{intent:z,risks:V,metadata:{strategy:"two-pass",overviewFileCount:$.length,flaggedFileCount:W.flaggedFiles.length,deepDiveFileCount:W.flaggedFiles.length}}}var KD=K1({flows:K1({name:"string",description:"string",files:"string[]",priority:"number"}).array()}),BD=8,LD=`You are an expert code reviewer analyzing a large diff to identify logical "flows" or concerns.
442
+
443
+ Your task is to GROUP the changed files into logical flows. A flow is a cohesive unit of related changes that serve a common purpose.
444
+
445
+ ## Guidelines
446
+
447
+ 1. **Identify 3-8 flows** - Too few loses granularity, too many fragments the review
448
+ 2. **Each file belongs to ONE flow** - No overlap. Assign to the PRIMARY concern.
449
+ 3. **Name flows clearly** - Use names like "Authentication", "Data Layer", "API Routes", "UI Components", "Configuration", "Testing"
450
+ 4. **Set priority based on risk/importance**:
451
+ - Priority 1: Security, auth, data mutations
452
+ - Priority 2: Core business logic, API changes
453
+ - Priority 3: Supporting code, utilities
454
+ - Priority 4: Tests, config, docs
455
+
456
+ ## Common Flow Patterns
457
+
458
+ - **Authentication/Security**: Login, auth middleware, tokens, permissions
459
+ - **Data Layer**: Database, models, migrations, queries
460
+ - **API Layer**: Routes, controllers, handlers, middleware
461
+ - **UI Components**: React components, Vue components, templates
462
+ - **State Management**: Redux, MobX, stores, actions
463
+ - **Configuration**: Build config, env, CI/CD
464
+ - **Testing**: Test files, fixtures, mocks
465
+ - **Utilities**: Helpers, shared functions, types
466
+
467
+ ## Edge Cases
468
+
469
+ - **Cross-cutting files** (e.g., types used everywhere): Assign to the flow they MOST support
470
+ - **Mixed-purpose files**: Assign to the HIGHER priority flow
471
+ - **Very small groups** (1-2 files): Consider merging with related flow or marking as uncategorized
472
+
473
+ ## Output Quality
474
+
475
+ - Order flows by priority (1 first)
476
+ - Descriptions should be 1-2 sentences
477
+ - Don't create a flow for just 1 file unless it's critical`;function MD(Z,Y){let X=[],Q=0;for(let $ of Z.hunks){if(Q>=Y)break;for(let W of $.lines){if(Q>=Y)break;if(W.type==="add"||W.type==="delete"){let J=W.type==="add"?"+":"-";X.push(`${J}${W.content}`),Q++}}}return X}function Vq(Z,Y){let X=Y.filter((J)=>J.tier<=2),Q=[];Q.push("## Diff Overview"),Q.push(`Total files to group: ${X.length}`);let $=X.filter((J)=>J.tier===1).length,W=X.filter((J)=>J.tier===2).length;Q.push(`- Tier 1 (high priority): ${$} files (source code, tests, critical config)`),Q.push(`- Tier 2 (lower priority): ${W} files (docs, other config, types)`),Q.push(""),Q.push("## Files to Group"),Q.push("");for(let J of X){let z=J.file,V=z.hunks.reduce((G,K)=>G+K.lines.filter((M)=>M.type==="add").length,0),q=z.hunks.reduce((G,K)=>G+K.lines.filter((M)=>M.type==="delete").length,0),U=z.status.toUpperCase();if(Q.push(`### ${z.path} (${U}) [+${V}/-${q}] [Tier ${J.tier}]`),z.isBinary){Q.push("[binary file]"),Q.push("");continue}let H=MD(z,BD);if(H.length>0){if(Q.push("```"),Q.push(...H),V+q>H.length)Q.push(`... (${V+q-H.length} more lines)`);Q.push("```")}Q.push("")}return Q.push("---"),Q.push(`Group these ${X.length} files into logical flows.
478
+
479
+ REQUIREMENTS:
480
+ 1. Create 3-8 flows (no more, no fewer unless diff is very small)
481
+ 2. Every file must be assigned to exactly ONE flow
482
+ 3. Set priority: 1 = most important to review, higher = less critical
483
+ 4. If a file doesn't fit any flow well, you can leave it out (it will be uncategorized)
484
+
485
+ OUTPUT FORMAT:
486
+ {
487
+ "flows": [
488
+ {
489
+ "name": "Flow Name",
490
+ "description": "What this flow accomplishes",
491
+ "files": ["path/to/file1.ts", "path/to/file2.ts"],
492
+ "priority": 1
493
+ }
494
+ ]
495
+ }`),Q.join(`
496
+ `)}async function o7(Z,Y){let X=Y.filter((q)=>q.tier<=2),Q=new Set(X.map((q)=>q.file.path)),$=Vq(Z,Y),W=await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[LD],messages:[{role:"user",content:$}],outputSchema:s1(KD),temperature:0.3,stream:!1,maxTokens:4096}),J=new Set,z=[];for(let q of W.flows){let U=q.files.filter((H)=>{if(!Q.has(H))return!1;if(J.has(H))return!1;return!0});for(let H of U)J.add(H);if(U.length>0)z.push({name:q.name,description:q.description,files:U,priority:Math.max(1,Math.min(10,Math.round(q.priority)))})}z.sort((q,U)=>q.priority-U.priority);let V=X.filter((q)=>!J.has(q.file.path)).map((q)=>q.file.path);return{flows:z,uncategorized:V}}function n7(Z,Y){let X=new Set(Z.files);return Y.filter((Q)=>X.has(Q.file.path))}var FD=K1({summary:"string",purpose:"string",scope:"'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'",affectedAreas:"string[]","suggestedReviewOrder?":"string[]",overallRisk:"'low' | 'medium' | 'high' | 'critical'",riskSummary:"string",crossFlowConcerns:"string[]",confidence:"'high' | 'medium' | 'low'"}),qq=3;function Uq(Z,Y){let X=new Set(Y.files);return{files:Z.files.filter((Q)=>X.has(Q.path))}}function Hq(Z,Y){return n7(Y,Z)}function ND(Z,Y){return`## Flow Context
497
+
498
+ This analysis is for the "${Z.name}" flow (${Z.files.length} files, priority ${Z.priority}/${Y}).
499
+
500
+ **Flow description:** ${Z.description}
501
+
502
+ Focus your analysis on this specific concern. Other flows in this diff will be analyzed separately.
503
+
504
+ `}async function Gq(Z,Y,X,Q,$,W){let J=Uq(Y,Z),z=Hq(X,Z),V=ND(Z,Q),q=W?`${V}${W}`:V,[U,H]=await Promise.all([H2(J,z,$,q),G2(J,z,$,q)]);return{flow:Z,intent:U,risks:H}}async function Kq(Z,Y,X,Q,$,W){let J=[],z=Z.length;for(let V=0;V<Z.length;V+=qq){let q=Z.slice(V,V+qq),U=await Promise.all(q.map(async(H,G)=>{let K=V+G;if(W)W(K,H.name,z);return Gq(H,Y,X,z,Q,$)}));J.push(...U)}return J}var wD=`You are an expert code reviewer synthesizing analysis from multiple code flows.
505
+
506
+ You've received individual analyses for different logical flows (groups of related files) in a large diff. Your task is to:
507
+
508
+ 1. **Synthesize intent** - Combine the individual flow intents into a coherent overall understanding
509
+ 2. **Merge risks** - Identify the most important risks across all flows, note cross-flow concerns
510
+ 3. **Identify patterns** - Look for patterns that span multiple flows (e.g., consistent error handling, shared security concerns)
511
+
512
+ ## Key Principles
513
+
514
+ - Be CONCISE - this is a summary, not a repetition of all findings
515
+ - Focus on the BIG PICTURE - what is this change as a whole trying to accomplish?
516
+ - Highlight CROSS-FLOW concerns - risks that span multiple flows are often the most important
517
+ - Don't just concatenate - SYNTHESIZE into a coherent narrative
518
+
519
+ ## Severity Calibration
520
+
521
+ When determining overall risk:
522
+ - Use the HIGHEST severity from any flow as the baseline
523
+ - Elevate if multiple flows have high-severity risks (compounding concern)
524
+ - Cross-flow risks (issues that span boundaries) may warrant higher severity`;function Bq(Z,Y){let X=[];X.push("## Flow Analysis Summary"),X.push(""),X.push(`Total flows analyzed: ${Z.length}`),X.push(`Total files: ${Z.reduce((Q,$)=>Q+$.flow.files.length,0)}`),X.push("");for(let Q of Z){if(X.push(`### Flow: ${Q.flow.name} (Priority ${Q.flow.priority})`),X.push(`**Files:** ${Q.flow.files.length}`),X.push(`**Description:** ${Q.flow.description}`),X.push(""),X.push("**Intent:**"),X.push(`- Summary: ${Q.intent.summary}`),X.push(`- Purpose: ${Q.intent.purpose}`),X.push(`- Scope: ${Q.intent.scope}`),X.push(`- Affected Areas: ${Q.intent.affectedAreas.join(", ")}`),X.push(""),X.push("**Risks:**"),X.push(`- Overall: ${Q.risks.overallRisk}`),X.push(`- Summary: ${Q.risks.summary}`),Q.risks.risks.length>0){X.push(`- Individual risks (${Q.risks.risks.length}):`);for(let $ of Q.risks.risks.slice(0,5))X.push(` - [${$.severity}] ${$.category}: ${$.description}`);if(Q.risks.risks.length>5)X.push(` - ... and ${Q.risks.risks.length-5} more`)}else X.push("- No significant risks identified");X.push("")}if(Y)X.push("## Author's Stated Intent"),X.push(""),X.push(Y),X.push(""),X.push("Consider how well the combined flows achieve this intent."),X.push("");return X.push("---"),X.push(`Synthesize these flow analyses into a unified assessment.
525
+
526
+ REQUIRED OUTPUT:
527
+ - summary: string - 1-2 sentence summary of what the ENTIRE diff accomplishes
528
+ - purpose: string - the overall WHY behind all these changes
529
+ - scope: "feature" | "bugfix" | "refactor" | "config" | "docs" | "test" | "mixed"
530
+ - affectedAreas: string[] - all areas affected (deduplicated and consolidated)
531
+ - suggestedReviewOrder: string[] - suggested order to review files (optional)
532
+ - overallRisk: "low" | "medium" | "high" | "critical" - highest severity across all flows
533
+ - riskSummary: string - actionable summary of risks across all flows
534
+ - crossFlowConcerns: string[] - risks or issues that span multiple flows
535
+ - confidence: "high" | "medium" | "low"
536
+
537
+ Focus on synthesis - what does this change mean AS A WHOLE?`),X.join(`
538
+ `)}async function Lq(Z,Y){let X=Bq(Z,Y),Q=await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[wD],messages:[{role:"user",content:X}],outputSchema:s1(FD),temperature:0.3,stream:!1,maxTokens:4096}),$=Z.flatMap((U)=>U.risks.risks),W=new Set,J=$.filter((U)=>{let H=`${U.category}:${U.description.slice(0,50)}`;if(W.has(H))return!1;return W.add(H),!0}),z={critical:0,high:1,medium:2,low:3};J.sort((U,H)=>z[U.severity]-z[H.severity]);let V={summary:Q.summary,purpose:Q.purpose,scope:Q.scope,affectedAreas:Q.affectedAreas,suggestedReviewOrder:Q.suggestedReviewOrder},q={overallRisk:Q.overallRisk,summary:Q.riskSummary,risks:J,confidence:Q.confidence};return{overallIntent:V,overallRisks:q}}async function g8(Z,Y,X,Q,$){if($)$("detecting","Identifying logical flows in diff...");let W=await o7(Z,Y);if(W.flows.length===0){let U={name:"All Changes",description:"All changes in this diff",files:Y.filter((H)=>H.tier<=2).map((H)=>H.file.path),priority:1};W.flows=[U],W.uncategorized=[]}let J=$?(U,H,G)=>{$("analyzing",`Flow ${U+1}/${G}: ${H}`)}:void 0,z=await Kq(W.flows,Z,Y,X,Q,J);if($)$("synthesizing","Combining flow analyses...");let V=await Lq(z,X),q={strategy:"flow-based",totalFileCount:Y.filter((U)=>U.tier<=2).length,flowCount:W.flows.length,uncategorizedCount:W.uncategorized.length,flowFileCounts:W.flows.map((U)=>({name:U.name,fileCount:U.files.length}))};return{flows:z,synthesis:V,metadata:q}}async function DD(Z){if(Z.intent)return Z.intent.trim();if(Z.intentFile){if(!await pV(Z.intentFile))throw new Error(`Intent file not found: ${Z.intentFile}`);return(await mV(Z.intentFile)).trim()||void 0}if(Z.target.startsWith("commit:")){let Y=Z.target.slice(7);if(Y){let X=await q$(Y,Z.cwd);return`Commit ${Y.length>7?Y.slice(0,7):Y}: ${X}`}}if(!process.stdin.isTTY)return(await dV()).trim()||void 0;return}function Mq(Z,Y,X,Q,$){if(X.json)console.log(JSON.stringify({intent:Z,risks:Y,statedIntent:Q,alignment:$},null,2));else if(X.verbose)console.log(s6(Z,Y,Q,$));else console.log(r6(Z,Y,Q,$))}var c6=new R9;c6.name("diffloupe").description("AI-powered diff analysis tool").version("0.1.0");var AD={summary:"Adds rate limiting middleware to protect API endpoints from abuse",purpose:"Prevents API abuse and ensures fair usage across tenants by limiting requests per IP",scope:"feature",affectedAreas:["API middleware","authentication","rate limiting"],suggestedReviewOrder:["src/middleware/rateLimit.ts","src/config/limits.ts","src/routes/api.ts","src/tests/rateLimit.test.ts"]},ED={overallRisk:"medium",summary:"One medium-severity issue with error handling; otherwise looks good",confidence:"high",risks:[{severity:"medium",category:"error-handling",description:"Rate limit errors return 500 instead of 429 status code",evidence:"Line 45: catch block uses generic error response without setting status",file:"src/middleware/rateLimit.ts",mitigation:"Return 429 Too Many Requests with Retry-After header"},{severity:"low",category:"performance",description:"Redis lookup on every request may add latency",evidence:"No caching of rate limit state between checks",file:"src/middleware/rateLimit.ts"},{severity:"low",category:"test-coverage",description:"Missing test for concurrent request handling",evidence:"Tests only cover sequential requests, not race conditions",file:"src/tests/rateLimit.test.ts"}]};c6.command("analyze").description("Analyze code changes with AI assistance").argument("[target]","What to diff: staged, unstaged, HEAD, branch:name, commit:hash, or range:a..b","staged").option("-v, --verbose","Show detailed output",!1).option("--json","Output results as JSON",!1).option("-f, --force","Skip cache and force fresh analysis",!1).option("-i, --intent <intent>","Describe the intent of the changes").option("--intent-file <path>","Read intent from a file").option("-C, --cwd <path>","Run as if git was started in <path>").option("--demo","Show demo output with mock data",!1).option("--strategy <strategy>","Force decomposition strategy (direct, two-pass, flow-based, hierarchical)").action(async(Z,Y)=>{let X={target:Z,...Y},Q;try{Q=await DD(X)}catch($){let W=$ instanceof Error?$.message:String($);console.error(p.default.red(`Error: ${W}`)),process.exit(1)}if(X.demo){Mq(AD,ED,X,Q);return}if(!f8())console.error(p.default.red(`Error: ANTHROPIC_API_KEY environment variable is not set.
539
+ `)+p.default.dim(`Set it in your .env file or export it in your shell:
540
+ `)+p.default.dim(` export ANTHROPIC_API_KEY=sk-ant-...
541
+
542
+ `)+p.default.dim("Or use --demo to see example output without an API key.")),process.exit(1);try{console.log(p.default.dim(`Fetching ${X.target} diff...`));let $=await P4(X.target,X.cwd);if(!$.hasChanges){if(console.log(p.default.yellow(`
543
+ No changes found.`)),X.target==="staged")console.log(p.default.dim(`Stage some changes with 'git add' first, or try:
544
+ `)+p.default.dim(` diffloupe analyze HEAD # all uncommitted changes
545
+ `)+p.default.dim(" diffloupe analyze branch:main # compare to main"));return}console.log(p.default.dim("Parsing diff..."));let W=v9($.diff),J=f9(W),z=c7(W,J),V=X.strategy?{strategy:X.strategy,reason:"Forced via --strategy flag",metrics:z}:l7(z);console.log(p.default.dim(`Found ${W.files.length} file(s), ~${z.estimatedTokens} tokens`)),console.log(p.default.dim(`Strategy: ${V.strategy} (${V.reason})`));let q=await K$(W,X.cwd),U,H;if(V.strategy==="two-pass"){console.log(p.default.dim("Pass 1: Quick overview..."));let K=await i7(W,J,Q,q);console.log(p.default.dim(`Pass 2: Deep-dive on ${K.metadata.flaggedFileCount} flagged file(s)...`)),U=K.intent,H=K.risks}else if(V.strategy==="flow-based"){let K=await g8(W,J,Q,q,(M,E)=>{if(M==="detecting")console.log(p.default.dim("Detecting logical flows..."));else if(M==="analyzing"&&E)console.log(p.default.dim(E));else if(M==="synthesizing")console.log(p.default.dim("Synthesizing results..."))});console.log(p.default.dim(`Analyzed ${K.metadata.flowCount} flows across ${K.metadata.totalFileCount} files`)),U=K.synthesis.overallIntent,H=K.synthesis.overallRisks}else if(V.strategy==="hierarchical"){console.log(p.default.yellow("Note: hierarchical strategy not yet implemented, using flow-based analysis"));let K=await g8(W,J,Q,q,(M,E)=>{if(M==="detecting")console.log(p.default.dim("Detecting logical flows..."));else if(M==="analyzing"&&E)console.log(p.default.dim(E));else if(M==="synthesizing")console.log(p.default.dim("Synthesizing results..."))});U=K.synthesis.overallIntent,H=K.synthesis.overallRisks}else console.log(p.default.dim("Analyzing with AI...")),[U,H]=await Promise.all([H2(W,J,Q,q),G2(W,J,Q,q)]);let G;if(Q)console.log(p.default.dim("Analyzing intent alignment...")),G=await v8(Q,U,W,J,q);console.log(""),Mq(U,H,X,Q,G)}catch($){if($ instanceof O1){if(console.error(p.default.red(`Git error: ${$.message}`)),$.code==="NOT_A_REPO")console.error(p.default.dim("Run this command from within a git repository."));process.exit(1)}if($ instanceof K2)console.error(p.default.red(`Error: Invalid or missing API key.
546
+ `)+p.default.dim("Check that your ANTHROPIC_API_KEY is correct.")),process.exit(1);if($ instanceof B2)console.error(p.default.red(`Error: AI analysis failed.
547
+ `)+p.default.dim($.message)),process.exit(1);let W=$ instanceof Error?$.message:String($);console.error(p.default.red(`Error: ${W}`)),process.exit(1)}});c6.addCommand(rV());c6.addCommand(Yq());function Fq(){c6.parse()}Fq();