aws-cdk 2.175.0 → 2.175.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-info.json +2 -2
- package/lib/cdk-toolkit.d.ts +0 -1
- package/lib/cdk-toolkit.js +1 -44
- package/lib/index.js +3 -3
- package/lib/init-templates/.init-version.json +1 -1
- package/package.json +9 -9
- package/test/cdk-toolkit.test.js +1 -46
package/lib/index.js
CHANGED
|
@@ -845,10 +845,10 @@ ${customMsgs.join("\n")}`:"";usage2.fail(__n("Missing required argument: %s","Mi
|
|
|
845
845
|
${__("Argument: %s, Given: %s, Choices: %s",key,usage2.stringifiedValues(invalid[key]),usage2.stringifiedValues(options.choices[key]))}`});usage2.fail(msg)};let checks=[];self2.check=function check(f,global2){checks.push({func:f,global:global2})};self2.customChecks=function customChecks(argv,aliases){for(let i=0,f;(f=checks[i])!==void 0;i++){const func=f.func;let result=null;try{result=func(argv,aliases)}catch(err){usage2.fail(err.message?err.message:err,err);continue}if(!result){usage2.fail(__("Argument check failed: %s",func.toString()))}else if(typeof result==="string"||result instanceof Error){usage2.fail(result.toString(),result)}}};let implied={};self2.implies=function implies(key,value){argsert("<string|object> [array|number|string]",[key,value],arguments.length);if(typeof key==="object"){Object.keys(key).forEach(k=>{self2.implies(k,key[k])})}else{yargs2.global(key);if(!implied[key]){implied[key]=[]}if(Array.isArray(value)){value.forEach(i=>self2.implies(key,i))}else{assertNotStrictEqual(value,void 0,shim2);implied[key].push(value)}}};self2.getImplied=function getImplied(){return implied};function keyExists(argv,val2){const num=Number(val2);val2=isNaN(num)?val2:num;if(typeof val2==="number"){val2=argv._.length>=val2}else if(val2.match(/^--no-.+/)){val2=val2.match(/^--no-(.+)/)[1];val2=!argv[val2]}else{val2=argv[val2]}return val2}self2.implications=function implications(argv){const implyFail=[];Object.keys(implied).forEach(key=>{const origKey=key;(implied[key]||[]).forEach(value=>{let key2=origKey;const origValue=value;key2=keyExists(argv,key2);value=keyExists(argv,value);if(key2&&!value){implyFail.push(` ${origKey} -> ${origValue}`)}})});if(implyFail.length){let msg=`${__("Implications failed:")}
|
|
846
846
|
`;implyFail.forEach(value=>{msg+=value});usage2.fail(msg)}};let conflicting={};self2.conflicts=function conflicts(key,value){argsert("<string|object> [array|string]",[key,value],arguments.length);if(typeof key==="object"){Object.keys(key).forEach(k=>{self2.conflicts(k,key[k])})}else{yargs2.global(key);if(!conflicting[key]){conflicting[key]=[]}if(Array.isArray(value)){value.forEach(i=>self2.conflicts(key,i))}else{conflicting[key].push(value)}}};self2.getConflicting=()=>conflicting;self2.conflicting=function conflictingFn(argv){Object.keys(argv).forEach(key=>{if(conflicting[key]){conflicting[key].forEach(value=>{if(value&&argv[key]!==void 0&&argv[value]!==void 0){usage2.fail(__("Arguments %s and %s are mutually exclusive",key,value))}})}})};self2.recommendCommands=function recommendCommands(cmd,potentialCommands){const threshold=3;potentialCommands=potentialCommands.sort((a,b)=>b.length-a.length);let recommended=null;let bestDistance=Infinity;for(let i=0,candidate;(candidate=potentialCommands[i])!==void 0;i++){const d=levenshtein(cmd,candidate);if(d<=threshold&&d<bestDistance){bestDistance=d;recommended=candidate}}if(recommended)usage2.fail(__("Did you mean %s?",recommended))};self2.reset=function reset2(localLookup){implied=objFilter(implied,k=>!localLookup[k]);conflicting=objFilter(conflicting,k=>!localLookup[k]);checks=checks.filter(c=>c.global);return self2};const frozens=[];self2.freeze=function freeze(){frozens.push({implied,checks,conflicting})};self2.unfreeze=function unfreeze(){const frozen=frozens.pop();assertNotStrictEqual(frozen,void 0,shim2);({implied,checks,conflicting}=frozen)};return self2}var shim$1;function YargsWithShim(_shim){shim$1=_shim;return Yargs}function Yargs(processArgs=[],cwd=shim$1.process.cwd(),parentRequire){const self2={};let command$1;let completion$1=null;let groups={};const globalMiddleware=[];let output="";const preservedGroups={};let usage$1;let validation$1;let handlerFinishCommand=null;const y18n2=shim$1.y18n;self2.middleware=globalMiddlewareFactory(globalMiddleware,self2);self2.scriptName=function(scriptName){self2.customScriptName=true;self2.$0=scriptName;return self2};let default$0;if(/\b(node|iojs|electron)(\.exe)?$/.test(shim$1.process.argv()[0])){default$0=shim$1.process.argv().slice(1,2)}else{default$0=shim$1.process.argv().slice(0,1)}self2.$0=default$0.map(x=>{const b=rebase(cwd,x);return x.match(/^(\/|([a-zA-Z]:)?\\)/)&&b.length<x.length?b:x}).join(" ").trim();if(shim$1.getEnv("_")&&shim$1.getProcessArgvBin()===shim$1.getEnv("_")){self2.$0=shim$1.getEnv("_").replace(`${shim$1.path.dirname(shim$1.process.execPath())}/`,"")}const context={resets:-1,commands:[],fullCommands:[],files:[]};self2.getContext=()=>context;let hasOutput=false;let exitError=null;self2.exit=(code,err)=>{hasOutput=true;exitError=err;if(exitProcess)shim$1.process.exit(code)};let completionCommand=null;self2.completion=function(cmd,desc,fn){argsert("[string] [string|boolean|function] [function]",[cmd,desc,fn],arguments.length);if(typeof desc==="function"){fn=desc;desc=void 0}completionCommand=cmd||completionCommand||"completion";if(!desc&&desc!==false){desc="generate completion script"}self2.command(completionCommand,desc);if(fn)completion$1.registerFunction(fn);return self2};let options;self2.resetOptions=self2.reset=function resetOptions(aliases={}){context.resets++;options=options||{};const tmpOptions={};tmpOptions.local=options.local?options.local:[];tmpOptions.configObjects=options.configObjects?options.configObjects:[];const localLookup={};tmpOptions.local.forEach(l=>{localLookup[l]=true;(aliases[l]||[]).forEach(a=>{localLookup[a]=true})});Object.assign(preservedGroups,Object.keys(groups).reduce((acc,groupName)=>{const keys=groups[groupName].filter(key=>!(key in localLookup));if(keys.length>0){acc[groupName]=keys}return acc},{}));groups={};const arrayOptions=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"];const objectOptions=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","coerce","deprecatedOptions"];arrayOptions.forEach(k=>{tmpOptions[k]=(options[k]||[]).filter(k2=>!localLookup[k2])});objectOptions.forEach(k=>{tmpOptions[k]=objFilter(options[k],k2=>!localLookup[k2])});tmpOptions.envPrefix=options.envPrefix;options=tmpOptions;usage$1=usage$1?usage$1.reset(localLookup):usage(self2,y18n2,shim$1);validation$1=validation$1?validation$1.reset(localLookup):validation(self2,usage$1,y18n2,shim$1);command$1=command$1?command$1.reset():command(self2,usage$1,validation$1,globalMiddleware,shim$1);if(!completion$1)completion$1=completion(self2,usage$1,command$1,shim$1);completionCommand=null;output="";exitError=null;hasOutput=false;self2.parsed=false;return self2};self2.resetOptions();const frozens=[];function freeze(){frozens.push({options,configObjects:options.configObjects.slice(0),exitProcess,groups,strict,strictCommands,strictOptions,completionCommand,output,exitError,hasOutput,parsed:self2.parsed,parseFn,parseContext,handlerFinishCommand});usage$1.freeze();validation$1.freeze();command$1.freeze()}function unfreeze(){const frozen=frozens.pop();assertNotStrictEqual(frozen,void 0,shim$1);let configObjects;({options,configObjects,exitProcess,groups,output,exitError,hasOutput,parsed:self2.parsed,strict,strictCommands,strictOptions,completionCommand,parseFn,parseContext,handlerFinishCommand}=frozen);options.configObjects=configObjects;usage$1.unfreeze();validation$1.unfreeze();command$1.unfreeze()}self2.boolean=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("boolean",keys);return self2};self2.array=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("array",keys);return self2};self2.number=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("number",keys);return self2};self2.normalize=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("normalize",keys);return self2};self2.count=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("count",keys);return self2};self2.string=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("string",keys);return self2};self2.requiresArg=function(keys){argsert("<array|string|object> [number]",[keys],arguments.length);if(typeof keys==="string"&&options.narg[keys]){return self2}else{populateParserHintSingleValueDictionary(self2.requiresArg,"narg",keys,NaN)}return self2};self2.skipValidation=function(keys){argsert("<array|string>",[keys],arguments.length);populateParserHintArray("skipValidation",keys);return self2};function populateParserHintArray(type,keys){keys=[].concat(keys);keys.forEach(key=>{key=sanitizeKey(key);options[type].push(key)})}self2.nargs=function(key,value){argsert("<string|object|array> [number]",[key,value],arguments.length);populateParserHintSingleValueDictionary(self2.nargs,"narg",key,value);return self2};self2.choices=function(key,value){argsert("<object|string|array> [string|array]",[key,value],arguments.length);populateParserHintArrayDictionary(self2.choices,"choices",key,value);return self2};self2.alias=function(key,value){argsert("<object|string|array> [string|array]",[key,value],arguments.length);populateParserHintArrayDictionary(self2.alias,"alias",key,value);return self2};self2.default=self2.defaults=function(key,value,defaultDescription){argsert("<object|string|array> [*] [string]",[key,value,defaultDescription],arguments.length);if(defaultDescription){assertSingleKey(key,shim$1);options.defaultDescription[key]=defaultDescription}if(typeof value==="function"){assertSingleKey(key,shim$1);if(!options.defaultDescription[key])options.defaultDescription[key]=usage$1.functionDescription(value);value=value.call()}populateParserHintSingleValueDictionary(self2.default,"default",key,value);return self2};self2.describe=function(key,desc){argsert("<object|string|array> [string]",[key,desc],arguments.length);setKey(key,true);usage$1.describe(key,desc);return self2};function setKey(key,set){populateParserHintSingleValueDictionary(setKey,"key",key,set);return self2}function demandOption(keys,msg){argsert("<object|string|array> [string]",[keys,msg],arguments.length);populateParserHintSingleValueDictionary(self2.demandOption,"demandedOptions",keys,msg);return self2}self2.demandOption=demandOption;self2.coerce=function(keys,value){argsert("<object|string|array> [function]",[keys,value],arguments.length);populateParserHintSingleValueDictionary(self2.coerce,"coerce",keys,value);return self2};function populateParserHintSingleValueDictionary(builder,type,key,value){populateParserHintDictionary(builder,type,key,value,(type2,key2,value2)=>{options[type2][key2]=value2})}function populateParserHintArrayDictionary(builder,type,key,value){populateParserHintDictionary(builder,type,key,value,(type2,key2,value2)=>{options[type2][key2]=(options[type2][key2]||[]).concat(value2)})}function populateParserHintDictionary(builder,type,key,value,singleKeyHandler){if(Array.isArray(key)){key.forEach(k=>{builder(k,value)})}else if((key2=>typeof key2==="object")(key)){for(const k of objectKeys(key)){builder(k,key[k])}}else{singleKeyHandler(type,sanitizeKey(key),value)}}function sanitizeKey(key){if(key==="__proto__")return"___proto___";return key}function deleteFromParserHintObject(optionKey){objectKeys(options).forEach(hintKey=>{if((key=>key==="configObjects")(hintKey))return;const hint=options[hintKey];if(Array.isArray(hint)){if(~hint.indexOf(optionKey))hint.splice(hint.indexOf(optionKey),1)}else if(typeof hint==="object"){delete hint[optionKey]}});delete usage$1.getDescriptions()[optionKey]}self2.config=function config(key="config",msg,parseFn2){argsert("[object|string] [string|function] [function]",[key,msg,parseFn2],arguments.length);if(typeof key==="object"&&!Array.isArray(key)){key=applyExtends(key,cwd,self2.getParserConfiguration()["deep-merge-config"]||false,shim$1);options.configObjects=(options.configObjects||[]).concat(key);return self2}if(typeof msg==="function"){parseFn2=msg;msg=void 0}self2.describe(key,msg||usage$1.deferY18nLookup("Path to JSON config file"));(Array.isArray(key)?key:[key]).forEach(k=>{options.config[k]=parseFn2||true});return self2};self2.example=function(cmd,description){argsert("<string|array> [string]",[cmd,description],arguments.length);if(Array.isArray(cmd)){cmd.forEach(exampleParams=>self2.example(...exampleParams))}else{usage$1.example(cmd,description)}return self2};self2.command=function(cmd,description,builder,handler,middlewares,deprecated){argsert("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[cmd,description,builder,handler,middlewares,deprecated],arguments.length);command$1.addHandler(cmd,description,builder,handler,middlewares,deprecated);return self2};self2.commandDir=function(dir,opts){argsert("<string> [object]",[dir,opts],arguments.length);const req=parentRequire||shim$1.require;command$1.addDirectory(dir,self2.getContext(),req,shim$1.getCallerFile(),opts);return self2};self2.demand=self2.required=self2.require=function demand(keys,max,msg){if(Array.isArray(max)){max.forEach(key=>{assertNotStrictEqual(msg,true,shim$1);demandOption(key,msg)});max=Infinity}else if(typeof max!=="number"){msg=max;max=Infinity}if(typeof keys==="number"){assertNotStrictEqual(msg,true,shim$1);self2.demandCommand(keys,max,msg,msg)}else if(Array.isArray(keys)){keys.forEach(key=>{assertNotStrictEqual(msg,true,shim$1);demandOption(key,msg)})}else{if(typeof msg==="string"){demandOption(keys,msg)}else if(msg===true||typeof msg==="undefined"){demandOption(keys)}}return self2};self2.demandCommand=function demandCommand(min=1,max,minMsg,maxMsg){argsert("[number] [number|string] [string|null|undefined] [string|null|undefined]",[min,max,minMsg,maxMsg],arguments.length);if(typeof max!=="number"){minMsg=max;max=Infinity}self2.global("_",false);options.demandedCommands._={min,max,minMsg,maxMsg};return self2};self2.getDemandedOptions=()=>{argsert([],0);return options.demandedOptions};self2.getDemandedCommands=()=>{argsert([],0);return options.demandedCommands};self2.deprecateOption=function deprecateOption(option,message){argsert("<string> [string|boolean]",[option,message],arguments.length);options.deprecatedOptions[option]=message;return self2};self2.getDeprecatedOptions=()=>{argsert([],0);return options.deprecatedOptions};self2.implies=function(key,value){argsert("<string|object> [number|string|array]",[key,value],arguments.length);validation$1.implies(key,value);return self2};self2.conflicts=function(key1,key2){argsert("<string|object> [string|array]",[key1,key2],arguments.length);validation$1.conflicts(key1,key2);return self2};self2.usage=function(msg,description,builder,handler){argsert("<string|null|undefined> [string|boolean] [function|object] [function]",[msg,description,builder,handler],arguments.length);if(description!==void 0){assertNotStrictEqual(msg,null,shim$1);if((msg||"").match(/^\$0( |$)/)){return self2.command(msg,description,builder,handler)}else{throw new YError(".usage() description must start with $0 if being used as alias for .command()")}}else{usage$1.usage(msg);return self2}};self2.epilogue=self2.epilog=function(msg){argsert("<string>",[msg],arguments.length);usage$1.epilog(msg);return self2};self2.fail=function(f){argsert("<function>",[f],arguments.length);usage$1.failFn(f);return self2};self2.onFinishCommand=function(f){argsert("<function>",[f],arguments.length);handlerFinishCommand=f;return self2};self2.getHandlerFinishCommand=()=>handlerFinishCommand;self2.check=function(f,_global){argsert("<function> [boolean]",[f,_global],arguments.length);validation$1.check(f,_global!==false);return self2};self2.global=function global2(globals,global2){argsert("<string|array> [boolean]",[globals,global2],arguments.length);globals=[].concat(globals);if(global2!==false){options.local=options.local.filter(l=>globals.indexOf(l)===-1)}else{globals.forEach(g=>{if(options.local.indexOf(g)===-1)options.local.push(g)})}return self2};self2.pkgConf=function pkgConf(key,rootPath){argsert("<string> [string]",[key,rootPath],arguments.length);let conf=null;const obj=pkgUp(rootPath||cwd);if(obj[key]&&typeof obj[key]==="object"){conf=applyExtends(obj[key],rootPath||cwd,self2.getParserConfiguration()["deep-merge-config"]||false,shim$1);options.configObjects=(options.configObjects||[]).concat(conf)}return self2};const pkgs={};function pkgUp(rootPath){const npath=rootPath||"*";if(pkgs[npath])return pkgs[npath];let obj={};try{let startDir=rootPath||shim$1.mainFilename;if(!rootPath&&shim$1.path.extname(startDir)){startDir=shim$1.path.dirname(startDir)}const pkgJsonPath=shim$1.findUp(startDir,(dir,names)=>{if(names.includes("package.json")){return"package.json"}else{return void 0}});assertNotStrictEqual(pkgJsonPath,void 0,shim$1);obj=JSON.parse(shim$1.readFileSync(pkgJsonPath,"utf8"))}catch(_noop){}pkgs[npath]=obj||{};return pkgs[npath]}let parseFn=null;let parseContext=null;self2.parse=function parse11(args,shortCircuit,_parseFn){argsert("[string|array] [function|boolean|object] [function]",[args,shortCircuit,_parseFn],arguments.length);freeze();if(typeof args==="undefined"){const argv=self2._parseArgs(processArgs);const tmpParsed=self2.parsed;unfreeze();self2.parsed=tmpParsed;return argv}if(typeof shortCircuit==="object"){parseContext=shortCircuit;shortCircuit=_parseFn}if(typeof shortCircuit==="function"){parseFn=shortCircuit;shortCircuit=false}if(!shortCircuit)processArgs=args;if(parseFn)exitProcess=false;const parsed=self2._parseArgs(args,!!shortCircuit);completion$1.setParsed(self2.parsed);if(parseFn)parseFn(exitError,parsed,output);unfreeze();return parsed};self2._getParseContext=()=>parseContext||{};self2._hasParseCallback=()=>!!parseFn;self2.option=self2.options=function option(key,opt){argsert("<string|object> [object]",[key,opt],arguments.length);if(typeof key==="object"){Object.keys(key).forEach(k=>{self2.options(k,key[k])})}else{if(typeof opt!=="object"){opt={}}options.key[key]=true;if(opt.alias)self2.alias(key,opt.alias);const deprecate=opt.deprecate||opt.deprecated;if(deprecate){self2.deprecateOption(key,deprecate)}const demand=opt.demand||opt.required||opt.require;if(demand){self2.demand(key,demand)}if(opt.demandOption){self2.demandOption(key,typeof opt.demandOption==="string"?opt.demandOption:void 0)}if(opt.conflicts){self2.conflicts(key,opt.conflicts)}if("default"in opt){self2.default(key,opt.default)}if(opt.implies!==void 0){self2.implies(key,opt.implies)}if(opt.nargs!==void 0){self2.nargs(key,opt.nargs)}if(opt.config){self2.config(key,opt.configParser)}if(opt.normalize){self2.normalize(key)}if(opt.choices){self2.choices(key,opt.choices)}if(opt.coerce){self2.coerce(key,opt.coerce)}if(opt.group){self2.group(key,opt.group)}if(opt.boolean||opt.type==="boolean"){self2.boolean(key);if(opt.alias)self2.boolean(opt.alias)}if(opt.array||opt.type==="array"){self2.array(key);if(opt.alias)self2.array(opt.alias)}if(opt.number||opt.type==="number"){self2.number(key);if(opt.alias)self2.number(opt.alias)}if(opt.string||opt.type==="string"){self2.string(key);if(opt.alias)self2.string(opt.alias)}if(opt.count||opt.type==="count"){self2.count(key)}if(typeof opt.global==="boolean"){self2.global(key,opt.global)}if(opt.defaultDescription){options.defaultDescription[key]=opt.defaultDescription}if(opt.skipValidation){self2.skipValidation(key)}const desc=opt.describe||opt.description||opt.desc;self2.describe(key,desc);if(opt.hidden){self2.hide(key)}if(opt.requiresArg){self2.requiresArg(key)}}return self2};self2.getOptions=()=>options;self2.positional=function(key,opts){argsert("<string> <object>",[key,opts],arguments.length);if(context.resets===0){throw new YError(".positional() can only be called in a command's builder function")}const supportedOpts=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];opts=objFilter(opts,(k,v)=>{let accept=supportedOpts.indexOf(k)!==-1;if(k==="type"&&["string","number","boolean"].indexOf(v)===-1)accept=false;return accept});const fullCommand=context.fullCommands[context.fullCommands.length-1];const parseOptions=fullCommand?command$1.cmdToParseOptions(fullCommand):{array:[],alias:{},default:{},demand:{}};objectKeys(parseOptions).forEach(pk=>{const parseOption=parseOptions[pk];if(Array.isArray(parseOption)){if(parseOption.indexOf(key)!==-1)opts[pk]=true}else{if(parseOption[key]&&!(pk in opts))opts[pk]=parseOption[key]}});self2.group(key,usage$1.getPositionalGroupName());return self2.option(key,opts)};self2.group=function group(opts,groupName){argsert("<string|array> <string>",[opts,groupName],arguments.length);const existing=preservedGroups[groupName]||groups[groupName];if(preservedGroups[groupName]){delete preservedGroups[groupName]}const seen={};groups[groupName]=(existing||[]).concat(opts).filter(key=>{if(seen[key])return false;return seen[key]=true});return self2};self2.getGroups=()=>Object.assign({},groups,preservedGroups);self2.env=function(prefix){argsert("[string|boolean]",[prefix],arguments.length);if(prefix===false)delete options.envPrefix;else options.envPrefix=prefix||"";return self2};self2.wrap=function(cols){argsert("<number|null|undefined>",[cols],arguments.length);usage$1.wrap(cols);return self2};let strict=false;self2.strict=function(enabled){argsert("[boolean]",[enabled],arguments.length);strict=enabled!==false;return self2};self2.getStrict=()=>strict;let strictCommands=false;self2.strictCommands=function(enabled){argsert("[boolean]",[enabled],arguments.length);strictCommands=enabled!==false;return self2};self2.getStrictCommands=()=>strictCommands;let strictOptions=false;self2.strictOptions=function(enabled){argsert("[boolean]",[enabled],arguments.length);strictOptions=enabled!==false;return self2};self2.getStrictOptions=()=>strictOptions;let parserConfig={};self2.parserConfiguration=function parserConfiguration(config){argsert("<object>",[config],arguments.length);parserConfig=config;return self2};self2.getParserConfiguration=()=>parserConfig;self2.showHelp=function(level){argsert("[string|function]",[level],arguments.length);if(!self2.parsed)self2._parseArgs(processArgs);if(command$1.hasDefaultCommand()){context.resets++;command$1.runDefaultBuilderOn(self2)}usage$1.showHelp(level);return self2};let versionOpt=null;self2.version=function version10(opt,msg,ver){const defaultVersionOpt="version";argsert("[boolean|string] [string] [string]",[opt,msg,ver],arguments.length);if(versionOpt){deleteFromParserHintObject(versionOpt);usage$1.version(void 0);versionOpt=null}if(arguments.length===0){ver=guessVersion();opt=defaultVersionOpt}else if(arguments.length===1){if(opt===false){return self2}ver=opt;opt=defaultVersionOpt}else if(arguments.length===2){ver=msg;msg=void 0}versionOpt=typeof opt==="string"?opt:defaultVersionOpt;msg=msg||usage$1.deferY18nLookup("Show version number");usage$1.version(ver||void 0);self2.boolean(versionOpt);self2.describe(versionOpt,msg);return self2};function guessVersion(){const obj=pkgUp();return obj.version||"unknown"}let helpOpt=null;self2.addHelpOpt=self2.help=function addHelpOpt(opt,msg){const defaultHelpOpt="help";argsert("[string|boolean] [string]",[opt,msg],arguments.length);if(helpOpt){deleteFromParserHintObject(helpOpt);helpOpt=null}if(arguments.length===1){if(opt===false)return self2}helpOpt=typeof opt==="string"?opt:defaultHelpOpt;self2.boolean(helpOpt);self2.describe(helpOpt,msg||usage$1.deferY18nLookup("Show help"));return self2};const defaultShowHiddenOpt="show-hidden";options.showHiddenOpt=defaultShowHiddenOpt;self2.addShowHiddenOpt=self2.showHidden=function addShowHiddenOpt(opt,msg){argsert("[string|boolean] [string]",[opt,msg],arguments.length);if(arguments.length===1){if(opt===false)return self2}const showHiddenOpt=typeof opt==="string"?opt:defaultShowHiddenOpt;self2.boolean(showHiddenOpt);self2.describe(showHiddenOpt,msg||usage$1.deferY18nLookup("Show hidden options"));options.showHiddenOpt=showHiddenOpt;return self2};self2.hide=function hide(key){argsert("<string>",[key],arguments.length);options.hiddenOptions.push(key);return self2};self2.showHelpOnFail=function showHelpOnFail(enabled,message){argsert("[boolean|string] [string]",[enabled,message],arguments.length);usage$1.showHelpOnFail(enabled,message);return self2};let exitProcess=true;self2.exitProcess=function(enabled=true){argsert("[boolean]",[enabled],arguments.length);exitProcess=enabled;return self2};self2.getExitProcess=()=>exitProcess;self2.showCompletionScript=function($0,cmd){argsert("[string] [string]",[$0,cmd],arguments.length);$0=$0||self2.$0;_logger.log(completion$1.generateCompletionScript($0,cmd||completionCommand||"completion"));return self2};self2.getCompletion=function(args,done){argsert("<array> <function>",[args,done],arguments.length);completion$1.getCompletion(args,done)};self2.locale=function(locale){argsert("[string]",[locale],arguments.length);if(!locale){guessLocale();return y18n2.getLocale()}detectLocale=false;y18n2.setLocale(locale);return self2};self2.updateStrings=self2.updateLocale=function(obj){argsert("<object>",[obj],arguments.length);detectLocale=false;y18n2.updateLocale(obj);return self2};let detectLocale=true;self2.detectLocale=function(detect){argsert("<boolean>",[detect],arguments.length);detectLocale=detect;return self2};self2.getDetectLocale=()=>detectLocale;const _logger={log(...args){if(!self2._hasParseCallback())console.log(...args);hasOutput=true;if(output.length)output+="\n";output+=args.join(" ")},error(...args){if(!self2._hasParseCallback())console.error(...args);hasOutput=true;if(output.length)output+="\n";output+=args.join(" ")}};self2._getLoggerInstance=()=>_logger;self2._hasOutput=()=>hasOutput;self2._setHasOutput=()=>{hasOutput=true};let recommendCommands;self2.recommendCommands=function(recommend=true){argsert("[boolean]",[recommend],arguments.length);recommendCommands=recommend;return self2};self2.getUsageInstance=()=>usage$1;self2.getValidationInstance=()=>validation$1;self2.getCommandInstance=()=>command$1;self2.terminalWidth=()=>{argsert([],0);return shim$1.process.stdColumns};Object.defineProperty(self2,"argv",{get:()=>self2._parseArgs(processArgs),enumerable:true});self2._parseArgs=function parseArgs(args,shortCircuit,_calledFromCommand,commandIndex){let skipValidation=!!_calledFromCommand;args=args||processArgs;options.__=y18n2.__;options.configuration=self2.getParserConfiguration();const populateDoubleDash=!!options.configuration["populate--"];const config=Object.assign({},options.configuration,{"populate--":true});const parsed=shim$1.Parser.detailed(args,Object.assign({},options,{configuration:Object.assign({"parse-positional-numbers":false},config)}));let argv=parsed.argv;if(parseContext)argv=Object.assign({},argv,parseContext);const aliases=parsed.aliases;argv.$0=self2.$0;self2.parsed=parsed;try{guessLocale();if(shortCircuit){return self2._postProcess(argv,populateDoubleDash,_calledFromCommand)}if(helpOpt){const helpCmds=[helpOpt].concat(aliases[helpOpt]||[]).filter(k=>k.length>1);if(~helpCmds.indexOf(""+argv._[argv._.length-1])){argv._.pop();argv[helpOpt]=true}}const handlerKeys=command$1.getCommands();const requestCompletions=completion$1.completionKey in argv;const skipRecommendation=argv[helpOpt]||requestCompletions;const skipDefaultCommand=skipRecommendation&&(handlerKeys.length>1||handlerKeys[0]!=="$0");if(argv._.length){if(handlerKeys.length){let firstUnknownCommand;for(let i=commandIndex||0,cmd;argv._[i]!==void 0;i++){cmd=String(argv._[i]);if(~handlerKeys.indexOf(cmd)&&cmd!==completionCommand){const innerArgv=command$1.runCommand(cmd,self2,parsed,i+1);return self2._postProcess(innerArgv,populateDoubleDash)}else if(!firstUnknownCommand&&cmd!==completionCommand){firstUnknownCommand=cmd;break}}if(command$1.hasDefaultCommand()&&!skipDefaultCommand){const innerArgv=command$1.runCommand(null,self2,parsed);return self2._postProcess(innerArgv,populateDoubleDash)}if(recommendCommands&&firstUnknownCommand&&!skipRecommendation){validation$1.recommendCommands(firstUnknownCommand,handlerKeys)}}if(completionCommand&&~argv._.indexOf(completionCommand)&&!requestCompletions){if(exitProcess)setBlocking(true);self2.showCompletionScript();self2.exit(0)}}else if(command$1.hasDefaultCommand()&&!skipDefaultCommand){const innerArgv=command$1.runCommand(null,self2,parsed);return self2._postProcess(innerArgv,populateDoubleDash)}if(requestCompletions){if(exitProcess)setBlocking(true);args=[].concat(args);const completionArgs=args.slice(args.indexOf(`--${completion$1.completionKey}`)+1);completion$1.getCompletion(completionArgs,completions=>{(completions||[]).forEach(completion2=>{_logger.log(completion2)});self2.exit(0)});return self2._postProcess(argv,!populateDoubleDash,_calledFromCommand)}if(!hasOutput){Object.keys(argv).forEach(key=>{if(key===helpOpt&&argv[key]){if(exitProcess)setBlocking(true);skipValidation=true;self2.showHelp("log");self2.exit(0)}else if(key===versionOpt&&argv[key]){if(exitProcess)setBlocking(true);skipValidation=true;usage$1.showVersion();self2.exit(0)}})}if(!skipValidation&&options.skipValidation.length>0){skipValidation=Object.keys(argv).some(key=>options.skipValidation.indexOf(key)>=0&&argv[key]===true)}if(!skipValidation){if(parsed.error)throw new YError(parsed.error.message);if(!requestCompletions){self2._runValidation(argv,aliases,{},parsed.error)}}}catch(err){if(err instanceof YError)usage$1.fail(err.message,err);else throw err}return self2._postProcess(argv,populateDoubleDash,_calledFromCommand)};self2._postProcess=function(argv,populateDoubleDash,calledFromCommand=false){if(isPromise(argv))return argv;if(calledFromCommand)return argv;if(!populateDoubleDash){argv=self2._copyDoubleDash(argv)}const parsePositionalNumbers=self2.getParserConfiguration()["parse-positional-numbers"]||self2.getParserConfiguration()["parse-positional-numbers"]===void 0;if(parsePositionalNumbers){argv=self2._parsePositionalNumbers(argv)}return argv};self2._copyDoubleDash=function(argv){if(!argv._||!argv["--"])return argv;argv._.push.apply(argv._,argv["--"]);try{delete argv["--"]}catch(_err){}return argv};self2._parsePositionalNumbers=function(argv){const args=argv["--"]?argv["--"]:argv._;for(let i=0,arg;(arg=args[i])!==void 0;i++){if(shim$1.Parser.looksLikeNumber(arg)&&Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))){args[i]=Number(arg)}}return argv};self2._runValidation=function runValidation(argv,aliases,positionalMap,parseErrors,isDefaultCommand=false){if(parseErrors)throw new YError(parseErrors.message);validation$1.nonOptionCount(argv);validation$1.requiredArguments(argv);let failedStrictCommands=false;if(strictCommands){failedStrictCommands=validation$1.unknownCommands(argv)}if(strict&&!failedStrictCommands){validation$1.unknownArguments(argv,aliases,positionalMap,isDefaultCommand)}else if(strictOptions){validation$1.unknownArguments(argv,aliases,{},false,false)}validation$1.customChecks(argv,aliases);validation$1.limitedChoices(argv);validation$1.implications(argv);validation$1.conflicting(argv)};function guessLocale(){if(!detectLocale)return;const locale=shim$1.getEnv("LC_ALL")||shim$1.getEnv("LC_MESSAGES")||shim$1.getEnv("LANG")||shim$1.getEnv("LANGUAGE")||"en_US";self2.locale(locale.replace(/[.:].*/,""))}self2.help();self2.version();return self2}var rebase=(base,dir)=>shim$1.path.relative(base,dir);function isYargsInstance(y){return!!y&&typeof y._parseArgs==="function"}var _a;var _b;var{readFileSync:readFileSync6}=require("fs");var{inspect:inspect4}=require("util");var{resolve:resolve7}=require("path");var y18n=require_build2();var Parser=require_build3();var cjsPlatformShim={assert:{notStrictEqual:assert.notStrictEqual,strictEqual:assert.strictEqual},cliui:require_build4(),findUp:require_sync2(),getEnv:key=>{return process.env[key]},getCallerFile:require_get_caller_file(),getProcessArgvBin,inspect:inspect4,mainFilename:(_b=(_a=require===null||require===void 0?void 0:require.main)===null||_a===void 0?void 0:_a.filename)!==null&&_b!==void 0?_b:process.cwd(),Parser,path:require("path"),process:{argv:()=>process.argv,cwd:process.cwd,execPath:()=>process.execPath,exit:code=>{process.exit(code)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns!=="undefined"?process.stdout.columns:null},readFileSync:readFileSync6,require,requireDirectory:require_require_directory(),stringWidth:require_string_width(),y18n:y18n({directory:resolve7(__dirname,"../locales"),updateFiles:false})};var minNodeVersion=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):10;if(process&&process.version){const major4=Number(process.version.match(/v([^.]+)/)[1]);if(major4<minNodeVersion){throw Error(`yargs supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs#supported-nodejs-versions`)}}var Parser$1=require_build3();var Yargs$1=YargsWithShim(cjsPlatformShim);var cjs={applyExtends,cjsPlatformShim,Yargs:Yargs$1,argsert,globalMiddlewareFactory,isPromise,objFilter,parseCommand,Parser:Parser$1,processArgv,rebase,YError};module2.exports=cjs}});var require_yargs=__commonJS({"../../node_modules/yargs/index.cjs"(exports2,module2){"use strict";var{Yargs,processArgv}=require_build5();Argv(processArgv.hideBin(process.argv));module2.exports=Argv;function Argv(processArgs,cwd){const argv=Yargs(processArgs,cwd,require);singletonify(argv);return argv}function singletonify(inst){Object.keys(inst).forEach(key=>{if(key==="argv"){Argv.__defineGetter__(key,inst.__lookupGetter__(key))}else if(typeof inst[key]==="function"){Argv[key]=inst[key].bind(inst)}else{Argv.__defineGetter__("$0",()=>{return inst.$0});Argv.__defineGetter__("parsed",()=>{return inst.parsed})}})}}});function parseCommandLineArguments(args){return yargs.env("CDK").usage("Usage: cdk -a <cdk-app> COMMAND").option("app",{default:void 0,type:"string",alias:"a",desc:'REQUIRED WHEN RUNNING APP: command-line for executing your app or a cloud assembly directory (e.g. "node bin/my-app.js"). Can also be specified in cdk.json or ~/.cdk.json',requiresArg:true}).option("build",{default:void 0,type:"string",desc:"Command-line for a pre-synth build"}).option("context",{default:[],type:"array",alias:"c",desc:"Add contextual string parameter (KEY=VALUE)",nargs:1,requiresArg:true}).option("plugin",{default:[],type:"array",alias:"p",desc:"Name or path of a node package that extend the CDK features. Can be specified multiple times",nargs:1,requiresArg:true}).option("trace",{default:void 0,type:"boolean",desc:"Print trace for stack warnings"}).option("strict",{default:void 0,type:"boolean",desc:"Do not construct stacks with warnings"}).option("lookups",{default:true,type:"boolean",desc:"Perform context lookups (synthesis fails if this is disabled and context lookups need to be performed)"}).option("ignore-errors",{default:false,type:"boolean",desc:"Ignores synthesis errors, which will likely produce an invalid output"}).option("json",{default:false,type:"boolean",alias:"j",desc:"Use JSON output instead of YAML when templates are printed to STDOUT"}).option("verbose",{default:false,type:"boolean",alias:"v",desc:"Show debug logs (specify multiple times to increase verbosity)",count:true}).option("debug",{default:false,type:"boolean",desc:"Debug the CDK app. Log additional information during synthesis, such as creation stack traces of tokens (sets CDK_DEBUG, will slow down synthesis)"}).option("profile",{default:void 0,type:"string",desc:"Use the indicated AWS profile as the default environment",requiresArg:true}).option("proxy",{default:void 0,type:"string",desc:"Use the indicated proxy. Will read from HTTPS_PROXY environment variable if not specified",requiresArg:true}).option("ca-bundle-path",{default:void 0,type:"string",desc:"Path to CA certificate to use when validating HTTPS requests. Will read from AWS_CA_BUNDLE environment variable if not specified",requiresArg:true}).option("ec2creds",{default:void 0,type:"boolean",alias:"i",desc:"Force trying to fetch EC2 instance credentials. Default: guess EC2 instance status"}).option("version-reporting",{default:void 0,type:"boolean",desc:'Include the "AWS::CDK::Metadata" resource in synthesized templates (enabled by default)'}).option("path-metadata",{default:void 0,type:"boolean",desc:'Include "aws:cdk:path" CloudFormation metadata for each resource (enabled by default)'}).option("asset-metadata",{default:void 0,type:"boolean",desc:'Include "aws:asset:*" CloudFormation metadata for resources that uses assets (enabled by default)'}).option("role-arn",{default:void 0,type:"string",alias:"r",desc:"ARN of Role to use when invoking CloudFormation",requiresArg:true}).option("staging",{default:true,type:"boolean",desc:"Copy assets to the output directory (use --no-staging to disable the copy of assets which allows local debugging via the SAM CLI to reference the original source files)"}).option("output",{default:void 0,type:"string",alias:"o",desc:"Emits the synthesized cloud assembly into a directory (default: cdk.out)",requiresArg:true}).option("notices",{default:void 0,type:"boolean",desc:"Show relevant notices"}).option("no-color",{default:false,type:"boolean",desc:"Removes colors and other style from console output"}).option("ci",{default:isCI(),type:"boolean",desc:"Force CI detection. If CI=true then logs will be sent to stdout instead of stderr"}).option("unstable",{default:[],type:"array",desc:"Opt in to unstable features. The flag indicates that the scope and API of a feature might still change. Otherwise the feature is generally production ready and fully supported. Can be specified multiple times.",nargs:1,requiresArg:true}).command(["list [STACKS..]","ls [STACKS..]"],"Lists all stacks in the app",yargs2=>yargs2.option("long",{default:false,type:"boolean",alias:"l",desc:"Display environment information for each stack"}).option("show-dependencies",{default:false,type:"boolean",alias:"d",desc:"Display stack dependency information for each stack"})).command(["synthesize [STACKS..]","synth [STACKS..]"],"Synthesizes and prints the CloudFormation template for this stack",yargs2=>yargs2.option("exclusively",{default:void 0,type:"boolean",alias:"e",desc:"Only synthesize requested stacks, don't include dependencies"}).option("validation",{default:true,type:"boolean",desc:'After synthesis, validate stacks with the "validateOnSynth" attribute set (can also be controlled with CDK_VALIDATION)'}).option("quiet",{default:false,type:"boolean",alias:"q",desc:"Do not output CloudFormation Template to stdout"})).command("bootstrap [ENVIRONMENTS..]","Deploys the CDK toolkit stack into an AWS environment",yargs2=>yargs2.option("bootstrap-bucket-name",{default:void 0,type:"string",alias:["b","toolkit-bucket-name"],desc:"The name of the CDK toolkit bucket; bucket will be created and must not exist"}).option("bootstrap-kms-key-id",{default:void 0,type:"string",desc:"AWS KMS master key ID used for the SSE-KMS encryption",conflicts:"bootstrap-customer-key"}).option("example-permissions-boundary",{default:void 0,type:"boolean",alias:"epb",desc:"Use the example permissions boundary.",conflicts:"custom-permissions-boundary"}).option("custom-permissions-boundary",{default:void 0,type:"string",alias:"cpb",desc:"Use the permissions boundary specified by name.",conflicts:"example-permissions-boundary"}).option("bootstrap-customer-key",{default:void 0,type:"boolean",desc:"Create a Customer Master Key (CMK) for the bootstrap bucket (you will be charged but can customize permissions, modern bootstrapping only)",conflicts:"bootstrap-kms-key-id"}).option("qualifier",{default:void 0,type:"string",desc:"String which must be unique for each bootstrap stack. You must configure it on your CDK app if you change this from the default."}).option("public-access-block-configuration",{default:void 0,type:"boolean",desc:"Block public access configuration on CDK toolkit bucket (enabled by default) "}).option("tags",{default:[],type:"array",alias:"t",desc:"Tags to add for the stack (KEY=VALUE)",nargs:1,requiresArg:true}).option("execute",{default:true,type:"boolean",desc:"Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet)"}).option("trust",{default:[],type:"array",desc:"The AWS account IDs that should be trusted to perform deployments into this environment (may be repeated, modern bootstrapping only)",nargs:1,requiresArg:true}).option("trust-for-lookup",{default:[],type:"array",desc:"The AWS account IDs that should be trusted to look up values in this environment (may be repeated, modern bootstrapping only)",nargs:1,requiresArg:true}).option("cloudformation-execution-policies",{default:[],type:"array",desc:"The Managed Policy ARNs that should be attached to the role performing deployments into this environment (may be repeated, modern bootstrapping only)",nargs:1,requiresArg:true}).option("force",{default:false,alias:"f",type:"boolean",desc:"Always bootstrap even if it would downgrade template version"}).option("termination-protection",{default:void 0,type:"boolean",desc:"Toggle CloudFormation termination protection on the bootstrap stacks"}).option("show-template",{default:false,type:"boolean",desc:"Instead of actual bootstrapping, print the current CLI's bootstrapping template to stdout for customization"}).option("toolkit-stack-name",{default:void 0,type:"string",desc:"The name of the CDK toolkit stack to create",requiresArg:true}).option("template",{default:void 0,type:"string",requiresArg:true,desc:"Use the template from the given file instead of the built-in one (use --show-template to obtain an example)"}).option("previous-parameters",{default:true,type:"boolean",desc:"Use previous values for existing parameters (you must specify all parameters on every deployment if this is disabled)"})).command("gc [ENVIRONMENTS..]","Garbage collect assets. Options detailed here: https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk/README.md#cdk-gc",yargs2=>yargs2.option("action",{default:"full",type:"string",desc:'The action (or sub-action) you want to perform. Valid entires are "print", "tag", "delete-tagged", "full".'}).option("type",{default:"all",type:"string",desc:"Specify either ecr, s3, or all"}).option("rollback-buffer-days",{default:0,type:"number",desc:"Delete assets that have been marked as isolated for this many days"}).option("created-buffer-days",{default:1,type:"number",desc:"Never delete assets younger than this (in days)"}).option("confirm",{default:true,type:"boolean",desc:"Confirm via manual prompt before deletion"}).option("bootstrap-stack-name",{default:void 0,type:"string",desc:'The name of the CDK toolkit stack, if different from the default "CDKToolkit"',requiresArg:true})).command("deploy [STACKS..]","Deploys the stack(s) named STACKS into your AWS account",yargs2=>yargs2.option("all",{default:false,type:"boolean",desc:"Deploy all available stacks"}).option("build-exclude",{default:[],type:"array",alias:"E",desc:"Do not rebuild asset with the given ID. Can be specified multiple times",nargs:1,requiresArg:true}).option("exclusively",{default:void 0,type:"boolean",alias:"e",desc:"Only deploy requested stacks, don't include dependencies"}).option("require-approval",{default:void 0,type:"string",choices:["never","any-change","broadening"],desc:"What security-sensitive changes need manual approval"}).option("notification-arns",{type:"array",desc:"ARNs of SNS topics that CloudFormation will notify with stack related events. These will be added to ARNs specified with the 'notificationArns' stack property.",nargs:1,requiresArg:true}).option("tags",{default:[],type:"array",alias:"t",desc:"Tags to add to the stack (KEY=VALUE), overrides tags from Cloud Assembly (deprecated)",nargs:1,requiresArg:true}).option("execute",{default:void 0,type:"boolean",desc:"Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) (deprecated)",deprecated:true}).option("change-set-name",{default:void 0,type:"string",desc:"Name of the CloudFormation change set to create (only if method is not direct)"}).option("method",{default:void 0,alias:"m",type:"string",choices:["direct","change-set","prepare-change-set"],requiresArg:true,desc:"How to perform the deployment. Direct is a bit faster but lacks progress information"}).option("import-existing-resources",{default:false,type:"boolean",desc:"Indicates if the stack set imports resources that already exist."}).option("force",{default:false,alias:"f",type:"boolean",desc:"Always deploy stack even if templates are identical"}).option("parameters",{default:{},type:"array",desc:"Additional parameters passed to CloudFormation at deploy time (STACK:KEY=VALUE)",nargs:1,requiresArg:true}).option("outputs-file",{default:void 0,type:"string",alias:"O",desc:"Path to file where stack outputs will be written as JSON",requiresArg:true}).option("previous-parameters",{default:true,type:"boolean",desc:"Use previous values for existing parameters (you must specify all parameters on every deployment if this is disabled)"}).option("toolkit-stack-name",{default:void 0,type:"string",desc:"The name of the existing CDK toolkit stack (only used for app using legacy synthesis)",requiresArg:true}).option("progress",{default:void 0,type:"string",choices:["bar","events"],desc:"Display mode for stack activity events"}).option("rollback",{default:void 0,type:"boolean",desc:"Rollback stack to stable state on failure. Defaults to 'true', iterate more rapidly with --no-rollback or -R. Note: do **not** disable this flag for deployments with resource replacements, as that will always fail"}).option("R",{type:"boolean",hidden:true}).middleware(yargsNegativeAlias("R","rollback"),true).option("hotswap",{default:void 0,type:"boolean",desc:"Attempts to perform a 'hotswap' deployment, but does not fall back to a full deployment if that is not possible. Instead, changes to any non-hotswappable properties are ignored.Do not use this in production environments"}).option("hotswap-fallback",{default:void 0,type:"boolean",desc:"Attempts to perform a 'hotswap' deployment, which skips CloudFormation and updates the resources directly, and falls back to a full deployment if that is not possible. Do not use this in production environments"}).option("watch",{default:void 0,type:"boolean",desc:"Continuously observe the project files, and deploy the given stack(s) automatically when changes are detected. Implies --hotswap by default"}).option("logs",{default:true,type:"boolean",desc:"Show CloudWatch log events from all resources in the selected Stacks in the terminal. 'true' by default, use --no-logs to turn off. Only in effect if specified alongside the '--watch' option"}).option("concurrency",{default:1,type:"number",desc:"Maximum number of simultaneous deployments (dependency permitting) to execute.",requiresArg:true}).option("asset-parallelism",{default:void 0,type:"boolean",desc:"Whether to build/publish assets in parallel"}).option("asset-prebuild",{default:true,type:"boolean",desc:"Whether to build all assets before deploying the first stack (useful for failing Docker builds)"}).option("ignore-no-stacks",{default:false,type:"boolean",desc:"Whether to deploy if the app contains no stacks"})).command("rollback [STACKS..]","Rolls back the stack(s) named STACKS to their last stable state",yargs2=>yargs2.option("all",{default:false,type:"boolean",desc:"Roll back all available stacks"}).option("toolkit-stack-name",{default:void 0,type:"string",desc:"The name of the CDK toolkit stack the environment is bootstrapped with",requiresArg:true}).option("force",{default:void 0,alias:"f",type:"boolean",desc:"Orphan all resources for which the rollback operation fails."}).option("validate-bootstrap-version",{default:void 0,type:"boolean",desc:"Whether to validate the bootstrap stack version. Defaults to 'true', disable with --no-validate-bootstrap-version."}).option("orphan",{default:[],type:"array",desc:"Orphan the given resources, identified by their logical ID (can be specified multiple times)",nargs:1,requiresArg:true})).command("import [STACK]","Import existing resource(s) into the given STACK",yargs2=>yargs2.option("execute",{default:true,type:"boolean",desc:"Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet)"}).option("change-set-name",{default:void 0,type:"string",desc:"Name of the CloudFormation change set to create"}).option("toolkit-stack-name",{default:void 0,type:"string",desc:"The name of the CDK toolkit stack to create",requiresArg:true}).option("rollback",{default:void 0,type:"boolean",desc:"Rollback stack to stable state on failure. Defaults to 'true', iterate more rapidly with --no-rollback or -R. Note: do **not** disable this flag for deployments with resource replacements, as that will always fail"}).option("force",{default:void 0,alias:"f",type:"boolean",desc:"Do not abort if the template diff includes updates or deletes. This is probably safe but we're not sure, let us know how it goes."}).option("record-resource-mapping",{default:void 0,type:"string",alias:"r",requiresArg:true,desc:"If specified, CDK will generate a mapping of existing physical resources to CDK resources to be imported as. The mapping will be written in the given file path. No actual import operation will be performed"}).option("resource-mapping",{default:void 0,type:"string",alias:"m",requiresArg:true,desc:"If specified, CDK will use the given file to map physical resources to CDK resources for import, instead of interactively asking the user. Can be run from scripts"})).command("watch [STACKS..]","Shortcut for 'deploy --watch'",yargs2=>yargs2.option("build-exclude",{default:[],type:"array",alias:"E",desc:"Do not rebuild asset with the given ID. Can be specified multiple times",nargs:1,requiresArg:true}).option("exclusively",{default:void 0,type:"boolean",alias:"e",desc:"Only deploy requested stacks, don't include dependencies"}).option("change-set-name",{default:void 0,type:"string",desc:"Name of the CloudFormation change set to create"}).option("force",{default:false,alias:"f",type:"boolean",desc:"Always deploy stack even if templates are identical"}).option("toolkit-stack-name",{default:void 0,type:"string",desc:"The name of the existing CDK toolkit stack (only used for app using legacy synthesis)",requiresArg:true}).option("progress",{default:void 0,type:"string",choices:["bar","events"],desc:"Display mode for stack activity events"}).option("rollback",{default:void 0,type:"boolean",desc:"Rollback stack to stable state on failure. Defaults to 'true', iterate more rapidly with --no-rollback or -R. Note: do **not** disable this flag for deployments with resource replacements, as that will always fail"}).option("R",{type:"boolean",hidden:true}).middleware(yargsNegativeAlias("R","rollback"),true).option("hotswap",{default:void 0,type:"boolean",desc:"Attempts to perform a 'hotswap' deployment, but does not fall back to a full deployment if that is not possible. Instead, changes to any non-hotswappable properties are ignored.'true' by default, use --no-hotswap to turn off"}).option("hotswap-fallback",{default:void 0,type:"boolean",desc:"Attempts to perform a 'hotswap' deployment, which skips CloudFormation and updates the resources directly, and falls back to a full deployment if that is not possible."}).option("logs",{default:true,type:"boolean",desc:"Show CloudWatch log events from all resources in the selected Stacks in the terminal. 'true' by default, use --no-logs to turn off"}).option("concurrency",{default:1,type:"number",desc:"Maximum number of simultaneous deployments (dependency permitting) to execute.",requiresArg:true})).command("destroy [STACKS..]","Destroy the stack(s) named STACKS",yargs2=>yargs2.option("all",{default:false,type:"boolean",desc:"Destroy all available stacks"}).option("exclusively",{default:void 0,type:"boolean",alias:"e",desc:"Only destroy requested stacks, don't include dependees"}).option("force",{default:void 0,type:"boolean",alias:"f",desc:"Do not ask for confirmation before destroying the stacks"})).command("diff [STACKS..]","Compares the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is found",yargs2=>yargs2.option("exclusively",{default:void 0,type:"boolean",alias:"e",desc:"Only diff requested stacks, don't include dependencies"}).option("context-lines",{default:3,type:"number",desc:"Number of context lines to include in arbitrary JSON diff rendering",requiresArg:true}).option("template",{default:void 0,type:"string",desc:"The path to the CloudFormation template to compare with",requiresArg:true}).option("strict",{default:false,type:"boolean",desc:"Do not filter out AWS::CDK::Metadata resources, mangled non-ASCII characters, or the CheckBootstrapVersionRule"}).option("security-only",{default:false,type:"boolean",desc:"Only diff for broadened security changes"}).option("fail",{default:void 0,type:"boolean",desc:"Fail with exit code 1 in case of diff"}).option("processed",{default:false,type:"boolean",desc:"Whether to compare against the template with Transforms already processed"}).option("quiet",{default:false,type:"boolean",alias:"q",desc:"Do not print stack name and default message when there is no diff to stdout"}).option("change-set",{default:true,type:"boolean",alias:"changeset",desc:"Whether to create a changeset to analyze resource replacements. In this mode, diff will use the deploy role instead of the lookup role."})).command("metadata [STACK]","Returns all metadata associated with this stack").command(["acknowledge [ID]","ack [ID]"],"Acknowledge a notice so that it does not show up anymore").command("notices","Returns a list of relevant notices",yargs2=>yargs2.option("unacknowledged",{default:false,type:"boolean",alias:"u",desc:"Returns a list of unacknowledged notices"})).command("init [TEMPLATE]","Create a new, empty CDK project from a template.",yargs2=>yargs2.option("language",{default:void 0,type:"string",alias:"l",desc:"The language to be used for the new project (default can be configured in ~/.cdk.json)",choices:["csharp","fsharp","go","java","javascript","python","typescript"]}).option("list",{default:void 0,type:"boolean",desc:"List the available templates"}).option("generate-only",{default:false,type:"boolean",desc:"If true, only generates project files, without executing additional operations such as setting up a git repo, installing dependencies or compiling the project"})).command("migrate","Migrate existing AWS resources into a CDK app",yargs2=>yargs2.option("stack-name",{default:void 0,type:"string",alias:"n",desc:"The name assigned to the stack created in the new project. The name of the app will be based off this name as well.",requiresArg:true}).option("language",{default:"typescript",type:"string",alias:"l",desc:"The language to be used for the new project",choices:["typescript","go","java","python","csharp"]}).option("account",{default:void 0,type:"string",desc:"The account to retrieve the CloudFormation stack template from"}).option("region",{default:void 0,type:"string",desc:"The region to retrieve the CloudFormation stack template from"}).option("from-path",{default:void 0,type:"string",desc:"The path to the CloudFormation template to migrate. Use this for locally stored templates"}).option("from-stack",{default:void 0,type:"boolean",desc:"Use this flag to retrieve the template for an existing CloudFormation stack"}).option("output-path",{default:void 0,type:"string",desc:"The output path for the migrated CDK app"}).option("from-scan",{default:void 0,type:"string",desc:'Determines if a new scan should be created, or the last successful existing scan should be used \n options are "new" or "most-recent"'}).option("filter",{default:[],type:"array",desc:'Filters the resource scan based on the provided criteria in the following format: "key1=value1,key2=value2"\n This field can be passed multiple times for OR style filtering: \n filtering options: \n resource-identifier: A key-value pair that identifies the target resource. i.e. {"ClusterName", "myCluster"}\n resource-type-prefix: A string that represents a type-name prefix. i.e. "AWS::DynamoDB::"\n tag-key: a string that matches resources with at least one tag with the provided key. i.e. "myTagKey"\n tag-value: a string that matches resources with at least one tag with the provided value. i.e. "myTagValue"',nargs:1,requiresArg:true}).option("compress",{default:void 0,type:"boolean",desc:"Use this flag to zip the generated CDK app"})).command("context","Manage cached context values",yargs2=>yargs2.option("reset",{default:void 0,alias:"e",desc:"The context key (or its index) to reset",type:"string",requiresArg:true}).option("force",{default:false,alias:"f",desc:"Ignore missing key error",type:"boolean"}).option("clear",{default:false,desc:"Clear all context",type:"boolean"})).command(["docs","doc"],"Opens the reference documentation in a browser",yargs2=>yargs2.option("browser",{default:browserForPlatform(),alias:"b",desc:"the command to use to open the browser, using %u as a placeholder for the path of the file to open",type:"string"})).command("doctor","Check your set-up for potential problems").version(cliVersion()).demandCommand(1,"").recommendCommands().help().alias("h","help").epilogue("If your app has a single stack, there is no need to specify the stack name\n\nIf one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence.").parse(args)}var yargs;var init_parse_command_line_arguments=__esm({"lib/parse-command-line-arguments.ts"(){"use strict";init_yargs_helpers();yargs=require_yargs()}});async function checkForPlatformWarnings(){if(await hasDockerCopyBug()){warning("`cdk synth` may hang in Docker on Linux 5.6-5.10. See https://github.com/aws/aws-cdk/issues/21379 for workarounds.")}}async function hasDockerCopyBug(){return await runningInDocker()&&os5.platform()==="linux"&&isVersionBetween(os5.release(),"5.6","5.10")}async function runningInDocker(){return fs14.pathExists("/.dockerenv")}function isVersionBetween(version10,lower,upper){const ver=splitVersion(version10);const lo=splitVersion(lower);const up=splitVersion(upper);while(lo.length<ver.length){lo.push(0)}while(up.length<ver.length){up.push(9999999)}let n=ver.length;for(let i=0;i<n;i++){if(lo[i]<ver[i]&&ver[i]<up[i]){return true}if(lo[i]>ver[i]||ver[i]>up[i]){return false}}return false}function splitVersion(version10){return`${version10}`.split(".").map(x=>parseInt(x,10)).map(x=>isNaN(x)?0:x)}var os5,fs14;var init_platform_warnings=__esm({"lib/platform-warnings.ts"(){"use strict";os5=__toESM(require("os"));fs14=__toESM(require_lib4());init_logging()}});var MAX_PATTERN_LENGTH,assertValidPattern;var init_assert_valid_pattern=__esm({"node_modules/minimatch/dist/esm/assert-valid-pattern.js"(){MAX_PATTERN_LENGTH=1024*64;assertValidPattern=pattern=>{if(typeof pattern!=="string"){throw new TypeError("invalid pattern")}if(pattern.length>MAX_PATTERN_LENGTH){throw new TypeError("pattern is too long")}}}});var posixClasses,braceEscape,regexpEscape,rangesToString,parseClass;var init_brace_expressions=__esm({"node_modules/minimatch/dist/esm/brace-expressions.js"(){posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]};braceEscape=s=>s.replace(/[[\]\\-]/g,"\\$&");regexpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");rangesToString=ranges=>ranges.join("");parseClass=(glob2,position)=>{const pos=position;if(glob2.charAt(pos)!=="["){throw new Error("not in a brace expression")}const ranges=[];const negs=[];let i=pos+1;let sawStart=false;let uflag=false;let escaping=false;let negate=false;let endPos=pos;let rangeStart="";WHILE:while(i<glob2.length){const c=glob2.charAt(i);if((c==="!"||c==="^")&&i===pos+1){negate=true;i++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i+1;break}sawStart=true;if(c==="\\"){if(!escaping){escaping=true;i++;continue}}if(c==="["&&!escaping){for(const[cls,[unip,u,neg]]of Object.entries(posixClasses)){if(glob2.startsWith(cls,i)){if(rangeStart){return["$.",false,glob2.length-pos,true]}i+=cls.length;if(neg)negs.push(unip);else ranges.push(unip);uflag=uflag||u;continue WHILE}}}escaping=false;if(rangeStart){if(c>rangeStart){ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c))}else if(c===rangeStart){ranges.push(braceEscape(c))}rangeStart="";i++;continue}if(glob2.startsWith("-]",i+1)){ranges.push(braceEscape(c+"-"));i+=2;continue}if(glob2.startsWith("-",i+1)){rangeStart=c;i+=2;continue}ranges.push(braceEscape(c));i++}if(endPos<i){return["",false,0,false]}if(!ranges.length&&!negs.length){return["$.",false,glob2.length-pos,true]}if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){const r=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r),false,endPos-pos,false]}const sranges="["+(negate?"^":"")+rangesToString(ranges)+"]";const snegs="["+(negate?"":"^")+rangesToString(negs)+"]";const comb=ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs;return[comb,uflag,endPos-pos,true]}}});var unescape2;var init_unescape=__esm({"node_modules/minimatch/dist/esm/unescape.js"(){unescape2=(s,{windowsPathsNoEscape=false}={})=>{return windowsPathsNoEscape?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")}}});var types2,isExtglobType,startNoTraversal,startNoDot,addPatternStart,justDots,reSpecials,regExpEscape,qmark,star,starNoEmpty,_root,_hasMagic,_uflag,_parts,_parent,_parentIndex,_negs,_filledNegs,_options,_toString,_emptyExt,_AST_instances,fillNegs_fn,_AST_static,parseAST_fn,partsToRegExp_fn,parseGlob_fn,_AST,AST;var init_ast=__esm({"node_modules/minimatch/dist/esm/ast.js"(){init_brace_expressions();init_unescape();types2=new Set(["!","?","+","*","@"]);isExtglobType=c=>types2.has(c);startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))";startNoDot="(?!\\.)";addPatternStart=new Set(["[","."]);justDots=new Set(["..","."]);reSpecials=new Set("().*{}+?[]^$\\!");regExpEscape=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");qmark="[^/]";star=qmark+"*?";starNoEmpty=qmark+"+?";_AST=class _AST{constructor(type,parent,options={}){__privateAdd(this,_AST_instances);__publicField(this,"type");__privateAdd(this,_root);__privateAdd(this,_hasMagic);__privateAdd(this,_uflag,false);__privateAdd(this,_parts,[]);__privateAdd(this,_parent);__privateAdd(this,_parentIndex);__privateAdd(this,_negs);__privateAdd(this,_filledNegs,false);__privateAdd(this,_options);__privateAdd(this,_toString);__privateAdd(this,_emptyExt,false);this.type=type;if(type)__privateSet(this,_hasMagic,true);__privateSet(this,_parent,parent);__privateSet(this,_root,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_root):this);__privateSet(this,_options,__privateGet(this,_root)===this?options:__privateGet(__privateGet(this,_root),_options));__privateSet(this,_negs,__privateGet(this,_root)===this?[]:__privateGet(__privateGet(this,_root),_negs));if(type==="!"&&!__privateGet(__privateGet(this,_root),_filledNegs))__privateGet(this,_negs).push(this);__privateSet(this,_parentIndex,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0)}get hasMagic(){if(__privateGet(this,_hasMagic)!==void 0)return __privateGet(this,_hasMagic);for(const p of __privateGet(this,_parts)){if(typeof p==="string")continue;if(p.type||p.hasMagic)return __privateSet(this,_hasMagic,true)}return __privateGet(this,_hasMagic)}toString(){if(__privateGet(this,_toString)!==void 0)return __privateGet(this,_toString);if(!this.type){return __privateSet(this,_toString,__privateGet(this,_parts).map(p=>String(p)).join(""))}else{return __privateSet(this,_toString,this.type+"("+__privateGet(this,_parts).map(p=>String(p)).join("|")+")")}}push(...parts){for(const p of parts){if(p==="")continue;if(typeof p!=="string"&&!(p instanceof _AST&&__privateGet(p,_parent)===this)){throw new Error("invalid part: "+p)}__privateGet(this,_parts).push(p)}}toJSON(){var _a;const ret=this.type===null?__privateGet(this,_parts).slice().map(p=>typeof p==="string"?p:p.toJSON()):[this.type,...__privateGet(this,_parts).map(p=>p.toJSON())];if(this.isStart()&&!this.type)ret.unshift([]);if(this.isEnd()&&(this===__privateGet(this,_root)||__privateGet(__privateGet(this,_root),_filledNegs)&&((_a=__privateGet(this,_parent))==null?void 0:_a.type)==="!")){ret.push({})}return ret}isStart(){var _a;if(__privateGet(this,_root)===this)return true;if(!((_a=__privateGet(this,_parent))==null?void 0:_a.isStart()))return false;if(__privateGet(this,_parentIndex)===0)return true;const p=__privateGet(this,_parent);for(let i=0;i<__privateGet(this,_parentIndex);i++){const pp=__privateGet(p,_parts)[i];if(!(pp instanceof _AST&&pp.type==="!")){return false}}return true}isEnd(){var _a,_b,_c;if(__privateGet(this,_root)===this)return true;if(((_a=__privateGet(this,_parent))==null?void 0:_a.type)==="!")return true;if(!((_b=__privateGet(this,_parent))==null?void 0:_b.isEnd()))return false;if(!this.type)return(_c=__privateGet(this,_parent))==null?void 0:_c.isEnd();const pl=__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0;return __privateGet(this,_parentIndex)===pl-1}copyIn(part){if(typeof part==="string")this.push(part);else this.push(part.clone(this))}clone(parent){const c=new _AST(this.type,parent);for(const p of __privateGet(this,_parts)){c.copyIn(p)}return c}static fromGlob(pattern,options={}){var _a;const ast=new _AST(null,void 0,options);__privateMethod(_a=_AST,_AST_static,parseAST_fn).call(_a,pattern,ast,0,options);return ast}toMMPattern(){if(this!==__privateGet(this,_root))return __privateGet(this,_root).toMMPattern();const glob2=this.toString();const[re,body,hasMagic,uflag]=this.toRegExpSource();const anyMagic=hasMagic||__privateGet(this,_hasMagic)||__privateGet(this,_options).nocase&&!__privateGet(this,_options).nocaseMagicOnly&&glob2.toUpperCase()!==glob2.toLowerCase();if(!anyMagic){return body}const flags=(__privateGet(this,_options).nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob2})}get options(){return __privateGet(this,_options)}toRegExpSource(allowDot){var _a;const dot=allowDot??!!__privateGet(this,_options).dot;if(__privateGet(this,_root)===this)__privateMethod(this,_AST_instances,fillNegs_fn).call(this);if(!this.type){const noEmpty=this.isStart()&&this.isEnd();const src=__privateGet(this,_parts).map(p=>{var _a2;const[re,_2,hasMagic,uflag]=typeof p==="string"?__privateMethod(_a2=_AST,_AST_static,parseGlob_fn).call(_a2,p,__privateGet(this,_hasMagic),noEmpty):p.toRegExpSource(allowDot);__privateSet(this,_hasMagic,__privateGet(this,_hasMagic)||hasMagic);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re}).join("");let start2="";if(this.isStart()){if(typeof __privateGet(this,_parts)[0]==="string"){const dotTravAllowed=__privateGet(this,_parts).length===1&&justDots.has(__privateGet(this,_parts)[0]);if(!dotTravAllowed){const aps=addPatternStart;const needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4));const needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}}}let end="";if(this.isEnd()&&__privateGet(__privateGet(this,_root),_filledNegs)&&((_a=__privateGet(this,_parent))==null?void 0:_a.type)==="!"){end="(?:$|\\/)"}const final2=start2+src+end;return[final2,unescape2(src),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}const repeated=this.type==="*"||this.type==="+";const start=this.type==="!"?"(?:(?!(?:":"(?:";let body=__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){const s=this.toString();__privateSet(this,_parts,[s]);this.type=null;__privateSet(this,_hasMagic,void 0);return[s,unescape2(this.toString()),false,false]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,true);if(bodyDotAllowed===body){bodyDotAllowed=""}if(bodyDotAllowed){body=`(?:${body})(?:${bodyDotAllowed})*?`}let final="";if(this.type==="!"&&__privateGet(this,_emptyExt)){final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty}else{const close=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?`)?`:`)${this.type}`;final=start+body+close}return[final,unescape2(body),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}};_root=new WeakMap;_hasMagic=new WeakMap;_uflag=new WeakMap;_parts=new WeakMap;_parent=new WeakMap;_parentIndex=new WeakMap;_negs=new WeakMap;_filledNegs=new WeakMap;_options=new WeakMap;_toString=new WeakMap;_emptyExt=new WeakMap;_AST_instances=new WeakSet;fillNegs_fn=function(){if(this!==__privateGet(this,_root))throw new Error("should only call on root");if(__privateGet(this,_filledNegs))return this;this.toString();__privateSet(this,_filledNegs,true);let n;while(n=__privateGet(this,_negs).pop()){if(n.type!=="!")continue;let p=n;let pp=__privateGet(p,_parent);while(pp){for(let i=__privateGet(p,_parentIndex)+1;!pp.type&&i<__privateGet(pp,_parts).length;i++){for(const part of __privateGet(n,_parts)){if(typeof part==="string"){throw new Error("string part in extglob AST??")}part.copyIn(__privateGet(pp,_parts)[i])}}p=pp;pp=__privateGet(p,_parent)}}return this};_AST_static=new WeakSet;parseAST_fn=function(str,ast,pos,opt){var _a,_b;let escaping=false;let inBrace=false;let braceStart=-1;let braceNeg=false;if(ast.type===null){let i2=pos;let acc2="";while(i2<str.length){const c=str.charAt(i2++);if(escaping||c==="\\"){escaping=!escaping;acc2+=c;continue}if(inBrace){if(i2===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i2===braceStart+2&&braceNeg)){inBrace=false}acc2+=c;continue}else if(c==="["){inBrace=true;braceStart=i2;braceNeg=false;acc2+=c;continue}if(!opt.noext&&isExtglobType(c)&&str.charAt(i2)==="("){ast.push(acc2);acc2="";const ext2=new _AST(c,ast);i2=__privateMethod(_a=_AST,_AST_static,parseAST_fn).call(_a,str,ext2,i2,opt);ast.push(ext2);continue}acc2+=c}ast.push(acc2);return i2}let i=pos+1;let part=new _AST(null,ast);const parts=[];let acc="";while(i<str.length){const c=str.charAt(i++);if(escaping||c==="\\"){escaping=!escaping;acc+=c;continue}if(inBrace){if(i===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i===braceStart+2&&braceNeg)){inBrace=false}acc+=c;continue}else if(c==="["){inBrace=true;braceStart=i;braceNeg=false;acc+=c;continue}if(isExtglobType(c)&&str.charAt(i)==="("){part.push(acc);acc="";const ext2=new _AST(c,part);part.push(ext2);i=__privateMethod(_b=_AST,_AST_static,parseAST_fn).call(_b,str,ext2,i,opt);continue}if(c==="|"){part.push(acc);acc="";parts.push(part);part=new _AST(null,ast);continue}if(c===")"){if(acc===""&&__privateGet(ast,_parts).length===0){__privateSet(ast,_emptyExt,true)}part.push(acc);acc="";ast.push(...parts,part);return i}acc+=c}ast.type=null;__privateSet(ast,_hasMagic,void 0);__privateSet(ast,_parts,[str.substring(pos-1)]);return i};partsToRegExp_fn=function(dot){return __privateGet(this,_parts).map(p=>{if(typeof p==="string"){throw new Error("string type in extglob ast??")}const[re,_2,_hasMagic2,uflag]=p.toRegExpSource(dot);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")};parseGlob_fn=function(glob2,hasMagic,noEmpty=false){let escaping=false;let re="";let uflag=false;for(let i=0;i<glob2.length;i++){const c=glob2.charAt(i);if(escaping){escaping=false;re+=(reSpecials.has(c)?"\\":"")+c;continue}if(c==="\\"){if(i===glob2.length-1){re+="\\\\"}else{escaping=true}continue}if(c==="["){const[src,needUflag,consumed,magic]=parseClass(glob2,i);if(consumed){re+=src;uflag=uflag||needUflag;i+=consumed-1;hasMagic=hasMagic||magic;continue}}if(c==="*"){if(noEmpty&&glob2==="*")re+=starNoEmpty;else re+=star;hasMagic=true;continue}if(c==="?"){re+=qmark;hasMagic=true;continue}re+=regExpEscape(c)}return[re,unescape2(glob2),!!hasMagic,uflag]};__privateAdd(_AST,_AST_static);AST=_AST}});var escape;var init_escape=__esm({"node_modules/minimatch/dist/esm/escape.js"(){escape=(s,{windowsPathsNoEscape=false}={})=>{return windowsPathsNoEscape?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&")}}});var import_brace_expansion,minimatch,starDotExtRE,starDotExtTest,starDotExtTestDot,starDotExtTestNocase,starDotExtTestNocaseDot,starDotStarRE,starDotStarTest,starDotStarTestDot,dotStarRE,dotStarTest,starRE,starTest,starTestDot,qmarksRE,qmarksTestNocase,qmarksTestNocaseDot,qmarksTestDot,qmarksTest,qmarksTestNoExt,qmarksTestNoExtDot,defaultPlatform,path16,sep,GLOBSTAR,qmark2,star2,twoStarDot,twoStarNoDot,filter,ext,defaults,braceExpand,makeRe,match,globMagic,regExpEscape2,Minimatch;var init_esm=__esm({"node_modules/minimatch/dist/esm/index.js"(){import_brace_expansion=__toESM(require_brace_expansion(),1);init_assert_valid_pattern();init_ast();init_escape();init_unescape();init_ast();init_escape();init_unescape();minimatch=(p,pattern,options={})=>{assertValidPattern(pattern);if(!options.nocomment&&pattern.charAt(0)==="#"){return false}return new Minimatch(pattern,options).match(p)};starDotExtRE=/^\*+([^+@!?\*\[\(]*)$/;starDotExtTest=ext2=>f=>!f.startsWith(".")&&f.endsWith(ext2);starDotExtTestDot=ext2=>f=>f.endsWith(ext2);starDotExtTestNocase=ext2=>{ext2=ext2.toLowerCase();return f=>!f.startsWith(".")&&f.toLowerCase().endsWith(ext2)};starDotExtTestNocaseDot=ext2=>{ext2=ext2.toLowerCase();return f=>f.toLowerCase().endsWith(ext2)};starDotStarRE=/^\*+\.\*+$/;starDotStarTest=f=>!f.startsWith(".")&&f.includes(".");starDotStarTestDot=f=>f!=="."&&f!==".."&&f.includes(".");dotStarRE=/^\.\*+$/;dotStarTest=f=>f!=="."&&f!==".."&&f.startsWith(".");starRE=/^\*+$/;starTest=f=>f.length!==0&&!f.startsWith(".");starTestDot=f=>f.length!==0&&f!=="."&&f!=="..";qmarksRE=/^\?+([^+@!?\*\[\(]*)?$/;qmarksTestNocase=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f=>noext(f)&&f.toLowerCase().endsWith(ext2)};qmarksTestNocaseDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f=>noext(f)&&f.toLowerCase().endsWith(ext2)};qmarksTestDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);return!ext2?noext:f=>noext(f)&&f.endsWith(ext2)};qmarksTest=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);return!ext2?noext:f=>noext(f)&&f.endsWith(ext2)};qmarksTestNoExt=([$0])=>{const len=$0.length;return f=>f.length===len&&!f.startsWith(".")};qmarksTestNoExtDot=([$0])=>{const len=$0.length;return f=>f.length===len&&f!=="."&&f!==".."};defaultPlatform=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";path16={win32:{sep:"\\"},posix:{sep:"/"}};sep=defaultPlatform==="win32"?path16.win32.sep:path16.posix.sep;minimatch.sep=sep;GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;qmark2="[^/]";star2=qmark2+"*?";twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?";filter=(pattern,options={})=>p=>minimatch(p,pattern,options);minimatch.filter=filter;ext=(a,b={})=>Object.assign({},a,b);defaults=def=>{if(!def||typeof def!=="object"||!Object.keys(def).length){return minimatch}const orig=minimatch;const m=(p,pattern,options={})=>orig(p,pattern,ext(def,options));return Object.assign(m,{Minimatch:class Minimatch extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s,options={})=>orig.unescape(s,ext(def,options)),escape:(s,options={})=>orig.escape(s,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list,pattern,options={})=>orig.match(list,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;braceExpand=(pattern,options={})=>{assertValidPattern(pattern);if(options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)){return[pattern]}return(0,import_brace_expansion.default)(pattern)};minimatch.braceExpand=braceExpand;makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;match=(list,pattern,options={})=>{const mm=new Minimatch(pattern,options);list=list.filter(f=>mm.match(f));if(mm.options.nonull&&!list.length){list.push(pattern)}return list};minimatch.match=match;globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;regExpEscape2=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(pattern,options={}){assertValidPattern(pattern);options=options||{};this.options=options;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows=this.platform==="win32";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options.allowWindowsEscape===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=false;this.nonegate=!!options.nonegate;this.comment=false;this.empty=false;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1){return true}for(const pattern of this.set){for(const part of pattern){if(typeof part!=="string")return true}}return false}debug(..._2){}make(){const pattern=this.pattern;const options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=true;return}if(!pattern){this.empty=true;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];if(options.debug){this.debug=(...args)=>console.error(...args)}this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set=this.globParts.map((s,_2,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=s[0]===""&&s[1]===""&&(s[2]==="?"||!globMagic.test(s[2]))&&!globMagic.test(s[3]);const isDrive=/^[a-z]:/i.test(s[0]);if(isUNC){return[...s.slice(0,4),...s.slice(4).map(ss=>this.parse(ss))]}else if(isDrive){return[s[0],...s.slice(1).map(ss=>this.parse(ss))]}}return s.map(ss=>this.parse(ss))});this.debug(this.pattern,set);this.set=set.filter(s=>s.indexOf(false)===-1);if(this.isWindows){for(let i=0;i<this.set.length;i++){const p=this.set[i];if(p[0]===""&&p[1]===""&&this.globParts[i][2]==="?"&&typeof p[3]==="string"&&/^[a-z]:$/i.test(p[3])){p[2]="?"}}}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar){for(let i=0;i<globParts.length;i++){for(let j=0;j<globParts[i].length;j++){if(globParts[i][j]==="**"){globParts[i][j]="*"}}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else if(optimizationLevel>=1){globParts=this.levelOneOptimize(globParts)}else{globParts=this.adjascentGlobstarOptimize(globParts)}return globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs=-1;while(-1!==(gs=parts.indexOf("**",gs+1))){let i=gs;while(parts[i+1]==="**"){i++}if(i!==gs){parts.splice(gs,i-gs)}}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{parts=parts.reduce((set,part)=>{const prev=set[set.length-1];if(part==="**"&&prev==="**"){return set}if(part===".."){if(prev&&prev!==".."&&prev!=="."&&prev!=="**"){set.pop();return set}}set.push(part);return set},[]);return parts.length===0?[""]:parts})}levelTwoFileOptimize(parts){if(!Array.isArray(parts)){parts=this.slashSplit(parts)}let didSomething=false;do{didSomething=false;if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){const p=parts[i];if(i===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i,1);i--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd=0;while(-1!==(dd=parts.indexOf("..",dd+1))){const p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;parts.splice(dd-1,2);dd-=2}}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let didSomething=false;do{didSomething=false;for(let parts of globParts){let gs=-1;while(-1!==(gs=parts.indexOf("**",gs+1))){let gss=gs;while(parts[gss+1]==="**"){gss++}if(gss>gs){parts.splice(gs+1,gss-gs)}let next=parts[gs+1];const p=parts[gs+2];const p2=parts[gs+3];if(next!=="..")continue;if(!p||p==="."||p===".."||!p2||p2==="."||p2===".."){continue}didSomething=true;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";globParts.push(other);gs--}if(!this.preserveMultipleSlashes){for(let i=1;i<parts.length-1;i++){const p=parts[i];if(i===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i,1);i--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd=0;while(-1!==(dd=parts.indexOf("..",dd+1))){const p=parts[dd-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;const needDot=dd===1&&parts[dd+1]==="**";const splin=needDot?["."]:[];parts.splice(dd-1,2,...splin);if(parts.length===0)parts.push("");dd-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i=0;i<globParts.length-1;i++){for(let j=i+1;j<globParts.length;j++){const matched=this.partsMatch(globParts[i],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i]=[];globParts[j]=matched;break}}}return globParts.filter(gs=>gs.length)}partsMatch(a,b,emptyGSMatch=false){let ai=0;let bi=0;let result=[];let which="";while(ai<a.length&&bi<b.length){if(a[ai]===b[bi]){result.push(which==="b"?b[bi]:a[ai]);ai++;bi++}else if(emptyGSMatch&&a[ai]==="**"&&b[bi]===a[ai+1]){result.push(a[ai]);ai++}else if(emptyGSMatch&&b[bi]==="**"&&a[ai]===b[bi+1]){result.push(b[bi]);bi++}else if(a[ai]==="*"&&b[bi]&&(this.options.dot||!b[bi].startsWith("."))&&b[bi]!=="**"){if(which==="b")return false;which="a";result.push(a[ai]);ai++;bi++}else if(b[bi]==="*"&&a[ai]&&(this.options.dot||!a[ai].startsWith("."))&&a[ai]!=="**"){if(which==="a")return false;which="b";result.push(b[bi]);ai++;bi++}else{return false}}return a.length===b.length&&result}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate=false;let negateOffset=0;for(let i=0;i<pattern.length&&pattern.charAt(i)==="!";i++){negate=!negate;negateOffset++}if(negateOffset)this.pattern=pattern.slice(negateOffset);this.negate=negate}matchOne(file,pattern,partial=false){const options=this.options;if(this.isWindows){const fileDrive=typeof file[0]==="string"&&/^[a-z]:$/i.test(file[0]);const fileUNC=!fileDrive&&file[0]===""&&file[1]===""&&file[2]==="?"&&/^[a-z]:$/i.test(file[3]);const patternDrive=typeof pattern[0]==="string"&&/^[a-z]:$/i.test(pattern[0]);const patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]==="string"&&/^[a-z]:$/i.test(pattern[3]);const fdi=fileUNC?3:fileDrive?0:void 0;const pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi==="number"&&typeof pdi==="number"){const[fd,pd]=[file[fdi],pattern[pdi]];if(fd.toLowerCase()===pd.toLowerCase()){pattern[pdi]=fd;if(pdi>fdi){pattern=pattern.slice(pdi)}else if(fdi>pdi){file=file.slice(fdi)}}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){file=this.levelTwoFileOptimize(file)}this.debug("matchOne",this,{file,pattern});this.debug("matchOne",file.length,pattern.length);for(var fi=0,pi=0,fl=file.length,pl=pattern.length;fi<fl&&pi<pl;fi++,pi++){this.debug("matchOne loop");var p=pattern[pi];var f=file[fi];this.debug(pattern,p,f);if(p===false){return false}if(p===GLOBSTAR){this.debug("GLOBSTAR",[pattern,p,f]);var fr=fi;var pr=pi+1;if(pr===pl){this.debug("** at the end");for(;fi<fl;fi++){if(file[fi]==="."||file[fi]===".."||!options.dot&&file[fi].charAt(0)===".")return false}return true}while(fr<fl){var swallowee=file[fr];this.debug("\nglobstar while",file,fr,pattern,pr,swallowee);if(this.matchOne(file.slice(fr),pattern.slice(pr),partial)){this.debug("globstar found match!",fr,fl,swallowee);return true}else{if(swallowee==="."||swallowee===".."||!options.dot&&swallowee.charAt(0)==="."){this.debug("dot detected!",file,fr,pattern,pr);break}this.debug("globstar swallow a segment, and continue");fr++}}if(partial){this.debug("\n>>> no match, partial?",file,fr,pattern,pr);if(fr===fl){return true}}return false}let hit;if(typeof p==="string"){hit=f===p;this.debug("string match",p,f,hit)}else{hit=p.test(f);this.debug("pattern match",p,f,hit)}if(!hit)return false}if(fi===fl&&pi===pl){return true}else if(fi===fl){return partial}else if(pi===pl){return fi===fl-1&&file[fi]===""}else{throw new Error("wtf?")}}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m;let fastTest=null;if(m=pattern.match(starRE)){fastTest=options.dot?starTestDot:starTest}else if(m=pattern.match(starDotExtRE)){fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1])}else if(m=pattern.match(qmarksRE)){fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m)}else if(m=pattern.match(starDotStarRE)){fastTest=options.dot?starDotStarTestDot:starDotStarTest}else if(m=pattern.match(dotStarRE)){fastTest=dotStarTest}const re=AST.fromGlob(pattern,this.options).toMMPattern();if(fastTest&&typeof re==="object"){Reflect.defineProperty(re,"test",{value:fastTest})}return re}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;const set=this.set;if(!set.length){this.regexp=false;return this.regexp}const options=this.options;const twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot;const flags=new Set(options.nocase?["i"]:[]);let re=set.map(pattern=>{const pp=pattern.map(p=>{if(p instanceof RegExp){for(const f of p.flags.split(""))flags.add(f)}return typeof p==="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp.forEach((p,i)=>{const next=pp[i+1];const prev=pp[i-1];if(p!==GLOBSTAR||prev===GLOBSTAR){return}if(prev===void 0){if(next!==void 0&&next!==GLOBSTAR){pp[i+1]="(?:\\/|"+twoStar+"\\/)?"+next}else{pp[i]=twoStar}}else if(next===void 0){pp[i-1]=prev+"(?:\\/|"+twoStar+")?"}else if(next!==GLOBSTAR){pp[i-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next;pp[i+1]=GLOBSTAR}});return pp.filter(p=>p!==GLOBSTAR).join("/")}).join("|");const[open,close]=set.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$";if(this.negate)re="^(?!"+re+").+$";try{this.regexp=new RegExp(re,[...flags].join(""))}catch(ex){this.regexp=false}return this.regexp}slashSplit(p){if(this.preserveMultipleSlashes){return p.split("/")}else if(this.isWindows&&/^\/\/[^\/]+/.test(p)){return["",...p.split(/\/+/)]}else{return p.split(/\/+/)}}match(f,partial=this.partial){this.debug("match",f,this.pattern);if(this.comment){return false}if(this.empty){return f===""}if(f==="/"&&partial){return true}const options=this.options;if(this.isWindows){f=f.split("\\").join("/")}const ff=this.slashSplit(f);this.debug(this.pattern,"split",ff);const set=this.set;this.debug(this.pattern,"set",set);let filename=ff[ff.length-1];if(!filename){for(let i=ff.length-2;!filename&&i>=0;i--){filename=ff[i]}}for(let i=0;i<set.length;i++){const pattern=set[i];let file=ff;if(options.matchBase&&pattern.length===1){file=[filename]}const hit=this.matchOne(file,pattern,partial);if(hit){if(options.flipNegate){return true}return!this.negate}}if(options.flipNegate){return false}return this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape2}});function indexByHierarchicalId(stacks){const result=new Map;for(const stack of stacks){result.set(stack.hierarchicalId,stack)}return result}function includeDownstreamStacks(selectedStacks,allStacks){const added=new Array;let madeProgress;do{madeProgress=false;for(const[id,stack]of allStacks){if(!selectedStacks.has(id)&&(stack.dependencies||[]).some(dep=>selectedStacks.has(dep.id))){selectedStacks.set(id,stack);added.push(id);madeProgress=true}}}while(madeProgress);if(added.length>0){print("Including depending stacks: %s",chalk16.bold(added.join(", ")))}}function includeUpstreamStacks(selectedStacks,allStacks){const added=new Array;let madeProgress=true;while(madeProgress){madeProgress=false;for(const stack of selectedStacks.values()){for(const dependencyId of stack.dependencies.map(x=>x.manifest.displayName??x.id)){if(!selectedStacks.has(dependencyId)&&allStacks.has(dependencyId)){added.push(dependencyId);selectedStacks.set(dependencyId,allStacks.get(dependencyId));madeProgress=true}}}}if(added.length>0){print("Including dependency stacks: %s",chalk16.bold(added.join(", ")))}}function sanitizePatterns(patterns){let sanitized=patterns.filter(s=>s!=null);sanitized=[...new Set(sanitized)];return sanitized}var cxapi3,chalk16,semver4,CloudAssembly2,StackCollection;var init_cloud_assembly2=__esm({"lib/api/cxapp/cloud-assembly.ts"(){"use strict";cxapi3=__toESM(require_lib3());chalk16=__toESM(require_source());init_esm();semver4=__toESM(require_semver4());init_logging();init_error();init_util3();CloudAssembly2=class{constructor(assembly){this.assembly=assembly;this.directory=assembly.directory}async selectStacks(selector,options){const asm=this.assembly;const topLevelStacks=asm.stacks;const stacks=semver4.major(asm.version)<10?asm.stacks:asm.stacksRecursively;const allTopLevel=selector.allTopLevel??false;const patterns=sanitizePatterns(selector.patterns);if(stacks.length===0){if(options.ignoreNoStacks){return new StackCollection(this,[])}throw new ToolkitError("This app contains no stacks")}if(allTopLevel){return this.selectTopLevelStacks(stacks,topLevelStacks,options.extend)}else if(patterns.length>0){return this.selectMatchingStacks(stacks,patterns,options.extend)}else{return this.selectDefaultStacks(stacks,topLevelStacks,options.defaultBehavior)}}selectTopLevelStacks(stacks,topLevelStacks,extend=0){if(topLevelStacks.length>0){return this.extendStacks(topLevelStacks,stacks,extend)}else{throw new ToolkitError('No stack found in the main cloud assembly. Use "list" to print manifest')}}selectMatchingStacks(stacks,patterns,extend=0){const matchingPattern=pattern=>stack=>minimatch(stack.hierarchicalId,pattern);const matchedStacks=flatten(patterns.map(pattern=>stacks.filter(matchingPattern(pattern))));return this.extendStacks(matchedStacks,stacks,extend)}selectDefaultStacks(stacks,topLevelStacks,defaultSelection){switch(defaultSelection){case"main":return new StackCollection(this,topLevelStacks);case"all":return new StackCollection(this,stacks);case"none":return new StackCollection(this,[]);case"single":if(topLevelStacks.length===1){return new StackCollection(this,topLevelStacks)}else{throw new ToolkitError(`Since this app includes more than a single stack, specify which stacks to use (wildcards are supported) or specify \`--all\`
|
|
847
847
|
Stacks: ${stacks.map(x=>x.hierarchicalId).join(" \xB7 ")}`)}default:throw new ToolkitError(`invalid default behavior: ${defaultSelection}`)}}extendStacks(matched,all,extend=0){const allStacks=new Map;for(const stack of all){allStacks.set(stack.hierarchicalId,stack)}const index=indexByHierarchicalId(matched);switch(extend){case 2:includeDownstreamStacks(index,allStacks);break;case 1:includeUpstreamStacks(index,allStacks);break}const selectedList=all.filter(s=>index.has(s.hierarchicalId));return new StackCollection(this,selectedList)}stackById(stackId){return new StackCollection(this,[this.assembly.getStackArtifact(stackId)])}};StackCollection=class _StackCollection{constructor(assembly,stackArtifacts){this.assembly=assembly;this.stackArtifacts=stackArtifacts}get stackCount(){return this.stackArtifacts.length}get firstStack(){if(this.stackCount<1){throw new ToolkitError("StackCollection contains no stack artifacts (trying to access the first one)")}return this.stackArtifacts[0]}get stackIds(){return this.stackArtifacts.map(s=>s.id)}reversed(){const arts=[...this.stackArtifacts];arts.reverse();return new _StackCollection(this.assembly,arts)}filter(predicate){return new _StackCollection(this.assembly,this.stackArtifacts.filter(predicate))}concat(other){return new _StackCollection(this.assembly,this.stackArtifacts.concat(other.stackArtifacts))}processMetadataMessages(options={}){let warnings=false;let errors=false;for(const stack of this.stackArtifacts){for(const message of stack.messages){switch(message.level){case cxapi3.SynthesisMessageLevel.WARNING:warnings=true;printMessage(warning,"Warning",message.id,message.entry);break;case cxapi3.SynthesisMessageLevel.ERROR:errors=true;printMessage(error,"Error",message.id,message.entry);break;case cxapi3.SynthesisMessageLevel.INFO:printMessage(print,"Info",message.id,message.entry);break}}}if(errors&&!options.ignoreErrors){throw new ToolkitError("Found errors")}if(options.strict&&warnings){throw new ToolkitError("Found warnings (--strict mode)")}function printMessage(logFn,prefix,id,entry){logFn(`[${prefix} at ${id}] ${entry.data}`);if(options.verbose&&entry.trace){logFn(` ${entry.trace.join("\n ")}`)}}}}}});function descending(valueOf){return(a,b)=>{return valueOf(b)-valueOf(a)}}var AmiContextProviderPlugin;var init_ami2=__esm({"lib/context-providers/ami.ts"(){"use strict";init_sdk_provider();init_logging();AmiContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const region=args.region;const account=args.account;print(`Searching for AMI in ${account}:${region}`);debug(`AMI search parameters: ${JSON.stringify(args)}`);const ec2=(await initContextProviderSdk(this.aws,args)).ec2();const response=await ec2.describeImages({Owners:args.owners,Filters:Object.entries(args.filters).map(([key,values])=>({Name:key,Values:values}))});const images=[...response.Images||[]].filter(i=>i.ImageId!==void 0);if(images.length===0){throw new Error("No AMI found that matched the search criteria")}images.sort(descending(i=>Date.parse(i.CreationDate||"1970")));debug(`Selected image '${images[0].ImageId}' created at '${images[0].CreationDate}'`);return images[0].ImageId}}}});var AZContextProviderPlugin;var init_availability_zones2=__esm({"lib/context-providers/availability-zones.ts"(){"use strict";init_sdk_provider();init_logging();AZContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const region=args.region;const account=args.account;debug(`Reading AZs for ${account}:${region}`);const ec2=(await initContextProviderSdk(this.aws,args)).ec2();const response=await ec2.describeAvailabilityZones({});if(!response.AvailabilityZones){return[]}const azs=response.AvailabilityZones.filter(zone=>zone.State==="available").map(zone=>zone.ZoneName);return azs}}}});var EndpointServiceAZContextProviderPlugin;var init_endpoint_service_availability_zones2=__esm({"lib/context-providers/endpoint-service-availability-zones.ts"(){"use strict";init_sdk_provider();init_logging();EndpointServiceAZContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const region=args.region;const account=args.account;const serviceName=args.serviceName;debug(`Reading AZs for ${account}:${region}:${serviceName}`);const ec2=(await initContextProviderSdk(this.aws,args)).ec2();const response=await ec2.describeVpcEndpointServices({ServiceNames:[serviceName]});if(!response.ServiceDetails||response.ServiceDetails.length===0){debug(`Could not retrieve service details for ${account}:${region}:${serviceName}`);return[]}const azs=response.ServiceDetails[0].AvailabilityZones;debug(`Endpoint service ${account}:${region}:${serviceName} is available in availability zones ${azs}`);return azs}}}});var HostedZoneContextProviderPlugin;var init_hosted_zones=__esm({"lib/context-providers/hosted-zones.ts"(){"use strict";init_sdk_provider();init_logging();HostedZoneContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const account=args.account;const region=args.region;if(!this.isHostedZoneQuery(args)){throw new Error(`HostedZoneProvider requires domainName property to be set in ${args}`)}const domainName=args.domainName;debug(`Reading hosted zone ${account}:${region}:${domainName}`);const r53=(await initContextProviderSdk(this.aws,args)).route53();const response=await r53.listHostedZonesByName({DNSName:domainName});if(!response.HostedZones){throw new Error(`Hosted Zone not found in account ${account}, region ${region}: ${domainName}`)}const candidateZones=await this.filterZones(r53,response.HostedZones,args);if(candidateZones.length!==1){const filteProps=`dns:${domainName}, privateZone:${args.privateZone}, vpcId:${args.vpcId}`;throw new Error(`Found zones: ${JSON.stringify(candidateZones)} for ${filteProps}, but wanted exactly 1 zone`)}return{Id:candidateZones[0].Id,Name:candidateZones[0].Name}}async filterZones(r53,zones,props){let candidates=[];const domainName=props.domainName.endsWith(".")?props.domainName:`${props.domainName}.`;debug(`Found the following zones ${JSON.stringify(zones)}`);candidates=zones.filter(zone=>zone.Name===domainName);debug(`Found the following matched name zones ${JSON.stringify(candidates)}`);if(props.privateZone){candidates=candidates.filter(zone=>zone.Config&&zone.Config.PrivateZone)}else{candidates=candidates.filter(zone=>!zone.Config||!zone.Config.PrivateZone)}if(props.vpcId){const vpcZones=[];for(const zone of candidates){const data2=await r53.getHostedZone({Id:zone.Id});if(!data2.VPCs){debug(`Expected VPC for private zone but no VPC found ${zone.Id}`);continue}if(data2.VPCs.map(vpc=>vpc.VPCId).includes(props.vpcId)){vpcZones.push(zone)}}return vpcZones}return candidates}isHostedZoneQuery(props){return props.domainName!==void 0}}}});var KeyContextProviderPlugin;var init_keys=__esm({"lib/context-providers/keys.ts"(){"use strict";init_sdk_provider();init_logging();KeyContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const kms=(await initContextProviderSdk(this.aws,args)).kms();const aliasListEntry=await this.findKey(kms,args);return this.readKeyProps(aliasListEntry,args)}async findKey(kms,args){debug(`Listing keys in ${args.account}:${args.region}`);let response;let nextMarker;do{response=await kms.listAliases({Marker:nextMarker});const aliases=response.Aliases||[];for(const alias of aliases){if(alias.AliasName==args.aliasName){return alias}}nextMarker=response.NextMarker}while(nextMarker);const suppressError="ignoreErrorOnMissingContext"in args&&args.ignoreErrorOnMissingContext;const hasDummyKeyId="dummyValue"in args&&typeof args.dummyValue==="object"&&args.dummyValue!==null&&"keyId"in args.dummyValue;if(suppressError&&hasDummyKeyId){const keyId=args.dummyValue.keyId;return{TargetKeyId:keyId}}throw new Error(`Could not find any key with alias named ${args.aliasName}`)}async readKeyProps(alias,args){if(!alias.TargetKeyId){throw new Error(`Could not find any key with alias named ${args.aliasName}`)}debug(`Key found ${alias.TargetKeyId}`);return{keyId:alias.TargetKeyId}}}}});var import_cx_api6,LoadBalancerContextProviderPlugin,LoadBalancerListenerContextProviderPlugin,LoadBalancerProvider;var init_load_balancers=__esm({"lib/context-providers/load-balancers.ts"(){"use strict";import_cx_api6=__toESM(require_lib3());init_sdk_provider();LoadBalancerContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(query){if(!query.loadBalancerArn&&!query.loadBalancerTags){throw new Error("The load balancer lookup query must specify either `loadBalancerArn` or `loadBalancerTags`")}const loadBalancer=await(await LoadBalancerProvider.getClient(this.aws,query)).getLoadBalancer();const ipAddressType=loadBalancer.IpAddressType==="ipv4"?import_cx_api6.LoadBalancerIpAddressType.IPV4:import_cx_api6.LoadBalancerIpAddressType.DUAL_STACK;return{loadBalancerArn:loadBalancer.LoadBalancerArn,loadBalancerCanonicalHostedZoneId:loadBalancer.CanonicalHostedZoneId,loadBalancerDnsName:loadBalancer.DNSName,vpcId:loadBalancer.VpcId,securityGroupIds:loadBalancer.SecurityGroups??[],ipAddressType}}};LoadBalancerListenerContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(query){if(!query.listenerArn&&!query.loadBalancerArn&&!query.loadBalancerTags){throw new Error("The load balancer listener query must specify at least one of: `listenerArn`, `loadBalancerArn` or `loadBalancerTags`")}return(await LoadBalancerProvider.getClient(this.aws,query)).getListener()}};LoadBalancerProvider=class _LoadBalancerProvider{constructor(client,filter2,listener){this.client=client;this.filter=filter2;this.listener=listener}static async getClient(aws,query){const client=(await initContextProviderSdk(aws,query)).elbv2();try{const listener=query.listenerArn?(await client.describeListeners({ListenerArns:[query.listenerArn]})).Listeners[0]:void 0;return new _LoadBalancerProvider(client,{...query,loadBalancerArn:(listener==null?void 0:listener.LoadBalancerArn)||query.loadBalancerArn},listener)}catch(err){throw new Error(`No load balancer listeners found matching arn ${query.listenerArn}`)}}async getLoadBalancer(){const loadBalancers=await this.getLoadBalancers();if(loadBalancers.length===0){throw new Error(`No load balancers found matching ${JSON.stringify(this.filter)}`)}if(loadBalancers.length>1){throw new Error(`Multiple load balancers found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`)}return loadBalancers[0]}async getListener(){var _a;if(this.listener){try{const loadBalancer=await this.getLoadBalancer();return{listenerArn:this.listener.ListenerArn,listenerPort:this.listener.Port,securityGroupIds:loadBalancer.SecurityGroups||[]}}catch(err){throw new Error(`No associated load balancer found for listener arn ${this.filter.listenerArn}`)}}const loadBalancers=await this.getLoadBalancers();if(loadBalancers.length===0){throw new Error(`No associated load balancers found for load balancer listener query ${JSON.stringify(this.filter)}`)}const listeners=(await this.getListenersForLoadBalancers(loadBalancers)).filter(listener=>{return(!this.filter.listenerPort||listener.Port===this.filter.listenerPort)&&(!this.filter.listenerProtocol||listener.Protocol===this.filter.listenerProtocol)});if(listeners.length===0){throw new Error(`No load balancer listeners found matching ${JSON.stringify(this.filter)}`)}if(listeners.length>1){throw new Error(`Multiple load balancer listeners found matching ${JSON.stringify(this.filter)} - please provide more specific criteria`)}return{listenerArn:listeners[0].ListenerArn,listenerPort:listeners[0].Port,securityGroupIds:((_a=loadBalancers.find(lb=>listeners[0].LoadBalancerArn===lb.LoadBalancerArn))==null?void 0:_a.SecurityGroups)||[]}}async getLoadBalancers(){const loadBalancerArns=this.filter.loadBalancerArn?[this.filter.loadBalancerArn]:void 0;const loadBalancers=(await this.client.paginateDescribeLoadBalancers({LoadBalancerArns:loadBalancerArns})).filter(lb=>lb.Type===this.filter.loadBalancerType);return this.filterByTags(loadBalancers)}async filterByTags(loadBalancers){if(!this.filter.loadBalancerTags){return loadBalancers}return(await this.describeTags(loadBalancers.map(lb=>lb.LoadBalancerArn))).filter(tagDescription=>{return this.filter.loadBalancerTags.every(filter2=>{var _a;return(_a=tagDescription.Tags)==null?void 0:_a.some(tag=>filter2.key===tag.Key&&filter2.value===tag.Value)})}).flatMap(tag=>loadBalancers.filter(loadBalancer=>tag.ResourceArn===loadBalancer.LoadBalancerArn))}async describeTags(resourceArns){const chunkSize=20;const tags=Array();for(let i=0;i<resourceArns.length;i+=chunkSize){const chunk=resourceArns.slice(i,Math.min(i+chunkSize,resourceArns.length));const chunkTags=await this.client.describeTags({ResourceArns:chunk});tags.push(...chunkTags.TagDescriptions||[])}return tags}async getListenersForLoadBalancers(loadBalancers){const listeners=[];for(const loadBalancer of loadBalancers.map(lb=>lb.LoadBalancerArn)){listeners.push(...await this.client.paginateDescribeListeners({LoadBalancerArn:loadBalancer}))}return listeners}}}});function hasAllTrafficEgress(securityGroup){var _a,_b;let hasAllTrafficCidrV4=false;let hasAllTrafficCidrV6=false;for(const ipPermission of securityGroup.IpPermissionsEgress??[]){const isAllProtocols=ipPermission.IpProtocol==="-1";if(isAllProtocols&&((_a=ipPermission.IpRanges)==null?void 0:_a.some(m=>m.CidrIp==="0.0.0.0/0"))){hasAllTrafficCidrV4=true}if(isAllProtocols&&((_b=ipPermission.Ipv6Ranges)==null?void 0:_b.some(m=>m.CidrIpv6==="::/0"))){hasAllTrafficCidrV6=true}}return hasAllTrafficCidrV4&&hasAllTrafficCidrV6}var SecurityGroupContextProviderPlugin;var init_security_groups=__esm({"lib/context-providers/security-groups.ts"(){"use strict";init_sdk_provider();SecurityGroupContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){if(args.securityGroupId&&args.securityGroupName){throw new Error("'securityGroupId' and 'securityGroupName' can not be specified both when looking up a security group")}if(!args.securityGroupId&&!args.securityGroupName){throw new Error("'securityGroupId' or 'securityGroupName' must be specified to look up a security group")}const ec2=(await initContextProviderSdk(this.aws,args)).ec2();const filters=[];if(args.vpcId){filters.push({Name:"vpc-id",Values:[args.vpcId]})}if(args.securityGroupName){filters.push({Name:"group-name",Values:[args.securityGroupName]})}const response=await ec2.describeSecurityGroups({GroupIds:args.securityGroupId?[args.securityGroupId]:void 0,Filters:filters.length>0?filters:void 0});const securityGroups=response.SecurityGroups??[];if(securityGroups.length===0){throw new Error(`No security groups found matching ${JSON.stringify(args)}`)}if(securityGroups.length>1){throw new Error(`More than one security groups found matching ${JSON.stringify(args)}`)}const[securityGroup]=securityGroups;return{securityGroupId:securityGroup.GroupId,allowAllOutbound:hasAllTrafficEgress(securityGroup)}}}}});var SSMContextProviderPlugin;var init_ssm_parameters=__esm({"lib/context-providers/ssm-parameters.ts"(){"use strict";init_sdk_provider();init_logging();SSMContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const region=args.region;const account=args.account;if(!("parameterName"in args)){throw new Error("parameterName must be provided in props for SSMContextProviderPlugin")}const parameterName=args.parameterName;debug(`Reading SSM parameter ${account}:${region}:${parameterName}`);const response=await this.getSsmParameterValue(args);const parameterNotFound=!response.Parameter||response.Parameter.Value===void 0;const suppressError="ignoreErrorOnMissingContext"in args&&args.ignoreErrorOnMissingContext;if(parameterNotFound&&suppressError&&"dummyValue"in args){return args.dummyValue}if(parameterNotFound){throw new Error(`SSM parameter not available in account ${account}, region ${region}: ${parameterName}`)}return response.Parameter.Value}async getSsmParameterValue(args){const ssm=(await initContextProviderSdk(this.aws,args)).ssm();try{return await ssm.getParameter({Name:args.parameterName})}catch(e){if(e.name==="ParameterNotFound"){return{$metadata:{}}}throw e}}}}});function getTag(name,tags){for(const tag of tags||[]){if(tag.Key===name){return tag.Value}}return void 0}function groupSubnets(subnets){const grouping={};for(const subnet of subnets){const key=[subnet.type,subnet.name].toString();if(!(key in grouping)){grouping[key]=[]}grouping[key].push(subnet)}const groups=Object.values(grouping).map(sns=>{sns.sort((a,b)=>a.az.localeCompare(b.az));return{type:sns[0].type,name:sns[0].name,subnets:sns}});const azs=groups[0].subnets.map(s=>s.az);for(const group of groups){const groupAZs=group.subnets.map(s=>s.az);if(!arraysEqual(groupAZs,azs)){throw new Error(`Not all subnets in VPC have the same AZs: ${groupAZs} vs ${azs}`)}}return{azs,groups}}function groupAsymmetricSubnets(subnets){const grouping={};for(const subnet of subnets){const key=[subnet.type,subnet.name].toString();if(!(key in grouping)){grouping[key]=[]}grouping[key].push(subnet)}return Object.values(grouping).map(subnetArray=>{subnetArray.sort((subnet1,subnet2)=>subnet1.az.localeCompare(subnet2.az));return{name:subnetArray[0].name,type:subnetTypeToVpcSubnetType(subnetArray[0].type),subnets:subnetArray.map(subnet=>({subnetId:subnet.subnetId,cidr:subnet.cidr,availabilityZone:subnet.az,routeTableId:subnet.routeTableId}))}})}function subnetTypeToVpcSubnetType(type){switch(type){case"Isolated":return import_cx_api7.VpcSubnetGroupType.ISOLATED;case"Private":return import_cx_api7.VpcSubnetGroupType.PRIVATE;case"Public":return import_cx_api7.VpcSubnetGroupType.PUBLIC}}function isValidSubnetType(val2){return val2==="Public"||val2==="Private"||val2==="Isolated"}function arraysEqual(as,bs){if(as.length!==bs.length){return false}for(let i=0;i<as.length;i++){if(as[i]!==bs[i]){return false}}return true}function findGroups(type,groups){return groups.groups.filter(g=>g.type===type)}function flatMap3(xs,fn){const ret=new Array;for(const x of xs){ret.push(...fn(x))}return ret}function collapse(xs){if(xs.length>0){return xs}return void 0}var import_cx_api7,VpcNetworkContextProviderPlugin,RouteTables;var init_vpcs=__esm({"lib/context-providers/vpcs.ts"(){"use strict";import_cx_api7=__toESM(require_lib3());init_sdk_provider();init_logging();VpcNetworkContextProviderPlugin=class{constructor(aws){this.aws=aws}async getValue(args){const ec2=(await initContextProviderSdk(this.aws,args)).ec2();const vpcId=await this.findVpc(ec2,args);return this.readVpcProps(ec2,vpcId,args)}async findVpc(ec2,args){const filters=Object.entries(args.filter).map(([tag,value])=>({Name:tag,Values:[value]}));debug(`Listing VPCs in ${args.account}:${args.region}`);const response=await ec2.describeVpcs({Filters:filters});const vpcs=response.Vpcs||[];if(vpcs.length===0){throw new Error(`Could not find any VPCs matching ${JSON.stringify(args)}`)}if(vpcs.length>1){throw new Error(`Found ${vpcs.length} VPCs matching ${JSON.stringify(args)}; please narrow the search criteria`)}return vpcs[0]}async readVpcProps(ec2,vpc,args){var _a;const vpcId=vpc.VpcId;debug(`Describing VPC ${vpcId}`);const filters={Filters:[{Name:"vpc-id",Values:[vpcId]}]};const subnetsResponse=await ec2.describeSubnets(filters);const listedSubnets=subnetsResponse.Subnets||[];const routeTablesResponse=await ec2.describeRouteTables(filters);const routeTables=new RouteTables(routeTablesResponse.RouteTables||[]);const azs=Array.from(new Set(listedSubnets.map(s=>s.AvailabilityZone)));azs.sort();const subnets=listedSubnets.map(subnet=>{let type=getTag("aws-cdk:subnet-type",subnet.Tags);if(type===void 0&&subnet.MapPublicIpOnLaunch){type="Public"}if(type===void 0&&routeTables.hasRouteToIgw(subnet.SubnetId)){type="Public"}if(type===void 0&&routeTables.hasRouteToNatGateway(subnet.SubnetId)){type="Private"}if(type===void 0&&routeTables.hasRouteToTransitGateway(subnet.SubnetId)){type="Private"}if(type===void 0){type="Isolated"}if(!isValidSubnetType(type)){throw new Error(`Subnet ${subnet.SubnetArn} has invalid subnet type ${type} (must be ${"Public"}, ${"Private"} or ${"Isolated"})`)}if(args.subnetGroupNameTag&&!getTag(args.subnetGroupNameTag,subnet.Tags)){throw new Error(`Invalid subnetGroupNameTag: Subnet ${subnet.SubnetArn} does not have an associated tag with Key='${args.subnetGroupNameTag}'`)}const name=getTag(args.subnetGroupNameTag||"aws-cdk:subnet-name",subnet.Tags)||type;const routeTableId=routeTables.routeTableIdForSubnetId(subnet.SubnetId);if(!routeTableId){throw new Error(`Subnet ${subnet.SubnetArn} does not have an associated route table (and there is no "main" table)`)}return{az:subnet.AvailabilityZone,cidr:subnet.CidrBlock,type,name,subnetId:subnet.SubnetId,routeTableId}});let grouped;let assymetricSubnetGroups;if(args.returnAsymmetricSubnets){grouped={azs:[],groups:[]};assymetricSubnetGroups=groupAsymmetricSubnets(subnets)}else{grouped=groupSubnets(subnets);assymetricSubnetGroups=void 0}const vpnGatewayResponse=args.returnVpnGateways??true?await ec2.describeVpnGateways({Filters:[{Name:"attachment.vpc-id",Values:[vpcId]},{Name:"attachment.state",Values:["attached"]},{Name:"state",Values:["available"]}]}):void 0;const vpnGatewayId=((_a=vpnGatewayResponse==null?void 0:vpnGatewayResponse.VpnGateways)==null?void 0:_a.length)===1?vpnGatewayResponse.VpnGateways[0].VpnGatewayId:void 0;return{vpcId,vpcCidrBlock:vpc.CidrBlock,ownerAccountId:vpc.OwnerId,availabilityZones:grouped.azs,isolatedSubnetIds:collapse(flatMap3(findGroups("Isolated",grouped),group=>group.subnets.map(s=>s.subnetId))),isolatedSubnetNames:collapse(flatMap3(findGroups("Isolated",grouped),group=>group.name?[group.name]:[])),isolatedSubnetRouteTableIds:collapse(flatMap3(findGroups("Isolated",grouped),group=>group.subnets.map(s=>s.routeTableId))),privateSubnetIds:collapse(flatMap3(findGroups("Private",grouped),group=>group.subnets.map(s=>s.subnetId))),privateSubnetNames:collapse(flatMap3(findGroups("Private",grouped),group=>group.name?[group.name]:[])),privateSubnetRouteTableIds:collapse(flatMap3(findGroups("Private",grouped),group=>group.subnets.map(s=>s.routeTableId))),publicSubnetIds:collapse(flatMap3(findGroups("Public",grouped),group=>group.subnets.map(s=>s.subnetId))),publicSubnetNames:collapse(flatMap3(findGroups("Public",grouped),group=>group.name?[group.name]:[])),publicSubnetRouteTableIds:collapse(flatMap3(findGroups("Public",grouped),group=>group.subnets.map(s=>s.routeTableId))),vpnGatewayId,subnetGroups:assymetricSubnetGroups}}};RouteTables=class{constructor(tables){this.tables=tables;this.mainRouteTable=this.tables.find(table3=>!!table3.Associations&&table3.Associations.some(assoc=>!!assoc.Main))}routeTableIdForSubnetId(subnetId){const table3=this.tableForSubnet(subnetId);return table3&&table3.RouteTableId||this.mainRouteTable&&this.mainRouteTable.RouteTableId}hasRouteToNatGateway(subnetId){const table3=this.tableForSubnet(subnetId)||this.mainRouteTable;return!!table3&&!!table3.Routes&&table3.Routes.some(route=>!!route.NatGatewayId&&route.DestinationCidrBlock==="0.0.0.0/0")}hasRouteToTransitGateway(subnetId){const table3=this.tableForSubnet(subnetId)||this.mainRouteTable;return!!table3&&!!table3.Routes&&table3.Routes.some(route=>!!route.TransitGatewayId&&route.DestinationCidrBlock==="0.0.0.0/0")}hasRouteToIgw(subnetId){const table3=this.tableForSubnet(subnetId)||this.mainRouteTable;return!!table3&&!!table3.Routes&&table3.Routes.some(route=>!!route.GatewayId&&route.GatewayId.startsWith("igw-"))}tableForSubnet(subnetId){return this.tables.find(table3=>!!table3.Associations&&table3.Associations.some(assoc=>assoc.SubnetId===subnetId))}}}});var init_plugin2=__esm({"lib/api/plugin/index.ts"(){"use strict";init_plugin();init_context_provider_plugin()}});async function replaceEnvPlaceholders(object,env2,sdkProvider){return import_cx_api8.EnvironmentPlaceholders.replaceAsync(object,{accountId:()=>Promise.resolve(env2.account),region:()=>Promise.resolve(env2.region),partition:async()=>{return await sdkProvider.baseCredentialsPartition(env2,0)??"aws"}})}var import_cx_api8;var init_placeholders2=__esm({"lib/api/util/placeholders.ts"(){"use strict";import_cx_api8=__toESM(require_lib3());init_mode()}});async function loadAndLog(fileName){const ret=new Settings;await ret.load(fileName);if(!ret.empty){debug(fileName+":",JSON.stringify(ret.all,void 0,2))}return ret}function expandHomeDir(x){if(x.startsWith("~")){return fs_path.join(os6.homedir(),x.slice(1))}return x}function stripTransientValues(obj){const ret={};for(const[key,value]of Object.entries(obj)){if(!isTransientValue(value)){ret[key]=value}}return ret}function isTransientValue(value){return typeof value==="object"&&value!==null&&value[TRANSIENT_CONTEXT_KEY]}function expectStringList(x){if(x===void 0){return void 0}if(!Array.isArray(x)){throw new ToolkitError(`Expected array, got '${x}'`)}const nonStrings=x.filter(e=>typeof e!=="string");if(nonStrings.length>0){throw new ToolkitError(`Expected list of strings, found ${nonStrings}`)}return x}var os6,fs_path,fs15,PROJECT_CONFIG,PROJECT_CONTEXT,USER_DEFAULTS,TRANSIENT_CONTEXT_KEY,CONTEXT_KEY,BUNDLING_COMMANDS,Configuration,Context,Settings;var init_settings=__esm({"lib/settings.ts"(){"use strict";os6=__toESM(require("os"));fs_path=__toESM(require("path"));fs15=__toESM(require_lib4());init_logging();init_error();init_util3();PROJECT_CONFIG="cdk.json";PROJECT_CONTEXT="cdk.context.json";USER_DEFAULTS="~/.cdk.json";TRANSIENT_CONTEXT_KEY="$dontSaveContext";CONTEXT_KEY="context";BUNDLING_COMMANDS=["deploy","diff","synth","synthesize","watch"];Configuration=class{constructor(props={}){this.props=props;this.settings=new Settings;this.context=new Context;this.defaultConfig=new Settings({versionReporting:true,assetMetadata:true,pathMetadata:true,output:"cdk.out"});this.loaded=false;this.commandLineArguments=props.commandLineArguments?Settings.fromCommandLineArguments(props.commandLineArguments):new Settings;this.commandLineContext=this.commandLineArguments.subSettings([CONTEXT_KEY]).makeReadOnly()}get projectConfig(){if(!this._projectConfig){throw new ToolkitError("#load has not been called yet!")}return this._projectConfig}get projectContext(){if(!this._projectContext){throw new ToolkitError("#load has not been called yet!")}return this._projectContext}async load(){const userConfig=await loadAndLog(USER_DEFAULTS);this._projectConfig=await loadAndLog(PROJECT_CONFIG);this._projectContext=await loadAndLog(PROJECT_CONTEXT);const readUserContext=this.props.readUserContext??true;if(userConfig.get(["build"])){throw new ToolkitError("The `build` key cannot be specified in the user config (~/.cdk.json), specify it in the project config (cdk.json) instead")}const contextSources=[{bag:this.commandLineContext},{fileName:PROJECT_CONFIG,bag:this.projectConfig.subSettings([CONTEXT_KEY]).makeReadOnly()},{fileName:PROJECT_CONTEXT,bag:this.projectContext}];if(readUserContext){contextSources.push({fileName:USER_DEFAULTS,bag:userConfig.subSettings([CONTEXT_KEY]).makeReadOnly()})}this.context=new Context(...contextSources);this.settings=this.defaultConfig.merge(userConfig).merge(this.projectConfig).merge(this.commandLineArguments).makeReadOnly();debug("merged settings:",this.settings.all);this.loaded=true;return this}async saveContext(){if(!this.loaded){return this}await this.projectContext.save(PROJECT_CONTEXT);return this}};Context=class{constructor(...bags){this.bags=bags.length>0?bags.map(b=>b.bag):[new Settings];this.fileNames=bags.length>0?bags.map(b=>b.fileName):["default"]}get keys(){return Object.keys(this.all)}has(key){return this.keys.indexOf(key)>-1}get all(){let ret=new Settings;for(const bag of[...this.bags].reverse()){ret=ret.merge(bag)}return ret.all}get(key){for(const bag of this.bags){const v=bag.get([key]);if(v!==void 0){return v}}return void 0}set(key,value){for(const bag of this.bags){if(bag.readOnly){continue}bag.set([key],value);value=void 0}}unset(key){this.set(key,void 0)}clear(){for(const key of this.keys){this.unset(key)}}async save(fileName){const index=this.fileNames.indexOf(fileName);if(index===-1){return this}const bag=this.bags[index];if(bag.readOnly){throw new Error(`Context file ${fileName} is read only!`)}await bag.save(fileName);return this}};Settings=class _Settings{constructor(settings={},readOnly=false){this.settings=settings;this.readOnly=readOnly}static fromCommandLineArguments(argv){const context=this.parseStringContextListToObject(argv);const tags=this.parseStringTagsListToObject(expectStringList(argv.tags));let bundlingStacks;if(BUNDLING_COMMANDS.includes(argv._[0])){bundlingStacks=argv.exclusively?argv.STACKS??["**"]:["**"]}else{bundlingStacks=[]}return new _Settings({app:argv.app,browser:argv.browser,build:argv.build,caBundlePath:argv.caBundlePath,context,debug:argv.debug,tags,language:argv.language,pathMetadata:argv.pathMetadata,assetMetadata:argv.assetMetadata,profile:argv.profile,plugin:argv.plugin,requireApproval:argv.requireApproval,toolkitStackName:argv.toolkitStackName,toolkitBucket:{bucketName:argv.bootstrapBucketName,kmsKeyId:argv.bootstrapKmsKeyId},versionReporting:argv.versionReporting,staging:argv.staging,output:argv.output,outputsFile:argv.outputsFile,progress:argv.progress,proxy:argv.proxy,bundlingStacks,lookups:argv.lookups,rollback:argv.rollback,notices:argv.notices,assetParallelism:argv["asset-parallelism"],assetPrebuild:argv["asset-prebuild"],ignoreNoStacks:argv["ignore-no-stacks"],hotswap:{ecs:{minimumEcsHealthyPercent:argv.minimumEcsHealthyPercent,maximumEcsHealthyPercent:argv.maximumEcsHealthyPercent}},unstable:argv.unstable})}static mergeAll(...settings){let ret=new _Settings;for(const setting of settings){ret=ret.merge(setting)}return ret}static parseStringContextListToObject(argv){const context={};for(const assignment of argv.context||[]){const parts=assignment.split(/=(.*)/,2);if(parts.length===2){debug("CLI argument context: %s=%s",parts[0],parts[1]);if(parts[0].match(/^aws:.+/)){throw new ToolkitError(`User-provided context cannot use keys prefixed with 'aws:', but ${parts[0]} was provided.`)}context[parts[0]]=parts[1]}else{warning("Context argument is not an assignment (key=value): %s",assignment)}}return context}static parseStringTagsListToObject(argTags){if(argTags===void 0){return void 0}if(argTags.length===0){return void 0}const nonEmptyTags=argTags.filter(t=>t!=="");if(nonEmptyTags.length===0){return[]}const tags=[];for(const assignment of nonEmptyTags){const parts=assignment.split(/=(.*)/,2);if(parts.length===2){debug("CLI argument tags: %s=%s",parts[0],parts[1]);tags.push({Key:parts[0],Value:parts[1]})}else{warning("Tags argument is not an assignment (key=value): %s",assignment)}}return tags.length>0?tags:void 0}async load(fileName){if(this.readOnly){throw new ToolkitError(`Can't load ${fileName}: settings object is readonly`)}this.settings={};const expanded=expandHomeDir(fileName);if(await fs15.pathExists(expanded)){this.settings=await fs15.readJson(expanded)}this.prohibitContextKey("default-account",fileName);this.prohibitContextKey("default-region",fileName);this.warnAboutContextKey("aws:",fileName);return this}async save(fileName){const expanded=expandHomeDir(fileName);await fs15.writeJson(expanded,stripTransientValues(this.settings),{spaces:2});return this}get all(){return this.get([])}merge(other){return new _Settings(deepMerge(this.settings,other.settings))}subSettings(keyPrefix){return new _Settings(this.get(keyPrefix)||{},false)}makeReadOnly(){return new _Settings(this.settings,true)}clear(){if(this.readOnly){throw new ToolkitError("Cannot clear(): settings are readonly")}this.settings={}}get empty(){return Object.keys(this.settings).length===0}get(path24){return deepClone(deepGet(this.settings,path24))}set(path24,value){if(this.readOnly){throw new ToolkitError(`Can't set ${path24}: settings object is readonly`)}if(path24.length===0){this.settings=value}else{deepSet(this.settings,path24,value)}return this}unset(path24){this.set(path24,void 0)}prohibitContextKey(key,fileName){if(!this.settings.context){return}if(key in this.settings.context){throw new ToolkitError(`The 'context.${key}' key was found in ${fs_path.resolve(fileName)}, but it is no longer supported. Please remove it.`)}}warnAboutContextKey(prefix,fileName){if(!this.settings.context){return}for(const contextKey of Object.keys(this.settings.context)){if(contextKey.startsWith(prefix)){warning(`A reserved context key ('context.${prefix}') key was found in ${fs_path.resolve(fileName)}, it might cause surprising behavior and should be removed.`)}}}}}});async function provideContextValues(missingValues,context,sdk){for(const missingContext of missingValues){const key=missingContext.key;const providerName=missingContext.provider===cxschema7.ContextProvider.PLUGIN?`${PLUGIN_PROVIDER_PREFIX}:${missingContext.props.pluginName}`:missingContext.provider;let factory;if(providerName.startsWith(`${PLUGIN_PROVIDER_PREFIX}:`)){const plugin=PluginHost.instance.contextProviderPlugins[providerName.substring(PLUGIN_PROVIDER_PREFIX.length+1)];if(!plugin){throw new Error(`Unrecognized plugin context provider name: ${missingContext.provider}.`)}factory=()=>plugin}else{factory=availableContextProviders[providerName];if(!factory){throw new Error(`Unrecognized context provider name: ${missingContext.provider}. You might need to update the toolkit to match the version of the construct library.`)}}const provider=factory(sdk);let value;try{const environment=missingContext.props.account&&missingContext.props.region?cxapi4.EnvironmentUtils.make(missingContext.props.account,missingContext.props.region):void 0;const resolvedEnvironment=environment?await sdk.resolveEnvironment(environment):{account:"?",region:"?",name:"?"};const arns=await replaceEnvPlaceholders({lookupRoleArn:missingContext.props.lookupRoleArn},resolvedEnvironment,sdk);value=await provider.getValue({...missingContext.props,lookupRoleArn:arns.lookupRoleArn})}catch(e){value={[cxapi4.PROVIDER_ERROR_KEY]:e.message,[TRANSIENT_CONTEXT_KEY]:true}}context.set(key,value);debug(`Setting "${key}" context to ${JSON.stringify(value)}`)}}var cxschema7,cxapi4,PLUGIN_PROVIDER_PREFIX,availableContextProviders;var init_context_providers=__esm({"lib/context-providers/index.ts"(){"use strict";cxschema7=__toESM(require_lib2());cxapi4=__toESM(require_lib3());init_ami2();init_availability_zones2();init_endpoint_service_availability_zones2();init_hosted_zones();init_keys();init_load_balancers();init_security_groups();init_ssm_parameters();init_vpcs();init_plugin2();init_placeholders2();init_logging();init_settings();PLUGIN_PROVIDER_PREFIX="plugin";availableContextProviders={[cxschema7.ContextProvider.AVAILABILITY_ZONE_PROVIDER]:s=>new AZContextProviderPlugin(s),[cxschema7.ContextProvider.SSM_PARAMETER_PROVIDER]:s=>new SSMContextProviderPlugin(s),[cxschema7.ContextProvider.HOSTED_ZONE_PROVIDER]:s=>new HostedZoneContextProviderPlugin(s),[cxschema7.ContextProvider.VPC_PROVIDER]:s=>new VpcNetworkContextProviderPlugin(s),[cxschema7.ContextProvider.AMI_PROVIDER]:s=>new AmiContextProviderPlugin(s),[cxschema7.ContextProvider.ENDPOINT_SERVICE_AVAILABILITY_ZONE_PROVIDER]:s=>new EndpointServiceAZContextProviderPlugin(s),[cxschema7.ContextProvider.SECURITY_GROUP_PROVIDER]:s=>new SecurityGroupContextProviderPlugin(s),[cxschema7.ContextProvider.LOAD_BALANCER_PROVIDER]:s=>new LoadBalancerContextProviderPlugin(s),[cxschema7.ContextProvider.LOAD_BALANCER_LISTENER_PROVIDER]:s=>new LoadBalancerListenerContextProviderPlugin(s),[cxschema7.ContextProvider.KEY_PROVIDER]:s=>new KeyContextProviderPlugin(s)}}});function missingContextKeys(missing){return new Set((missing||[]).map(m=>m.key))}function setsEqual(a,b){if(a.size!==b.size){return false}for(const x of a){if(!b.has(x)){return false}}return true}var CloudExecutable;var init_cloud_executable=__esm({"lib/api/cxapp/cloud-executable.ts"(){"use strict";init_cloud_assembly2();init_context_providers();init_logging();init_error();CloudExecutable=class{constructor(props){this.props=props}get hasApp(){return!!this.props.configuration.settings.get(["app"])}async synthesize(cacheCloudAssembly=true){if(!this._cloudAssembly||!cacheCloudAssembly){this._cloudAssembly=await this.doSynthesize()}return this._cloudAssembly}async doSynthesize(){let previouslyMissingKeys;while(true){const assembly=await this.props.synthesizer(this.props.sdkProvider,this.props.configuration);if(assembly.manifest.missing&&assembly.manifest.missing.length>0){const missingKeys=missingContextKeys(assembly.manifest.missing);if(!this.canLookup){throw new ToolkitError(`Context lookups have been disabled. Make sure all necessary context is already in 'cdk.context.json' by running 'cdk synth' on a machine with sufficient AWS credentials and committing the result. Missing context keys: '${Array.from(missingKeys).join(", ")}'`)}let tryLookup=true;if(previouslyMissingKeys&&setsEqual(missingKeys,previouslyMissingKeys)){debug("Not making progress trying to resolve environmental context. Giving up.");tryLookup=false}previouslyMissingKeys=missingKeys;if(tryLookup){debug("Some context information is missing. Fetching...");await provideContextValues(assembly.manifest.missing,this.props.configuration.context,this.props.sdkProvider);await this.props.configuration.saveContext();continue}}return new CloudAssembly2(assembly)}}get canLookup(){return!!(this.props.configuration.settings.get(["lookups"])??true)}}}});async function readFileIfExists(filename){try{return await import_fs.promises.readFile(filename,{encoding:"utf-8"})}catch(e){if(e.code==="ENOENT"){return void 0}throw e}}async function writeFileAtomic(filename,contents){await import_fs.promises.mkdir(path17.dirname(filename),{recursive:true});const tmpFile=`${filename}.${process.pid}_${++tmpCounter}`;await import_fs.promises.writeFile(tmpFile,contents,{encoding:"utf-8"});await import_fs.promises.rename(tmpFile,filename)}async function deleteFile(filename){try{await import_fs.promises.unlink(filename)}catch(e){if(e.code==="ENOENT"){return}throw e}}function processExists(pid){try{process.kill(pid,0);return true}catch(e){return false}}var import_fs,path17,RWLock,tmpCounter;var init_rwlock=__esm({"lib/api/util/rwlock.ts"(){"use strict";import_fs=require("fs");path17=__toESM(require("path"));RWLock=class{constructor(directory){this.directory=directory;this.readCounter=0;this.pidString=`${process.pid}`;this.writerFile=path17.join(this.directory,"synth.lock")}async acquireWrite(){await this.assertNoOtherWriters();const readers=await this.currentReaders();if(readers.length>0){throw new Error(`Other CLIs (PID=${readers}) are currently reading from ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`)}await writeFileAtomic(this.writerFile,this.pidString);return{release:async()=>{await deleteFile(this.writerFile)},convertToReaderLock:async()=>{const ret=await this.doAcquireRead();await deleteFile(this.writerFile);return ret}}}async acquireRead(){await this.assertNoOtherWriters();return this.doAcquireRead()}readerFile(){return path17.join(this.directory,`read.${this.pidString}.${++this.readCounter}.lock`)}async doAcquireRead(){const readerFile=this.readerFile();await writeFileAtomic(readerFile,this.pidString);return{release:async()=>{await deleteFile(readerFile)}}}async assertNoOtherWriters(){const writer=await this.currentWriter();if(writer){throw new Error(`Another CLI (PID=${writer}) is currently synthing to ${this.directory}. Invoke the CLI in sequence, or use '--output' to synth into different directories.`)}}async currentWriter(){const contents=await readFileIfExists(this.writerFile);if(!contents){return void 0}const pid=parseInt(contents,10);if(!processExists(pid)){await deleteFile(this.writerFile);return void 0}return pid}async currentReaders(){const re=/^read\.([^.]+)\.[^.]+\.lock$/;const ret=new Array;let children;try{children=await import_fs.promises.readdir(this.directory,{encoding:"utf-8"})}catch(e){if(e.code==="ENOENT"){return[]}throw e}for(const fname of children){const m=fname.match(re);if(m){const pid=parseInt(m[1],10);if(processExists(pid)){ret.push(pid)}else{await deleteFile(path17.join(this.directory,fname))}}}return ret}};tmpCounter=0}});async function execProgram(aws,config){const env2=await prepareDefaultEnvironment(aws);const context=await prepareContext(config,env2);const build=config.settings.get(["build"]);if(build){await exec4(build)}const app=config.settings.get(["app"]);if(!app){throw new ToolkitError(`--app is required either in command-line, in ${PROJECT_CONFIG} or in ${USER_DEFAULTS}`)}if(await fs17.pathExists(app)&&(await fs17.stat(app)).isDirectory()){debug("--app points to a cloud assembly, so we bypass synth");const lock=await new RWLock(app).acquireRead();return{assembly:createAssembly(app),lock}}const commandLine=await guessExecutable(appToArray(app));const outdir=config.settings.get(["output"]);if(!outdir){throw new ToolkitError("unexpected: --output is required")}if(typeof outdir!=="string"){throw new ToolkitError(`--output takes a string, got ${JSON.stringify(outdir)}`)}try{await fs17.mkdirp(outdir)}catch(error3){throw new ToolkitError(`Could not create output directory ${outdir} (${error3.message})`)}debug("outdir:",outdir);env2[cxapi5.OUTDIR_ENV]=outdir;const writerLock=await new RWLock(outdir).acquireWrite();try{env2[cxapi5.CLI_ASM_VERSION_ENV]=cxschema8.Manifest.version();env2[cxapi5.CLI_VERSION_ENV]=versionNumber();debug("env:",env2);const envVariableSizeLimit=os7.platform()==="win32"?32760:131072;const[smallContext,overflow]=splitBySize(context,spaceAvailableForContext(env2,envVariableSizeLimit));env2[cxapi5.CONTEXT_ENV]=JSON.stringify(smallContext);let contextOverflowLocation;if(Object.keys(overflow??{}).length>0){const contextDir=await fs17.mkdtemp(path18.join(os7.tmpdir(),"cdk-context"));contextOverflowLocation=path18.join(contextDir,"context-overflow.json");fs17.writeJSONSync(contextOverflowLocation,overflow);env2[cxapi5.CONTEXT_OVERFLOW_LOCATION_ENV]=contextOverflowLocation}await exec4(commandLine.join(" "));const assembly=createAssembly(outdir);contextOverflowCleanup(contextOverflowLocation,assembly);return{assembly,lock:await writerLock.convertToReaderLock()}}catch(e){await writerLock.release();throw e}async function exec4(commandAndArgs){return new Promise((ok,fail)=>{const proc=childProcess.spawn(commandAndArgs,{stdio:["ignore","inherit","inherit"],detached:false,shell:true,env:{...process.env,...env2}});proc.on("error",fail);proc.on("exit",code=>{if(code===0){return ok()}else{debug("failed command:",commandAndArgs);return fail(new ToolkitError(`Subprocess exited with error ${code}`))}})})}}function createAssembly(appDir){try{return new cxapi5.CloudAssembly(appDir,{topoSort:false})}catch(error3){if(error3.message.includes(cxschema8.VERSION_MISMATCH)){throw new ToolkitError(`This CDK CLI is not compatible with the CDK library used by your application. Please upgrade the CLI to the latest version.
|
|
848
|
-
(${error3.message})`)}throw error3}}async function prepareDefaultEnvironment(aws){var _a;const env2={};env2[cxapi5.DEFAULT_REGION_ENV]=aws.defaultRegion;debug(`Setting "${cxapi5.DEFAULT_REGION_ENV}" environment variable to`,env2[cxapi5.DEFAULT_REGION_ENV]);const accountId=(_a=await aws.defaultAccount())==null?void 0:_a.accountId;if(accountId){env2[cxapi5.DEFAULT_ACCOUNT_ENV]=accountId;debug(`Setting "${cxapi5.DEFAULT_ACCOUNT_ENV}" environment variable to`,env2[cxapi5.DEFAULT_ACCOUNT_ENV])}return env2}async function prepareContext(config,env2){const context=config.context.all;const debugMode=config.settings.get(["debug"])??true;if(debugMode){env2.CDK_DEBUG="true"}const pathMetadata=config.settings.get(["pathMetadata"])??true;if(pathMetadata){context[cxapi5.PATH_METADATA_ENABLE_CONTEXT]=true}const assetMetadata=config.settings.get(["assetMetadata"])??true;if(assetMetadata){context[cxapi5.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT]=true}const versionReporting=config.settings.get(["versionReporting"])??true;if(versionReporting){context[cxapi5.ANALYTICS_REPORTING_ENABLED_CONTEXT]=true}if(!versionReporting){context["aws:cdk:disable-version-reporting"]=true}const stagingEnabled=config.settings.get(["staging"])??true;if(!stagingEnabled){context[cxapi5.DISABLE_ASSET_STAGING_CONTEXT]=true}const bundlingStacks=config.settings.get(["bundlingStacks"])??["**"];context[cxapi5.BUNDLING_STACKS]=bundlingStacks;debug("context:",context);return context}function appToArray(app){return typeof app==="string"?app.split(" "):app}function executeNode(scriptFile){return[process.execPath,scriptFile]}async function guessExecutable(commandLine){if(commandLine.length===1){let fstat;try{fstat=await fs17.stat(commandLine[0])}catch{debug(`Not a file: '${commandLine[0]}'. Using '${commandLine}' as command-line`);return commandLine}const isExecutable=(fstat.mode&fs17.constants.X_OK)!==0;const isWindows=process.platform==="win32";const handler=EXTENSION_MAP.get(path18.extname(commandLine[0]));if(handler&&(!isExecutable||isWindows)){return handler(commandLine[0])}}return commandLine}function contextOverflowCleanup(location,assembly){if(location){fs17.removeSync(path18.dirname(location));const tree=loadTree(assembly);const frameworkDoesNotSupportContextOverflow=some(tree,node=>{var _a,_b;const fqn=(_a=node.constructInfo)==null?void 0:_a.fqn;const version10=(_b=node.constructInfo)==null?void 0:_b.version;return fqn==="aws-cdk-lib.App"&&version10!=null&&semver5.lte(version10,"2.38.0")||fqn==="@aws-cdk/core.App"});if(frameworkDoesNotSupportContextOverflow){warning("Part of the context could not be sent to the application. Please update the AWS CDK library to the latest version.")}}}function spaceAvailableForContext(env2,limit){const size=value=>value!=null?Buffer.byteLength(value):0;const usedSpace=Object.entries(env2).map(([k,v])=>k===cxapi5.CONTEXT_ENV?size(k):size(k)+size(v)).reduce((a,b)=>a+b,0);return Math.max(0,limit-usedSpace)}var childProcess,os7,path18,cxschema8,cxapi5,fs17,semver5,EXTENSION_MAP;var init_exec=__esm({"lib/api/cxapp/exec.ts"(){"use strict";childProcess=__toESM(require("child_process"));os7=__toESM(require("os"));path18=__toESM(require("path"));cxschema8=__toESM(require_lib2());cxapi5=__toESM(require_lib3());fs17=__toESM(require_lib4());semver5=__toESM(require_semver4());init_logging();init_settings();init_error();init_tree();init_objects();init_version4();init_rwlock();EXTENSION_MAP=new Map([[".js",executeNode]])}});var EnvironmentAccess;var init_environment_access=__esm({"lib/api/environment-access.ts"(){"use strict";init_logging();init_environment_resources();init_mode();init_placeholders2();EnvironmentAccess=class{constructor(sdkProvider,toolkitStackName){this.sdkProvider=sdkProvider;this.sdkCache=new Map;this.environmentResources=new EnvironmentResourcesRegistry(toolkitStackName)}async resolveStackEnvironment(stack){return this.sdkProvider.resolveEnvironment(stack.environment)}async accessStackForReadOnlyStackOperations(stack){return this.accessStackForStackOperations(stack,0)}async accessStackForMutableStackOperations(stack){return this.accessStackForStackOperations(stack,1)}async accessStackForLookup(stack){var _a,_b,_c,_d,_e;if(!stack.environment){throw new Error(`The stack ${stack.displayName} does not have an environment`)}const lookupEnv=await this.prepareSdk({environment:stack.environment,mode:0,assumeRoleArn:(_a=stack.lookupRole)==null?void 0:_a.arn,assumeRoleExternalId:(_b=stack.lookupRole)==null?void 0:_b.assumeRoleExternalId,assumeRoleAdditionalOptions:(_c=stack.lookupRole)==null?void 0:_c.assumeRoleAdditionalOptions});if(lookupEnv.didAssumeRole&&((_d=stack.lookupRole)==null?void 0:_d.bootstrapStackVersionSsmParameter)&&stack.lookupRole.requiresBootstrapStackVersion){const version10=await lookupEnv.resources.versionFromSsmParameter(stack.lookupRole.bootstrapStackVersionSsmParameter);if(version10<stack.lookupRole.requiresBootstrapStackVersion){throw new Error(`Bootstrap stack version '${stack.lookupRole.requiresBootstrapStackVersion}' is required, found version '${version10}'. To get rid of this error, please upgrade to bootstrap version >= ${stack.lookupRole.requiresBootstrapStackVersion}`)}}if(lookupEnv.isFallbackCredentials){const arn=await lookupEnv.replacePlaceholders((_e=stack.lookupRole)==null?void 0:_e.arn);warning(`Lookup role ${arn} was not assumed. Proceeding with default credentials.`)}return lookupEnv}async accessStackForLookupBestEffort(stack){if(!stack.environment){throw new Error(`The stack ${stack.displayName} does not have an environment`)}try{return await this.accessStackForLookup(stack)}catch(e){warning(`${e.message}`)}return this.accessStackForStackOperations(stack,0)}async accessStackForStackOperations(stack,mode){if(!stack.environment){throw new Error(`The stack ${stack.displayName} does not have an environment`)}return this.prepareSdk({environment:stack.environment,mode,assumeRoleArn:stack.assumeRoleArn,assumeRoleExternalId:stack.assumeRoleExternalId,assumeRoleAdditionalOptions:stack.assumeRoleAdditionalOptions})}async prepareSdk(options){const resolvedEnvironment=await this.sdkProvider.resolveEnvironment(options.environment);const{assumeRoleArn}=await replaceEnvPlaceholders({assumeRoleArn:options.assumeRoleArn},resolvedEnvironment,this.sdkProvider);const stackSdk=await this.cachedSdkForEnvironment(resolvedEnvironment,options.mode,{assumeRoleArn,assumeRoleExternalId:options.assumeRoleExternalId,assumeRoleAdditionalOptions:options.assumeRoleAdditionalOptions});return{sdk:stackSdk.sdk,resolvedEnvironment,resources:this.environmentResources.for(resolvedEnvironment,stackSdk.sdk),isFallbackCredentials:!stackSdk.didAssumeRole&&!!assumeRoleArn,didAssumeRole:stackSdk.didAssumeRole,replacePlaceholders:async str=>{const ret=await replaceEnvPlaceholders({str},resolvedEnvironment,this.sdkProvider);return ret.str}}}async cachedSdkForEnvironment(environment,mode,options){const cacheKeyElements=[environment.account,environment.region,`${mode}`,(options==null?void 0:options.assumeRoleArn)??"",(options==null?void 0:options.assumeRoleExternalId)??""];if(options==null?void 0:options.assumeRoleAdditionalOptions){cacheKeyElements.push(JSON.stringify(options.assumeRoleAdditionalOptions))}const cacheKey=cacheKeyElements.join(":");const existing=this.sdkCache.get(cacheKey);if(existing){return existing}const ret=await this.sdkProvider.forEnvironment(environment,mode,options);this.sdkCache.set(cacheKey,ret);return ret}}}});function suffixWithErrors2(msg,errors){return errors&&errors.length>0?`${msg}: ${errors.join(", ")}`:msg}var import_crypto38,cdk_assets2,import_cdk_assets3,chalk17,BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,Deployments,ParallelSafeAssetProgress;var init_deployments=__esm({"lib/api/deployments.ts"(){"use strict";import_crypto38=require("crypto");cdk_assets2=__toESM(require_lib11());import_cdk_assets3=__toESM(require_lib11());chalk17=__toESM(require_source());init_deploy_stack();init_logging();init_environment_access();init_nested_stack_helpers();init_toolkit_info();init_checks();init_cloudformation();init_stack_activity_monitor();init_stack_event_poller();init_stack_status();init_template_body_parameter();init_asset_manifest_builder();init_asset_publishing();BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK=23;Deployments=class{constructor(props){this.props=props;this.publisherCache=new Map;this.assetSdkProvider=props.sdkProvider;this.deployStackSdkProvider=props.sdkProvider;this.envs=new EnvironmentAccess(props.sdkProvider,props.toolkitStackName??DEFAULT_TOOLKIT_STACK_NAME)}async resolveEnvironment(stack){return this.envs.resolveStackEnvironment(stack)}async readCurrentTemplateWithNestedStacks(rootStackArtifact,retrieveProcessedTemplate=false){const env2=await this.envs.accessStackForLookupBestEffort(rootStackArtifact);return loadCurrentTemplateWithNestedStacks(rootStackArtifact,env2.sdk,retrieveProcessedTemplate)}async readCurrentTemplate(stackArtifact){debug(`Reading existing template for stack ${stackArtifact.displayName}.`);const env2=await this.envs.accessStackForLookupBestEffort(stackArtifact);return loadCurrentTemplate(stackArtifact,env2.sdk)}async resourceIdentifierSummaries(stackArtifact){debug(`Retrieving template summary for stack ${stackArtifact.displayName}.`);const env2=await this.envs.accessStackForReadOnlyStackOperations(stackArtifact);const cfn=env2.sdk.cloudFormation();await uploadStackTemplateAssets(stackArtifact,this);const builder=new AssetManifestBuilder;const cfnParam=await makeBodyParameter(stackArtifact,env2.resolvedEnvironment,builder,env2.resources);const addedAssets=builder.toManifest(stackArtifact.assembly.directory);for(const entry of addedAssets.entries){await this.buildSingleAsset("no-version-validation",addedAssets,entry,{stack:stackArtifact});await this.publishSingleAsset(addedAssets,entry,{stack:stackArtifact})}const response=await cfn.getTemplateSummary(cfnParam);if(!response.ResourceIdentifierSummaries){debug('GetTemplateSummary API call did not return "ResourceIdentifierSummaries"')}return response.ResourceIdentifierSummaries??[]}async deployStack(options){let deploymentMethod=options.deploymentMethod;if(options.changeSetName||options.execute!==void 0){if(deploymentMethod){throw new Error("You cannot supply both 'deploymentMethod' and 'changeSetName/execute'. Supply one or the other.")}deploymentMethod={method:"change-set",changeSetName:options.changeSetName,execute:options.execute}}const env2=await this.envs.accessStackForMutableStackOperations(options.stack);await this.validateBootstrapStackVersion(options.stack.stackName,options.stack.requiresBootstrapStackVersion,options.stack.bootstrapStackVersionSsmParameter,env2.resources);const executionRoleArn=await env2.replacePlaceholders(options.roleArn??options.stack.cloudFormationExecutionRoleArn);return deployStack({stack:options.stack,resolvedEnvironment:env2.resolvedEnvironment,deployName:options.deployName,notificationArns:options.notificationArns,quiet:options.quiet,sdk:env2.sdk,sdkProvider:this.deployStackSdkProvider,roleArn:executionRoleArn,reuseAssets:options.reuseAssets,envResources:env2.resources,tags:options.tags,deploymentMethod,force:options.force,parameters:options.parameters,usePreviousParameters:options.usePreviousParameters,progress:options.progress,ci:options.ci,rollback:options.rollback,hotswap:options.hotswap,hotswapPropertyOverrides:options.hotswapPropertyOverrides,extraUserAgent:options.extraUserAgent,resourcesToImport:options.resourcesToImport,overrideTemplate:options.overrideTemplate,assetParallelism:options.assetParallelism})}async rollbackStack(options){var _a;let resourcesToSkip=options.orphanLogicalIds??[];if(options.force&&resourcesToSkip.length>0){throw new Error("Cannot combine --force with --orphan")}const env2=await this.envs.accessStackForMutableStackOperations(options.stack);if(options.validateBootstrapStackVersion??true){await this.validateBootstrapStackVersion(options.stack.stackName,BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,options.stack.bootstrapStackVersionSsmParameter,env2.resources)}const cfn=env2.sdk.cloudFormation();const deployName=options.stack.stackName;let maxLoops=10;while(maxLoops--){let cloudFormationStack=await CloudFormationStack.lookup(cfn,deployName);const executionRoleArn=await env2.replacePlaceholders(options.roleArn??options.stack.cloudFormationExecutionRoleArn);switch(cloudFormationStack.stackStatus.rollbackChoice){case 3:warning(`Stack ${deployName} does not need a rollback: ${cloudFormationStack.stackStatus}`);return{notInRollbackableState:true};case 0:debug(`Initiating rollback of stack ${deployName}`);await cfn.rollbackStack({StackName:deployName,RoleARN:executionRoleArn,ClientRequestToken:(0,import_crypto38.randomUUID)(),RetainExceptOnCreate:true});break;case 1:if(options.force){const poller=new StackEventPoller(cfn,{stackName:deployName,stackStatuses:["ROLLBACK_IN_PROGRESS","UPDATE_ROLLBACK_IN_PROGRESS"]});await poller.poll();resourcesToSkip=poller.resourceErrors.filter(r=>!r.isStackEvent&&r.parentStackLogicalIds.length===0).map(r=>r.event.LogicalResourceId??"")}const skipDescription=resourcesToSkip.length>0?` (orphaning: ${resourcesToSkip.join(", ")})`:"";warning(`Continuing rollback of stack ${deployName}${skipDescription}`);await cfn.continueUpdateRollback({StackName:deployName,ClientRequestToken:(0,import_crypto38.randomUUID)(),RoleARN:executionRoleArn,ResourcesToSkip:resourcesToSkip});break;case 2:warning(`Stack ${deployName} failed creation and rollback. This state cannot be rolled back. You can recreate this stack by running 'cdk deploy'.`);return{notInRollbackableState:true};default:throw new Error(`Unexpected rollback choice: ${cloudFormationStack.stackStatus.rollbackChoice}`)}const monitor=options.quiet?void 0:StackActivityMonitor.withDefaultPrinter(cfn,deployName,options.stack,{ci:options.ci}).start();let stackErrorMessage=void 0;let finalStackState=cloudFormationStack;try{const successStack=await stabilizeStack(cfn,deployName);if(!successStack){throw new Error("Stack deploy failed (the stack disappeared while we were rolling it back)")}finalStackState=successStack;const errors=(_a=monitor==null?void 0:monitor.errors)==null?void 0:_a.join(", ");if(errors){stackErrorMessage=errors}}catch(e){stackErrorMessage=suffixWithErrors2(e.message,monitor==null?void 0:monitor.errors)}finally{await(monitor==null?void 0:monitor.stop())}if(finalStackState.stackStatus.isRollbackSuccess||!stackErrorMessage){return{success:true}}if(finalStackState.stackStatus.rollbackChoice===1&&options.force){continue}throw new Error(`${stackErrorMessage} (fix problem and retry, or orphan these resources using --orphan or --force)`)}throw new Error("Rollback did not finish after a large number of iterations; stopping because it looks like we're not making progress anymore. You can retry if rollback was progressing as expected.")}async destroyStack(options){const env2=await this.envs.accessStackForMutableStackOperations(options.stack);const executionRoleArn=await env2.replacePlaceholders(options.roleArn??options.stack.cloudFormationExecutionRoleArn);return destroyStack({sdk:env2.sdk,roleArn:executionRoleArn,stack:options.stack,deployName:options.deployName,quiet:options.quiet,ci:options.ci})}async stackExists(options){let env2;if(options.tryLookupRole){env2=await this.envs.accessStackForLookupBestEffort(options.stack)}else{env2=await this.envs.accessStackForReadOnlyStackOperations(options.stack)}const stack=await CloudFormationStack.lookup(env2.sdk.cloudFormation(),options.deployName??options.stack.stackName);return stack.exists}async prepareAndValidateAssets(asset,options){const env2=await this.envs.accessStackForMutableStackOperations(options.stack);await this.validateBootstrapStackVersion(options.stack.stackName,asset.requiresBootstrapStackVersion,asset.bootstrapStackVersionSsmParameter,env2.resources);const manifest=import_cdk_assets3.AssetManifest.fromFile(asset.file);return{manifest,stackEnv:env2.resolvedEnvironment}}async buildAssets(asset,options){const{manifest,stackEnv}=await this.prepareAndValidateAssets(asset,options);await buildAssets(manifest,this.assetSdkProvider,stackEnv,options.buildOptions)}async publishAssets(asset,options){const{manifest,stackEnv}=await this.prepareAndValidateAssets(asset,options);await publishAssets(manifest,this.assetSdkProvider,stackEnv,{...options.publishOptions,allowCrossAccount:await this.allowCrossAccountAssetPublishingForEnv(options.stack)})}async buildSingleAsset(assetArtifact,assetManifest,asset,options){if(assetArtifact!=="no-version-validation"){const env2=await this.envs.accessStackForReadOnlyStackOperations(options.stack);await this.validateBootstrapStackVersion(options.stack.stackName,assetArtifact.requiresBootstrapStackVersion,assetArtifact.bootstrapStackVersionSsmParameter,env2.resources)}const resolvedEnvironment=await this.envs.resolveStackEnvironment(options.stack);const publisher=this.cachedPublisher(assetManifest,resolvedEnvironment,options.stackName);await publisher.buildEntry(asset);if(publisher.hasFailures){throw new Error(`Failed to build asset ${asset.id}`)}}async publishSingleAsset(assetManifest,asset,options){const stackEnv=await this.envs.resolveStackEnvironment(options.stack);const publisher=this.cachedPublisher(assetManifest,stackEnv,options.stackName);await publisher.publishEntry(asset,{allowCrossAccount:await this.allowCrossAccountAssetPublishingForEnv(options.stack)});if(publisher.hasFailures){throw new Error(`Failed to publish asset ${asset.id}`)}}async allowCrossAccountAssetPublishingForEnv(stack){if(this._allowCrossAccountAssetPublishing===void 0){const env2=await this.envs.accessStackForReadOnlyStackOperations(stack);this._allowCrossAccountAssetPublishing=await determineAllowCrossAccountAssetPublishing(env2.sdk,this.props.toolkitStackName)}return this._allowCrossAccountAssetPublishing}async isSingleAssetPublished(assetManifest,asset,options){const stackEnv=await this.envs.resolveStackEnvironment(options.stack);const publisher=this.cachedPublisher(assetManifest,stackEnv,options.stackName);return publisher.isEntryPublished(asset)}async validateBootstrapStackVersion(stackName,requiresBootstrapStackVersion,bootstrapStackVersionSsmParameter,envResources){try{await envResources.validateVersion(requiresBootstrapStackVersion,bootstrapStackVersionSsmParameter)}catch(e){throw new Error(`${stackName}: ${e.message}`)}}cachedPublisher(assetManifest,env2,stackName){const existing=this.publisherCache.get(assetManifest);if(existing){return existing}const prefix=stackName?`${chalk17.bold(stackName)}: `:"";const publisher=new cdk_assets2.AssetPublishing(assetManifest,{aws:new PublishingAws(this.assetSdkProvider,env2),progressListener:new ParallelSafeAssetProgress(prefix,this.props.quiet??false)});this.publisherCache.set(assetManifest,publisher);return publisher}};ParallelSafeAssetProgress=class{constructor(prefix,quiet){this.prefix=prefix;this.quiet=quiet}onPublishEvent(type,event){const handler=this.quiet&&type!=="fail"?debug:EVENT_TO_LOGGER[type];handler(`${this.prefix}${type}: ${event.message}`)}}}});var require_constants8=__commonJS({"../../node_modules/picomatch/lib/constants.js"(exports2,module2){"use strict";var path24=require("path");var WIN_SLASH="\\\\/";var WIN_NO_SLASH=`[^${WIN_SLASH}]`;var DOT_LITERAL="\\.";var PLUS_LITERAL="\\+";var QMARK_LITERAL="\\?";var SLASH_LITERAL="\\/";var ONE_CHAR="(?=.)";var QMARK="[^/]";var END_ANCHOR=`(?:${SLASH_LITERAL}|$)`;var START_ANCHOR=`(?:^|${SLASH_LITERAL})`;var DOTS_SLASH=`${DOT_LITERAL}{1,2}${END_ANCHOR}`;var NO_DOT=`(?!${DOT_LITERAL})`;var NO_DOTS=`(?!${START_ANCHOR}${DOTS_SLASH})`;var NO_DOT_SLASH=`(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;var NO_DOTS_SLASH=`(?!${DOTS_SLASH})`;var QMARK_NO_DOT=`[^.${SLASH_LITERAL}]`;var STAR=`${QMARK}*?`;var POSIX_CHARS={DOT_LITERAL,PLUS_LITERAL,QMARK_LITERAL,SLASH_LITERAL,ONE_CHAR,QMARK,END_ANCHOR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK_NO_DOT,STAR,START_ANCHOR};var WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:`[${WIN_SLASH}]`,QMARK:WIN_NO_SLASH,STAR:`${WIN_NO_SLASH}*?`,DOTS_SLASH:`${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,NO_DOT:`(?!${DOT_LITERAL})`,NO_DOTS:`(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,NO_DOT_SLASH:`(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,NO_DOTS_SLASH:`(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,QMARK_NO_DOT:`[^.${WIN_SLASH}]`,START_ANCHOR:`(?:^|[${WIN_SLASH}])`,END_ANCHOR:`(?:[${WIN_SLASH}]|$)`};var POSIX_REGEX_SOURCE={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module2.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:path24.sep,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win32){return win32===true?WINDOWS_CHARS:POSIX_CHARS}}}});var require_utils6=__commonJS({"../../node_modules/picomatch/lib/utils.js"(exports2){"use strict";var path24=require("path");var win32=process.platform==="win32";var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants8();exports2.isObject=val2=>val2!==null&&typeof val2==="object"&&!Array.isArray(val2);exports2.hasRegexChars=str=>REGEX_SPECIAL_CHARS.test(str);exports2.isRegexChar=str=>str.length===1&&exports2.hasRegexChars(str);exports2.escapeRegex=str=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports2.toPosixSlashes=str=>str.replace(REGEX_BACKSLASH,"/");exports2.removeBackslashes=str=>{return str.replace(REGEX_REMOVE_BACKSLASH,match2=>{return match2==="\\"?"":match2})};exports2.supportsLookbehinds=()=>{const segs=process.version.slice(1).split(".").map(Number);if(segs.length===3&&segs[0]>=9||segs[0]===8&&segs[1]>=10){return true}return false};exports2.isWindows=options=>{if(options&&typeof options.windows==="boolean"){return options.windows}return win32===true||path24.sep==="\\"};exports2.escapeLast=(input,char,lastIdx)=>{const idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports2.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports2.removePrefix=(input,state6={})=>{let output=input;if(output.startsWith("./")){output=output.slice(2);state6.prefix="./"}return output};exports2.wrapOutput=(input,state6={},options={})=>{const prepend=options.contains?"":"^";const append=options.contains?"":"$";let output=`${prepend}(?:${input})${append}`;if(state6.negated===true){output=`(?:^(?!${output}).*$)`}return output}}});var require_scan2=__commonJS({"../../node_modules/picomatch/lib/scan.js"(exports2,module2){"use strict";var utils=require_utils6();var{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants8();var isPathSeparator=code=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH};var depth=token=>{if(token.isPrefix!==true){token.depth=token.isGlobstar?Infinity:1}};var scan=(input,options)=>{const opts=options||{};const length=input.length-1;const scanToEnd=opts.parts===true||opts.scanToEnd===true;const slashes=[];const tokens=[];const parts=[];let str=input;let index=-1;let start=0;let lastIndex=0;let isBrace=false;let isBracket=false;let isGlob=false;let isExtglob=false;let isGlobstar=false;let braceEscaped=false;let backslashes=false;let negated=false;let negatedExtglob=false;let finished=false;let braces=0;let prev;let code;let token={value:"",depth:0,isGlob:false};const eos=()=>index>=length;const peek=()=>str.charCodeAt(index+1);const advance=()=>{prev=code;return str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;code=advance();if(code===CHAR_LEFT_CURLY_BRACE){braceEscaped=true}continue}if(braceEscaped===true||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==true&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==true&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){isBrace=token.isBrace=true;isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(braceEscaped!==true&&code===CHAR_COMMA){isBrace=token.isBrace=true;isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(code===CHAR_RIGHT_CURLY_BRACE){braces--;if(braces===0){braceEscaped=false;isBrace=token.isBrace=true;finished=true;break}}}if(scanToEnd===true){continue}break}if(code===CHAR_FORWARD_SLASH){slashes.push(index);tokens.push(token);token={value:"",depth:0,isGlob:false};if(finished===true)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==true){const isExtglobChar=code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK;if(isExtglobChar===true&&peek()===CHAR_LEFT_PARENTHESES){isGlob=token.isGlob=true;isExtglob=token.isExtglob=true;finished=true;if(code===CHAR_EXCLAMATION_MARK&&index===start){negatedExtglob=true}if(scanToEnd===true){while(eos()!==true&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=true;finished=true;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=true;isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(code===CHAR_QUESTION_MARK){isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==true&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=true;isGlob=token.isGlob=true;finished=true;break}}if(scanToEnd===true){continue}break}if(opts.nonegate!==true&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=true;start++;continue}if(opts.noparen!==true&&code===CHAR_LEFT_PARENTHESES){isGlob=token.isGlob=true;if(scanToEnd===true){while(eos()!==true&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=true;code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=true;break}}continue}break}if(isGlob===true){finished=true;if(scanToEnd===true){continue}break}}if(opts.noext===true){isExtglob=false;isGlob=false}let base=str;let prefix="";let glob2="";if(start>0){prefix=str.slice(0,start);str=str.slice(start);lastIndex-=start}if(base&&isGlob===true&&lastIndex>0){base=str.slice(0,lastIndex);glob2=str.slice(lastIndex)}else if(isGlob===true){base="";glob2=str}else{base=str}if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1))){base=base.slice(0,-1)}}if(opts.unescape===true){if(glob2)glob2=utils.removeBackslashes(glob2);if(base&&backslashes===true){base=utils.removeBackslashes(base)}}const state6={prefix,input,start,base,glob:glob2,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===true){state6.maxDepth=0;if(!isPathSeparator(code)){tokens.push(token)}state6.tokens=tokens}if(opts.parts===true||opts.tokens===true){let prevIndex;for(let idx=0;idx<slashes.length;idx++){const n=prevIndex?prevIndex+1:start;const i=slashes[idx];const value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0){tokens[idx].isPrefix=true;tokens[idx].value=prefix}else{tokens[idx].value=value}depth(tokens[idx]);state6.maxDepth+=tokens[idx].depth}if(idx!==0||value!==""){parts.push(value)}prevIndex=i}if(prevIndex&&prevIndex+1<input.length){const value=input.slice(prevIndex+1);parts.push(value);if(opts.tokens){tokens[tokens.length-1].value=value;depth(tokens[tokens.length-1]);state6.maxDepth+=tokens[tokens.length-1].depth}}state6.slashes=slashes;state6.parts=parts}return state6};module2.exports=scan}});var require_parse4=__commonJS({"../../node_modules/picomatch/lib/parse.js"(exports2,module2){"use strict";var constants3=require_constants8();var utils=require_utils6();var{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants3;var expandRange=(args,options)=>{if(typeof options.expandRange==="function"){return options.expandRange(...args,options)}args.sort();const value=`[${args.join("-")}]`;try{new RegExp(value)}catch(ex){return args.map(v=>utils.escapeRegex(v)).join("..")}return value};var syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`};var parse11=(input,options)=>{if(typeof input!=="string"){throw new TypeError("Expected a string")}input=REPLACEMENTS[input]||input;const opts={...options};const max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH;let len=input.length;if(len>max){throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`)}const bos={type:"bos",value:"",output:opts.prepend||""};const tokens=[bos];const capture=opts.capture?"":"?:";const win32=utils.isWindows(options);const PLATFORM_CHARS=constants3.globChars(win32);const EXTGLOB_CHARS=constants3.extglobChars(PLATFORM_CHARS);const{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS;const globstar=opts2=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`};const nodot=opts.dot?"":NO_DOT;const qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT;let star3=opts.bash===true?globstar(opts):STAR;if(opts.capture){star3=`(${star3})`}if(typeof opts.noext==="boolean"){opts.noextglob=opts.noext}const state6={input,index:-1,start:0,dot:opts.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens};input=utils.removePrefix(input,state6);len=input.length;const extglobs=[];const braces=[];const stack=[];let prev=bos;let value;const eos=()=>state6.index===len-1;const peek=state6.peek=(n=1)=>input[state6.index+n];const advance=state6.advance=()=>input[++state6.index]||"";const remaining=()=>input.slice(state6.index+1);const consume=(value2="",num=0)=>{state6.consumed+=value2;state6.index+=num};const append=token=>{state6.output+=token.output!=null?token.output:token.value;consume(token.value)};const negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?")){advance();state6.start++;count++}if(count%2===0){return false}state6.negated=true;state6.start++;return true};const increment=type=>{state6[type]++;stack.push(type)};const decrement=type=>{state6[type]--;stack.pop()};const push=tok=>{if(prev.type==="globstar"){const isBrace=state6.braces>0&&(tok.type==="comma"||tok.type==="brace");const isExtglob=tok.extglob===true||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob){state6.output=state6.output.slice(0,-prev.output.length);prev.type="star";prev.value="*";prev.output=star3;state6.output+=prev.output}}if(extglobs.length&&tok.type!=="paren"){extglobs[extglobs.length-1].inner+=tok.value}if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.value+=tok.value;prev.output=(prev.output||"")+tok.value;return}tok.prev=prev;tokens.push(tok);prev=tok};const extglobOpen=(type,value2)=>{const token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev;token.parens=state6.parens;token.output=state6.output;const output=(opts.capture?"(":"")+token.open;increment("parens");push({type,value:value2,output:state6.output?"":ONE_CHAR});push({type:"paren",extglob:true,value:advance(),output});extglobs.push(token)};const extglobClose=token=>{let output=token.close+(opts.capture?")":"");let rest;if(token.type==="negate"){let extglobStar=star3;if(token.inner&&token.inner.length>1&&token.inner.includes("/")){extglobStar=globstar(opts)}if(extglobStar!==star3||eos()||/^\)+$/.test(remaining())){output=token.close=`)$))${extglobStar}`}if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){const expression=parse11(rest,{...options,fastpaths:false}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos"){state6.negatedExtglob=true}}push({type:"paren",extglob:true,value,output});decrement("parens")};if(opts.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=false;let output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc,chars,first,rest,index)=>{if(first==="\\"){backslashes=true;return m}if(first==="?"){if(esc){return esc+first+(rest?QMARK.repeat(rest.length):"")}if(index===0){return qmarkNoDot+(rest?QMARK.repeat(rest.length):"")}return QMARK.repeat(chars.length)}if(first==="."){return DOT_LITERAL.repeat(chars.length)}if(first==="*"){if(esc){return esc+first+(rest?star3:"")}return star3}return esc?m:`\\${m}`});if(backslashes===true){if(opts.unescape===true){output=output.replace(/\\/g,"")}else{output=output.replace(/\\+/g,m=>{return m.length%2===0?"\\\\":m?"\\":""})}}if(output===input&&opts.contains===true){state6.output=input;return state6}state6.output=utils.wrapOutput(output,state6,options);return state6}while(!eos()){value=advance();if(value==="\0"){continue}if(value==="\\"){const next=peek();if(next==="/"&&opts.bash!==true){continue}if(next==="."||next===";"){continue}if(!next){value+="\\";push({type:"text",value});continue}const match2=/^\\+/.exec(remaining());let slashes=0;if(match2&&match2[0].length>2){slashes=match2[0].length;state6.index+=slashes;if(slashes%2!==0){value+="\\"}}if(opts.unescape===true){value=advance()}else{value+=advance()}if(state6.brackets===0){push({type:"text",value});continue}}if(state6.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==false&&value===":"){const inner=prev.value.slice(1);if(inner.includes("[")){prev.posix=true;if(inner.includes(":")){const idx=prev.value.lastIndexOf("[");const pre=prev.value.slice(0,idx);const rest2=prev.value.slice(idx+2);const posix=POSIX_REGEX_SOURCE[rest2];if(posix){prev.value=pre+posix;state6.backtrack=true;advance();if(!bos.output&&tokens.indexOf(prev)===1){bos.output=ONE_CHAR}continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]"){value=`\\${value}`}if(value==="]"&&(prev.value==="["||prev.value==="[^")){value=`\\${value}`}if(opts.posix===true&&value==="!"&&prev.value==="["){value="^"}prev.value+=value;append({value});continue}if(state6.quotes===1&&value!=='"'){value=utils.escapeRegex(value);prev.value+=value;append({value});continue}if(value==='"'){state6.quotes=state6.quotes===1?0:1;if(opts.keepQuotes===true){push({type:"text",value})}continue}if(value==="("){increment("parens");push({type:"paren",value});continue}if(value===")"){if(state6.parens===0&&opts.strictBrackets===true){throw new SyntaxError(syntaxError("opening","("))}const extglob=extglobs[extglobs.length-1];if(extglob&&state6.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state6.parens?")":"\\)"});decrement("parens");continue}if(value==="["){if(opts.nobracket===true||!remaining().includes("]")){if(opts.nobracket!==true&&opts.strictBrackets===true){throw new SyntaxError(syntaxError("closing","]"))}value=`\\${value}`}else{increment("brackets")}push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===true||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state6.brackets===0){if(opts.strictBrackets===true){throw new SyntaxError(syntaxError("opening","["))}push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");const prevValue=prev.value.slice(1);if(prev.posix!==true&&prevValue[0]==="^"&&!prevValue.includes("/")){value=`/${value}`}prev.value+=value;append({value});if(opts.literalBrackets===false||utils.hasRegexChars(prevValue)){continue}const escaped=utils.escapeRegex(prev.value);state6.output=state6.output.slice(0,-prev.value.length);if(opts.literalBrackets===true){state6.output+=escaped;prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`;state6.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==true){increment("braces");const open={type:"brace",value,output:"(",outputIndex:state6.output.length,tokensIndex:state6.tokens.length};braces.push(open);push(open);continue}if(value==="}"){const brace=braces[braces.length-1];if(opts.nobrace===true||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===true){const arr=tokens.slice();const range=[];for(let i=arr.length-1;i>=0;i--){tokens.pop();if(arr[i].type==="brace"){break}if(arr[i].type!=="dots"){range.unshift(arr[i].value)}}output=expandRange(range,opts);state6.backtrack=true}if(brace.comma!==true&&brace.dots!==true){const out=state6.output.slice(0,brace.outputIndex);const toks=state6.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{";value=output="\\}";state6.output=out;for(const t of toks){state6.output+=t.output||t.value}}push({type:"brace",value,output});decrement("braces");braces.pop();continue}if(value==="|"){if(extglobs.length>0){extglobs[extglobs.length-1].conditions++}push({type:"text",value});continue}if(value===","){let output=value;const brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces"){brace.comma=true;output="|"}push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state6.index===state6.start+1){state6.start=state6.index+1;state6.consumed="";state6.output="";tokens.pop();prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state6.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;const brace=braces[braces.length-1];prev.type="dots";prev.output+=value;prev.value+=value;brace.dots=true;continue}if(state6.braces+state6.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){const isGroup=prev&&prev.value==="(";if(!isGroup&&opts.noextglob!==true&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){const next=peek();let output=value;if(next==="<"&&!utils.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining())){output=`\\${value}`}push({type:"text",value,output});continue}if(opts.dot!==true&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==true&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==true&&state6.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==true&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===false){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state6.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==true&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:true,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^"){value=`\\${value}`}const match2=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match2){value+=match2[0];state6.index+=match2[0].length}push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===true)){prev.type="star";prev.star=true;prev.value+=value;prev.output=star3;state6.backtrack=true;state6.globstar=true;consume(value);continue}let rest=remaining();if(opts.noextglob!==true&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===true){consume(value);continue}const prior=prev.prev;const before=prior.prev;const isStart=prior.type==="slash"||prior.type==="bos";const afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===true&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}const isBrace=state6.braces>0&&(prior.type==="comma"||prior.type==="brace");const isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){const after=input[state6.index+4];if(after&&after!=="/"){break}rest=rest.slice(3);consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar";prev.value+=value;prev.output=globstar(opts);state6.output=prev.output;state6.globstar=true;consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state6.output=state6.output.slice(0,-(prior.output+prev.output).length);prior.output=`(?:${prior.output}`;prev.type="globstar";prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)");prev.value+=value;state6.globstar=true;state6.output+=prior.output+prev.output;consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){const end=rest[1]!==void 0?"|$":"";state6.output=state6.output.slice(0,-(prior.output+prev.output).length);prior.output=`(?:${prior.output}`;prev.type="globstar";prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;prev.value+=value;state6.output+=prior.output+prev.output;state6.globstar=true;consume(value+advance());push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar";prev.value+=value;prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;state6.output=prev.output;state6.globstar=true;consume(value+advance());push({type:"slash",value:"/",output:""});continue}state6.output=state6.output.slice(0,-prev.output.length);prev.type="globstar";prev.output=globstar(opts);prev.value+=value;state6.output+=prev.output;state6.globstar=true;consume(value);continue}const token={type:"star",value,output:star3};if(opts.bash===true){token.output=".*?";if(prev.type==="bos"||prev.type==="slash"){token.output=nodot+token.output}push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===true){token.output=value;push(token);continue}if(state6.index===state6.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot"){state6.output+=NO_DOT_SLASH;prev.output+=NO_DOT_SLASH}else if(opts.dot===true){state6.output+=NO_DOTS_SLASH;prev.output+=NO_DOTS_SLASH}else{state6.output+=nodot;prev.output+=nodot}if(peek()!=="*"){state6.output+=ONE_CHAR;prev.output+=ONE_CHAR}}push(token)}while(state6.brackets>0){if(opts.strictBrackets===true)throw new SyntaxError(syntaxError("closing","]"));state6.output=utils.escapeLast(state6.output,"[");decrement("brackets")}while(state6.parens>0){if(opts.strictBrackets===true)throw new SyntaxError(syntaxError("closing",")"));state6.output=utils.escapeLast(state6.output,"(");decrement("parens")}while(state6.braces>0){if(opts.strictBrackets===true)throw new SyntaxError(syntaxError("closing","}"));state6.output=utils.escapeLast(state6.output,"{");decrement("braces")}if(opts.strictSlashes!==true&&(prev.type==="star"||prev.type==="bracket")){push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`})}if(state6.backtrack===true){state6.output="";for(const token of state6.tokens){state6.output+=token.output!=null?token.output:token.value;if(token.suffix){state6.output+=token.suffix}}}return state6};parse11.fastpaths=(input,options)=>{const opts={...options};const max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH;const len=input.length;if(len>max){throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`)}input=REPLACEMENTS[input]||input;const win32=utils.isWindows(options);const{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants3.globChars(win32);const nodot=opts.dot?NO_DOTS:NO_DOT;const slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT;const capture=opts.capture?"":"?:";const state6={negated:false,prefix:""};let star3=opts.bash===true?".*?":STAR;if(opts.capture){star3=`(${star3})`}const globstar=opts2=>{if(opts2.noglobstar===true)return star3;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`};const create=str=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star3}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star3}`;case"*.*":return`${nodot}${star3}${DOT_LITERAL}${ONE_CHAR}${star3}`;case"*/*":return`${nodot}${star3}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star3}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star3}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star3}${DOT_LITERAL}${ONE_CHAR}${star3}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star3}`;default:{const match2=/^(.*?)\.(\w+)$/.exec(str);if(!match2)return;const source2=create(match2[1]);if(!source2)return;return source2+DOT_LITERAL+match2[2]}}};const output=utils.removePrefix(input,state6);let source=create(output);if(source&&opts.strictSlashes!==true){source+=`${SLASH_LITERAL}?`}return source};module2.exports=parse11}});var require_picomatch=__commonJS({"../../node_modules/picomatch/lib/picomatch.js"(exports2,module2){"use strict";var path24=require("path");var scan=require_scan2();var parse11=require_parse4();var utils=require_utils6();var constants3=require_constants8();var isObject2=val2=>val2&&typeof val2==="object"&&!Array.isArray(val2);var picomatch=(glob2,options,returnState=false)=>{if(Array.isArray(glob2)){const fns=glob2.map(input=>picomatch(input,options,returnState));const arrayMatcher=str=>{for(const isMatch of fns){const state7=isMatch(str);if(state7)return state7}return false};return arrayMatcher}const isState=isObject2(glob2)&&glob2.tokens&&glob2.input;if(glob2===""||typeof glob2!=="string"&&!isState){throw new TypeError("Expected pattern to be a non-empty string")}const opts=options||{};const posix=utils.isWindows(options);const regex=isState?picomatch.compileRe(glob2,options):picomatch.makeRe(glob2,options,false,true);const state6=regex.state;delete regex.state;let isIgnored=()=>false;if(opts.ignore){const ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}const matcher=(input,returnObject=false)=>{const{isMatch,match:match2,output}=picomatch.test(input,regex,options,{glob:glob2,posix});const result={glob:glob2,state:state6,regex,posix,input,output,match:match2,isMatch};if(typeof opts.onResult==="function"){opts.onResult(result)}if(isMatch===false){result.isMatch=false;return returnObject?result:false}if(isIgnored(input)){if(typeof opts.onIgnore==="function"){opts.onIgnore(result)}result.isMatch=false;return returnObject?result:false}if(typeof opts.onMatch==="function"){opts.onMatch(result)}return returnObject?result:true};if(returnState){matcher.state=state6}return matcher};picomatch.test=(input,regex,options,{glob:glob2,posix}={})=>{if(typeof input!=="string"){throw new TypeError("Expected input to be a string")}if(input===""){return{isMatch:false,output:""}}const opts=options||{};const format7=opts.format||(posix?utils.toPosixSlashes:null);let match2=input===glob2;let output=match2&&format7?format7(input):input;if(match2===false){output=format7?format7(input):input;match2=output===glob2}if(match2===false||opts.capture===true){if(opts.matchBase===true||opts.basename===true){match2=picomatch.matchBase(input,regex,options,posix)}else{match2=regex.exec(output)}}return{isMatch:Boolean(match2),match:match2,output}};picomatch.matchBase=(input,glob2,options,posix=utils.isWindows(options))=>{const regex=glob2 instanceof RegExp?glob2:picomatch.makeRe(glob2,options);return regex.test(path24.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map(p=>picomatch.parse(p,options));return parse11(pattern,{...options,fastpaths:false})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state6,options,returnOutput=false,returnState=false)=>{if(returnOutput===true){return state6.output}const opts=options||{};const prepend=opts.contains?"":"^";const append=opts.contains?"":"$";let source=`${prepend}(?:${state6.output})${append}`;if(state6&&state6.negated===true){source=`^(?!${source}).*$`}const regex=picomatch.toRegex(source,options);if(returnState===true){regex.state=state6}return regex};picomatch.makeRe=(input,options={},returnOutput=false,returnState=false)=>{if(!input||typeof input!=="string"){throw new TypeError("Expected a non-empty string")}let parsed={negated:false,fastpaths:true};if(options.fastpaths!==false&&(input[0]==="."||input[0]==="*")){parsed.output=parse11.fastpaths(input,options)}if(!parsed.output){parsed=parse11(input,options)}return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{const opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===true)throw err;return/$^/}};picomatch.constants=constants3;module2.exports=picomatch}});var require_picomatch2=__commonJS({"../../node_modules/picomatch/index.js"(exports2,module2){"use strict";module2.exports=require_picomatch()}});var require_readdirp=__commonJS({"../../node_modules/readdirp/index.js"(exports2,module2){"use strict";var fs23=require("fs");var{Readable}=require("stream");var sysPath=require("path");var{promisify:promisify2}=require("util");var picomatch=require_picomatch2();var readdir2=promisify2(fs23.readdir);var stat4=promisify2(fs23.stat);var lstat=promisify2(fs23.lstat);var realpath=promisify2(fs23.realpath);var BANG="!";var RECURSIVE_ERROR_CODE="READDIRP_RECURSIVE_ERROR";var NORMAL_FLOW_ERRORS=new Set(["ENOENT","EPERM","EACCES","ELOOP",RECURSIVE_ERROR_CODE]);var FILE_TYPE="files";var DIR_TYPE="directories";var FILE_DIR_TYPE="files_directories";var EVERYTHING_TYPE="all";var ALL_TYPES=[FILE_TYPE,DIR_TYPE,FILE_DIR_TYPE,EVERYTHING_TYPE];var isNormalFlowError=error3=>NORMAL_FLOW_ERRORS.has(error3.code);var[maj,min]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10));var wantBigintFsStats=process.platform==="win32"&&(maj>10||maj===10&&min>=5);var normalizeFilter=filter2=>{if(filter2===void 0)return;if(typeof filter2==="function")return filter2;if(typeof filter2==="string"){const glob2=picomatch(filter2.trim());return entry=>glob2(entry.basename)}if(Array.isArray(filter2)){const positive=[];const negative=[];for(const item of filter2){const trimmed=item.trim();if(trimmed.charAt(0)===BANG){negative.push(picomatch(trimmed.slice(1)))}else{positive.push(picomatch(trimmed))}}if(negative.length>0){if(positive.length>0){return entry=>positive.some(f=>f(entry.basename))&&!negative.some(f=>f(entry.basename))}return entry=>!negative.some(f=>f(entry.basename))}return entry=>positive.some(f=>f(entry.basename))}};var ReaddirpStream=class _ReaddirpStream extends Readable{static get defaultOptions(){return{root:".",fileFilter:path24=>true,directoryFilter:path24=>true,type:FILE_TYPE,lstat:false,depth:2147483648,alwaysStat:false}}constructor(options={}){super({objectMode:true,autoDestroy:true,highWaterMark:options.highWaterMark||4096});const opts={..._ReaddirpStream.defaultOptions,...options};const{root,type}=opts;this._fileFilter=normalizeFilter(opts.fileFilter);this._directoryFilter=normalizeFilter(opts.directoryFilter);const statMethod=opts.lstat?lstat:stat4;if(wantBigintFsStats){this._stat=path24=>statMethod(path24,{bigint:true})}else{this._stat=statMethod}this._maxDepth=opts.depth;this._wantsDir=[DIR_TYPE,FILE_DIR_TYPE,EVERYTHING_TYPE].includes(type);this._wantsFile=[FILE_TYPE,FILE_DIR_TYPE,EVERYTHING_TYPE].includes(type);this._wantsEverything=type===EVERYTHING_TYPE;this._root=sysPath.resolve(root);this._isDirent="Dirent"in fs23&&!opts.alwaysStat;this._statsProp=this._isDirent?"dirent":"stats";this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};this.parents=[this._exploreDir(root,1)];this.reading=false;this.parent=void 0}async _read(batch){if(this.reading)return;this.reading=true;try{while(!this.destroyed&&batch>0){const{path:path24,depth,files=[]}=this.parent||{};if(files.length>0){const slice=files.splice(0,batch).map(dirent=>this._formatEntry(dirent,path24));for(const entry of await Promise.all(slice)){if(this.destroyed)return;const entryType=await this._getEntryType(entry);if(entryType==="directory"&&this._directoryFilter(entry)){if(depth<=this._maxDepth){this.parents.push(this._exploreDir(entry.fullPath,depth+1))}if(this._wantsDir){this.push(entry);batch--}}else if((entryType==="file"||this._includeAsFile(entry))&&this._fileFilter(entry)){if(this._wantsFile){this.push(entry);batch--}}}}else{const parent=this.parents.pop();if(!parent){this.push(null);break}this.parent=await parent;if(this.destroyed)return}}}catch(error3){this.destroy(error3)}finally{this.reading=false}}async _exploreDir(path24,depth){let files;try{files=await readdir2(path24,this._rdOptions)}catch(error3){this._onError(error3)}return{files,depth,path:path24}}async _formatEntry(dirent,path24){let entry;try{const basename3=this._isDirent?dirent.name:dirent;const fullPath=sysPath.resolve(sysPath.join(path24,basename3));entry={path:sysPath.relative(this._root,fullPath),fullPath,basename:basename3};entry[this._statsProp]=this._isDirent?dirent:await this._stat(fullPath)}catch(err){this._onError(err)}return entry}_onError(err){if(isNormalFlowError(err)&&!this.destroyed){this.emit("warn",err)}else{this.destroy(err)}}async _getEntryType(entry){const stats=entry&&entry[this._statsProp];if(!stats){return}if(stats.isFile()){return"file"}if(stats.isDirectory()){return"directory"}if(stats&&stats.isSymbolicLink()){const full=entry.fullPath;try{const entryRealPath=await realpath(full);const entryRealPathStats=await lstat(entryRealPath);if(entryRealPathStats.isFile()){return"file"}if(entryRealPathStats.isDirectory()){const len=entryRealPath.length;if(full.startsWith(entryRealPath)&&full.substr(len,1)===sysPath.sep){const recursiveError=new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);recursiveError.code=RECURSIVE_ERROR_CODE;return this._onError(recursiveError)}return"directory"}}catch(error3){this._onError(error3)}}}_includeAsFile(entry){const stats=entry&&entry[this._statsProp];return stats&&this._wantsEverything&&!stats.isDirectory()}};var readdirp=(root,options={})=>{let type=options.entryType||options.type;if(type==="both")type=FILE_DIR_TYPE;if(type)options.type=type;if(!root){throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)")}else if(typeof root!=="string"){throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)")}else if(type&&!ALL_TYPES.includes(type)){throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`)}options.root=root;return new ReaddirpStream(options)};var readdirpPromise=(root,options={})=>{return new Promise((resolve7,reject)=>{const files=[];readdirp(root,options).on("data",entry=>files.push(entry)).on("end",()=>resolve7(files)).on("error",error3=>reject(error3))})};readdirp.promise=readdirpPromise;readdirp.ReaddirpStream=ReaddirpStream;readdirp.default=readdirp;module2.exports=readdirp}});var require_anymatch=__commonJS({"../../node_modules/anymatch/index.js"(exports2,module2){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var picomatch=require_picomatch2();var normalizePath=require_normalize_path();var BANG="!";var DEFAULT_OPTIONS={returnIndex:false};var arrify=item=>Array.isArray(item)?item:[item];var createPattern=(matcher,options)=>{if(typeof matcher==="function"){return matcher}if(typeof matcher==="string"){const glob2=picomatch(matcher,options);return string=>matcher===string||glob2(string)}if(matcher instanceof RegExp){return string=>matcher.test(string)}return string=>false};var matchPatterns=(patterns,negPatterns,args,returnIndex)=>{const isList=Array.isArray(args);const _path=isList?args[0]:args;if(!isList&&typeof _path!=="string"){throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(_path))}const path24=normalizePath(_path,false);for(let index=0;index<negPatterns.length;index++){const nglob=negPatterns[index];if(nglob(path24)){return returnIndex?-1:false}}const applied=isList&&[path24].concat(args.slice(1));for(let index=0;index<patterns.length;index++){const pattern=patterns[index];if(isList?pattern(...applied):pattern(path24)){return returnIndex?index:true}}return returnIndex?-1:false};var anymatch=(matchers,testString,options=DEFAULT_OPTIONS)=>{if(matchers==null){throw new TypeError("anymatch: specify first argument")}const opts=typeof options==="boolean"?{returnIndex:options}:options;const returnIndex=opts.returnIndex||false;const mtchers=arrify(matchers);const negatedGlobs=mtchers.filter(item=>typeof item==="string"&&item.charAt(0)===BANG).map(item=>item.slice(1)).map(item=>picomatch(item,opts));const patterns=mtchers.filter(item=>typeof item!=="string"||typeof item==="string"&&item.charAt(0)!==BANG).map(matcher=>createPattern(matcher,opts));if(testString==null){return(testString2,ri=false)=>{const returnIndex2=typeof ri==="boolean"?ri:false;return matchPatterns(patterns,negatedGlobs,testString2,returnIndex2)}}return matchPatterns(patterns,negatedGlobs,testString,returnIndex)};anymatch.default=anymatch;module2.exports=anymatch}});var require_is_extglob=__commonJS({"../../node_modules/is-extglob/index.js"(exports2,module2){module2.exports=function isExtglob(str){if(typeof str!=="string"||str===""){return false}var match2;while(match2=/(\\).|([@?!+*]\(.*\))/g.exec(str)){if(match2[2])return true;str=str.slice(match2.index+match2[0].length)}return false}}});var require_is_glob=__commonJS({"../../node_modules/is-glob/index.js"(exports2,module2){var isExtglob=require_is_extglob();var chars={"{":"}","(":")","[":"]"};var strictCheck=function(str){if(str[0]==="!"){return true}var index=0;var pipeIndex=-2;var closeSquareIndex=-2;var closeCurlyIndex=-2;var closeParenIndex=-2;var backSlashIndex=-2;while(index<str.length){if(str[index]==="*"){return true}if(str[index+1]==="?"&&/[\].+)]/.test(str[index])){return true}if(closeSquareIndex!==-1&&str[index]==="["&&str[index+1]!=="]"){if(closeSquareIndex<index){closeSquareIndex=str.indexOf("]",index)}if(closeSquareIndex>index){if(backSlashIndex===-1||backSlashIndex>closeSquareIndex){return true}backSlashIndex=str.indexOf("\\",index);if(backSlashIndex===-1||backSlashIndex>closeSquareIndex){return true}}}if(closeCurlyIndex!==-1&&str[index]==="{"&&str[index+1]!=="}"){closeCurlyIndex=str.indexOf("}",index);if(closeCurlyIndex>index){backSlashIndex=str.indexOf("\\",index);if(backSlashIndex===-1||backSlashIndex>closeCurlyIndex){return true}}}if(closeParenIndex!==-1&&str[index]==="("&&str[index+1]==="?"&&/[:!=]/.test(str[index+2])&&str[index+3]!==")"){closeParenIndex=str.indexOf(")",index);if(closeParenIndex>index){backSlashIndex=str.indexOf("\\",index);if(backSlashIndex===-1||backSlashIndex>closeParenIndex){return true}}}if(pipeIndex!==-1&&str[index]==="("&&str[index+1]!=="|"){if(pipeIndex<index){pipeIndex=str.indexOf("|",index)}if(pipeIndex!==-1&&str[pipeIndex+1]!==")"){closeParenIndex=str.indexOf(")",pipeIndex);if(closeParenIndex>pipeIndex){backSlashIndex=str.indexOf("\\",pipeIndex);if(backSlashIndex===-1||backSlashIndex>closeParenIndex){return true}}}}if(str[index]==="\\"){var open=str[index+1];index+=2;var close=chars[open];if(close){var n=str.indexOf(close,index);if(n!==-1){index=n+1}}if(str[index]==="!"){return true}}else{index++}}return false};var relaxedCheck=function(str){if(str[0]==="!"){return true}var index=0;while(index<str.length){if(/[*?{}()[\]]/.test(str[index])){return true}if(str[index]==="\\"){var open=str[index+1];index+=2;var close=chars[open];if(close){var n=str.indexOf(close,index);if(n!==-1){index=n+1}}if(str[index]==="!"){return true}}else{index++}}return false};module2.exports=function isGlob(str,options){if(typeof str!=="string"||str===""){return false}if(isExtglob(str)){return true}var check=strictCheck;if(options&&options.strict===false){check=relaxedCheck}return check(str)}}});var require_glob_parent=__commonJS({"../../node_modules/glob-parent/index.js"(exports2,module2){"use strict";var isGlob=require_is_glob();var pathPosixDirname=require("path").posix.dirname;var isWin32=require("os").platform()==="win32";var slash="/";var backslash=/\\/g;var enclosure=/[\{\[].*[\}\]]$/;var globby=/(^|[^\\])([\{\[]|\([^\)]+$)/;var escaped=/\\([\!\*\?\|\[\]\(\)\{\}])/g;module2.exports=function globParent(str,opts){var options=Object.assign({flipBackslashes:true},opts);if(options.flipBackslashes&&isWin32&&str.indexOf(slash)<0){str=str.replace(backslash,slash)}if(enclosure.test(str)){str+=slash}str+="a";do{str=pathPosixDirname(str)}while(isGlob(str)||globby.test(str));return str.replace(escaped,"$1")}}});var require_utils7=__commonJS({"../../node_modules/braces/lib/utils.js"(exports2){"use strict";exports2.isInteger=num=>{if(typeof num==="number"){return Number.isInteger(num)}if(typeof num==="string"&&num.trim()!==""){return Number.isInteger(Number(num))}return false};exports2.find=(node,type)=>node.nodes.find(node2=>node2.type===type);exports2.exceedsLimit=(min,max,step=1,limit)=>{if(limit===false)return false;if(!exports2.isInteger(min)||!exports2.isInteger(max))return false;return(Number(max)-Number(min))/Number(step)>=limit};exports2.escapeNode=(block,n=0,type)=>{const node=block.nodes[n];if(!node)return;if(type&&node.type===type||node.type==="open"||node.type==="close"){if(node.escaped!==true){node.value="\\"+node.value;node.escaped=true}}};exports2.encloseBrace=node=>{if(node.type!=="brace")return false;if(node.commas>>0+node.ranges>>0===0){node.invalid=true;return true}return false};exports2.isInvalidBrace=block=>{if(block.type!=="brace")return false;if(block.invalid===true||block.dollar)return true;if(block.commas>>0+block.ranges>>0===0){block.invalid=true;return true}if(block.open!==true||block.close!==true){block.invalid=true;return true}return false};exports2.isOpenOrClose=node=>{if(node.type==="open"||node.type==="close"){return true}return node.open===true||node.close===true};exports2.reduce=nodes=>nodes.reduce((acc,node)=>{if(node.type==="text")acc.push(node.value);if(node.type==="range")node.type="text";return acc},[]);exports2.flatten=(...args)=>{const result=[];const flat=arr=>{for(let i=0;i<arr.length;i++){const ele=arr[i];if(Array.isArray(ele)){flat(ele);continue}if(ele!==void 0){result.push(ele)}}return result};flat(args);return result}}});var require_stringify=__commonJS({"../../node_modules/braces/lib/stringify.js"(exports2,module2){"use strict";var utils=require_utils7();module2.exports=(ast,options={})=>{const stringify12=(node,parent={})=>{const invalidBlock=options.escapeInvalid&&utils.isInvalidBrace(parent);const invalidNode=node.invalid===true&&options.escapeInvalid===true;let output="";if(node.value){if((invalidBlock||invalidNode)&&utils.isOpenOrClose(node)){return"\\"+node.value}return node.value}if(node.value){return node.value}if(node.nodes){for(const child of node.nodes){output+=stringify12(child)}}return output};return stringify12(ast)}}});var require_is_number=__commonJS({"../../node_modules/is-number/index.js"(exports2,module2){"use strict";module2.exports=function(num){if(typeof num==="number"){return num-num===0}if(typeof num==="string"&&num.trim()!==""){return Number.isFinite?Number.isFinite(+num):isFinite(+num)}return false}}});var require_to_regex_range=__commonJS({"../../node_modules/to-regex-range/index.js"(exports2,module2){"use strict";var isNumber=require_is_number();var toRegexRange=(min,max,options)=>{if(isNumber(min)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(max===void 0||min===max){return String(min)}if(isNumber(max)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let opts={relaxZeros:true,...options};if(typeof opts.strictZeros==="boolean"){opts.relaxZeros=opts.strictZeros===false}let relax=String(opts.relaxZeros);let shorthand=String(opts.shorthand);let capture=String(opts.capture);let wrap=String(opts.wrap);let cacheKey=min+":"+max+"="+relax+shorthand+capture+wrap;if(toRegexRange.cache.hasOwnProperty(cacheKey)){return toRegexRange.cache[cacheKey].result}let a=Math.min(min,max);let b=Math.max(min,max);if(Math.abs(a-b)===1){let result=min+"|"+max;if(opts.capture){return`(${result})`}if(opts.wrap===false){return result}return`(?:${result})`}let isPadded=hasPadding(min)||hasPadding(max);let state6={min,max,a,b};let positives=[];let negatives=[];if(isPadded){state6.isPadded=isPadded;state6.maxLen=String(state6.max).length}if(a<0){let newMin=b<0?Math.abs(b):1;negatives=splitToPatterns(newMin,Math.abs(a),state6,opts);a=state6.a=0}if(b>=0){positives=splitToPatterns(a,b,state6,opts)}state6.negatives=negatives;state6.positives=positives;state6.result=collatePatterns(negatives,positives,opts);if(opts.capture===true){state6.result=`(${state6.result})`}else if(opts.wrap!==false&&positives.length+negatives.length>1){state6.result=`(?:${state6.result})`}toRegexRange.cache[cacheKey]=state6;return state6.result};function collatePatterns(neg,pos,options){let onlyNegative=filterPatterns(neg,pos,"-",false,options)||[];let onlyPositive=filterPatterns(pos,neg,"",false,options)||[];let intersected=filterPatterns(neg,pos,"-?",true,options)||[];let subpatterns=onlyNegative.concat(intersected).concat(onlyPositive);return subpatterns.join("|")}function splitToRanges(min,max){let nines=1;let zeros=1;let stop=countNines(min,nines);let stops=new Set([max]);while(min<=stop&&stop<=max){stops.add(stop);nines+=1;stop=countNines(min,nines)}stop=countZeros(max+1,zeros)-1;while(min<stop&&stop<=max){stops.add(stop);zeros+=1;stop=countZeros(max+1,zeros)-1}stops=[...stops];stops.sort(compare2);return stops}function rangeToPattern(start,stop,options){if(start===stop){return{pattern:start,count:[],digits:0}}let zipped=zip(start,stop);let digits=zipped.length;let pattern="";let count=0;for(let i=0;i<digits;i++){let[startDigit,stopDigit]=zipped[i];if(startDigit===stopDigit){pattern+=startDigit}else if(startDigit!=="0"||stopDigit!=="9"){pattern+=toCharacterClass(startDigit,stopDigit,options)}else{count++}}if(count){pattern+=options.shorthand===true?"\\d":"[0-9]"}return{pattern,count:[count],digits}}function splitToPatterns(min,max,tok,options){let ranges=splitToRanges(min,max);let tokens=[];let start=min;let prev;for(let i=0;i<ranges.length;i++){let max2=ranges[i];let obj=rangeToPattern(String(start),String(max2),options);let zeros="";if(!tok.isPadded&&prev&&prev.pattern===obj.pattern){if(prev.count.length>1){prev.count.pop()}prev.count.push(obj.count[0]);prev.string=prev.pattern+toQuantifier(prev.count);start=max2+1;continue}if(tok.isPadded){zeros=padZeros(max2,tok,options)}obj.string=zeros+obj.pattern+toQuantifier(obj.count);tokens.push(obj);start=max2+1;prev=obj}return tokens}function filterPatterns(arr,comparison,prefix,intersection,options){let result=[];for(let ele of arr){let{string}=ele;if(!intersection&&!contains2(comparison,"string",string)){result.push(prefix+string)}if(intersection&&contains2(comparison,"string",string)){result.push(prefix+string)}}return result}function zip(a,b){let arr=[];for(let i=0;i<a.length;i++)arr.push([a[i],b[i]]);return arr}function compare2(a,b){return a>b?1:b>a?-1:0}function contains2(arr,key,val2){return arr.some(ele=>ele[key]===val2)}function countNines(min,len){return Number(String(min).slice(0,-len)+"9".repeat(len))}function countZeros(integer,zeros){return integer-integer%Math.pow(10,zeros)}function toQuantifier(digits){let[start=0,stop=""]=digits;if(stop||start>1){return`{${start+(stop?","+stop:"")}}`}return""}function toCharacterClass(a,b,options){return`[${a}${b-a===1?"":"-"}${b}]`}function hasPadding(str){return/^-?(0+)\d/.test(str)}function padZeros(value,tok,options){if(!tok.isPadded){return value}let diff=Math.abs(tok.maxLen-String(value).length);let relax=options.relaxZeros!==false;switch(diff){case 0:return"";case 1:return relax?"0?":"0";case 2:return relax?"0{0,2}":"00";default:{return relax?`0{0,${diff}}`:`0{${diff}}`}}}toRegexRange.cache={};toRegexRange.clearCache=()=>toRegexRange.cache={};module2.exports=toRegexRange}});var require_fill_range=__commonJS({"../../node_modules/fill-range/index.js"(exports2,module2){"use strict";var util4=require("util");var toRegexRange=require_to_regex_range();var isObject2=val2=>val2!==null&&typeof val2==="object"&&!Array.isArray(val2);var transform=toNumber=>{return value=>toNumber===true?Number(value):String(value)};var isValidValue=value=>{return typeof value==="number"||typeof value==="string"&&value!==""};var isNumber=num=>Number.isInteger(+num);var zeros=input=>{let value=`${input}`;let index=-1;if(value[0]==="-")value=value.slice(1);if(value==="0")return false;while(value[++index]==="0");return index>0};var stringify12=(start,end,options)=>{if(typeof start==="string"||typeof end==="string"){return true}return options.stringify===true};var pad=(input,maxLength,toNumber)=>{if(maxLength>0){let dash=input[0]==="-"?"-":"";if(dash)input=input.slice(1);input=dash+input.padStart(dash?maxLength-1:maxLength,"0")}if(toNumber===false){return String(input)}return input};var toMaxLen=(input,maxLength)=>{let negative=input[0]==="-"?"-":"";if(negative){input=input.slice(1);maxLength--}while(input.length<maxLength)input="0"+input;return negative?"-"+input:input};var toSequence=(parts,options,maxLen)=>{parts.negatives.sort((a,b)=>a<b?-1:a>b?1:0);parts.positives.sort((a,b)=>a<b?-1:a>b?1:0);let prefix=options.capture?"":"?:";let positives="";let negatives="";let result;if(parts.positives.length){positives=parts.positives.map(v=>toMaxLen(String(v),maxLen)).join("|")}if(parts.negatives.length){negatives=`-(${prefix}${parts.negatives.map(v=>toMaxLen(String(v),maxLen)).join("|")})`}if(positives&&negatives){result=`${positives}|${negatives}`}else{result=positives||negatives}if(options.wrap){return`(${prefix}${result})`}return result};var toRange=(a,b,isNumbers,options)=>{if(isNumbers){return toRegexRange(a,b,{wrap:false,...options})}let start=String.fromCharCode(a);if(a===b)return start;let stop=String.fromCharCode(b);return`[${start}-${stop}]`};var toRegex=(start,end,options)=>{if(Array.isArray(start)){let wrap=options.wrap===true;let prefix=options.capture?"":"?:";return wrap?`(${prefix}${start.join("|")})`:start.join("|")}return toRegexRange(start,end,options)};var rangeError=(...args)=>{return new RangeError("Invalid range arguments: "+util4.inspect(...args))};var invalidRange=(start,end,options)=>{if(options.strictRanges===true)throw rangeError([start,end]);return[]};var invalidStep=(step,options)=>{if(options.strictRanges===true){throw new TypeError(`Expected step "${step}" to be a number`)}return[]};var fillNumbers=(start,end,step=1,options={})=>{let a=Number(start);let b=Number(end);if(!Number.isInteger(a)||!Number.isInteger(b)){if(options.strictRanges===true)throw rangeError([start,end]);return[]}if(a===0)a=0;if(b===0)b=0;let descending2=a>b;let startString=String(start);let endString=String(end);let stepString=String(step);step=Math.max(Math.abs(step),1);let padded=zeros(startString)||zeros(endString)||zeros(stepString);let maxLen=padded?Math.max(startString.length,endString.length,stepString.length):0;let toNumber=padded===false&&stringify12(start,end,options)===false;let format7=options.transform||transform(toNumber);if(options.toRegex&&step===1){return toRange(toMaxLen(start,maxLen),toMaxLen(end,maxLen),true,options)}let parts={negatives:[],positives:[]};let push=num=>parts[num<0?"negatives":"positives"].push(Math.abs(num));let range=[];let index=0;while(descending2?a>=b:a<=b){if(options.toRegex===true&&step>1){push(a)}else{range.push(pad(format7(a,index),maxLen,toNumber))}a=descending2?a-step:a+step;index++}if(options.toRegex===true){return step>1?toSequence(parts,options,maxLen):toRegex(range,null,{wrap:false,...options})}return range};var fillLetters=(start,end,step=1,options={})=>{if(!isNumber(start)&&start.length>1||!isNumber(end)&&end.length>1){return invalidRange(start,end,options)}let format7=options.transform||(val2=>String.fromCharCode(val2));let a=`${start}`.charCodeAt(0);let b=`${end}`.charCodeAt(0);let descending2=a>b;let min=Math.min(a,b);let max=Math.max(a,b);if(options.toRegex&&step===1){return toRange(min,max,false,options)}let range=[];let index=0;while(descending2?a>=b:a<=b){range.push(format7(a,index));a=descending2?a-step:a+step;index++}if(options.toRegex===true){return toRegex(range,null,{wrap:false,options})}return range};var fill=(start,end,step,options={})=>{if(end==null&&isValidValue(start)){return[start]}if(!isValidValue(start)||!isValidValue(end)){return invalidRange(start,end,options)}if(typeof step==="function"){return fill(start,end,1,{transform:step})}if(isObject2(step)){return fill(start,end,0,step)}let opts={...options};if(opts.capture===true)opts.wrap=true;step=step||opts.step||1;if(!isNumber(step)){if(step!=null&&!isObject2(step))return invalidStep(step,opts);return fill(start,end,1,step)}if(isNumber(start)&&isNumber(end)){return fillNumbers(start,end,step,opts)}return fillLetters(start,end,Math.max(Math.abs(step),1),opts)};module2.exports=fill}});var require_compile2=__commonJS({"../../node_modules/braces/lib/compile.js"(exports2,module2){"use strict";var fill=require_fill_range();var utils=require_utils7();var compile=(ast,options={})=>{const walk=(node,parent={})=>{const invalidBlock=utils.isInvalidBrace(parent);const invalidNode=node.invalid===true&&options.escapeInvalid===true;const invalid=invalidBlock===true||invalidNode===true;const prefix=options.escapeInvalid===true?"\\":"";let output="";if(node.isOpen===true){return prefix+node.value}if(node.isClose===true){console.log("node.isClose",prefix,node.value);return prefix+node.value}if(node.type==="open"){return invalid?prefix+node.value:"("}if(node.type==="close"){return invalid?prefix+node.value:")"}if(node.type==="comma"){return node.prev.type==="comma"?"":invalid?node.value:"|"}if(node.value){return node.value}if(node.nodes&&node.ranges>0){const args=utils.reduce(node.nodes);const range=fill(...args,{...options,wrap:false,toRegex:true,strictZeros:true});if(range.length!==0){return args.length>1&&range.length>1?`(${range})`:range}}if(node.nodes){for(const child of node.nodes){output+=walk(child,node)}}return output};return walk(ast)};module2.exports=compile}});var require_expand=__commonJS({"../../node_modules/braces/lib/expand.js"(exports2,module2){"use strict";var fill=require_fill_range();var stringify12=require_stringify();var utils=require_utils7();var append=(queue="",stash="",enclose=false)=>{const result=[];queue=[].concat(queue);stash=[].concat(stash);if(!stash.length)return queue;if(!queue.length){return enclose?utils.flatten(stash).map(ele=>`{${ele}}`):stash}for(const item of queue){if(Array.isArray(item)){for(const value of item){result.push(append(value,stash,enclose))}}else{for(let ele of stash){if(enclose===true&&typeof ele==="string")ele=`{${ele}}`;result.push(Array.isArray(ele)?append(item,ele,enclose):item+ele)}}}return utils.flatten(result)};var expand2=(ast,options={})=>{const rangeLimit=options.rangeLimit===void 0?1e3:options.rangeLimit;const walk=(node,parent={})=>{node.queue=[];let p=parent;let q=parent.queue;while(p.type!=="brace"&&p.type!=="root"&&p.parent){p=p.parent;q=p.queue}if(node.invalid||node.dollar){q.push(append(q.pop(),stringify12(node,options)));return}if(node.type==="brace"&&node.invalid!==true&&node.nodes.length===2){q.push(append(q.pop(),["{}"]));return}if(node.nodes&&node.ranges>0){const args=utils.reduce(node.nodes);if(utils.exceedsLimit(...args,options.step,rangeLimit)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let range=fill(...args,options);if(range.length===0){range=stringify12(node,options)}q.push(append(q.pop(),range));node.nodes=[];return}const enclose=utils.encloseBrace(node);let queue=node.queue;let block=node;while(block.type!=="brace"&&block.type!=="root"&&block.parent){block=block.parent;queue=block.queue}for(let i=0;i<node.nodes.length;i++){const child=node.nodes[i];if(child.type==="comma"&&node.type==="brace"){if(i===1)queue.push("");queue.push("");continue}if(child.type==="close"){q.push(append(q.pop(),queue,enclose));continue}if(child.value&&child.type!=="open"){queue.push(append(queue.pop(),child.value));continue}if(child.nodes){walk(child,node)}}return queue};return utils.flatten(walk(ast))};module2.exports=expand2}});var require_constants9=__commonJS({"../../node_modules/braces/lib/constants.js"(exports2,module2){"use strict";module2.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:"\n",CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}}});var require_parse5=__commonJS({"../../node_modules/braces/lib/parse.js"(exports2,module2){"use strict";var stringify12=require_stringify();var{MAX_LENGTH,CHAR_BACKSLASH,CHAR_BACKTICK,CHAR_COMMA,CHAR_DOT,CHAR_LEFT_PARENTHESES,CHAR_RIGHT_PARENTHESES,CHAR_LEFT_CURLY_BRACE,CHAR_RIGHT_CURLY_BRACE,CHAR_LEFT_SQUARE_BRACKET,CHAR_RIGHT_SQUARE_BRACKET,CHAR_DOUBLE_QUOTE,CHAR_SINGLE_QUOTE,CHAR_NO_BREAK_SPACE,CHAR_ZERO_WIDTH_NOBREAK_SPACE}=require_constants9();var parse11=(input,options={})=>{if(typeof input!=="string"){throw new TypeError("Expected a string")}const opts=options||{};const max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH;if(input.length>max){throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`)}const ast={type:"root",input,nodes:[]};const stack=[ast];let block=ast;let prev=ast;let brackets=0;const length=input.length;let index=0;let depth=0;let value;const advance=()=>input[index++];const push=node=>{if(node.type==="text"&&prev.type==="dot"){prev.type="text"}if(prev&&prev.type==="text"&&node.type==="text"){prev.value+=node.value;return}block.nodes.push(node);node.parent=block;node.prev=prev;prev=node;return node};push({type:"bos"});while(index<length){block=stack[stack.length-1];value=advance();if(value===CHAR_ZERO_WIDTH_NOBREAK_SPACE||value===CHAR_NO_BREAK_SPACE){continue}if(value===CHAR_BACKSLASH){push({type:"text",value:(options.keepEscaping?value:"")+advance()});continue}if(value===CHAR_RIGHT_SQUARE_BRACKET){push({type:"text",value:"\\"+value});continue}if(value===CHAR_LEFT_SQUARE_BRACKET){brackets++;let next;while(index<length&&(next=advance())){value+=next;if(next===CHAR_LEFT_SQUARE_BRACKET){brackets++;continue}if(next===CHAR_BACKSLASH){value+=advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){brackets--;if(brackets===0){break}}}push({type:"text",value});continue}if(value===CHAR_LEFT_PARENTHESES){block=push({type:"paren",nodes:[]});stack.push(block);push({type:"text",value});continue}if(value===CHAR_RIGHT_PARENTHESES){if(block.type!=="paren"){push({type:"text",value});continue}block=stack.pop();push({type:"text",value});block=stack[stack.length-1];continue}if(value===CHAR_DOUBLE_QUOTE||value===CHAR_SINGLE_QUOTE||value===CHAR_BACKTICK){const open=value;let next;if(options.keepQuotes!==true){value=""}while(index<length&&(next=advance())){if(next===CHAR_BACKSLASH){value+=next+advance();continue}if(next===open){if(options.keepQuotes===true)value+=next;break}value+=next}push({type:"text",value});continue}if(value===CHAR_LEFT_CURLY_BRACE){depth++;const dollar=prev.value&&prev.value.slice(-1)==="$"||block.dollar===true;const brace={type:"brace",open:true,close:false,dollar,depth,commas:0,ranges:0,nodes:[]};block=push(brace);stack.push(block);push({type:"open",value});continue}if(value===CHAR_RIGHT_CURLY_BRACE){if(block.type!=="brace"){push({type:"text",value});continue}const type="close";block=stack.pop();block.close=true;push({type,value});depth--;block=stack[stack.length-1];continue}if(value===CHAR_COMMA&&depth>0){if(block.ranges>0){block.ranges=0;const open=block.nodes.shift();block.nodes=[open,{type:"text",value:stringify12(block)}]}push({type:"comma",value});block.commas++;continue}if(value===CHAR_DOT&&depth>0&&block.commas===0){const siblings=block.nodes;if(depth===0||siblings.length===0){push({type:"text",value});continue}if(prev.type==="dot"){block.range=[];prev.value+=value;prev.type="range";if(block.nodes.length!==3&&block.nodes.length!==5){block.invalid=true;block.ranges=0;prev.type="text";continue}block.ranges++;block.args=[];continue}if(prev.type==="range"){siblings.pop();const before=siblings[siblings.length-1];before.value+=prev.value+value;prev=before;block.ranges--;continue}push({type:"dot",value});continue}push({type:"text",value})}do{block=stack.pop();if(block.type!=="root"){block.nodes.forEach(node=>{if(!node.nodes){if(node.type==="open")node.isOpen=true;if(node.type==="close")node.isClose=true;if(!node.nodes)node.type="text";node.invalid=true}});const parent=stack[stack.length-1];const index2=parent.nodes.indexOf(block);parent.nodes.splice(index2,1,...block.nodes)}}while(stack.length>0);push({type:"eos"});return ast};module2.exports=parse11}});var require_braces=__commonJS({"../../node_modules/braces/index.js"(exports2,module2){"use strict";var stringify12=require_stringify();var compile=require_compile2();var expand2=require_expand();var parse11=require_parse5();var braces=(input,options={})=>{let output=[];if(Array.isArray(input)){for(const pattern of input){const result=braces.create(pattern,options);if(Array.isArray(result)){output.push(...result)}else{output.push(result)}}}else{output=[].concat(braces.create(input,options))}if(options&&options.expand===true&&options.nodupes===true){output=[...new Set(output)]}return output};braces.parse=(input,options={})=>parse11(input,options);braces.stringify=(input,options={})=>{if(typeof input==="string"){return stringify12(braces.parse(input,options),options)}return stringify12(input,options)};braces.compile=(input,options={})=>{if(typeof input==="string"){input=braces.parse(input,options)}return compile(input,options)};braces.expand=(input,options={})=>{if(typeof input==="string"){input=braces.parse(input,options)}let result=expand2(input,options);if(options.noempty===true){result=result.filter(Boolean)}if(options.nodupes===true){result=[...new Set(result)]}return result};braces.create=(input,options={})=>{if(input===""||input.length<3){return[input]}return options.expand!==true?braces.compile(input,options):braces.expand(input,options)};module2.exports=braces}});var require_binary_extensions=__commonJS({"../../node_modules/binary-extensions/binary-extensions.json"(exports2,module2){module2.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]}});var require_binary_extensions2=__commonJS({"../../node_modules/binary-extensions/index.js"(exports2,module2){module2.exports=require_binary_extensions()}});var require_is_binary_path=__commonJS({"../../node_modules/is-binary-path/index.js"(exports2,module2){"use strict";var path24=require("path");var binaryExtensions=require_binary_extensions2();var extensions=new Set(binaryExtensions);module2.exports=filePath=>extensions.has(path24.extname(filePath).slice(1).toLowerCase())}});var require_constants10=__commonJS({"../../node_modules/chokidar/lib/constants.js"(exports2){"use strict";var{sep:sep2}=require("path");var{platform:platform3}=process;var os8=require("os");exports2.EV_ALL="all";exports2.EV_READY="ready";exports2.EV_ADD="add";exports2.EV_CHANGE="change";exports2.EV_ADD_DIR="addDir";exports2.EV_UNLINK="unlink";exports2.EV_UNLINK_DIR="unlinkDir";exports2.EV_RAW="raw";exports2.EV_ERROR="error";exports2.STR_DATA="data";exports2.STR_END="end";exports2.STR_CLOSE="close";exports2.FSEVENT_CREATED="created";exports2.FSEVENT_MODIFIED="modified";exports2.FSEVENT_DELETED="deleted";exports2.FSEVENT_MOVED="moved";exports2.FSEVENT_CLONED="cloned";exports2.FSEVENT_UNKNOWN="unknown";exports2.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;exports2.FSEVENT_TYPE_FILE="file";exports2.FSEVENT_TYPE_DIRECTORY="directory";exports2.FSEVENT_TYPE_SYMLINK="symlink";exports2.KEY_LISTENERS="listeners";exports2.KEY_ERR="errHandlers";exports2.KEY_RAW="rawEmitters";exports2.HANDLER_KEYS=[exports2.KEY_LISTENERS,exports2.KEY_ERR,exports2.KEY_RAW];exports2.DOT_SLASH=`.${sep2}`;exports2.BACK_SLASH_RE=/\\/g;exports2.DOUBLE_SLASH_RE=/\/\//;exports2.SLASH_OR_BACK_SLASH_RE=/[/\\]/;exports2.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;exports2.REPLACER_RE=/^\.[/\\]/;exports2.SLASH="/";exports2.SLASH_SLASH="//";exports2.BRACE_START="{";exports2.BANG="!";exports2.ONE_DOT=".";exports2.TWO_DOTS="..";exports2.STAR="*";exports2.GLOBSTAR="**";exports2.ROOT_GLOBSTAR="/**/*";exports2.SLASH_GLOBSTAR="/**";exports2.DIR_SUFFIX="Dir";exports2.ANYMATCH_OPTS={dot:true};exports2.STRING_TYPE="string";exports2.FUNCTION_TYPE="function";exports2.EMPTY_STR="";exports2.EMPTY_FN=()=>{};exports2.IDENTITY_FN=val2=>val2;exports2.isWindows=platform3==="win32";exports2.isMacos=platform3==="darwin";exports2.isLinux=platform3==="linux";exports2.isIBMi=os8.type()==="OS400"}});var require_nodefs_handler=__commonJS({"../../node_modules/chokidar/lib/nodefs-handler.js"(exports2,module2){"use strict";var fs23=require("fs");var sysPath=require("path");var{promisify:promisify2}=require("util");var isBinaryPath=require_is_binary_path();var{isWindows,isLinux,EMPTY_FN,EMPTY_STR,KEY_LISTENERS,KEY_ERR,KEY_RAW,HANDLER_KEYS,EV_CHANGE,EV_ADD,EV_ADD_DIR,EV_ERROR,STR_DATA,STR_END,BRACE_START,STAR}=require_constants10();var THROTTLE_MODE_WATCH="watch";var open=promisify2(fs23.open);var stat4=promisify2(fs23.stat);var lstat=promisify2(fs23.lstat);var close=promisify2(fs23.close);var fsrealpath=promisify2(fs23.realpath);var statMethods={lstat,stat:stat4};var foreach=(val2,fn)=>{if(val2 instanceof Set){val2.forEach(fn)}else{fn(val2)}};var addAndConvert=(main,prop,item)=>{let container=main[prop];if(!(container instanceof Set)){main[prop]=container=new Set([container])}container.add(item)};var clearItem=cont=>key=>{const set=cont[key];if(set instanceof Set){set.clear()}else{delete cont[key]}};var delFromSet=(main,prop,item)=>{const container=main[prop];if(container instanceof Set){container.delete(item)}else if(container===item){delete main[prop]}};var isEmptySet=val2=>val2 instanceof Set?val2.size===0:!val2;var FsWatchInstances=new Map;function createFsWatchInstance(path24,options,listener,errHandler,emitRaw){const handleEvent=(rawEvent,evPath)=>{listener(path24);emitRaw(rawEvent,evPath,{watchedPath:path24});if(evPath&&path24!==evPath){fsWatchBroadcast(sysPath.resolve(path24,evPath),KEY_LISTENERS,sysPath.join(path24,evPath))}};try{return fs23.watch(path24,options,handleEvent)}catch(error3){errHandler(error3)}}var fsWatchBroadcast=(fullPath,type,val1,val2,val3)=>{const cont=FsWatchInstances.get(fullPath);if(!cont)return;foreach(cont[type],listener=>{listener(val1,val2,val3)})};var setFsWatchListener=(path24,fullPath,options,handlers)=>{const{listener,errHandler,rawEmitter}=handlers;let cont=FsWatchInstances.get(fullPath);let watcher;if(!options.persistent){watcher=createFsWatchInstance(path24,options,listener,errHandler,rawEmitter);return watcher.close.bind(watcher)}if(cont){addAndConvert(cont,KEY_LISTENERS,listener);addAndConvert(cont,KEY_ERR,errHandler);addAndConvert(cont,KEY_RAW,rawEmitter)}else{watcher=createFsWatchInstance(path24,options,fsWatchBroadcast.bind(null,fullPath,KEY_LISTENERS),errHandler,fsWatchBroadcast.bind(null,fullPath,KEY_RAW));if(!watcher)return;watcher.on(EV_ERROR,async error3=>{const broadcastErr=fsWatchBroadcast.bind(null,fullPath,KEY_ERR);cont.watcherUnusable=true;if(isWindows&&error3.code==="EPERM"){try{const fd=await open(path24,"r");await close(fd);broadcastErr(error3)}catch(err){}}else{broadcastErr(error3)}});cont={listeners:listener,errHandlers:errHandler,rawEmitters:rawEmitter,watcher};FsWatchInstances.set(fullPath,cont)}return()=>{delFromSet(cont,KEY_LISTENERS,listener);delFromSet(cont,KEY_ERR,errHandler);delFromSet(cont,KEY_RAW,rawEmitter);if(isEmptySet(cont.listeners)){cont.watcher.close();FsWatchInstances.delete(fullPath);HANDLER_KEYS.forEach(clearItem(cont));cont.watcher=void 0;Object.freeze(cont)}}};var FsWatchFileInstances=new Map;var setFsWatchFileListener=(path24,fullPath,options,handlers)=>{const{listener,rawEmitter}=handlers;let cont=FsWatchFileInstances.get(fullPath);let listeners=new Set;let rawEmitters=new Set;const copts=cont&&cont.options;if(copts&&(copts.persistent<options.persistent||copts.interval>options.interval)){listeners=cont.listeners;rawEmitters=cont.rawEmitters;fs23.unwatchFile(fullPath);cont=void 0}if(cont){addAndConvert(cont,KEY_LISTENERS,listener);addAndConvert(cont,KEY_RAW,rawEmitter)}else{cont={listeners:listener,rawEmitters:rawEmitter,options,watcher:fs23.watchFile(fullPath,options,(curr,prev)=>{foreach(cont.rawEmitters,rawEmitter2=>{rawEmitter2(EV_CHANGE,fullPath,{curr,prev})});const currmtime=curr.mtimeMs;if(curr.size!==prev.size||currmtime>prev.mtimeMs||currmtime===0){foreach(cont.listeners,listener2=>listener2(path24,curr))}})};FsWatchFileInstances.set(fullPath,cont)}return()=>{delFromSet(cont,KEY_LISTENERS,listener);delFromSet(cont,KEY_RAW,rawEmitter);if(isEmptySet(cont.listeners)){FsWatchFileInstances.delete(fullPath);fs23.unwatchFile(fullPath);cont.options=cont.watcher=void 0;Object.freeze(cont)}}};var NodeFsHandler=class{constructor(fsW){this.fsw=fsW;this._boundHandleError=error3=>fsW._handleError(error3)}_watchWithNodeFs(path24,listener){const opts=this.fsw.options;const directory=sysPath.dirname(path24);const basename3=sysPath.basename(path24);const parent=this.fsw._getWatchedDir(directory);parent.add(basename3);const absolutePath=sysPath.resolve(path24);const options={persistent:opts.persistent};if(!listener)listener=EMPTY_FN;let closer;if(opts.usePolling){options.interval=opts.enableBinaryInterval&&isBinaryPath(basename3)?opts.binaryInterval:opts.interval;closer=setFsWatchFileListener(path24,absolutePath,options,{listener,rawEmitter:this.fsw._emitRaw})}else{closer=setFsWatchListener(path24,absolutePath,options,{listener,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw})}return closer}_handleFile(file,stats,initialAdd){if(this.fsw.closed){return}const dirname7=sysPath.dirname(file);const basename3=sysPath.basename(file);const parent=this.fsw._getWatchedDir(dirname7);let prevStats=stats;if(parent.has(basename3))return;const listener=async(path24,newStats)=>{if(!this.fsw._throttle(THROTTLE_MODE_WATCH,file,5))return;if(!newStats||newStats.mtimeMs===0){try{const newStats2=await stat4(file);if(this.fsw.closed)return;const at=newStats2.atimeMs;const mt=newStats2.mtimeMs;if(!at||at<=mt||mt!==prevStats.mtimeMs){this.fsw._emit(EV_CHANGE,file,newStats2)}if(isLinux&&prevStats.ino!==newStats2.ino){this.fsw._closeFile(path24);prevStats=newStats2;this.fsw._addPathCloser(path24,this._watchWithNodeFs(file,listener))}else{prevStats=newStats2}}catch(error3){this.fsw._remove(dirname7,basename3)}}else if(parent.has(basename3)){const at=newStats.atimeMs;const mt=newStats.mtimeMs;if(!at||at<=mt||mt!==prevStats.mtimeMs){this.fsw._emit(EV_CHANGE,file,newStats)}prevStats=newStats}};const closer=this._watchWithNodeFs(file,listener);if(!(initialAdd&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(file)){if(!this.fsw._throttle(EV_ADD,file,0))return;this.fsw._emit(EV_ADD,file,stats)}return closer}async _handleSymlink(entry,directory,path24,item){if(this.fsw.closed){return}const full=entry.fullPath;const dir=this.fsw._getWatchedDir(directory);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let linkPath;try{linkPath=await fsrealpath(path24)}catch(e){this.fsw._emitReady();return true}if(this.fsw.closed)return;if(dir.has(item)){if(this.fsw._symlinkPaths.get(full)!==linkPath){this.fsw._symlinkPaths.set(full,linkPath);this.fsw._emit(EV_CHANGE,path24,entry.stats)}}else{dir.add(item);this.fsw._symlinkPaths.set(full,linkPath);this.fsw._emit(EV_ADD,path24,entry.stats)}this.fsw._emitReady();return true}if(this.fsw._symlinkPaths.has(full)){return true}this.fsw._symlinkPaths.set(full,true)}_handleRead(directory,initialAdd,wh,target,dir,depth,throttler){directory=sysPath.join(directory,EMPTY_STR);if(!wh.hasGlob){throttler=this.fsw._throttle("readdir",directory,1e3);if(!throttler)return}const previous=this.fsw._getWatchedDir(wh.path);const current=new Set;let stream=this.fsw._readdirp(directory,{fileFilter:entry=>wh.filterPath(entry),directoryFilter:entry=>wh.filterDir(entry),depth:0}).on(STR_DATA,async entry=>{if(this.fsw.closed){stream=void 0;return}const item=entry.path;let path24=sysPath.join(directory,item);current.add(item);if(entry.stats.isSymbolicLink()&&await this._handleSymlink(entry,directory,path24,item)){return}if(this.fsw.closed){stream=void 0;return}if(item===target||!target&&!previous.has(item)){this.fsw._incrReadyCount();path24=sysPath.join(dir,sysPath.relative(dir,path24));this._addToNodeFs(path24,initialAdd,wh,depth+1)}}).on(EV_ERROR,this._boundHandleError);return new Promise(resolve7=>stream.once(STR_END,()=>{if(this.fsw.closed){stream=void 0;return}const wasThrottled=throttler?throttler.clear():false;resolve7();previous.getChildren().filter(item=>{return item!==directory&&!current.has(item)&&(!wh.hasGlob||wh.filterPath({fullPath:sysPath.resolve(directory,item)}))}).forEach(item=>{this.fsw._remove(directory,item)});stream=void 0;if(wasThrottled)this._handleRead(directory,false,wh,target,dir,depth,throttler)}))}async _handleDir(dir,stats,initialAdd,depth,target,wh,realpath){const parentDir=this.fsw._getWatchedDir(sysPath.dirname(dir));const tracked=parentDir.has(sysPath.basename(dir));if(!(initialAdd&&this.fsw.options.ignoreInitial)&&!target&&!tracked){if(!wh.hasGlob||wh.globFilter(dir))this.fsw._emit(EV_ADD_DIR,dir,stats)}parentDir.add(sysPath.basename(dir));this.fsw._getWatchedDir(dir);let throttler;let closer;const oDepth=this.fsw.options.depth;if((oDepth==null||depth<=oDepth)&&!this.fsw._symlinkPaths.has(realpath)){if(!target){await this._handleRead(dir,initialAdd,wh,target,dir,depth,throttler);if(this.fsw.closed)return}closer=this._watchWithNodeFs(dir,(dirPath,stats2)=>{if(stats2&&stats2.mtimeMs===0)return;this._handleRead(dirPath,false,wh,target,dir,depth,throttler)})}return closer}async _addToNodeFs(path24,initialAdd,priorWh,depth,target){const ready=this.fsw._emitReady;if(this.fsw._isIgnored(path24)||this.fsw.closed){ready();return false}const wh=this.fsw._getWatchHelpers(path24,depth);if(!wh.hasGlob&&priorWh){wh.hasGlob=priorWh.hasGlob;wh.globFilter=priorWh.globFilter;wh.filterPath=entry=>priorWh.filterPath(entry);wh.filterDir=entry=>priorWh.filterDir(entry)}try{const stats=await statMethods[wh.statMethod](wh.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(wh.watchPath,stats)){ready();return false}const follow=this.fsw.options.followSymlinks&&!path24.includes(STAR)&&!path24.includes(BRACE_START);let closer;if(stats.isDirectory()){const absPath=sysPath.resolve(path24);const targetPath=follow?await fsrealpath(path24):path24;if(this.fsw.closed)return;closer=await this._handleDir(wh.watchPath,stats,initialAdd,depth,target,wh,targetPath);if(this.fsw.closed)return;if(absPath!==targetPath&&targetPath!==void 0){this.fsw._symlinkPaths.set(absPath,targetPath)}}else if(stats.isSymbolicLink()){const targetPath=follow?await fsrealpath(path24):path24;if(this.fsw.closed)return;const parent=sysPath.dirname(wh.watchPath);this.fsw._getWatchedDir(parent).add(wh.watchPath);this.fsw._emit(EV_ADD,wh.watchPath,stats);closer=await this._handleDir(parent,stats,initialAdd,depth,path24,wh,targetPath);if(this.fsw.closed)return;if(targetPath!==void 0){this.fsw._symlinkPaths.set(sysPath.resolve(path24),targetPath)}}else{closer=this._handleFile(wh.watchPath,stats,initialAdd)}ready();this.fsw._addPathCloser(path24,closer);return false}catch(error3){if(this.fsw._handleError(error3)){ready();return path24}}}};module2.exports=NodeFsHandler}});var require_fsevents_handler=__commonJS({"../../node_modules/chokidar/lib/fsevents-handler.js"(exports2,module2){"use strict";var fs23=require("fs");var sysPath=require("path");var{promisify:promisify2}=require("util");var fsevents;try{fsevents=require("fsevents")}catch(error3){if(process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR)console.error(error3)}if(fsevents){const mtch=process.version.match(/v(\d+)\.(\d+)/);if(mtch&&mtch[1]&&mtch[2]){const maj=Number.parseInt(mtch[1],10);const min=Number.parseInt(mtch[2],10);if(maj===8&&min<16){fsevents=void 0}}}var{EV_ADD,EV_CHANGE,EV_ADD_DIR,EV_UNLINK,EV_ERROR,STR_DATA,STR_END,FSEVENT_CREATED,FSEVENT_MODIFIED,FSEVENT_DELETED,FSEVENT_MOVED,FSEVENT_UNKNOWN,FSEVENT_FLAG_MUST_SCAN_SUBDIRS,FSEVENT_TYPE_FILE,FSEVENT_TYPE_DIRECTORY,FSEVENT_TYPE_SYMLINK,ROOT_GLOBSTAR,DIR_SUFFIX,DOT_SLASH,FUNCTION_TYPE,EMPTY_FN,IDENTITY_FN}=require_constants10();var Depth=value=>isNaN(value)?{}:{depth:value};var stat4=promisify2(fs23.stat);var lstat=promisify2(fs23.lstat);var realpath=promisify2(fs23.realpath);var statMethods={stat:stat4,lstat};var FSEventsWatchers=new Map;var consolidateThreshhold=10;var wrongEventFlags=new Set([69888,70400,71424,72704,73472,131328,131840,262912]);var createFSEventsInstance=(path24,callback)=>{const stop=fsevents.watch(path24,callback);return{stop}};function setFSEventsListener(path24,realPath,listener,rawEmitter){let watchPath=sysPath.extname(realPath)?sysPath.dirname(realPath):realPath;const parentPath=sysPath.dirname(watchPath);let cont=FSEventsWatchers.get(watchPath);if(couldConsolidate(parentPath)){watchPath=parentPath}const resolvedPath7=sysPath.resolve(path24);const hasSymlink=resolvedPath7!==realPath;const filteredListener=(fullPath,flags,info2)=>{if(hasSymlink)fullPath=fullPath.replace(realPath,resolvedPath7);if(fullPath===resolvedPath7||!fullPath.indexOf(resolvedPath7+sysPath.sep))listener(fullPath,flags,info2)};let watchedParent=false;for(const watchedPath of FSEventsWatchers.keys()){if(realPath.indexOf(sysPath.resolve(watchedPath)+sysPath.sep)===0){watchPath=watchedPath;cont=FSEventsWatchers.get(watchPath);watchedParent=true;break}}if(cont||watchedParent){cont.listeners.add(filteredListener)}else{cont={listeners:new Set([filteredListener]),rawEmitter,watcher:createFSEventsInstance(watchPath,(fullPath,flags)=>{if(!cont.listeners.size)return;if(flags&FSEVENT_FLAG_MUST_SCAN_SUBDIRS)return;const info2=fsevents.getInfo(fullPath,flags);cont.listeners.forEach(list=>{list(fullPath,flags,info2)});cont.rawEmitter(info2.event,fullPath,info2)})};FSEventsWatchers.set(watchPath,cont)}return()=>{const lst=cont.listeners;lst.delete(filteredListener);if(!lst.size){FSEventsWatchers.delete(watchPath);if(cont.watcher)return cont.watcher.stop().then(()=>{cont.rawEmitter=cont.watcher=void 0;Object.freeze(cont)})}}}var couldConsolidate=path24=>{let count=0;for(const watchPath of FSEventsWatchers.keys()){if(watchPath.indexOf(path24)===0){count++;if(count>=consolidateThreshhold){return true}}}return false};var canUse=()=>fsevents&&FSEventsWatchers.size<128;var calcDepth=(path24,root)=>{let i=0;while(!path24.indexOf(root)&&(path24=sysPath.dirname(path24))!==root)i++;return i};var sameTypes=(info2,stats)=>info2.type===FSEVENT_TYPE_DIRECTORY&&stats.isDirectory()||info2.type===FSEVENT_TYPE_SYMLINK&&stats.isSymbolicLink()||info2.type===FSEVENT_TYPE_FILE&&stats.isFile();var FsEventsHandler=class{constructor(fsw){this.fsw=fsw}checkIgnored(path24,stats){const ipaths=this.fsw._ignoredPaths;if(this.fsw._isIgnored(path24,stats)){ipaths.add(path24);if(stats&&stats.isDirectory()){ipaths.add(path24+ROOT_GLOBSTAR)}return true}ipaths.delete(path24);ipaths.delete(path24+ROOT_GLOBSTAR)}addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts){const event=watchedDir.has(item)?EV_CHANGE:EV_ADD;this.handleEvent(event,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}async checkExists(path24,fullPath,realPath,parent,watchedDir,item,info2,opts){try{const stats=await stat4(path24);if(this.fsw.closed)return;if(sameTypes(info2,stats)){this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}else{this.handleEvent(EV_UNLINK,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}catch(error3){if(error3.code==="EACCES"){this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}else{this.handleEvent(EV_UNLINK,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}}handleEvent(event,path24,fullPath,realPath,parent,watchedDir,item,info2,opts){if(this.fsw.closed||this.checkIgnored(path24))return;if(event===EV_UNLINK){const isDirectory=info2.type===FSEVENT_TYPE_DIRECTORY;if(isDirectory||watchedDir.has(item)){this.fsw._remove(parent,item,isDirectory)}}else{if(event===EV_ADD){if(info2.type===FSEVENT_TYPE_DIRECTORY)this.fsw._getWatchedDir(path24);if(info2.type===FSEVENT_TYPE_SYMLINK&&opts.followSymlinks){const curDepth=opts.depth===void 0?void 0:calcDepth(fullPath,realPath)+1;return this._addToFsEvents(path24,false,true,curDepth)}this.fsw._getWatchedDir(parent).add(item)}const eventName=info2.type===FSEVENT_TYPE_DIRECTORY?event+DIR_SUFFIX:event;this.fsw._emit(eventName,path24);if(eventName===EV_ADD_DIR)this._addToFsEvents(path24,false,true)}}_watchWithFsEvents(watchPath,realPath,transform,globFilter){if(this.fsw.closed||this.fsw._isIgnored(watchPath))return;const opts=this.fsw.options;const watchCallback=async(fullPath,flags,info2)=>{if(this.fsw.closed)return;if(opts.depth!==void 0&&calcDepth(fullPath,realPath)>opts.depth)return;const path24=transform(sysPath.join(watchPath,sysPath.relative(watchPath,fullPath)));if(globFilter&&!globFilter(path24))return;const parent=sysPath.dirname(path24);const item=sysPath.basename(path24);const watchedDir=this.fsw._getWatchedDir(info2.type===FSEVENT_TYPE_DIRECTORY?path24:parent);if(wrongEventFlags.has(flags)||info2.event===FSEVENT_UNKNOWN){if(typeof opts.ignored===FUNCTION_TYPE){let stats;try{stats=await stat4(path24)}catch(error3){}if(this.fsw.closed)return;if(this.checkIgnored(path24,stats))return;if(sameTypes(info2,stats)){this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}else{this.handleEvent(EV_UNLINK,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}else{this.checkExists(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}else{switch(info2.event){case FSEVENT_CREATED:case FSEVENT_MODIFIED:return this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts);case FSEVENT_DELETED:case FSEVENT_MOVED:return this.checkExists(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}};const closer=setFSEventsListener(watchPath,realPath,watchCallback,this.fsw._emitRaw);this.fsw._emitReady();return closer}async _handleFsEventsSymlink(linkPath,fullPath,transform,curDepth){if(this.fsw.closed||this.fsw._symlinkPaths.has(fullPath))return;this.fsw._symlinkPaths.set(fullPath,true);this.fsw._incrReadyCount();try{const linkTarget=await realpath(linkPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(linkTarget)){return this.fsw._emitReady()}this.fsw._incrReadyCount();this._addToFsEvents(linkTarget||linkPath,path24=>{let aliasedPath=linkPath;if(linkTarget&&linkTarget!==DOT_SLASH){aliasedPath=path24.replace(linkTarget,linkPath)}else if(path24!==DOT_SLASH){aliasedPath=sysPath.join(linkPath,path24)}return transform(aliasedPath)},false,curDepth)}catch(error3){if(this.fsw._handleError(error3)){return this.fsw._emitReady()}}}emitAdd(newPath,stats,processPath,opts,forceAdd){const pp=processPath(newPath);const isDir=stats.isDirectory();const dirObj=this.fsw._getWatchedDir(sysPath.dirname(pp));const base=sysPath.basename(pp);if(isDir)this.fsw._getWatchedDir(pp);if(dirObj.has(base))return;dirObj.add(base);if(!opts.ignoreInitial||forceAdd===true){this.fsw._emit(isDir?EV_ADD_DIR:EV_ADD,pp,stats)}}initWatch(realPath,path24,wh,processPath){if(this.fsw.closed)return;const closer=this._watchWithFsEvents(wh.watchPath,sysPath.resolve(realPath||wh.watchPath),processPath,wh.globFilter);this.fsw._addPathCloser(path24,closer)}async _addToFsEvents(path24,transform,forceAdd,priorDepth){if(this.fsw.closed){return}const opts=this.fsw.options;const processPath=typeof transform===FUNCTION_TYPE?transform:IDENTITY_FN;const wh=this.fsw._getWatchHelpers(path24);try{const stats=await statMethods[wh.statMethod](wh.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(wh.watchPath,stats)){throw null}if(stats.isDirectory()){if(!wh.globFilter)this.emitAdd(processPath(path24),stats,processPath,opts,forceAdd);if(priorDepth&&priorDepth>opts.depth)return;this.fsw._readdirp(wh.watchPath,{fileFilter:entry=>wh.filterPath(entry),directoryFilter:entry=>wh.filterDir(entry),...Depth(opts.depth-(priorDepth||0))}).on(STR_DATA,entry=>{if(this.fsw.closed){return}if(entry.stats.isDirectory()&&!wh.filterPath(entry))return;const joinedPath=sysPath.join(wh.watchPath,entry.path);const{fullPath}=entry;if(wh.followSymlinks&&entry.stats.isSymbolicLink()){const curDepth=opts.depth===void 0?void 0:calcDepth(joinedPath,sysPath.resolve(wh.watchPath))+1;this._handleFsEventsSymlink(joinedPath,fullPath,processPath,curDepth)}else{this.emitAdd(joinedPath,entry.stats,processPath,opts,forceAdd)}}).on(EV_ERROR,EMPTY_FN).on(STR_END,()=>{this.fsw._emitReady()})}else{this.emitAdd(wh.watchPath,stats,processPath,opts,forceAdd);this.fsw._emitReady()}}catch(error3){if(!error3||this.fsw._handleError(error3)){this.fsw._emitReady();this.fsw._emitReady()}}if(opts.persistent&&forceAdd!==true){if(typeof transform===FUNCTION_TYPE){this.initWatch(void 0,path24,wh,processPath)}else{let realPath;try{realPath=await realpath(wh.watchPath)}catch(e){}this.initWatch(realPath,path24,wh,processPath)}}}};module2.exports=FsEventsHandler;module2.exports.canUse=canUse}});var require_chokidar=__commonJS({"../../node_modules/chokidar/index.js"(exports2){"use strict";var{EventEmitter}=require("events");var fs23=require("fs");var sysPath=require("path");var{promisify:promisify2}=require("util");var readdirp=require_readdirp();var anymatch=require_anymatch().default;var globParent=require_glob_parent();var isGlob=require_is_glob();var braces=require_braces();var normalizePath=require_normalize_path();var NodeFsHandler=require_nodefs_handler();var FsEventsHandler=require_fsevents_handler();var{EV_ALL,EV_READY,EV_ADD,EV_CHANGE,EV_UNLINK,EV_ADD_DIR,EV_UNLINK_DIR,EV_RAW,EV_ERROR,STR_CLOSE,STR_END,BACK_SLASH_RE,DOUBLE_SLASH_RE,SLASH_OR_BACK_SLASH_RE,DOT_RE,REPLACER_RE,SLASH,SLASH_SLASH,BRACE_START,BANG,ONE_DOT,TWO_DOTS,GLOBSTAR:GLOBSTAR2,SLASH_GLOBSTAR,ANYMATCH_OPTS,STRING_TYPE,FUNCTION_TYPE,EMPTY_STR,EMPTY_FN,isWindows,isMacos,isIBMi}=require_constants10();var stat4=promisify2(fs23.stat);var readdir2=promisify2(fs23.readdir);var arrify=(value=[])=>Array.isArray(value)?value:[value];var flatten2=(list,result=[])=>{list.forEach(item=>{if(Array.isArray(item)){flatten2(item,result)}else{result.push(item)}});return result};var unifyPaths=paths_=>{const paths=flatten2(arrify(paths_));if(!paths.every(p=>typeof p===STRING_TYPE)){throw new TypeError(`Non-string provided as watch path: ${paths}`)}return paths.map(normalizePathToUnix)};var toUnix=string=>{let str=string.replace(BACK_SLASH_RE,SLASH);let prepend=false;if(str.startsWith(SLASH_SLASH)){prepend=true}while(str.match(DOUBLE_SLASH_RE)){str=str.replace(DOUBLE_SLASH_RE,SLASH)}if(prepend){str=SLASH+str}return str};var normalizePathToUnix=path24=>toUnix(sysPath.normalize(toUnix(path24)));var normalizeIgnored=(cwd=EMPTY_STR)=>path24=>{if(typeof path24!==STRING_TYPE)return path24;return normalizePathToUnix(sysPath.isAbsolute(path24)?path24:sysPath.join(cwd,path24))};var getAbsolutePath=(path24,cwd)=>{if(sysPath.isAbsolute(path24)){return path24}if(path24.startsWith(BANG)){return BANG+sysPath.join(cwd,path24.slice(1))}return sysPath.join(cwd,path24)};var undef=(opts,key)=>opts[key]===void 0;var DirEntry=class{constructor(dir,removeWatcher){this.path=dir;this._removeWatcher=removeWatcher;this.items=new Set}add(item){const{items}=this;if(!items)return;if(item!==ONE_DOT&&item!==TWO_DOTS)items.add(item)}async remove(item){const{items}=this;if(!items)return;items.delete(item);if(items.size>0)return;const dir=this.path;try{await readdir2(dir)}catch(err){if(this._removeWatcher){this._removeWatcher(sysPath.dirname(dir),sysPath.basename(dir))}}}has(item){const{items}=this;if(!items)return;return items.has(item)}getChildren(){const{items}=this;if(!items)return;return[...items.values()]}dispose(){this.items.clear();delete this.path;delete this._removeWatcher;delete this.items;Object.freeze(this)}};var STAT_METHOD_F="stat";var STAT_METHOD_L="lstat";var WatchHelper=class{constructor(path24,watchPath,follow,fsw){this.fsw=fsw;this.path=path24=path24.replace(REPLACER_RE,EMPTY_STR);this.watchPath=watchPath;this.fullWatchPath=sysPath.resolve(watchPath);this.hasGlob=watchPath!==path24;if(path24===EMPTY_STR)this.hasGlob=false;this.globSymlink=this.hasGlob&&follow?void 0:false;this.globFilter=this.hasGlob?anymatch(path24,void 0,ANYMATCH_OPTS):false;this.dirParts=this.getDirParts(path24);this.dirParts.forEach(parts=>{if(parts.length>1)parts.pop()});this.followSymlinks=follow;this.statMethod=follow?STAT_METHOD_F:STAT_METHOD_L}checkGlobSymlink(entry){if(this.globSymlink===void 0){this.globSymlink=entry.fullParentDir===this.fullWatchPath?false:{realPath:entry.fullParentDir,linkPath:this.fullWatchPath}}if(this.globSymlink){return entry.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath)}return entry.fullPath}entryPath(entry){return sysPath.join(this.watchPath,sysPath.relative(this.watchPath,this.checkGlobSymlink(entry)))}filterPath(entry){const{stats}=entry;if(stats&&stats.isSymbolicLink())return this.filterDir(entry);const resolvedPath7=this.entryPath(entry);const matchesGlob=this.hasGlob&&typeof this.globFilter===FUNCTION_TYPE?this.globFilter(resolvedPath7):true;return matchesGlob&&this.fsw._isntIgnored(resolvedPath7,stats)&&this.fsw._hasReadPermissions(stats)}getDirParts(path24){if(!this.hasGlob)return[];const parts=[];const expandedPath=path24.includes(BRACE_START)?braces.expand(path24):[path24];expandedPath.forEach(path25=>{parts.push(sysPath.relative(this.watchPath,path25).split(SLASH_OR_BACK_SLASH_RE))});return parts}filterDir(entry){if(this.hasGlob){const entryParts=this.getDirParts(this.checkGlobSymlink(entry));let globstar=false;this.unmatchedGlob=!this.dirParts.some(parts=>{return parts.every((part,i)=>{if(part===GLOBSTAR2)globstar=true;return globstar||!entryParts[0][i]||anymatch(part,entryParts[0][i],ANYMATCH_OPTS)})})}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(entry),entry.stats)}};var FSWatcher=class extends EventEmitter{constructor(_opts){super();const opts={};if(_opts)Object.assign(opts,_opts);this._watched=new Map;this._closers=new Map;this._ignoredPaths=new Set;this._throttled=new Map;this._symlinkPaths=new Map;this._streams=new Set;this.closed=false;if(undef(opts,"persistent"))opts.persistent=true;if(undef(opts,"ignoreInitial"))opts.ignoreInitial=false;if(undef(opts,"ignorePermissionErrors"))opts.ignorePermissionErrors=false;if(undef(opts,"interval"))opts.interval=100;if(undef(opts,"binaryInterval"))opts.binaryInterval=300;if(undef(opts,"disableGlobbing"))opts.disableGlobbing=false;opts.enableBinaryInterval=opts.binaryInterval!==opts.interval;if(undef(opts,"useFsEvents"))opts.useFsEvents=!opts.usePolling;const canUseFsEvents=FsEventsHandler.canUse();if(!canUseFsEvents)opts.useFsEvents=false;if(undef(opts,"usePolling")&&!opts.useFsEvents){opts.usePolling=isMacos}if(isIBMi){opts.usePolling=true}const envPoll=process.env.CHOKIDAR_USEPOLLING;if(envPoll!==void 0){const envLower=envPoll.toLowerCase();if(envLower==="false"||envLower==="0"){opts.usePolling=false}else if(envLower==="true"||envLower==="1"){opts.usePolling=true}else{opts.usePolling=!!envLower}}const envInterval=process.env.CHOKIDAR_INTERVAL;if(envInterval){opts.interval=Number.parseInt(envInterval,10)}if(undef(opts,"atomic"))opts.atomic=!opts.usePolling&&!opts.useFsEvents;if(opts.atomic)this._pendingUnlinks=new Map;if(undef(opts,"followSymlinks"))opts.followSymlinks=true;if(undef(opts,"awaitWriteFinish"))opts.awaitWriteFinish=false;if(opts.awaitWriteFinish===true)opts.awaitWriteFinish={};const awf=opts.awaitWriteFinish;if(awf){if(!awf.stabilityThreshold)awf.stabilityThreshold=2e3;if(!awf.pollInterval)awf.pollInterval=100;this._pendingWrites=new Map}if(opts.ignored)opts.ignored=arrify(opts.ignored);let readyCalls=0;this._emitReady=()=>{readyCalls++;if(readyCalls>=this._readyCount){this._emitReady=EMPTY_FN;this._readyEmitted=true;process.nextTick(()=>this.emit(EV_READY))}};this._emitRaw=(...args)=>this.emit(EV_RAW,...args);this._readyEmitted=false;this.options=opts;if(opts.useFsEvents){this._fsEventsHandler=new FsEventsHandler(this)}else{this._nodeFsHandler=new NodeFsHandler(this)}Object.freeze(opts)}add(paths_,_origAdd,_internal){const{cwd,disableGlobbing}=this.options;this.closed=false;let paths=unifyPaths(paths_);if(cwd){paths=paths.map(path24=>{const absPath=getAbsolutePath(path24,cwd);if(disableGlobbing||!isGlob(path24)){return absPath}return normalizePath(absPath)})}paths=paths.filter(path24=>{if(path24.startsWith(BANG)){this._ignoredPaths.add(path24.slice(1));return false}this._ignoredPaths.delete(path24);this._ignoredPaths.delete(path24+SLASH_GLOBSTAR);this._userIgnored=void 0;return true});if(this.options.useFsEvents&&this._fsEventsHandler){if(!this._readyCount)this._readyCount=paths.length;if(this.options.persistent)this._readyCount+=paths.length;paths.forEach(path24=>this._fsEventsHandler._addToFsEvents(path24))}else{if(!this._readyCount)this._readyCount=0;this._readyCount+=paths.length;Promise.all(paths.map(async path24=>{const res=await this._nodeFsHandler._addToNodeFs(path24,!_internal,0,0,_origAdd);if(res)this._emitReady();return res})).then(results=>{if(this.closed)return;results.filter(item=>item).forEach(item=>{this.add(sysPath.dirname(item),sysPath.basename(_origAdd||item))})})}return this}unwatch(paths_){if(this.closed)return this;const paths=unifyPaths(paths_);const{cwd}=this.options;paths.forEach(path24=>{if(!sysPath.isAbsolute(path24)&&!this._closers.has(path24)){if(cwd)path24=sysPath.join(cwd,path24);path24=sysPath.resolve(path24)}this._closePath(path24);this._ignoredPaths.add(path24);if(this._watched.has(path24)){this._ignoredPaths.add(path24+SLASH_GLOBSTAR)}this._userIgnored=void 0});return this}close(){if(this.closed)return this._closePromise;this.closed=true;this.removeAllListeners();const closers=[];this._closers.forEach(closerList=>closerList.forEach(closer=>{const promise=closer();if(promise instanceof Promise)closers.push(promise)}));this._streams.forEach(stream=>stream.destroy());this._userIgnored=void 0;this._readyCount=0;this._readyEmitted=false;this._watched.forEach(dirent=>dirent.dispose());["closers","watched","streams","symlinkPaths","throttled"].forEach(key=>{this[`_${key}`].clear()});this._closePromise=closers.length?Promise.all(closers).then(()=>void 0):Promise.resolve();return this._closePromise}getWatched(){const watchList={};this._watched.forEach((entry,dir)=>{const key=this.options.cwd?sysPath.relative(this.options.cwd,dir):dir;watchList[key||ONE_DOT]=entry.getChildren().sort()});return watchList}emitWithAll(event,args){this.emit(...args);if(event!==EV_ERROR)this.emit(EV_ALL,...args)}async _emit(event,path24,val1,val2,val3){if(this.closed)return;const opts=this.options;if(isWindows)path24=sysPath.normalize(path24);if(opts.cwd)path24=sysPath.relative(opts.cwd,path24);const args=[event,path24];if(val3!==void 0)args.push(val1,val2,val3);else if(val2!==void 0)args.push(val1,val2);else if(val1!==void 0)args.push(val1);const awf=opts.awaitWriteFinish;let pw;if(awf&&(pw=this._pendingWrites.get(path24))){pw.lastChange=new Date;return this}if(opts.atomic){if(event===EV_UNLINK){this._pendingUnlinks.set(path24,args);setTimeout(()=>{this._pendingUnlinks.forEach((entry,path25)=>{this.emit(...entry);this.emit(EV_ALL,...entry);this._pendingUnlinks.delete(path25)})},typeof opts.atomic==="number"?opts.atomic:100);return this}if(event===EV_ADD&&this._pendingUnlinks.has(path24)){event=args[0]=EV_CHANGE;this._pendingUnlinks.delete(path24)}}if(awf&&(event===EV_ADD||event===EV_CHANGE)&&this._readyEmitted){const awfEmit=(err,stats)=>{if(err){event=args[0]=EV_ERROR;args[1]=err;this.emitWithAll(event,args)}else if(stats){if(args.length>2){args[2]=stats}else{args.push(stats)}this.emitWithAll(event,args)}};this._awaitWriteFinish(path24,awf.stabilityThreshold,event,awfEmit);return this}if(event===EV_CHANGE){const isThrottled=!this._throttle(EV_CHANGE,path24,50);if(isThrottled)return this}if(opts.alwaysStat&&val1===void 0&&(event===EV_ADD||event===EV_ADD_DIR||event===EV_CHANGE)){const fullPath=opts.cwd?sysPath.join(opts.cwd,path24):path24;let stats;try{stats=await stat4(fullPath)}catch(err){}if(!stats||this.closed)return;args.push(stats)}this.emitWithAll(event,args);return this}_handleError(error3){const code=error3&&error3.code;if(error3&&code!=="ENOENT"&&code!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||code!=="EPERM"&&code!=="EACCES")){this.emit(EV_ERROR,error3)}return error3||this.closed}_throttle(actionType,path24,timeout){if(!this._throttled.has(actionType)){this._throttled.set(actionType,new Map)}const action=this._throttled.get(actionType);const actionPath=action.get(path24);if(actionPath){actionPath.count++;return false}let timeoutObject;const clear=()=>{const item=action.get(path24);const count=item?item.count:0;action.delete(path24);clearTimeout(timeoutObject);if(item)clearTimeout(item.timeoutObject);return count};timeoutObject=setTimeout(clear,timeout);const thr={timeoutObject,clear,count:0};action.set(path24,thr);return thr}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(path24,threshold,event,awfEmit){let timeoutHandler;let fullPath=path24;if(this.options.cwd&&!sysPath.isAbsolute(path24)){fullPath=sysPath.join(this.options.cwd,path24)}const now=new Date;const awaitWriteFinish=prevStat=>{fs23.stat(fullPath,(err,curStat)=>{if(err||!this._pendingWrites.has(path24)){if(err&&err.code!=="ENOENT")awfEmit(err);return}const now2=Number(new Date);if(prevStat&&curStat.size!==prevStat.size){this._pendingWrites.get(path24).lastChange=now2}const pw=this._pendingWrites.get(path24);const df=now2-pw.lastChange;if(df>=threshold){this._pendingWrites.delete(path24);awfEmit(void 0,curStat)}else{timeoutHandler=setTimeout(awaitWriteFinish,this.options.awaitWriteFinish.pollInterval,curStat)}})};if(!this._pendingWrites.has(path24)){this._pendingWrites.set(path24,{lastChange:now,cancelWait:()=>{this._pendingWrites.delete(path24);clearTimeout(timeoutHandler);return event}});timeoutHandler=setTimeout(awaitWriteFinish,this.options.awaitWriteFinish.pollInterval)}}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(path24,stats){if(this.options.atomic&&DOT_RE.test(path24))return true;if(!this._userIgnored){const{cwd}=this.options;const ign=this.options.ignored;const ignored=ign&&ign.map(normalizeIgnored(cwd));const paths=arrify(ignored).filter(path25=>typeof path25===STRING_TYPE&&!isGlob(path25)).map(path25=>path25+SLASH_GLOBSTAR);const list=this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored,paths);this._userIgnored=anymatch(list,void 0,ANYMATCH_OPTS)}return this._userIgnored([path24,stats])}_isntIgnored(path24,stat5){return!this._isIgnored(path24,stat5)}_getWatchHelpers(path24,depth){const watchPath=depth||this.options.disableGlobbing||!isGlob(path24)?path24:globParent(path24);const follow=this.options.followSymlinks;return new WatchHelper(path24,watchPath,follow,this)}_getWatchedDir(directory){if(!this._boundRemove)this._boundRemove=this._remove.bind(this);const dir=sysPath.resolve(directory);if(!this._watched.has(dir))this._watched.set(dir,new DirEntry(dir,this._boundRemove));return this._watched.get(dir)}_hasReadPermissions(stats){if(this.options.ignorePermissionErrors)return true;const md=stats&&Number.parseInt(stats.mode,10);const st=md&511;const it=Number.parseInt(st.toString(8)[0],10);return Boolean(4&it)}_remove(directory,item,isDirectory){const path24=sysPath.join(directory,item);const fullPath=sysPath.resolve(path24);isDirectory=isDirectory!=null?isDirectory:this._watched.has(path24)||this._watched.has(fullPath);if(!this._throttle("remove",path24,100))return;if(!isDirectory&&!this.options.useFsEvents&&this._watched.size===1){this.add(directory,item,true)}const wp=this._getWatchedDir(path24);const nestedDirectoryChildren=wp.getChildren();nestedDirectoryChildren.forEach(nested=>this._remove(path24,nested));const parent=this._getWatchedDir(directory);const wasTracked=parent.has(item);parent.remove(item);if(this._symlinkPaths.has(fullPath)){this._symlinkPaths.delete(fullPath)}let relPath=path24;if(this.options.cwd)relPath=sysPath.relative(this.options.cwd,path24);if(this.options.awaitWriteFinish&&this._pendingWrites.has(relPath)){const event=this._pendingWrites.get(relPath).cancelWait();if(event===EV_ADD)return}this._watched.delete(path24);this._watched.delete(fullPath);const eventName=isDirectory?EV_UNLINK_DIR:EV_UNLINK;if(wasTracked&&!this._isIgnored(path24))this._emit(eventName,path24);if(!this.options.useFsEvents){this._closePath(path24)}}_closePath(path24){this._closeFile(path24);const dir=sysPath.dirname(path24);this._getWatchedDir(dir).remove(sysPath.basename(path24))}_closeFile(path24){const closers=this._closers.get(path24);if(!closers)return;closers.forEach(closer=>closer());this._closers.delete(path24)}_addPathCloser(path24,closer){if(!closer)return;let list=this._closers.get(path24);if(!list){list=[];this._closers.set(path24,list)}list.push(closer)}_readdirp(root,opts){if(this.closed)return;const options={type:EV_ALL,alwaysStat:true,lstat:true,...opts};let stream=readdirp(root,options);this._streams.add(stream);stream.once(STR_CLOSE,()=>{stream=void 0});stream.once(STR_END,()=>{if(stream){this._streams.delete(stream);stream=void 0}});return stream}};exports2.FSWatcher=FSWatcher;var watch2=(paths,options)=>{const watcher=new FSWatcher(options);watcher.add(paths);return watcher};exports2.watch=watch2}});async function findCloudWatchLogGroups(sdkProvider,stackArtifact){let sdk;const resolvedEnv=await sdkProvider.resolveEnvironment(stackArtifact.environment);try{sdk=(await new EnvironmentAccess(sdkProvider,DEFAULT_TOOLKIT_STACK_NAME).accessStackForLookup(stackArtifact)).sdk}catch(e){debug(`Failed to access SDK environment: ${e.message}`);sdk=(await sdkProvider.forEnvironment(resolvedEnv,0)).sdk}const listStackResources=new LazyListStackResources(sdk,stackArtifact.stackName);const evaluateCfnTemplate=new EvaluateCloudFormationTemplate({stackName:stackArtifact.stackName,template:stackArtifact.template,parameters:{},account:resolvedEnv.account,region:resolvedEnv.region,partition:(await sdk.currentAccount()).partition,sdk});const stackResources=await listStackResources.listStackResources();const logGroupNames=findAllLogGroupNames(stackResources,evaluateCfnTemplate);return{env:resolvedEnv,sdk,logGroupNames}}function isReferencedFromIgnoredResource(logGroupResource,evaluateCfnTemplate){const resourcesReferencingLogGroup=evaluateCfnTemplate.findReferencesTo(logGroupResource.LogicalResourceId);return resourcesReferencingLogGroup.some(reference=>{return IGNORE_LOGS_RESOURCE_TYPES.includes(reference.Type)})}function findAllLogGroupNames(stackResources,evaluateCfnTemplate){const logGroupNames=[];for(const resource of stackResources){const logGroupResolver=cloudWatchLogsResolvers[resource.ResourceType];if(logGroupResolver){const logGroupName=logGroupResolver(resource,evaluateCfnTemplate);if(logGroupName){logGroupNames.push(logGroupName)}}}return logGroupNames}var IGNORE_LOGS_RESOURCE_TYPES,cloudWatchLogsResolvers;var init_find_cloudwatch_logs=__esm({"lib/api/logs/find-cloudwatch-logs.ts"(){"use strict";init_logging();init_environment_access();init_evaluate_cloudformation_template();init_mode();init_toolkit_info();IGNORE_LOGS_RESOURCE_TYPES=["AWS::EC2::FlowLog","AWS::CloudTrail::Trail","AWS::CodeBuild::Project"];cloudWatchLogsResolvers={"AWS::Logs::LogGroup":(resource,evaluateCfnTemplate)=>{var _a;if(isReferencedFromIgnoredResource(resource,evaluateCfnTemplate)){return void 0}return(_a=resource.PhysicalResourceId)==null?void 0:_a.toString()},"AWS::Lambda::Function":(resource,evaluateCfnTemplate)=>{const loggingConfig=evaluateCfnTemplate.getResourceProperty(resource.LogicalResourceId,"LoggingConfig");if(loggingConfig==null?void 0:loggingConfig.LogGroup){if(typeof loggingConfig.LogGroup==="string"){return loggingConfig.LogGroup}if(typeof loggingConfig.LogGroup==="object"){if(loggingConfig.LogGroup.Ref){return evaluateCfnTemplate.getResourceProperty(loggingConfig.LogGroup.Ref,"LogGroupName")}}}return`/aws/lambda/${resource.PhysicalResourceId}`}}}});var util3,chalk18,SLEEP,CloudWatchLogEventMonitor;var init_logs_monitor=__esm({"lib/api/logs/logs-monitor.ts"(){"use strict";util3=__toESM(require("util"));chalk18=__toESM(require_source());init_logging();init_arrays();SLEEP=2e3;CloudWatchLogEventMonitor=class{constructor(startTime){this.envsLogGroupsAccessSettings=new Map;this.active=false;this.startTime=(startTime==null?void 0:startTime.getTime())??Date.now()}activate(){this.active=true;this.scheduleNextTick(0)}deactivate(){this.active=false;this.startTime=Date.now();this.envsLogGroupsAccessSettings.clear()}addLogGroups(env2,sdk,logGroupNames){var _a;const awsEnv=`${env2.account}:${env2.region}`;const logGroupsStartTimes=logGroupNames.reduce((acc,groupName)=>{acc[groupName]=this.startTime;return acc},{});this.envsLogGroupsAccessSettings.set(awsEnv,{sdk,logGroupsStartTimes:{...(_a=this.envsLogGroupsAccessSettings.get(awsEnv))==null?void 0:_a.logGroupsStartTimes,...logGroupsStartTimes}})}scheduleNextTick(sleep3){setTimeout(()=>void this.tick(),sleep3)}async tick(){if(!this.active){return}try{const events=flatten(await this.readNewEvents());events.forEach(event=>{this.print(event)})}catch(e){error("Error occurred while monitoring logs: %s",e)}this.scheduleNextTick(SLEEP)}async readNewEvents(){const promises=[];for(const settings of this.envsLogGroupsAccessSettings.values()){for(const group of Object.keys(settings.logGroupsStartTimes)){promises.push(this.readEventsFromLogGroup(settings,group))}}return Promise.all(promises)}print(event){print(util3.format("[%s] %s %s",chalk18.blue(event.logGroupName),chalk18.yellow(event.timestamp.toLocaleTimeString()),event.message.trim()))}async readEventsFromLogGroup(logGroupsAccessSettings,logGroupName){const events=[];const startTime=logGroupsAccessSettings.logGroupsStartTimes[logGroupName]??this.startTime;let endTime=startTime;try{const response=await logGroupsAccessSettings.sdk.cloudWatchLogs().filterLogEvents({logGroupName,limit:100,startTime});const filteredEvents=response.events??[];for(const event of filteredEvents){if(event.message){events.push({message:event.message,logGroupName,timestamp:event.timestamp?new Date(event.timestamp):new Date});if(event.timestamp&&endTime<event.timestamp){endTime=event.timestamp}}}if(filteredEvents.length===100&&response.nextToken){events.push({message:">>> `watch` shows only the first 100 log messages - the rest have been truncated...",logGroupName,timestamp:new Date(endTime)})}}catch(e){if(e.name==="ResourceNotFoundException"){return[]}throw e}logGroupsAccessSettings.logGroupsStartTimes[logGroupName]=endTime+1;return events}}}});var require_cdk_from_cfn=__commonJS({"../../node_modules/cdk-from-cfn/index.js"(exports2,module2){var imports={};imports["__wbindgen_placeholder__"]=module2.exports;var wasm;var{TextDecoder:TextDecoder2,TextEncoder}=require("util");var cachedTextDecoder=new TextDecoder2("utf-8",{ignoreBOM:true,fatal:true});cachedTextDecoder.decode();var cachedUint8Memory0=null;function getUint8Memory0(){if(cachedUint8Memory0===null||cachedUint8Memory0.byteLength===0){cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)}return cachedUint8Memory0}function getStringFromWasm0(ptr,len){ptr=ptr>>>0;return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr,ptr+len))}var heap=new Array(128).fill(void 0);heap.push(void 0,null,true,false);var heap_next=heap.length;function addHeapObject(obj){if(heap_next===heap.length)heap.push(heap.length+1);const idx=heap_next;heap_next=heap[idx];heap[idx]=obj;return idx}var cachedInt32Memory0=null;function getInt32Memory0(){if(cachedInt32Memory0===null||cachedInt32Memory0.byteLength===0){cachedInt32Memory0=new Int32Array(wasm.memory.buffer)}return cachedInt32Memory0}var cachedUint32Memory0=null;function getUint32Memory0(){if(cachedUint32Memory0===null||cachedUint32Memory0.byteLength===0){cachedUint32Memory0=new Uint32Array(wasm.memory.buffer)}return cachedUint32Memory0}function getObject(idx){return heap[idx]}function dropObject(idx){if(idx<132)return;heap[idx]=heap_next;heap_next=idx}function takeObject(idx){const ret=getObject(idx);dropObject(idx);return ret}function getArrayJsValueFromWasm0(ptr,len){ptr=ptr>>>0;const mem=getUint32Memory0();const slice=mem.subarray(ptr/4,ptr/4+len);const result=[];for(let i=0;i<slice.length;i++){result.push(takeObject(slice[i]))}return result}module2.exports.supported_languages=function(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.supported_languages(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var v110=getArrayJsValueFromWasm0(r0,r1).slice();wasm.__wbindgen_free(r0,r1*4,4);return v110}finally{wasm.__wbindgen_add_to_stack_pointer(16)}};var WASM_VECTOR_LEN=0;var cachedTextEncoder=new TextEncoder("utf-8");var encodeString=typeof cachedTextEncoder.encodeInto==="function"?function(arg,view){return cachedTextEncoder.encodeInto(arg,view)}:function(arg,view){const buf=cachedTextEncoder.encode(arg);view.set(buf);return{read:arg.length,written:buf.length}};function passStringToWasm0(arg,malloc,realloc){if(realloc===void 0){const buf=cachedTextEncoder.encode(arg);const ptr2=malloc(buf.length,1)>>>0;getUint8Memory0().subarray(ptr2,ptr2+buf.length).set(buf);WASM_VECTOR_LEN=buf.length;return ptr2}let len=arg.length;let ptr=malloc(len,1)>>>0;const mem=getUint8Memory0();let offset=0;for(;offset<len;offset++){const code=arg.charCodeAt(offset);if(code>127)break;mem[ptr+offset]=code}if(offset!==len){if(offset!==0){arg=arg.slice(offset)}ptr=realloc(ptr,len,len=offset+arg.length*3,1)>>>0;const view=getUint8Memory0().subarray(ptr+offset,ptr+len);const ret=encodeString(arg,view);offset+=ret.written;ptr=realloc(ptr,len,offset,1)>>>0}WASM_VECTOR_LEN=offset;return ptr}module2.exports.transmute=function(template,language,stack_name){let deferred5_0;let deferred5_1;try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);const ptr0=passStringToWasm0(template,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;const ptr1=passStringToWasm0(language,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;const ptr2=passStringToWasm0(stack_name,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len2=WASM_VECTOR_LEN;wasm.transmute(retptr,ptr0,len0,ptr1,len1,ptr2,len2);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];var r3=getInt32Memory0()[retptr/4+3];var ptr4=r0;var len4=r1;if(r3){ptr4=0;len4=0;throw takeObject(r2)}deferred5_0=ptr4;deferred5_1=len4;return getStringFromWasm0(ptr4,len4)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(deferred5_0,deferred5_1,1)}};module2.exports.__wbindgen_error_new=function(arg0,arg1){const ret=new Error(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)};module2.exports.__wbindgen_string_new=function(arg0,arg1){const ret=getStringFromWasm0(arg0,arg1);return addHeapObject(ret)};var path24=require("path").join(__dirname,"index_bg.wasm");var bytes=require("fs").readFileSync(path24);var wasmModule=new WebAssembly.Module(bytes);var wasmInstance=new WebAssembly.Instance(wasmModule,imports);wasm=wasmInstance.exports;module2.exports.__wasm=wasm}});async function shell(command){const commandLine=renderCommandLine(command);debug(`Executing ${chalk19.blue(commandLine)}`);const child=child_process.spawn(command[0],renderArguments(command.slice(1)),{shell:true,stdio:["ignore","pipe","inherit"]});return new Promise((resolve7,reject)=>{const stdout2=new Array;child.stdout.on("data",chunk=>{process.stdout.write(chunk);stdout2.push(chunk)});child.once("error",reject);child.once("exit",code=>{if(code===0){resolve7(Buffer.from(stdout2).toString("utf-8"))}else{reject(new ToolkitError(`${commandLine} exited with error code ${code}`))}})})}function renderCommandLine(cmd){return renderArguments(cmd).join(" ")}function renderArguments(cmd){if(process.platform!=="win32"){return doRender(cmd,hasAnyChars(" ","\\","!",'"',"'","&","$"),posixEscape)}else{return doRender(cmd,hasAnyChars(" ",'"',"&","^","%"),windowsEscape)}}function doRender(cmd,needsEscaping,doEscape){return cmd.map(x=>needsEscaping(x)?doEscape(x):x)}function hasAnyChars(...chars){return str=>{return chars.some(c=>str.indexOf(c)!==-1)}}function posixEscape(x){x=x.replace(/'/g,`'"'"'`);return`'${x}'`}function windowsEscape(x){x=`"${x}"`;const shellMeta=new Set(['"',"&","^","%"]);return x.split("").map(c=>shellMeta.has(x)?"^"+c:c).join("")}var child_process,chalk19;var init_os=__esm({"lib/os.ts"(){"use strict";child_process=__toESM(require("child_process"));chalk19=__toESM(require_source());init_logging();init_error()}});async function invokeBuiltinHooks(target,context){switch(target.language){case"csharp":if(["app","sample-app"].includes(target.templateName)){return dotnetAddProject(target.targetDirectory,context)}break;case"fsharp":if(["app","sample-app"].includes(target.templateName)){return dotnetAddProject(target.targetDirectory,context,"fsproj")}break;case"python":await context.substitutePlaceholdersIn("requirements.txt");break;case"java":await context.substitutePlaceholdersIn("pom.xml");break;case"javascript":case"typescript":await context.substitutePlaceholdersIn("package.json")}}async function dotnetAddProject(targetDirectory,context,ext2="csproj"){const pname=context.placeholder("name.PascalCased");const slnPath=path19.join(targetDirectory,"src",`${pname}.sln`);const csprojPath=path19.join(targetDirectory,"src",pname,`${pname}.${ext2}`);try{await shell(["dotnet","sln",slnPath,"add",csprojPath])}catch(e){throw new ToolkitError(`Could not add project ${pname}.${ext2} to solution ${pname}.sln. ${e.message}`)}}var path19;var init_init_hooks=__esm({"lib/init-hooks.ts"(){"use strict";path19=__toESM(require("path"));init_os();init_error()}});function rangeFromSemver(ver,targetType){const re=ver.match(/^([^\d]*)([\d.]*)$/);if(!re||!semver6.valid(re[2])){throw new Error("not a semver or unsupported range syntax")}const prefixPart=re[1];const verPart=re[2];switch(targetType){case"bracket":switch(prefixPart){case"":return ver;case"^":return`[${verPart},${semver6.major(verPart)+1}.0.0)`;default:throw new Error(`unsupported range syntax - ${prefixPart}`)}case"pep":switch(prefixPart){case"":return`==${ver}`;case"^":return`>=${verPart},<${semver6.major(verPart)+1}.0.0`;default:throw new Error(`unsupported range syntax - ${prefixPart}`)}}}var semver6;var init_version_range=__esm({"lib/util/version-range.ts"(){"use strict";semver6=__toESM(require_semver4())}});var require_camelcase=__commonJS({"../../node_modules/camelcase/index.js"(exports2,module2){"use strict";var UPPERCASE=/[\p{Lu}]/u;var LOWERCASE=/[\p{Ll}]/u;var LEADING_CAPITAL=/^[\p{Lu}](?![\p{Lu}])/gu;var IDENTIFIER=/([\p{Alpha}\p{N}_]|$)/u;var SEPARATORS=/[_.\- ]+/;var LEADING_SEPARATORS=new RegExp("^"+SEPARATORS.source);var SEPARATORS_AND_IDENTIFIER=new RegExp(SEPARATORS.source+IDENTIFIER.source,"gu");var NUMBERS_AND_IDENTIFIER=new RegExp("\\d+"+IDENTIFIER.source,"gu");var preserveCamelCase=(string,toLowerCase,toUpperCase)=>{let isLastCharLower=false;let isLastCharUpper=false;let isLastLastCharUpper=false;for(let i=0;i<string.length;i++){const character=string[i];if(isLastCharLower&&UPPERCASE.test(character)){string=string.slice(0,i)+"-"+string.slice(i);isLastCharLower=false;isLastLastCharUpper=isLastCharUpper;isLastCharUpper=true;i++}else if(isLastCharUpper&&isLastLastCharUpper&&LOWERCASE.test(character)){string=string.slice(0,i-1)+"-"+string.slice(i-1);isLastLastCharUpper=isLastCharUpper;isLastCharUpper=false;isLastCharLower=true}else{isLastCharLower=toLowerCase(character)===character&&toUpperCase(character)!==character;isLastLastCharUpper=isLastCharUpper;isLastCharUpper=toUpperCase(character)===character&&toLowerCase(character)!==character}}return string};var preserveConsecutiveUppercase=(input,toLowerCase)=>{LEADING_CAPITAL.lastIndex=0;return input.replace(LEADING_CAPITAL,m1=>toLowerCase(m1))};var postProcess=(input,toUpperCase)=>{SEPARATORS_AND_IDENTIFIER.lastIndex=0;NUMBERS_AND_IDENTIFIER.lastIndex=0;return input.replace(SEPARATORS_AND_IDENTIFIER,(_2,identifier)=>toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER,m=>toUpperCase(m))};var camelCase3=(input,options)=>{if(!(typeof input==="string"||Array.isArray(input))){throw new TypeError("Expected the input to be `string | string[]`")}options={pascalCase:false,preserveConsecutiveUppercase:false,...options};if(Array.isArray(input)){input=input.map(x=>x.trim()).filter(x=>x.length).join("-")}else{input=input.trim()}if(input.length===0){return""}const toLowerCase=options.locale===false?string=>string.toLowerCase():string=>string.toLocaleLowerCase(options.locale);const toUpperCase=options.locale===false?string=>string.toUpperCase():string=>string.toLocaleUpperCase(options.locale);if(input.length===1){return options.pascalCase?toUpperCase(input):toLowerCase(input)}const hasUpperCase=input!==toLowerCase(input);if(hasUpperCase){input=preserveCamelCase(input,toLowerCase,toUpperCase)}input=input.replace(LEADING_SEPARATORS,"");if(options.preserveConsecutiveUppercase){input=preserveConsecutiveUppercase(input,toLowerCase)}else{input=toLowerCase(input)}if(options.pascalCase){input=toUpperCase(input.charAt(0))+input.slice(1)}return postProcess(input,toUpperCase)};module2.exports=camelCase3;module2.exports.default=camelCase3}});var require_decamelize=__commonJS({"node_modules/decamelize/index.js"(exports2,module2){"use strict";var handlePreserveConsecutiveUppercase=(decamelized,separator)=>{decamelized=decamelized.replace(/((?<![\p{Uppercase_Letter}\d])[\p{Uppercase_Letter}\d](?![\p{Uppercase_Letter}\d]))/gu,$0=>{return $0.toLowerCase()});return decamelized.replace(new RegExp("(\\p{Uppercase_Letter}+)(\\p{Uppercase_Letter}\\p{Lowercase_Letter}+)","gu"),(_2,$1,$2)=>{return $1+separator+$2.toLowerCase()})};module2.exports=(text,{separator="_",preserveConsecutiveUppercase=false}={})=>{if(!(typeof text==="string"&&typeof separator==="string")){throw new TypeError("The `text` and `separator` arguments should be of type `string`")}if(text.length<2){return preserveConsecutiveUppercase?text:text.toLowerCase()}const replacement=`$1${separator}$2`;const decamelized=text.replace(new RegExp("([\\p{Lowercase_Letter}\\d])(\\p{Uppercase_Letter})","gu"),replacement);if(preserveConsecutiveUppercase){return handlePreserveConsecutiveUppercase(decamelized,separator)}return decamelized.replace(new RegExp("(\\p{Uppercase_Letter})(\\p{Uppercase_Letter}\\p{Lowercase_Letter}+)","gu"),replacement).toLowerCase()}}});async function cliInit(options){const canUseNetwork=options.canUseNetwork??true;const generateOnly=options.generateOnly??false;const workDir=options.workDir??process.cwd();if(!options.type&&!options.language){await printAvailableTemplates();return}const type=options.type||"default";const template=(await availableInitTemplates()).find(t=>t.hasName(type));if(!template){await printAvailableTemplates(options.language);throw new ToolkitError(`Unknown init template: ${type}`)}if(!options.language&&template.languages.length===1){const language=template.languages[0];warning(`No --language was provided, but '${type}' supports only '${language}', so defaulting to --language=${language}`)}if(!options.language){print(`Available languages for ${chalk20.green(type)}: ${template.languages.map(l=>chalk20.blue(l)).join(", ")}`);throw new ToolkitError("No language was selected")}await initializeProject(template,options.language,canUseNetwork,generateOnly,workDir,options.stackName,options.migrate)}function pythonExecutable(){let python="python3";if(process.platform==="win32"){python="python"}return python}async function availableInitTemplates(){return new Promise(async resolve7=>{try{const templatesDir=path20.join(rootDir(),"lib","init-templates");const templateNames=await listDirectory(templatesDir);const templates=new Array;for(const templateName of templateNames){templates.push(await InitTemplate.fromName(templatesDir,templateName))}resolve7(templates)}catch{resolve7([])}})}async function listDirectory(dirPath){return(await fs18.readdir(dirPath)).filter(p=>!p.startsWith(".")).filter(p=>!(p==="LICENSE")).filter(p=>!(p===INFO_DOT_JSON)).sort()}async function printAvailableTemplates(language){print("Available templates:");for(const template of await availableInitTemplates()){if(language&&template.languages.indexOf(language)===-1){continue}print(`* ${chalk20.green(template.name)}: ${template.description}`);const languageArg=language?chalk20.bold(language):template.languages.length>1?`[${template.languages.map(t=>chalk20.bold(t)).join("|")}]`:chalk20.bold(template.languages[0]);print(` \u2514\u2500 ${chalk20.blue(`cdk init ${chalk20.bold(template.name)} --language=${languageArg}`)}`)}}async function initializeProject(template,language,canUseNetwork,generateOnly,workDir,stackName,migrate){await assertIsEmptyDirectory(workDir);print(`Applying project template ${chalk20.green(template.name)} for ${chalk20.blue(language)}`);await template.install(language,workDir,stackName);if(migrate){await template.addMigrateContext(workDir)}if(await fs18.pathExists(`${workDir}/README.md`)){const readme=await fs18.readFile(`${workDir}/README.md`,{encoding:"utf-8"});print(chalk20.green(readme))}if(!generateOnly){await initializeGitRepository(workDir);await postInstall(language,canUseNetwork,workDir)}print("\u2705 All done!")}async function assertIsEmptyDirectory(workDir){const files=await fs18.readdir(workDir);if(files.filter(f=>!f.startsWith(".")).length!==0){throw new ToolkitError("`cdk init` cannot be run in a non-empty directory!")}}async function initializeGitRepository(workDir){if(await isInGitRepository(workDir)){return}print("Initializing a new git repository...");try{await execute("git",["init"],{cwd:workDir});await execute("git",["add","."],{cwd:workDir});await execute("git",["commit",'--message="Initial commit"',"--no-gpg-sign"],{cwd:workDir})}catch{warning("Unable to initialize git repository for your project.")}}async function postInstall(language,canUseNetwork,workDir){switch(language){case"javascript":return postInstallJavascript(canUseNetwork,workDir);case"typescript":return postInstallTypescript(canUseNetwork,workDir);case"java":return postInstallJava(canUseNetwork,workDir);case"python":return postInstallPython(workDir)}}async function postInstallJavascript(canUseNetwork,cwd){return postInstallTypescript(canUseNetwork,cwd)}async function postInstallTypescript(canUseNetwork,cwd){const command="npm";if(!canUseNetwork){warning(`Please run '${command} install'!`);return}print(`Executing ${chalk20.green(`${command} install`)}...`);try{await execute(command,["install"],{cwd})}catch(e){warning(`${command} install failed: `+e.message)}}async function postInstallJava(canUseNetwork,cwd){const mvnPackageWarning="Please run 'mvn package'!";if(!canUseNetwork){warning(mvnPackageWarning);return}print("Executing 'mvn package'");try{await execute("mvn",["package"],{cwd})}catch{warning("Unable to package compiled code as JAR");warning(mvnPackageWarning)}}async function postInstallPython(cwd){const python=pythonExecutable();warning(`Please run '${python} -m venv .venv'!`);print(`Executing ${chalk20.green("Creating virtualenv...")}`);try{await execute(python,["-m venv",".venv"],{cwd})}catch{warning("Unable to create virtualenv automatically");warning(`Please run '${python} -m venv .venv'!`)}}async function isInGitRepository(dir){while(true){if(await fs18.pathExists(path20.join(dir,".git"))){return true}if(isRoot(dir)){return false}dir=path20.dirname(dir)}}function isRoot(dir){return path20.dirname(dir)===dir}async function execute(cmd,args,{cwd}){const child=childProcess2.spawn(cmd,args,{cwd,shell:true,stdio:["ignore","pipe","inherit"]});let stdout2="";child.stdout.on("data",chunk=>stdout2+=chunk.toString());return new Promise((ok,fail)=>{child.once("error",err=>fail(err));child.once("exit",status=>{if(status===0){return ok(stdout2)}else{process.stderr.write(stdout2);return fail(new ToolkitError(`${cmd} exited with status ${status}`))}})})}async function loadInitVersions(){const recommendedFlagsFile=path20.join(__dirname,"./init-templates/.init-version.json");const contents=JSON.parse(await fs18.readFile(recommendedFlagsFile,{encoding:"utf-8"}));const ret={"aws-cdk-lib":contents["aws-cdk-lib"],"constructs":contents.constructs};for(const[key,value]of Object.entries(ret)){if(!value){throw new Error(`Missing init version from ${recommendedFlagsFile}: ${key}`)}}return ret}async function currentlyRecommendedAwsCdkLibFlags(){const recommendedFlagsFile=path20.join(__dirname,"./init-templates/.recommended-feature-flags.json");return JSON.parse(await fs18.readFile(recommendedFlagsFile,{encoding:"utf-8"}))}var childProcess2,path20,chalk20,fs18,camelCase,decamelize,INFO_DOT_JSON,InitTemplate;var init_init=__esm({"lib/init.ts"(){"use strict";childProcess2=__toESM(require("child_process"));path20=__toESM(require("path"));chalk20=__toESM(require_source());fs18=__toESM(require_lib4());init_init_hooks();init_logging();init_error();init_directories();init_version_range();camelCase=require_camelcase();decamelize=require_decamelize();INFO_DOT_JSON="info.json";InitTemplate=class _InitTemplate{constructor(basePath,name,languages,info2){this.basePath=basePath;this.name=name;this.languages=languages;this.aliases=new Set;this.description=info2.description;for(const alias of info2.aliases||[]){this.aliases.add(alias)}}static async fromName(templatesDir,name){const basePath=path20.join(templatesDir,name);const languages=await listDirectory(basePath);const info2=await fs18.readJson(path20.join(basePath,INFO_DOT_JSON));return new _InitTemplate(basePath,name,languages,info2)}hasName(name){return name===this.name||this.aliases.has(name)}async install(language,targetDirectory,stackName){if(this.languages.indexOf(language)===-1){error(`The ${chalk20.blue(language)} language is not supported for ${chalk20.green(this.name)} (it supports: ${this.languages.map(l=>chalk20.blue(l)).join(", ")})`);throw new ToolkitError(`Unsupported language: ${language}`)}const projectInfo={name:decamelize(path20.basename(path20.resolve(targetDirectory))),stackName,versions:await loadInitVersions()};const sourceDirectory=path20.join(this.basePath,language);await this.installFiles(sourceDirectory,targetDirectory,language,projectInfo);await this.applyFutureFlags(targetDirectory);await invokeBuiltinHooks({targetDirectory,language,templateName:this.name},{substitutePlaceholdersIn:async(...fileNames)=>{for(const fileName of fileNames){const fullPath=path20.join(targetDirectory,fileName);const template=await fs18.readFile(fullPath,{encoding:"utf-8"});await fs18.writeFile(fullPath,this.expand(template,language,projectInfo))}},placeholder:ph=>this.expand(`%${ph}%`,language,projectInfo)})}async installFiles(sourceDirectory,targetDirectory,language,project){for(const file of await fs18.readdir(sourceDirectory)){const fromFile=path20.join(sourceDirectory,file);const toFile=path20.join(targetDirectory,this.expand(file,language,project));if((await fs18.stat(fromFile)).isDirectory()){await fs18.mkdir(toFile);await this.installFiles(fromFile,toFile,language,project);continue}else if(file.match(/^.*\.template\.[^.]+$/)){await this.installProcessed(fromFile,toFile.replace(/\.template(\.[^.]+)$/,"$1"),language,project);continue}else if(file.match(/^.*\.hook\.(d.)?[^.]+$/)){continue}else{await fs18.copy(fromFile,toFile)}}}async installProcessed(templatePath,toFile,language,project){const template=await fs18.readFile(templatePath,{encoding:"utf-8"});await fs18.writeFile(toFile,this.expand(template,language,project))}expand(template,language,project){const cdkVersion=project.versions["aws-cdk-lib"];let constructsVersion=project.versions.constructs;switch(language){case"java":case"csharp":case"fsharp":constructsVersion=rangeFromSemver(constructsVersion,"bracket");break;case"python":constructsVersion=rangeFromSemver(constructsVersion,"pep");break}return template.replace(/%name%/g,project.name).replace(/%stackname%/,project.stackName??"%name.PascalCased%Stack").replace(/%PascalNameSpace%/,project.stackName?camelCase(project.stackName+"Stack",{pascalCase:true}):"%name.PascalCased%").replace(/%PascalStackProps%/,project.stackName?camelCase(project.stackName,{pascalCase:true})+"StackProps":"StackProps").replace(/%name\.camelCased%/g,camelCase(project.name)).replace(/%name\.PascalCased%/g,camelCase(project.name,{pascalCase:true})).replace(/%cdk-version%/g,cdkVersion).replace(/%constructs-version%/g,constructsVersion).replace(/%cdk-home%/g,cdkHomeDir()).replace(/%name\.PythonModule%/g,project.name.replace(/-/g,"_")).replace(/%python-executable%/g,pythonExecutable()).replace(/%name\.StackName%/g,project.name.replace(/[^A-Za-z0-9-]/g,"-"))}async applyFutureFlags(projectDir){const cdkJson=path20.join(projectDir,"cdk.json");if(!await fs18.pathExists(cdkJson)){return}const config=await fs18.readJson(cdkJson);config.context={...config.context,...await currentlyRecommendedAwsCdkLibFlags()};await fs18.writeJson(cdkJson,config,{spaces:2})}async addMigrateContext(projectDir){const cdkJson=path20.join(projectDir,"cdk.json");if(!await fs18.pathExists(cdkJson)){return}const config=await fs18.readJson(cdkJson);config.context={...config.context,"cdk-migrate":true};await fs18.writeJson(cdkJson,config,{spaces:2})}}}});async function zipDirectory(directory,outputFile){const temporaryOutputFile=`${outputFile}.${randomString()}._tmp`;await writeZipFile(directory,temporaryOutputFile);await moveIntoPlace(temporaryOutputFile,outputFile)}function writeZipFile(directory,outputFile){return new Promise(async(ok,fail)=>{const globOptions={dot:true,nodir:true,follow:true,cwd:directory};const files=glob.sync("**",globOptions);const output=(0,import_fs2.createWriteStream)(outputFile);const archive=archiver2("zip");archive.on("warning",fail);archive.on("error",fail);output.once("close",ok);archive.pipe(output);for(const file of files){const fullPath=path21.resolve(directory,file);const[data2,stat4]=await Promise.all([import_fs2.promises.readFile(fullPath),import_fs2.promises.stat(fullPath)]);archive.append(data2,{name:file,mode:stat4.mode})}await archive.finalize()})}async function moveIntoPlace(source,target){let delay=100;let attempts=5;while(true){try{await import_fs2.promises.rename(source,target);return}catch(e){if(e.code!=="EPERM"||attempts--<=0){throw e}(0,import_console2.error)(e.message);await sleep2(Math.floor(Math.random()*delay));delay*=2}}}function sleep2(ms){return new Promise(ok=>setTimeout(ok,ms))}function randomString(){return Math.random().toString(36).replace(/[^a-z0-9]+/g,"")}var import_console2,import_fs2,path21,glob,archiver2;var init_archive=__esm({"lib/util/archive.ts"(){"use strict";import_console2=require("console");import_fs2=require("fs");path21=__toESM(require("path"));glob=__toESM(require_glob());archiver2=require_archiver()}});async function generateCdkApp(stackName,stack,language,outputPath,compress){const resolvedOutputPath=path22.join(outputPath??process.cwd(),stackName);const formattedStackName=decamelize2(stackName);try{fs20.rmSync(resolvedOutputPath,{recursive:true,force:true});fs20.mkdirSync(resolvedOutputPath,{recursive:true});const generateOnly=compress;await cliInit({type:"app",language,canUseNetwork:true,generateOnly,workDir:resolvedOutputPath,stackName,migrate:true});let stackFileName;switch(language){case"typescript":stackFileName=`${resolvedOutputPath}/lib/${formattedStackName}-stack.ts`;break;case"java":stackFileName=`${resolvedOutputPath}/src/main/java/com/myorg/${camelCase2(formattedStackName,{pascalCase:true})}Stack.java`;break;case"python":stackFileName=`${resolvedOutputPath}/${formattedStackName.replace(/-/g,"_")}/${formattedStackName.replace(/-/g,"_")}_stack.py`;break;case"csharp":stackFileName=`${resolvedOutputPath}/src/${camelCase2(formattedStackName,{pascalCase:true})}/${camelCase2(formattedStackName,{pascalCase:true})}Stack.cs`;break;case"go":stackFileName=`${resolvedOutputPath}/${formattedStackName}.go`;break;default:throw new Error(`${language} is not supported by CDK Migrate. Please choose from: ${MIGRATE_SUPPORTED_LANGUAGES.join(", ")}`)}fs20.writeFileSync(stackFileName,stack);if(compress){await zipDirectory(resolvedOutputPath,`${resolvedOutputPath}.zip`);fs20.rmSync(resolvedOutputPath,{recursive:true,force:true})}}catch(error3){fs20.rmSync(resolvedOutputPath,{recursive:true,force:true});throw error3}}function generateStack(template,stackName,language){const formattedStackName=`${camelCase2(decamelize2(stackName),{pascalCase:true})}Stack`;try{return cdk_from_cfn.transmute(template,language,formattedStackName)}catch(e){throw new Error(`${formattedStackName} could not be generated because ${e.message}`)}}function readFromPath(inputPath){let readFile4;try{readFile4=fs20.readFileSync(inputPath,"utf8")}catch(e){throw new Error(`'${inputPath}' is not a valid path.`)}if(readFile4==""){throw new Error(`Cloudformation template filepath: '${inputPath}' is an empty file.`)}return readFile4}async function readFromStack(stackName,sdkProvider,environment){const cloudFormation=(await sdkProvider.forEnvironment(environment,0)).sdk.cloudFormation();const stack=await CloudFormationStack.lookup(cloudFormation,stackName,true);if(stack.stackStatus.isDeploySuccess||stack.stackStatus.isRollbackSuccess){return JSON.stringify(await stack.template())}else{throw new Error(`Stack '${stackName}' in account ${environment.account} and region ${environment.region} has a status of '${stack.stackStatus.name}' due to '${stack.stackStatus.reason}'. The stack cannot be migrated until it is in a healthy state.`)}}async function generateTemplate(options){const cfn=new CfnTemplateGeneratorProvider(await buildCfnClient(options.sdkProvider,options.environment));const scanId=await findLastSuccessfulScan(cfn,options);const curScan=await cfn.describeResourceScan(scanId);if(curScan.Status=="IN_PROGRESS"){print("Resource scan in progress. Please wait, this can take 10 minutes or longer.");await scanProgressBar(scanId,cfn)}displayTimeDiff(new Date,new Date(curScan.StartTime));let resources=await cfn.listResourceScanResources(scanId,options.filters);print("finding related resources.");let relatedResources=await cfn.getResourceScanRelatedResources(scanId,resources);print(`Found ${relatedResources.length} resources.`);print("Generating CFN template from scanned resources.");const templateArn=(await cfn.createGeneratedTemplate(options.stackName,relatedResources)).GeneratedTemplateId;let generatedTemplate=await cfn.describeGeneratedTemplate(templateArn);print("Please wait, template creation in progress. This may take a couple minutes.");while(generatedTemplate.Status!=="COMPLETE"&&generatedTemplate.Status!=="FAILED"){await printDots(`[${generatedTemplate.Status}] Template Creation in Progress`,400);generatedTemplate=await cfn.describeGeneratedTemplate(templateArn)}print("");print("Template successfully generated!");return buildGenertedTemplateOutput(generatedTemplate,(await cfn.getGeneratedTemplate(templateArn)).TemplateBody,templateArn)}async function findLastSuccessfulScan(cfn,options){let resourceScanSummaries=[];const clientRequestToken=`cdk-migrate-${options.environment.account}-${options.environment.region}`;if(options.fromScan===0){print(`Starting new scan for account ${options.environment.account} in region ${options.environment.region}`);try{await cfn.startResourceScan(clientRequestToken);resourceScanSummaries=(await cfn.listResourceScans()).ResourceScanSummaries}catch(e){print(`Scan failed to start due to error '${e.message}', defaulting to latest scan.`)}}else{resourceScanSummaries=(await cfn.listResourceScans()).ResourceScanSummaries;await cfn.checkForResourceScan(resourceScanSummaries,options,clientRequestToken)}resourceScanSummaries=(await cfn.listResourceScans()).ResourceScanSummaries;let scanId=resourceScanSummaries[0].ResourceScanId;for(const summary of resourceScanSummaries){if(summary.Status!=="FAILED"){scanId=summary.ResourceScanId;break}}return scanId}function parseFilters(filters){if(!filters){return{"resource-identifier":void 0,"resource-type-prefix":void 0,"tag-key":void 0,"tag-value":void 0}}const filterShorthands={"identifier":"resource-identifier","id":"resource-identifier","type":"resource-type-prefix","type-prefix":"resource-type-prefix"};const filterList=filters.split(",");let filterMap={["resource-identifier"]:void 0,["resource-type-prefix"]:void 0,["tag-key"]:void 0,["tag-value"]:void 0};for(const fil of filterList){const filter2=fil.split("=");let filterKey=filter2[0];const filterValue=filter2[1];if(filterKey in filterShorthands){filterKey=filterShorthands[filterKey]}if(Object.values(FilterType).includes(filterKey)){filterMap[filterKey]=filterValue}else{throw new Error(`Invalid filter: ${filterKey}`)}}return filterMap}function chunks(list,chunkSize){const chunkedList=[];for(let i=0;i<list.length;i+=chunkSize){chunkedList.push(list.slice(i,i+chunkSize))}return chunkedList}function setEnvironment(account,region){return{account:account??import_cx_api9.UNKNOWN_ACCOUNT,region:region??import_cx_api9.UNKNOWN_REGION,name:"cdk-migrate-env"}}function parseSourceOptions(fromPath,fromStack,stackName){if(fromPath&&fromStack){throw new Error("Only one of `--from-path` or `--from-stack` may be provided.")}if(!stackName){throw new Error("`--stack-name` is a required field.")}if(!fromPath&&!fromStack){return{source:"scan"}}if(fromPath){return{source:"path",templatePath:fromPath}}return{source:"stack",stackName}}function excludeManaged(resourceList){return resourceList.filter(r=>!r.ManagedByStack).map(r=>({ResourceType:r.ResourceType,ResourceIdentifier:r.ResourceIdentifier}))}function resourceIdentifiers(resourceList){const identifiers=[];resourceList.forEach(r=>{const identifier={ResourceType:r.ResourceType,ResourceIdentifier:r.ResourceIdentifier};identifiers.push(identifier)});return identifiers}async function scanProgressBar(scanId,cfn){let curProgress=.5;let curScan={Status:"IN_PROGRESS",$metadata:{}};while(curScan.Status=="IN_PROGRESS"){curScan=await cfn.describeResourceScan(scanId);curProgress=curScan.PercentageCompleted??curProgress;printBar(30,curProgress);await new Promise(resolve7=>setTimeout(resolve7,2e3))}print("");print("\u2705 Scan Complete!")}function printBar(width,progress){if(!process.env.MIGRATE_INTEG_TEST){const FULL_BLOCK2="\u2588";const PARTIAL_BLOCK2=["","\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589"];const fraction=Math.min(progress/100,1);const innerWidth=Math.max(1,width-2);const chars=innerWidth*fraction;const remainder=chars-Math.floor(chars);const fullChars=FULL_BLOCK2.repeat(Math.floor(chars));const partialChar=PARTIAL_BLOCK2[Math.floor(remainder*PARTIAL_BLOCK2.length)];const filler="\xB7".repeat(innerWidth-Math.floor(chars)-(partialChar?1:0));const color=chalk21.green;rewriteLine("["+color(fullChars+partialChar)+filler+`] (${progress}%)`)}}async function printDots(message,timeoutx4){if(!process.env.MIGRATE_INTEG_TEST){rewriteLine(message+" .");await new Promise(resolve7=>setTimeout(resolve7,timeoutx4));rewriteLine(message+" ..");await new Promise(resolve7=>setTimeout(resolve7,timeoutx4));rewriteLine(message+" ...");await new Promise(resolve7=>setTimeout(resolve7,timeoutx4));rewriteLine(message);await new Promise(resolve7=>setTimeout(resolve7,timeoutx4))}}function rewriteLine(message){process.stdout.clearLine(0);process.stdout.cursorTo(0);process.stdout.write(message)}function displayTimeDiff(time1,time2){const diff=Math.abs(time1.getTime()-time2.getTime());const days=Math.floor(diff/(1e3*60*60*24));const hours=Math.floor(diff%(1e3*60*60*24)/(1e3*60*60));const minutes=Math.floor(diff%(1e3*60*60)/(1e3*60));print(`Using the latest successful scan which is ${days} days, ${hours} hours, and ${minutes} minutes old.`)}function writeMigrateJsonFile(outputPath,stackName,migrateJson){const outputToJson={"//":"This file is generated by cdk migrate. It will be automatically deleted after the first successful deployment of this app to the environment of the original resources.","Source":migrateJson.source,"Resources":migrateJson.resources};fs20.writeFileSync(`${path22.join(outputPath??process.cwd(),stackName)}/migrate.json`,JSON.stringify(outputToJson,null,2))}function getMigrateScanType(scanType){switch(scanType){case"new":return 0;case"most-recent":return 1;case"":return 2;case void 0:return 2;default:throw new Error(`Unknown scan type: ${scanType}`)}}function isThereAWarning(generatedTemplateOutput){if(generatedTemplateOutput.resources){for(const resource of generatedTemplateOutput.resources){if(resource.Warnings&&resource.Warnings.length>0){return true}}}return false}function buildGenertedTemplateOutput(generatedTemplateSummary,templateBody,source){const resources=generatedTemplateSummary.Resources;const migrateJson={templateBody,source,resources:generatedTemplateSummary.Resources.map(r=>({ResourceType:r.ResourceType,LogicalResourceId:r.LogicalResourceId,ResourceIdentifier:r.ResourceIdentifier}))};const templateId=generatedTemplateSummary.GeneratedTemplateId;return{migrateJson,resources,templateId}}async function buildCfnClient(sdkProvider,environment){const sdk=(await sdkProvider.forEnvironment(environment,0)).sdk;sdk.appendCustomUserAgent("cdk-migrate");return sdk.cloudFormation()}function appendWarningsToReadme(filepath,resources){const readme=fs20.readFileSync(filepath,"utf8");const lines=readme.split("\n");const index=lines.findIndex(line=>line.trim()==="Enjoy!");let linesToAdd=["\n## Warnings"];linesToAdd.push("### Write-only properties");linesToAdd.push("Write-only properties are resource property values that can be written to but can't be read by AWS CloudFormation or CDK Migrate. For more information, see [IaC generator and write-only properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC-write-only-properties.html).");linesToAdd.push("\n");linesToAdd.push("Write-only properties discovered during migration are organized here by resource ID and categorized by write-only property type. Resolve write-only properties by providing property values in your CDK app. For guidance, see [Resolve write-only properties](https://docs.aws.amazon.com/cdk/v2/guide/migrate.html#migrate-resources-writeonly).");for(const resource of resources){if(resource.Warnings&&resource.Warnings.length>0){linesToAdd.push(`### ${resource.LogicalResourceId}`);for(const warning2 of resource.Warnings){linesToAdd.push(`- **${warning2.Type}**: `);for(const property of warning2.Properties){linesToAdd.push(` - ${property.PropertyPath}: ${property.Description}`)}}}}lines.splice(index,0,...linesToAdd);fs20.writeFileSync(filepath,lines.join("\n"))}function deduplicateResources(resources){let uniqueResources={};for(const resource of resources){const key=Object.keys(resource.ResourceIdentifier)[0];const uniqueIdentifer=`${resource.ResourceType}:${key}:${resource.ResourceIdentifier[key]}`;uniqueResources[uniqueIdentifer]=resource}return Object.values(uniqueResources)}var fs20,path22,import_cx_api9,cdk_from_cfn,chalk21,camelCase2,decamelize2,MIGRATE_SUPPORTED_LANGUAGES,FilterType,CfnTemplateGeneratorProvider;var init_migrate=__esm({"lib/commands/migrate.ts"(){"use strict";fs20=__toESM(require("fs"));path22=__toESM(require("path"));import_cx_api9=__toESM(require_lib3());cdk_from_cfn=__toESM(require_cdk_from_cfn());chalk21=__toESM(require_source());init_init();init_logging();init_cloudformation();init_archive();camelCase2=require_camelcase();decamelize2=require_decamelize();MIGRATE_SUPPORTED_LANGUAGES=cdk_from_cfn.supported_languages();FilterType=(FilterType2=>{FilterType2["RESOURCE_IDENTIFIER"]="resource-identifier";FilterType2["RESOURCE_TYPE_PREFIX"]="resource-type-prefix";FilterType2["TAG_KEY"]="tag-key";FilterType2["TAG_VALUE"]="tag-value";return FilterType2})(FilterType||{});CfnTemplateGeneratorProvider=class{constructor(cfn){this.cfn=cfn}async checkForResourceScan(resourceScanSummaries,options,clientRequestToken){if(!resourceScanSummaries||resourceScanSummaries.length===0){if(options.fromScan===1){throw new Error("No scans found. Please either start a new scan with the `--from-scan` new or do not specify a `--from-scan` option.")}else{print("No scans found. Initiating a new resource scan.");await this.startResourceScan(clientRequestToken)}}}async getResourceScanRelatedResources(scanId,resources){let relatedResourceList=resources;for(const chunk of chunks(resources,100)){const res=await this.cfn.listResourceScanRelatedResources({ResourceScanId:scanId,Resources:chunk});relatedResourceList.push(...res.RelatedResources??[]);let nextToken=res.NextToken;while(nextToken){const nextRelatedResources=await this.cfn.listResourceScanRelatedResources({ResourceScanId:scanId,Resources:resourceIdentifiers(resources),NextToken:nextToken});nextToken=nextRelatedResources.NextToken;relatedResourceList.push(...nextRelatedResources.RelatedResources??[])}}relatedResourceList=deduplicateResources(relatedResourceList);return process.env.MIGRATE_INTEG_TEST?resourceIdentifiers(relatedResourceList):resourceIdentifiers(excludeManaged(relatedResourceList))}async startResourceScan(requestToken){return(await this.cfn.startResourceScan({ClientRequestToken:requestToken})).ResourceScanId}async listResourceScans(){return this.cfn.listResourceScans()}async listResourceScanResources(scanId,filters=[]){let resourceList=[];let resourceScanInputs;if(filters.length>0){print("Applying filters to resource scan.");for(const filter2 of filters){const filterList=parseFilters(filter2);resourceScanInputs={ResourceScanId:scanId,ResourceIdentifier:filterList["resource-identifier"],ResourceTypePrefix:filterList["resource-type-prefix"],TagKey:filterList["tag-key"],TagValue:filterList["tag-value"]};const resources=await this.cfn.listResourceScanResources(resourceScanInputs);resourceList=resourceList.concat(resources.Resources??[]);let nextToken=resources.NextToken;while(nextToken){resourceScanInputs.NextToken=nextToken;const nextResources=await this.cfn.listResourceScanResources(resourceScanInputs);nextToken=nextResources.NextToken;resourceList=resourceList.concat(nextResources.Resources??[])}}}else{print("No filters provided. Retrieving all resources from scan.");resourceScanInputs={ResourceScanId:scanId};const resources=await this.cfn.listResourceScanResources(resourceScanInputs);resourceList=resourceList.concat(resources.Resources??[]);let nextToken=resources.NextToken;while(nextToken){resourceScanInputs.NextToken=nextToken;const nextResources=await this.cfn.listResourceScanResources(resourceScanInputs);nextToken=nextResources.NextToken;resourceList=resourceList.concat(nextResources.Resources??[])}}if(resourceList.length===0){throw new Error(`No resources found with filters ${filters.join(" ")}. Please try again with different filters.`)}resourceList=deduplicateResources(resourceList);return process.env.MIGRATE_INTEG_TEST?resourceIdentifiers(resourceList):resourceIdentifiers(excludeManaged(resourceList))}async describeResourceScan(scanId){return this.cfn.describeResourceScan({ResourceScanId:scanId})}async describeGeneratedTemplate(templateId){const generatedTemplate=await this.cfn.describeGeneratedTemplate({GeneratedTemplateName:templateId});if(generatedTemplate.Status=="FAILED"){throw new Error(generatedTemplate.StatusReason)}return generatedTemplate}async getGeneratedTemplate(templateId){return this.cfn.getGeneratedTemplate({GeneratedTemplateName:templateId})}async createGeneratedTemplate(stackName,resources){const createTemplateOutput=await this.cfn.createGeneratedTemplate({Resources:resources,GeneratedTemplateName:stackName});if(createTemplateOutput.GeneratedTemplateId===void 0){throw new Error("CreateGeneratedTemplate failed to return an Arn.")}return createTemplateOutput}async deleteGeneratedTemplate(templateArn){await this.cfn.deleteGeneratedTemplate({GeneratedTemplateName:templateArn})}}}});function printStackDiff(oldTemplate,newTemplate,strict,context,quiet,stackName,changeSet,isImport,stream=process.stderr,nestedStackTemplates){let diff=(0,import_cloudformation_diff.fullDiff)(oldTemplate,newTemplate.template,changeSet,isImport);if(stackName&&(!quiet||!diff.isEmpty)){stream.write((0,import_util17.format)("Stack %s\n",chalk22.bold(stackName)))}if(!quiet&&isImport){stream.write("Parameters and rules created during migration do not affect resource configuration.\n")}let filteredChangesCount=0;if(diff.differenceCount&&!strict){const mangledNewTemplate=JSON.parse((0,import_cloudformation_diff.mangleLikeCloudFormation)(JSON.stringify(newTemplate.template)));const mangledDiff=(0,import_cloudformation_diff.fullDiff)(oldTemplate,mangledNewTemplate,changeSet);filteredChangesCount=Math.max(0,diff.differenceCount-mangledDiff.differenceCount);if(filteredChangesCount>0){diff=mangledDiff}}if(!strict){obscureDiff(diff)}let stackDiffCount=0;if(!diff.isEmpty){stackDiffCount++;(0,import_cloudformation_diff.formatDifferences)(stream,diff,{...logicalIdMapFromTemplate(oldTemplate),...buildLogicalToPathMap(newTemplate)},context)}else if(!quiet){print(chalk22.green("There were no differences"))}if(filteredChangesCount>0){print(chalk22.yellow(`Omitted ${filteredChangesCount} changes because they are likely mangled non-ASCII characters. Use --strict to print them.`))}for(const nestedStackLogicalId of Object.keys(nestedStackTemplates??{})){if(!nestedStackTemplates){break}const nestedStack=nestedStackTemplates[nestedStackLogicalId];newTemplate._template=nestedStack.generatedTemplate;stackDiffCount+=printStackDiff(nestedStack.deployedTemplate,newTemplate,strict,context,quiet,nestedStack.physicalName??nestedStackLogicalId,void 0,isImport,stream,nestedStack.nestedStackTemplates)}return stackDiffCount}function printSecurityDiff(oldTemplate,newTemplate,requireApproval,_quiet,stackName,changeSet,stream=process.stderr){const diff=(0,import_cloudformation_diff.fullDiff)(oldTemplate,newTemplate.template,changeSet);if(diffRequiresApproval(diff,requireApproval)){stream.write((0,import_util17.format)("Stack %s\n",chalk22.bold(stackName)));warning(`This deployment will make potentially sensitive changes according to your current security approval level (--require-approval ${requireApproval}).`);warning("Please confirm you intend to make the following modifications:\n");(0,import_cloudformation_diff.formatSecurityChanges)(process.stdout,diff,buildLogicalToPathMap(newTemplate));return true}return false}function diffRequiresApproval(diff,requireApproval){switch(requireApproval){case"never":return false;case"any-change":return diff.permissionsAnyChanges;case"broadening":return diff.permissionsBroadened;default:throw new ToolkitError(`Unrecognized approval level: ${requireApproval}`)}}function buildLogicalToPathMap(stack){const map={};for(const md of stack.findMetadataByType(cxschema9.ArtifactMetadataEntryType.LOGICAL_ID)){map[md.data]=md.path}return map}function logicalIdMapFromTemplate(template){var _a;const ret={};for(const[logicalId,resource]of Object.entries(template.Resources??{})){const path24=(_a=resource==null?void 0:resource.Metadata)==null?void 0:_a["aws:cdk:path"];if(path24){ret[logicalId]=path24}}return ret}function obscureDiff(diff){if(diff.unknown){diff.unknown=diff.unknown.filter(change=>{var _a,_b;if(!change){return true}if((_a=change.newValue)==null?void 0:_a.CheckBootstrapVersion){return false}if((_b=change.oldValue)==null?void 0:_b.CheckBootstrapVersion){return false}return true})}if(diff.resources){diff.resources=diff.resources.filter(change=>{if(!change){return true}if(change.newResourceType==="AWS::CDK::Metadata"){return false}if(change.oldResourceType==="AWS::CDK::Metadata"){return false}return true})}}var import_util17,cxschema9,import_cloudformation_diff,chalk22;var init_diff2=__esm({"lib/diff.ts"(){"use strict";import_util17=require("util");cxschema9=__toESM(require_lib2());import_cloudformation_diff=__toESM(require_lib9());chalk22=__toESM(require_source());init_logging();init_error()}});function removeNonImportResources(stack){const template=stack.template;delete template.Resources.CDKMetadata;delete template.Outputs;return template}function fmtdict(xs){return Object.entries(xs).map(([k,v])=>`${k}=${v}`).join(", ")}function addDefaultDeletionPolicy(resource){if(resource.DeletionPolicy){return resource}return{...resource,DeletionPolicy:"Retain"}}var cfnDiff2,chalk23,fs21,promptly3,ResourceImporter;var init_import=__esm({"lib/import.ts"(){"use strict";cfnDiff2=__toESM(require_lib9());chalk23=__toESM(require_source());fs21=__toESM(require_lib4());promptly3=__toESM(require_promptly());init_deploy_stack();init_logging();init_error();ResourceImporter=class{constructor(stack,cfn){this.stack=stack;this.cfn=cfn}async askForResourceIdentifiers(available){const ret={importResources:[],resourceMap:{}};const resourceIdentifiers2=await this.resourceIdentifiers();for(const resource of available){const identifier=await this.askForResourceIdentifier(resourceIdentifiers2,resource);if(!identifier){continue}ret.importResources.push(resource);ret.resourceMap[resource.logicalId]=identifier}return ret}async loadResourceIdentifiers(available,filename){const contents=await fs21.readJson(filename);const ret={importResources:[],resourceMap:{}};for(const resource of available){const descr=this.describeResource(resource.logicalId);const idProps=contents[resource.logicalId];if(idProps){print("%s: importing using %s",chalk23.blue(descr),chalk23.blue(fmtdict(idProps)));ret.importResources.push(resource);ret.resourceMap[resource.logicalId]=idProps;delete contents[resource.logicalId]}else{print("%s: skipping",chalk23.blue(descr))}}const unknown=Object.keys(contents);if(unknown.length>0){warning(`Unrecognized resource identifiers in mapping file: ${unknown.join(", ")}`)}return ret}async importResourcesFromMap(importMap,options){const resourcesToImport=await this.makeResourcesToImport(importMap);const updatedTemplate=await this.currentTemplateWithAdditions(importMap.importResources);await this.importResources(updatedTemplate,resourcesToImport,options)}async importResourcesFromMigrate(resourcesToImport,options){const updatedTemplate=this.removeNonImportResources();await this.importResources(updatedTemplate,resourcesToImport,options)}async importResources(overrideTemplate,resourcesToImport,options){try{const result=await this.cfn.deployStack({stack:this.stack,deployName:this.stack.stackName,...options,overrideTemplate,resourcesToImport});assertIsSuccessfulDeployStackResult(result);const message=result.noOp?" \u2705 %s (no changes)":" \u2705 %s";success("\n"+message,this.stack.displayName)}catch(e){error("\n \u274C %s failed: %s",chalk23.bold(this.stack.displayName),e);throw e}}async discoverImportableResources(allowNonAdditions=false){const currentTemplate=await this.currentTemplate();const diff=cfnDiff2.fullDiff(currentTemplate,this.stack.template);const resourceChanges=Object.entries(diff.resources.changes).filter(([logicalId,_2])=>logicalId!=="CDKMetadata");const nonAdditions=resourceChanges.filter(([_2,dif])=>!dif.isAddition);const additions=resourceChanges.filter(([_2,dif])=>dif.isAddition);if(nonAdditions.length){const offendingResources=nonAdditions.map(([logId,_2])=>this.describeResource(logId));if(allowNonAdditions){warning(`Ignoring updated/deleted resources (--force): ${offendingResources.join(", ")}`)}else{throw new ToolkitError(`No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(", ")} (--force to override)`)}}return{additions:additions.map(([logicalId,resourceDiff])=>{var _a,_b;return{logicalId,resourceDiff,resourceDefinition:addDefaultDeletionPolicy(((_b=(_a=this.stack.template)==null?void 0:_a.Resources)==null?void 0:_b[logicalId])??{})}}),hasNonAdditions:nonAdditions.length>0}}async resolveEnvironment(){return this.cfn.resolveEnvironment(this.stack)}async currentTemplate(){if(!this._currentTemplate){this._currentTemplate=await this.cfn.readCurrentTemplate(this.stack)}return this._currentTemplate}async currentTemplateWithAdditions(additions){const template=await this.currentTemplate();if(!template.Resources){template.Resources={}}for(const add of additions){template.Resources[add.logicalId]=add.resourceDefinition}return template}async resourceIdentifiers(){var _a;const ret={};const resourceIdentifierSummaries=await this.cfn.resourceIdentifierSummaries(this.stack);for(const summary of resourceIdentifierSummaries){if("ResourceType"in summary&&summary.ResourceType&&"ResourceIdentifiers"in summary&&summary.ResourceIdentifiers){ret[summary.ResourceType]=(_a=summary.ResourceIdentifiers??[])==null?void 0:_a.map(x=>x.split(","))}}return ret}async askForResourceIdentifier(resourceIdentifiers2,chg){const resourceName=this.describeResource(chg.logicalId);const resourceType=chg.resourceDiff.newResourceType;if(resourceType===void 0||!(resourceType in resourceIdentifiers2)){warning(`${resourceName}: unsupported resource type ${resourceType}, skipping import.`);return void 0}const idPropSets=resourceIdentifiers2[resourceType];const resourceProps=Object.fromEntries(Object.entries(chg.resourceDefinition.Properties??{}).filter(([_2,v])=>typeof v==="string"));const satisfiedPropSets=idPropSets.filter(ps=>ps.every(p=>resourceProps[p]));for(const satisfiedPropSet of satisfiedPropSets){const candidateProps=Object.fromEntries(satisfiedPropSet.map(p=>[p,resourceProps[p]]));const displayCandidateProps=fmtdict(candidateProps);if(await promptly3.confirm(`${chalk23.blue(resourceName)} (${resourceType}): import with ${chalk23.yellow(displayCandidateProps)} (yes/no) [default: yes]? `,{default:"yes"})){return candidateProps}}if(satisfiedPropSets.length>0){print(chalk23.grey(`Skipping import of ${resourceName}`));return void 0}const prefix=`${chalk23.blue(resourceName)} (${resourceType})`;let preamble;let promptPattern;if(idPropSets.length>1){preamble=`${prefix}: enter one of ${idPropSets.map(x=>chalk23.blue(x.join("+"))).join(", ")} to import (all empty to skip)`;promptPattern=`${prefix}: enter %`}else{promptPattern=`${prefix}: enter %`}if(preamble){print(preamble)}for(const idProps of idPropSets){const input={};for(const idProp of idProps){const defaultValue=resourceProps[idProp]??"";const prompt4=[promptPattern.replace(/%/g,chalk23.blue(idProp)),defaultValue?`[${defaultValue}]`:"(empty to skip)"].join(" ")+":";const response=await promptly3.prompt(prompt4,{default:defaultValue,trim:true});if(!response){break}input[idProp]=response;resourceProps[idProp]=response}if(Object.keys(input).length===idProps.length){return input}}print(chalk23.grey(`Skipping import of ${resourceName}`));return void 0}async makeResourcesToImport(resourceMap){return resourceMap.importResources.map(res=>({LogicalResourceId:res.logicalId,ResourceType:res.resourceDiff.newResourceType,ResourceIdentifier:resourceMap.resourceMap[res.logicalId]}))}describeResource(logicalId){var _a,_b,_c,_d;return((_d=(_c=(_b=(_a=this.stack.template)==null?void 0:_a.Resources)==null?void 0:_b[logicalId])==null?void 0:_c.Metadata)==null?void 0:_d["aws:cdk:path"])??logicalId}removeNonImportResources(){return removeNonImportResources(this.stack)}}}});async function listStacks(toolkit,options){const assembly=await toolkit.assembly();const stacks=await assembly.selectStacks({patterns:options.selectors},{extend:1,defaultBehavior:"all"});function calculateStackDependencies(collectionOfStacks){const allData=[];for(const stack of collectionOfStacks.stackArtifacts){const data2={id:stack.displayName??stack.id,name:stack.stackName,environment:stack.environment,dependencies:[]};for(const dependencyId of stack.dependencies.map(x=>x.id)){if(dependencyId.includes(".assets")){continue}const depStack=assembly.stackById(dependencyId);if(depStack.stackArtifacts[0].dependencies.length>0&&depStack.stackArtifacts[0].dependencies.filter(dep=>!dep.id.includes(".assets")).length>0){const stackWithDeps=calculateStackDependencies(depStack);for(const stackDetail of stackWithDeps){data2.dependencies.push({id:stackDetail.id,dependencies:stackDetail.dependencies})}}else{data2.dependencies.push({id:depStack.stackArtifacts[0].displayName??depStack.stackArtifacts[0].id,dependencies:[]})}}allData.push(data2)}return allData}return calculateStackDependencies(stacks)}var import_run;var init_list_stacks=__esm({"lib/list-stacks.ts"(){"use strict";import_run=__toESM(require_run());init_cloud_assembly2()}});function validateSnsTopicArn(arn){return/^arn:aws:sns:[a-z0-9\-]+:[0-9]+:[a-z0-9\-\_]+$/i.test(arn)}var init_validate_notification_arn=__esm({"lib/util/validate-notification-arn.ts"(){"use strict"}});async function parallelPromises(n,promises){const ret=new Array;let count=0;let error3;const queue=[...promises];return new Promise((ok,ko)=>{tick();function tick(){if(count===0&&error3){ko(error3);return}if(count===0&&queue.length===0){ok(ret);return}while(count<n&&queue.length>0&&!error3){const next=queue.shift();if(next!==void 0){start(next)}}}function start(fn){count+=1;fn().then(result=>{ret.push(result)}).catch(e=>{error3=e}).finally(()=>{count-=1;tick()})}})}var init_parallel=__esm({"lib/util/parallel.ts"(){"use strict"}});var init_work_graph_types=__esm({"lib/util/work-graph-types.ts"(){"use strict"}});function sum2(xs){let ret=0;for(const x of xs){ret+=x}return ret}function retainOnly(xs,pred){xs.splice(0,xs.length,...xs.filter(pred))}function gv(id,attrs){const attrString=Object.entries(attrs??{}).flatMap(([k,v])=>v!==void 0?[`${k}="${v}"`]:[]).join(",");return attrString?`"${simplifyId(id)}" [${attrString}]`:`"${simplifyId(id)}"`}function simplifyId(id){return id.replace(/([0-9a-f]{6})[0-9a-f]{6,}/g,"$1")}var WorkGraph;var init_work_graph=__esm({"lib/util/work-graph.ts"(){"use strict";init_parallel();init_work_graph_types();init_logging();WorkGraph=class{constructor(nodes={}){this.readyPool=[];this.lazyDependencies=new Map;this.nodes={...nodes}}addNodes(...nodes){for(const node of nodes){if(this.nodes[node.id]){throw new Error(`Duplicate use of node id: ${node.id}`)}const ld=this.lazyDependencies.get(node.id);if(ld){for(const x of ld){node.dependencies.add(x)}this.lazyDependencies.delete(node.id)}this.nodes[node.id]=node}}removeNode(nodeId){const id=typeof nodeId==="string"?nodeId:nodeId.id;const removedNode=this.nodes[id];this.lazyDependencies.delete(id);delete this.nodes[id];if(removedNode){for(const node of Object.values(this.nodes)){node.dependencies.delete(removedNode.id)}}}nodesOfType(type){return Object.values(this.nodes).filter(n=>n.type===type)}dependees(nodeId){const id=typeof nodeId==="string"?nodeId:nodeId.id;return Object.values(this.nodes).filter(n=>n.dependencies.has(id))}addDependency(fromId,toId){const node=this.nodes[fromId];if(node){node.dependencies.add(toId);return}let lazyDeps=this.lazyDependencies.get(fromId);if(!lazyDeps){lazyDeps=[];this.lazyDependencies.set(fromId,lazyDeps)}lazyDeps.push(toId)}tryGetNode(id){return this.nodes[id]}node(id){const ret=this.nodes[id];if(!ret){throw new Error(`No node with id ${id} among ${Object.keys(this.nodes)}`)}return ret}absorb(graph){this.addNodes(...Object.values(graph.nodes))}hasFailed(){return Object.values(this.nodes).some(n=>n.deploymentState==="failed")}doParallel(concurrency,actions){return this.forAllArtifacts(concurrency,async x=>{switch(x.type){case"stack":await actions.deployStack(x);break;case"asset-build":await actions.buildAsset(x);break;case"asset-publish":await actions.publishAsset(x);break}})}ready(){this.updateReadyPool();return this.readyPool}forAllArtifacts(n,fn){const graph=this;const max=typeof n==="number"?{"asset-build":n,"asset-publish":n,"stack":n}:n;const totalMax=typeof n==="number"?n:sum2(Object.values(n));return new Promise((ok,fail)=>{let active={"asset-build":0,"asset-publish":0,"stack":0};function totalActive(){return sum2(Object.values(active))}start();function start(){graph.updateReadyPool();for(let i=0;i<graph.readyPool.length;){const node=graph.readyPool[i];if(active[node.type]<max[node.type]&&totalActive()<totalMax){graph.readyPool.splice(i,1);startOne(node)}else{i+=1}}if(totalActive()===0){if(graph.done()){ok()}if(graph.hasFailed()){fail(graph.error)}}}function startOne(x){x.deploymentState="deploying";active[x.type]++;void fn(x).finally(()=>{active[x.type]--}).then(()=>{graph.deployed(x);start()}).catch(err=>{graph.failed(x,err);start()})}})}done(){return Object.values(this.nodes).every(n=>"completed"===n.deploymentState)}deployed(node){node.deploymentState="completed"}failed(node,error3){this.error=error3;node.deploymentState="failed";this.skipRest();this.readyPool.splice(0)}toString(){return["digraph D {",...Object.entries(this.nodes).flatMap(([id,node])=>renderNode(id,node)),"}"].join("\n");function renderNode(id,node){const ret=[];if(node.deploymentState==="completed"){ret.push(` ${gv(id,{style:"filled",fillcolor:"yellow",comment:node.note})};`)}else{ret.push(` ${gv(id,{comment:node.note})};`)}for(const dep of node.dependencies){ret.push(` ${gv(id)} -> ${gv(dep)};`)}return ret}}removeUnavailableDependencies(){for(const node of Object.values(this.nodes)){const removeDeps=Array.from(node.dependencies).filter(dep=>this.nodes[dep]===void 0);removeDeps.forEach(d=>{node.dependencies.delete(d)})}}async removeUnnecessaryAssets(isUnnecessary){debug("Checking for previously published assets");const publishes=this.nodesOfType("asset-publish");const classifiedNodes=await parallelPromises(8,publishes.map(assetNode=>async()=>[assetNode,await isUnnecessary(assetNode)]));const alreadyPublished=classifiedNodes.filter(([_2,unnecessary])=>unnecessary).map(([assetNode,_2])=>assetNode);for(const assetNode of alreadyPublished){this.removeNode(assetNode)}debug(`${publishes.length} total assets, ${publishes.length-alreadyPublished.length} still need to be published`);const unusedBuilds=this.nodesOfType("asset-build").filter(build=>this.dependees(build).length===0);for(const unusedBuild of unusedBuilds){this.removeNode(unusedBuild)}}updateReadyPool(){const activeCount=Object.values(this.nodes).filter(x=>x.deploymentState==="deploying").length;const pendingCount=Object.values(this.nodes).filter(x=>x.deploymentState==="pending").length;const newlyReady=Object.values(this.nodes).filter(x=>x.deploymentState==="pending"&&Array.from(x.dependencies).every(id=>this.node(id).deploymentState==="completed"));for(const node of newlyReady){node.deploymentState="queued";this.readyPool.push(node)}retainOnly(this.readyPool,node=>node.deploymentState==="queued");this.readyPool.sort((a,b)=>(b.priority??0)-(a.priority??0));if(this.readyPool.length===0&&activeCount===0&&pendingCount>0){const cycle=this.findCycle()??["No cycle found!"];trace(`Cycle ${cycle.join(" -> ")} in graph ${this}`);throw new Error(`Unable to make progress anymore, dependency cycle between remaining artifacts: ${cycle.join(" -> ")} (run with -vv for full graph)`)}}skipRest(){for(const node of Object.values(this.nodes)){if(["queued","pending"].includes(node.deploymentState)){node.deploymentState="skipped"}}}findCycle(){const seen=new Set;const self2=this;for(const nodeId of Object.keys(this.nodes)){const cycle=recurse(nodeId,[nodeId]);if(cycle){return cycle}}return void 0;function recurse(nodeId,path24){if(seen.has(nodeId)){return void 0}try{for(const dep of self2.nodes[nodeId].dependencies??[]){const index=path24.indexOf(dep);if(index>-1){return[...path24.slice(index),dep]}const cycle=recurse(dep,[...path24,dep]);if(cycle){return cycle}}return void 0}finally{seen.add(nodeId)}}}reachable(start,end){const seen=new Set;const self2=this;return recurse(start);function recurse(current){if(seen.has(current)){return false}seen.add(current);if(current===end){return true}for(const dep of self2.nodes[current].dependencies){if(recurse(dep)){return true}}return false}}}}});function stacksFromAssets(artifacts){const ret=new Map;for(const stack of artifacts.filter(cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact)){const assetArtifacts=stack.dependencies.filter(cxapi6.AssetManifestArtifact.isAssetManifestArtifact);for(const art of assetArtifacts){ret.set(art,stack)}}return ret}function onlyStacks(artifacts){return artifacts.filter(cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact)}var cxapi6,import_cdk_assets4,_WorkGraphBuilder,WorkGraphBuilder;var init_work_graph_builder=__esm({"lib/util/work-graph-builder.ts"(){"use strict";cxapi6=__toESM(require_lib3());import_cdk_assets4=__toESM(require_lib11());init_content_hash();init_work_graph();init_work_graph_types();_WorkGraphBuilder=class _WorkGraphBuilder{constructor(prebuildAssets,idPrefix=""){this.prebuildAssets=prebuildAssets;this.idPrefix=idPrefix;this.graph=new WorkGraph}addStack(artifact){this.graph.addNodes({type:"stack",id:`${this.idPrefix}${artifact.id}`,dependencies:new Set(this.stackArtifactIds(onlyStacks(artifact.dependencies))),stack:artifact,deploymentState:"pending",priority:_WorkGraphBuilder.PRIORITIES.stack})}addAsset(parentStack,assetManifestArtifact,assetManifest,asset){const assetId=asset.id.assetId;const buildId=`build-${assetId}-${contentHashAny([assetId,asset.genericSource]).substring(0,10)}`;const publishId=`publish-${assetId}-${contentHashAny([assetId,asset.genericDestination]).substring(0,10)}`;if(!this.graph.tryGetNode(buildId)){const node={type:"asset-build",id:buildId,note:assetId,dependencies:new Set([...this.stackArtifactIds(assetManifestArtifact.dependencies),...!this.prebuildAssets?this.stackArtifactIds(onlyStacks(parentStack.dependencies)):[]]),parentStack,assetManifestArtifact,assetManifest,asset,deploymentState:"pending",priority:_WorkGraphBuilder.PRIORITIES["asset-build"]};this.graph.addNodes(node)}const publishNode=this.graph.tryGetNode(publishId);if(!publishNode){this.graph.addNodes({type:"asset-publish",id:publishId,note:`${asset.id}`,dependencies:new Set([buildId]),parentStack,assetManifestArtifact,assetManifest,asset,deploymentState:"pending",priority:_WorkGraphBuilder.PRIORITIES["asset-publish"]})}for(const inheritedDep of this.stackArtifactIds(onlyStacks(parentStack.dependencies))){this.graph.addDependency(publishId,inheritedDep)}this.graph.addDependency(`${this.idPrefix}${parentStack.id}`,publishId)}build(artifacts){const parentStacks=stacksFromAssets(artifacts);for(const artifact of artifacts){if(cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)){this.addStack(artifact)}else if(cxapi6.AssetManifestArtifact.isAssetManifestArtifact(artifact)){const manifest=import_cdk_assets4.AssetManifest.fromFile(artifact.file);for(const entry of manifest.entries){const parentStack=parentStacks.get(artifact);if(parentStack===void 0){throw new Error("Found an asset manifest that is not associated with a stack")}this.addAsset(parentStack,artifact,manifest,entry)}}else if(cxapi6.NestedCloudAssemblyArtifact.isNestedCloudAssemblyArtifact(artifact)){const assembly=new cxapi6.CloudAssembly(artifact.fullPath,{topoSort:false});const nestedGraph=new _WorkGraphBuilder(this.prebuildAssets,`${this.idPrefix}${artifact.id}.`).build(assembly.artifacts);this.graph.absorb(nestedGraph)}else{}}this.graph.removeUnavailableDependencies();this.removeStackPublishCycles();return this.graph}stackArtifactIds(deps){return deps.flatMap(d=>cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact(d)?[this.stackArtifactId(d)]:[])}stackArtifactId(artifact){if(!cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)){throw new Error(`Can only call this on CloudFormationStackArtifact, got: ${artifact.constructor.name}`)}return`${this.idPrefix}${artifact.id}`}removeStackPublishCycles(){const publishSteps=this.graph.nodesOfType("asset-publish");for(const publishStep of publishSteps){for(const dep of publishStep.dependencies){if(this.graph.reachable(dep,publishStep.id)){publishStep.dependencies.delete(dep)}}}}};_WorkGraphBuilder.PRIORITIES={"asset-build":10,"asset-publish":0,"stack":5};WorkGraphBuilder=_WorkGraphBuilder}});function looksLikeGlob(environment){return environment.indexOf("*")>-1}async function globEnvironmentsFromStacks(stacks,environmentGlobs,sdk){if(environmentGlobs.length===0){return[]}const availableEnvironments=new Array;for(const stack of stacks.stackArtifacts){const actual=await sdk.resolveEnvironment(stack.environment);availableEnvironments.push(actual)}const environments=distinct(availableEnvironments).filter(env2=>environmentGlobs.find(glob2=>minimatch(env2.name,glob2)));if(environments.length===0){const globs=JSON.stringify(environmentGlobs);const envList=availableEnvironments.length>0?availableEnvironments.map(env2=>env2.name).join(", "):"<none>";throw new ToolkitError(`No environments were found when selecting across ${globs} (available: ${envList})`)}return environments}function environmentsFromDescriptors(envSpecs){const ret=new Array;for(const spec of envSpecs){const parts=spec.replace(/^aws:\/\//,"").split("/");if(parts.length!==2){throw new ToolkitError(`Expected environment name in format 'aws://<account>/<region>', got: ${spec}`)}ret.push({name:spec,account:parts[0],region:parts[1]})}return ret}function distinct(envs){const unique={};for(const env2 of envs){const id=`${env2.account||"default"}/${env2.region||"default"}`;if(id in unique){continue}unique[id]=env2}return Object.values(unique)}var init_environments=__esm({"lib/api/cxapp/environments.ts"(){"use strict";init_esm();init_error()}});function printSerializedObject(obj,json){data(serializeStructure(obj,json))}function tagsForStack(stack){return Object.entries(stack.tags).map(([Key,Value])=>({Key,Value}))}function formatTime2(num){return roundPercentage(millisecondsToSeconds(num))}function roundPercentage(num){return Math.round(100*num)/100}function millisecondsToSeconds(num){return num/1e3}function buildParameterMap(parameters){const parameterMap={"*":{}};for(const key in parameters){if(parameters.hasOwnProperty(key)){const[stack,parameter]=key.split(":",2);if(!parameter){parameterMap["*"][stack]=parameters[key]}else{if(!parameterMap[stack]){parameterMap[stack]={}}parameterMap[stack][parameter]=parameters[key]}}}return parameterMap}function obscureTemplate(template={}){if(template.Rules){if(template.Rules.CheckBootstrapVersion){if(Object.keys(template.Rules).length>1){delete template.Rules.CheckBootstrapVersion}else{delete template.Rules}}}return template}async function askUserConfirmation(concurrency,motivation,question){await withCorkedLogging(async()=>{if(!TESTING2&&!process.stdin.isTTY){throw new ToolkitError(`${motivation}, but terminal (TTY) is not attached so we are unable to get a confirmation from the user`)}if(concurrency>1){throw new ToolkitError(`${motivation}, but concurrency is greater than 1 so we are unable to get a confirmation from the user`)}const confirmed=await promptly4.confirm(`${chalk24.cyan(question)} (y/n)?`);if(!confirmed){throw new ToolkitError("Aborted by user")}})}var path23,import_util18,cxapi7,chalk24,chokidar,fs22,promptly4,pLimit3,TESTING2,CdkToolkit;var init_cdk_toolkit=__esm({"lib/cdk-toolkit.ts"(){"use strict";path23=__toESM(require("path"));import_util18=require("util");cxapi7=__toESM(require_lib3());chalk24=__toESM(require_source());chokidar=__toESM(require_chokidar());fs22=__toESM(require_lib4());init_esm();promptly4=__toESM(require_promptly());init_esm_node();init_bootstrap();init_cloud_assembly2();init_garbage_collector();init_common();init_find_cloudwatch_logs();init_logs_monitor();init_cloudformation();init_stack_activity_monitor();init_migrate();init_diff2();init_import();init_list_stacks();init_logging();init_serialize();init_settings();init_error();init_util3();init_validate_notification_arn();init_work_graph_builder();init_environments();pLimit3=require_p_limit2();TESTING2=false;CdkToolkit=class{constructor(props){this.props=props}async metadata(stackName,json){const stacks=await this.selectSingleStackByName(stackName);printSerializedObject(stacks.firstStack.manifest.metadata??{},json)}async acknowledge(noticeId){const acks=this.props.configuration.context.get("acknowledged-issue-numbers")??[];acks.push(Number(noticeId));this.props.configuration.context.set("acknowledged-issue-numbers",acks);await this.props.configuration.saveContext()}async diff(options){const stacks=await this.selectStacksForDiff(options.stackNames,options.exclusively);const strict=!!options.strict;const contextLines=options.contextLines||3;const stream=options.stream||process.stderr;const quiet=options.quiet||false;let diffs=0;const parameterMap=buildParameterMap(options.parameters);if(options.templatePath!==void 0){if(stacks.stackCount!==1){throw new ToolkitError("Can only select one stack when comparing to fixed template. Use --exclusively to avoid selecting multiple stacks.")}if(!await fs22.pathExists(options.templatePath)){throw new ToolkitError(`There is no file at ${options.templatePath}`)}const template=deserializeStructure(await fs22.readFile(options.templatePath,{encoding:"UTF-8"}));diffs=options.securityOnly?numberFromBool(printSecurityDiff(template,stacks.firstStack,"broadening",quiet)):printStackDiff(template,stacks.firstStack,strict,contextLines,quiet,void 0,void 0,false,stream)}else{for(const stack of stacks.stackArtifacts){const templateWithNestedStacks=await this.props.deployments.readCurrentTemplateWithNestedStacks(stack,options.compareAgainstProcessedTemplate);const currentTemplate=templateWithNestedStacks.deployedRootTemplate;const nestedStacks=templateWithNestedStacks.nestedStacks;const resourcesToImport=await this.tryGetResources(await this.props.deployments.resolveEnvironment(stack));if(resourcesToImport){removeNonImportResources(stack)}let changeSet=void 0;if(options.changeSet){let stackExists=false;try{stackExists=await this.props.deployments.stackExists({stack,deployName:stack.stackName,tryLookupRole:true})}catch(e){debug(e.message);if(!quiet){stream.write(`Checking if the stack ${stack.stackName} exists before creating the changeset has failed, will base the diff on template differences (run again with -v to see the reason)
|
|
849
|
-
`)}stackExists=false}if(stackExists){changeSet=await createDiffChangeSet({stack,uuid:v4_default(),deployments:this.props.deployments,willExecute:false,sdkProvider:this.props.sdkProvider,parameters:Object.assign({},parameterMap["*"],parameterMap[stack.stackName]),resourcesToImport,stream})}else{debug(`the stack '${stack.stackName}' has not been deployed to CloudFormation or describeStacks call failed, skipping changeset creation.`)}}const stackCount=options.securityOnly?numberFromBool(printSecurityDiff(currentTemplate,stack,"broadening",quiet,stack.displayName,changeSet)):printStackDiff(currentTemplate,stack,strict,contextLines,quiet,stack.displayName,changeSet,!!resourcesToImport,stream,nestedStacks);diffs+=stackCount}}stream.write((0,import_util18.format)("\n\u2728 Number of stacks with differences: %s\n",diffs));return diffs&&options.fail?1:0}async deploy(options){var _a,_b;if(options.watch){return this.watch(options)}const startSynthTime=new Date().getTime();const stackCollection=await this.selectStacksForDeploy(options.selector,options.exclusively,options.cacheCloudAssembly,options.ignoreNoStacks);const elapsedSynthTime=new Date().getTime()-startSynthTime;print("\n\u2728 Synthesis time: %ss\n",formatTime2(elapsedSynthTime));if(stackCollection.stackCount===0){console.error("This app contains no stacks");return}await this.tryMigrateResources(stackCollection,options);const requireApproval=options.requireApproval??"broadening";const parameterMap=buildParameterMap(options.parameters);if(options.hotswap!=="full-deployment"){warning("\u26A0\uFE0F The --hotswap and --hotswap-fallback flags deliberately introduce CloudFormation drift to speed up deployments");warning("\u26A0\uFE0F They should only be used for development - never use them for your production Stacks!\n")}let hotswapPropertiesFromSettings=this.props.configuration.settings.get(["hotswap"])||{};let hotswapPropertyOverrides=new HotswapPropertyOverrides;hotswapPropertyOverrides.ecsHotswapProperties=new EcsHotswapProperties((_a=hotswapPropertiesFromSettings.ecs)==null?void 0:_a.minimumHealthyPercent,(_b=hotswapPropertiesFromSettings.ecs)==null?void 0:_b.maximumHealthyPercent);const stacks=stackCollection.stackArtifacts;const stackOutputs={};const outputsFile=options.outputsFile;const buildAsset=async assetNode=>{await this.props.deployments.buildSingleAsset(assetNode.assetManifestArtifact,assetNode.assetManifest,assetNode.asset,{stack:assetNode.parentStack,roleArn:options.roleArn,stackName:assetNode.parentStack.stackName})};const publishAsset=async assetNode=>{await this.props.deployments.publishSingleAsset(assetNode.assetManifest,assetNode.asset,{stack:assetNode.parentStack,roleArn:options.roleArn,stackName:assetNode.parentStack.stackName})};const deployStack2=async stackNode=>{const stack=stackNode.stack;if(stackCollection.stackCount!==1){highlight(stack.displayName)}if(!stack.environment){throw new ToolkitError(`Stack ${stack.displayName} does not define an environment, and AWS credentials could not be obtained from standard locations or no region was configured.`)}if(Object.keys(stack.template.Resources||{}).length===0){if(!await this.props.deployments.stackExists({stack})){warning("%s: stack has no resources, skipping deployment.",chalk24.bold(stack.displayName))}else{warning("%s: stack has no resources, deleting existing stack.",chalk24.bold(stack.displayName));await this.destroy({selector:{patterns:[stack.hierarchicalId]},exclusively:true,force:true,roleArn:options.roleArn,fromDeploy:true,ci:options.ci})}return}if(requireApproval!=="never"){const currentTemplate=await this.props.deployments.readCurrentTemplate(stack);if(printSecurityDiff(currentTemplate,stack,requireApproval)){await askUserConfirmation(concurrency,'"--require-approval" is enabled and stack includes security-sensitive updates',"Do you wish to deploy these changes")}}const notificationArns=!!options.notificationArns||!!stack.notificationArns?(options.notificationArns??[]).concat(stack.notificationArns??[]):void 0;for(const notificationArn of notificationArns??[]){if(!validateSnsTopicArn(notificationArn)){throw new ToolkitError(`Notification arn ${notificationArn} is not a valid arn for an SNS topic`)}}const stackIndex=stacks.indexOf(stack)+1;print("%s: deploying... [%s/%s]",chalk24.bold(stack.displayName),stackIndex,stackCollection.stackCount);const startDeployTime=new Date().getTime();let tags=options.tags;if(!tags||tags.length===0){tags=tagsForStack(stack)}let elapsedDeployTime=0;try{let deployResult;let rollback=options.rollback;let iteration=0;while(!deployResult){if(++iteration>2){throw new ToolkitError("This loop should have stabilized in 2 iterations, but didn't. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose")}const r=await this.props.deployments.deployStack({stack,deployName:stack.stackName,roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,reuseAssets:options.reuseAssets,notificationArns,tags,execute:options.execute,changeSetName:options.changeSetName,deploymentMethod:options.deploymentMethod,force:options.force,parameters:Object.assign({},parameterMap["*"],parameterMap[stack.stackName]),usePreviousParameters:options.usePreviousParameters,progress,ci:options.ci,rollback,hotswap:options.hotswap,hotswapPropertyOverrides,extraUserAgent:options.extraUserAgent,assetParallelism:options.assetParallelism,ignoreNoStacks:options.ignoreNoStacks});switch(r.type){case"did-deploy-stack":deployResult=r;break;case"failpaused-need-rollback-first":{const motivation=r.reason==="replacement"?`Stack is in a paused fail state (${r.status}) and change includes a replacement which cannot be deployed with "--no-rollback"`:`Stack is in a paused fail state (${r.status}) and command line arguments do not include "--no-rollback"`;if(options.force){warning(`${motivation}. Rolling back first (--force).`)}else{await askUserConfirmation(concurrency,motivation,`${motivation}. Roll back first and then proceed with deployment`)}await this.rollback({selector:{patterns:[stack.hierarchicalId]},toolkitStackName:options.toolkitStackName,force:options.force});rollback=true;break}case"replacement-requires-rollback":{const motivation='Change includes a replacement which cannot be deployed with "--no-rollback"';if(options.force){warning(`${motivation}. Proceeding with regular deployment (--force).`)}else{await askUserConfirmation(concurrency,motivation,`${motivation}. Perform a regular deployment`)}rollback=true;break}default:throw new ToolkitError(`Unexpected result type from deployStack: ${JSON.stringify(r)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose`)}}const message=deployResult.noOp?" \u2705 %s (no changes)":" \u2705 %s";success("\n"+message,stack.displayName);elapsedDeployTime=new Date().getTime()-startDeployTime;print("\n\u2728 Deployment time: %ss\n",formatTime2(elapsedDeployTime));if(Object.keys(deployResult.outputs).length>0){print("Outputs:");stackOutputs[stack.stackName]=deployResult.outputs}for(const name of Object.keys(deployResult.outputs).sort()){const value=deployResult.outputs[name];print("%s.%s = %s",chalk24.cyan(stack.id),chalk24.cyan(name),chalk24.underline(chalk24.cyan(value)))}print("Stack ARN:");data(deployResult.stackArn)}catch(e){throw new ToolkitError([`\u274C ${chalk24.bold(stack.stackName)} failed:`,...e.name?[`${e.name}:`]:[],e.message].join(" "))}finally{if(options.cloudWatchLogMonitor){const foundLogGroupsResult=await findCloudWatchLogGroups(this.props.sdkProvider,stack);options.cloudWatchLogMonitor.addLogGroups(foundLogGroupsResult.env,foundLogGroupsResult.sdk,foundLogGroupsResult.logGroupNames)}if(outputsFile){fs22.ensureFileSync(outputsFile);await fs22.writeJson(outputsFile,stackOutputs,{spaces:2,encoding:"utf8"})}}print("\n\u2728 Total time: %ss\n",formatTime2(elapsedSynthTime+elapsedDeployTime))};const assetBuildTime=options.assetBuildTime??0;const prebuildAssets=assetBuildTime===0;const concurrency=options.concurrency||1;const progress=concurrency>1?"events":options.progress;if(concurrency>1&&options.progress&&options.progress!="events"){warning('\u26A0\uFE0F The --concurrency flag only supports --progress "events". Switching to "events".')}const stacksAndTheirAssetManifests=stacks.flatMap(stack=>[stack,...stack.dependencies.filter(cxapi7.AssetManifestArtifact.isAssetManifestArtifact)]);const workGraph=new WorkGraphBuilder(prebuildAssets).build(stacksAndTheirAssetManifests);if(!options.force){await this.removePublishedAssets(workGraph,options)}const graphConcurrency={"stack":concurrency,"asset-build":1,"asset-publish":options.assetParallelism??true?8:1};await workGraph.doParallel(graphConcurrency,{deployStack:deployStack2,buildAsset,publishAsset})}async rollback(options){const startSynthTime=new Date().getTime();const stackCollection=await this.selectStacksForDeploy(options.selector,true);const elapsedSynthTime=new Date().getTime()-startSynthTime;print("\n\u2728 Synthesis time: %ss\n",formatTime2(elapsedSynthTime));if(stackCollection.stackCount===0){console.error("No stacks selected");return}let anyRollbackable=false;for(const stack of stackCollection.stackArtifacts){print("Rolling back %s",chalk24.bold(stack.displayName));const startRollbackTime=new Date().getTime();try{const result=await this.props.deployments.rollbackStack({stack,roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,force:options.force,validateBootstrapStackVersion:options.validateBootstrapStackVersion,orphanLogicalIds:options.orphanLogicalIds});if(!result.notInRollbackableState){anyRollbackable=true}const elapsedRollbackTime=new Date().getTime()-startRollbackTime;print("\n\u2728 Rollback time: %ss\n",formatTime2(elapsedRollbackTime))}catch(e){error("\n \u274C %s failed: %s",chalk24.bold(stack.displayName),e.message);throw new ToolkitError("Rollback failed (use --force to orphan failing resources)")}}if(!anyRollbackable){throw new ToolkitError("No stacks were in a state that could be rolled back")}}async watch(options){const rootDir2=path23.dirname(path23.resolve(PROJECT_CONFIG));debug("root directory used for 'watch' is: %s",rootDir2);const watchSettings=this.props.configuration.settings.get(["watch"]);if(!watchSettings){throw new ToolkitError(`Cannot use the 'watch' command without specifying at least one directory to monitor. Make sure to add a "watch" key to your cdk.json`)}const watchIncludes=this.patternsArrayForWatch(watchSettings.include,{rootDir:rootDir2,returnRootDirIfEmpty:true});debug("'include' patterns for 'watch': %s",watchIncludes);const outputDir=this.props.configuration.settings.get(["output"]);const watchExcludes=this.patternsArrayForWatch(watchSettings.exclude,{rootDir:rootDir2,returnRootDirIfEmpty:false}).concat(`${outputDir}/**`,"**/.*","**/.*/**","**/node_modules/**");debug("'exclude' patterns for 'watch': %s",watchExcludes);let latch="pre-ready";const cloudWatchLogMonitor=options.traceLogs?new CloudWatchLogEventMonitor:void 0;const deployAndWatch=async()=>{latch="deploying";cloudWatchLogMonitor==null?void 0:cloudWatchLogMonitor.deactivate();await this.invokeDeployFromWatch(options,cloudWatchLogMonitor);while(latch==="queued"){latch="deploying";print("Detected file changes during deployment. Invoking 'cdk deploy' again");await this.invokeDeployFromWatch(options,cloudWatchLogMonitor)}latch="open";cloudWatchLogMonitor==null?void 0:cloudWatchLogMonitor.activate()};chokidar.watch(watchIncludes,{ignored:watchExcludes,cwd:rootDir2}).on("ready",async()=>{latch="open";debug("'watch' received the 'ready' event. From now on, all file changes will trigger a deployment");print("Triggering initial 'cdk deploy'");await deployAndWatch()}).on("all",async(event,filePath)=>{if(latch==="pre-ready"){print(`'watch' is observing ${event==="addDir"?"directory":"the file"} '%s' for changes`,filePath)}else if(latch==="open"){print("Detected change to '%s' (type: %s). Triggering 'cdk deploy'",filePath,event);await deployAndWatch()}else{latch="queued";print("Detected change to '%s' (type: %s) while 'cdk deploy' is still running. Will queue for another deployment after this one finishes",filePath,event)}})}async import(options){const stacks=await this.selectStacksForDeploy(options.selector,true,true,false);if(stacks.stackCount>1){throw new ToolkitError(`Stack selection is ambiguous, please choose a specific stack for import [${stacks.stackArtifacts.map(x=>x.id).join(", ")}]`)}if(!process.stdout.isTTY&&!options.resourceMappingFile){throw new ToolkitError("--resource-mapping is required when input is not a terminal")}const stack=stacks.stackArtifacts[0];highlight(stack.displayName);const resourceImporter=new ResourceImporter(stack,this.props.deployments);const{additions,hasNonAdditions}=await resourceImporter.discoverImportableResources(options.force);if(additions.length===0){warning("%s: no new resources compared to the currently deployed stack, skipping import.",chalk24.bold(stack.displayName));return}const actualImport=!options.resourceMappingFile?await resourceImporter.askForResourceIdentifiers(additions):await resourceImporter.loadResourceIdentifiers(additions,options.resourceMappingFile);if(actualImport.importResources.length===0){warning("No resources selected for import.");return}if(options.recordResourceMapping){const outputFile=options.recordResourceMapping;fs22.ensureFileSync(outputFile);await fs22.writeJson(outputFile,actualImport.resourceMap,{spaces:2,encoding:"utf8"});print("%s: mapping file written.",outputFile);return}print("%s: importing resources into stack...",chalk24.bold(stack.displayName));const tags=tagsForStack(stack);await resourceImporter.importResourcesFromMap(actualImport,{roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,tags,deploymentMethod:options.deploymentMethod,usePreviousParameters:true,progress:options.progress,rollback:options.rollback});print(`Import operation complete. We recommend you run a ${chalk24.blueBright("drift detection")} operation to confirm your CDK app resource definitions are up-to-date. Read more here: `+chalk24.underline.blueBright("https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/detect-drift-stack.html"));if(actualImport.importResources.length<additions.length){print("");warning(`Some resources were skipped. Run another ${chalk24.blueBright("cdk import")} or a ${chalk24.blueBright("cdk deploy")} to bring the stack up-to-date with your CDK app definition.`)}else if(hasNonAdditions){print("");warning(`Your app has pending updates or deletes excluded from this import operation. Run a ${chalk24.blueBright("cdk deploy")} to bring the stack up-to-date with your CDK app definition.`)}}async destroy(options){let stacks=await this.selectStacksForDestroy(options.selector,options.exclusively);await this.suggestStacks({selector:options.selector,stacks,exclusively:options.exclusively});if(stacks.stackArtifacts.length===0){warning(`No stacks match the name(s): ${chalk24.red(options.selector.patterns.join(", "))}`);return}stacks=stacks.reversed();if(!options.force){const confirmed=await promptly4.confirm(`Are you sure you want to delete: ${chalk24.blue(stacks.stackArtifacts.map(s=>s.hierarchicalId).join(", "))} (y/n)?`);if(!confirmed){return}}const action=options.fromDeploy?"deploy":"destroy";for(const[index,stack]of stacks.stackArtifacts.entries()){success("%s: destroying... [%s/%s]",chalk24.blue(stack.displayName),index+1,stacks.stackCount);try{await this.props.deployments.destroyStack({stack,deployName:stack.stackName,roleArn:options.roleArn,ci:options.ci});success(`
|
|
848
|
+
(${error3.message})`)}throw error3}}async function prepareDefaultEnvironment(aws){var _a;const env2={};env2[cxapi5.DEFAULT_REGION_ENV]=aws.defaultRegion;debug(`Setting "${cxapi5.DEFAULT_REGION_ENV}" environment variable to`,env2[cxapi5.DEFAULT_REGION_ENV]);const accountId=(_a=await aws.defaultAccount())==null?void 0:_a.accountId;if(accountId){env2[cxapi5.DEFAULT_ACCOUNT_ENV]=accountId;debug(`Setting "${cxapi5.DEFAULT_ACCOUNT_ENV}" environment variable to`,env2[cxapi5.DEFAULT_ACCOUNT_ENV])}return env2}async function prepareContext(config,env2){const context=config.context.all;const debugMode=config.settings.get(["debug"])??true;if(debugMode){env2.CDK_DEBUG="true"}const pathMetadata=config.settings.get(["pathMetadata"])??true;if(pathMetadata){context[cxapi5.PATH_METADATA_ENABLE_CONTEXT]=true}const assetMetadata=config.settings.get(["assetMetadata"])??true;if(assetMetadata){context[cxapi5.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT]=true}const versionReporting=config.settings.get(["versionReporting"])??true;if(versionReporting){context[cxapi5.ANALYTICS_REPORTING_ENABLED_CONTEXT]=true}if(!versionReporting){context["aws:cdk:disable-version-reporting"]=true}const stagingEnabled=config.settings.get(["staging"])??true;if(!stagingEnabled){context[cxapi5.DISABLE_ASSET_STAGING_CONTEXT]=true}const bundlingStacks=config.settings.get(["bundlingStacks"])??["**"];context[cxapi5.BUNDLING_STACKS]=bundlingStacks;debug("context:",context);return context}function appToArray(app){return typeof app==="string"?app.split(" "):app}function executeNode(scriptFile){return[process.execPath,scriptFile]}async function guessExecutable(commandLine){if(commandLine.length===1){let fstat;try{fstat=await fs17.stat(commandLine[0])}catch{debug(`Not a file: '${commandLine[0]}'. Using '${commandLine}' as command-line`);return commandLine}const isExecutable=(fstat.mode&fs17.constants.X_OK)!==0;const isWindows=process.platform==="win32";const handler=EXTENSION_MAP.get(path18.extname(commandLine[0]));if(handler&&(!isExecutable||isWindows)){return handler(commandLine[0])}}return commandLine}function contextOverflowCleanup(location,assembly){if(location){fs17.removeSync(path18.dirname(location));const tree=loadTree(assembly);const frameworkDoesNotSupportContextOverflow=some(tree,node=>{var _a,_b;const fqn=(_a=node.constructInfo)==null?void 0:_a.fqn;const version10=(_b=node.constructInfo)==null?void 0:_b.version;return fqn==="aws-cdk-lib.App"&&version10!=null&&semver5.lte(version10,"2.38.0")||fqn==="@aws-cdk/core.App"});if(frameworkDoesNotSupportContextOverflow){warning("Part of the context could not be sent to the application. Please update the AWS CDK library to the latest version.")}}}function spaceAvailableForContext(env2,limit){const size=value=>value!=null?Buffer.byteLength(value):0;const usedSpace=Object.entries(env2).map(([k,v])=>k===cxapi5.CONTEXT_ENV?size(k):size(k)+size(v)).reduce((a,b)=>a+b,0);return Math.max(0,limit-usedSpace)}var childProcess,os7,path18,cxschema8,cxapi5,fs17,semver5,EXTENSION_MAP;var init_exec=__esm({"lib/api/cxapp/exec.ts"(){"use strict";childProcess=__toESM(require("child_process"));os7=__toESM(require("os"));path18=__toESM(require("path"));cxschema8=__toESM(require_lib2());cxapi5=__toESM(require_lib3());fs17=__toESM(require_lib4());semver5=__toESM(require_semver4());init_logging();init_settings();init_error();init_tree();init_objects();init_version4();init_rwlock();EXTENSION_MAP=new Map([[".js",executeNode]])}});var EnvironmentAccess;var init_environment_access=__esm({"lib/api/environment-access.ts"(){"use strict";init_logging();init_environment_resources();init_mode();init_placeholders2();EnvironmentAccess=class{constructor(sdkProvider,toolkitStackName){this.sdkProvider=sdkProvider;this.sdkCache=new Map;this.environmentResources=new EnvironmentResourcesRegistry(toolkitStackName)}async resolveStackEnvironment(stack){return this.sdkProvider.resolveEnvironment(stack.environment)}async accessStackForReadOnlyStackOperations(stack){return this.accessStackForStackOperations(stack,0)}async accessStackForMutableStackOperations(stack){return this.accessStackForStackOperations(stack,1)}async accessStackForLookup(stack){var _a,_b,_c,_d,_e;if(!stack.environment){throw new Error(`The stack ${stack.displayName} does not have an environment`)}const lookupEnv=await this.prepareSdk({environment:stack.environment,mode:0,assumeRoleArn:(_a=stack.lookupRole)==null?void 0:_a.arn,assumeRoleExternalId:(_b=stack.lookupRole)==null?void 0:_b.assumeRoleExternalId,assumeRoleAdditionalOptions:(_c=stack.lookupRole)==null?void 0:_c.assumeRoleAdditionalOptions});if(lookupEnv.didAssumeRole&&((_d=stack.lookupRole)==null?void 0:_d.bootstrapStackVersionSsmParameter)&&stack.lookupRole.requiresBootstrapStackVersion){const version10=await lookupEnv.resources.versionFromSsmParameter(stack.lookupRole.bootstrapStackVersionSsmParameter);if(version10<stack.lookupRole.requiresBootstrapStackVersion){throw new Error(`Bootstrap stack version '${stack.lookupRole.requiresBootstrapStackVersion}' is required, found version '${version10}'. To get rid of this error, please upgrade to bootstrap version >= ${stack.lookupRole.requiresBootstrapStackVersion}`)}}if(lookupEnv.isFallbackCredentials){const arn=await lookupEnv.replacePlaceholders((_e=stack.lookupRole)==null?void 0:_e.arn);warning(`Lookup role ${arn} was not assumed. Proceeding with default credentials.`)}return lookupEnv}async accessStackForLookupBestEffort(stack){if(!stack.environment){throw new Error(`The stack ${stack.displayName} does not have an environment`)}try{return await this.accessStackForLookup(stack)}catch(e){warning(`${e.message}`)}return this.accessStackForStackOperations(stack,0)}async accessStackForStackOperations(stack,mode){if(!stack.environment){throw new Error(`The stack ${stack.displayName} does not have an environment`)}return this.prepareSdk({environment:stack.environment,mode,assumeRoleArn:stack.assumeRoleArn,assumeRoleExternalId:stack.assumeRoleExternalId,assumeRoleAdditionalOptions:stack.assumeRoleAdditionalOptions})}async prepareSdk(options){const resolvedEnvironment=await this.sdkProvider.resolveEnvironment(options.environment);const{assumeRoleArn}=await replaceEnvPlaceholders({assumeRoleArn:options.assumeRoleArn},resolvedEnvironment,this.sdkProvider);const stackSdk=await this.cachedSdkForEnvironment(resolvedEnvironment,options.mode,{assumeRoleArn,assumeRoleExternalId:options.assumeRoleExternalId,assumeRoleAdditionalOptions:options.assumeRoleAdditionalOptions});return{sdk:stackSdk.sdk,resolvedEnvironment,resources:this.environmentResources.for(resolvedEnvironment,stackSdk.sdk),isFallbackCredentials:!stackSdk.didAssumeRole&&!!assumeRoleArn,didAssumeRole:stackSdk.didAssumeRole,replacePlaceholders:async str=>{const ret=await replaceEnvPlaceholders({str},resolvedEnvironment,this.sdkProvider);return ret.str}}}async cachedSdkForEnvironment(environment,mode,options){const cacheKeyElements=[environment.account,environment.region,`${mode}`,(options==null?void 0:options.assumeRoleArn)??"",(options==null?void 0:options.assumeRoleExternalId)??""];if(options==null?void 0:options.assumeRoleAdditionalOptions){cacheKeyElements.push(JSON.stringify(options.assumeRoleAdditionalOptions))}const cacheKey=cacheKeyElements.join(":");const existing=this.sdkCache.get(cacheKey);if(existing){return existing}const ret=await this.sdkProvider.forEnvironment(environment,mode,options);this.sdkCache.set(cacheKey,ret);return ret}}}});function suffixWithErrors2(msg,errors){return errors&&errors.length>0?`${msg}: ${errors.join(", ")}`:msg}var import_crypto38,cdk_assets2,import_cdk_assets3,chalk17,BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,Deployments,ParallelSafeAssetProgress;var init_deployments=__esm({"lib/api/deployments.ts"(){"use strict";import_crypto38=require("crypto");cdk_assets2=__toESM(require_lib11());import_cdk_assets3=__toESM(require_lib11());chalk17=__toESM(require_source());init_deploy_stack();init_logging();init_environment_access();init_nested_stack_helpers();init_toolkit_info();init_checks();init_cloudformation();init_stack_activity_monitor();init_stack_event_poller();init_stack_status();init_template_body_parameter();init_asset_manifest_builder();init_asset_publishing();BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK=23;Deployments=class{constructor(props){this.props=props;this.publisherCache=new Map;this.assetSdkProvider=props.sdkProvider;this.deployStackSdkProvider=props.sdkProvider;this.envs=new EnvironmentAccess(props.sdkProvider,props.toolkitStackName??DEFAULT_TOOLKIT_STACK_NAME)}async resolveEnvironment(stack){return this.envs.resolveStackEnvironment(stack)}async readCurrentTemplateWithNestedStacks(rootStackArtifact,retrieveProcessedTemplate=false){const env2=await this.envs.accessStackForLookupBestEffort(rootStackArtifact);return loadCurrentTemplateWithNestedStacks(rootStackArtifact,env2.sdk,retrieveProcessedTemplate)}async readCurrentTemplate(stackArtifact){debug(`Reading existing template for stack ${stackArtifact.displayName}.`);const env2=await this.envs.accessStackForLookupBestEffort(stackArtifact);return loadCurrentTemplate(stackArtifact,env2.sdk)}async resourceIdentifierSummaries(stackArtifact){debug(`Retrieving template summary for stack ${stackArtifact.displayName}.`);const env2=await this.envs.accessStackForReadOnlyStackOperations(stackArtifact);const cfn=env2.sdk.cloudFormation();await uploadStackTemplateAssets(stackArtifact,this);const builder=new AssetManifestBuilder;const cfnParam=await makeBodyParameter(stackArtifact,env2.resolvedEnvironment,builder,env2.resources);const addedAssets=builder.toManifest(stackArtifact.assembly.directory);for(const entry of addedAssets.entries){await this.buildSingleAsset("no-version-validation",addedAssets,entry,{stack:stackArtifact});await this.publishSingleAsset(addedAssets,entry,{stack:stackArtifact})}const response=await cfn.getTemplateSummary(cfnParam);if(!response.ResourceIdentifierSummaries){debug('GetTemplateSummary API call did not return "ResourceIdentifierSummaries"')}return response.ResourceIdentifierSummaries??[]}async deployStack(options){let deploymentMethod=options.deploymentMethod;if(options.changeSetName||options.execute!==void 0){if(deploymentMethod){throw new Error("You cannot supply both 'deploymentMethod' and 'changeSetName/execute'. Supply one or the other.")}deploymentMethod={method:"change-set",changeSetName:options.changeSetName,execute:options.execute}}const env2=await this.envs.accessStackForMutableStackOperations(options.stack);await this.validateBootstrapStackVersion(options.stack.stackName,options.stack.requiresBootstrapStackVersion,options.stack.bootstrapStackVersionSsmParameter,env2.resources);const executionRoleArn=await env2.replacePlaceholders(options.roleArn??options.stack.cloudFormationExecutionRoleArn);return deployStack({stack:options.stack,resolvedEnvironment:env2.resolvedEnvironment,deployName:options.deployName,notificationArns:options.notificationArns,quiet:options.quiet,sdk:env2.sdk,sdkProvider:this.deployStackSdkProvider,roleArn:executionRoleArn,reuseAssets:options.reuseAssets,envResources:env2.resources,tags:options.tags,deploymentMethod,force:options.force,parameters:options.parameters,usePreviousParameters:options.usePreviousParameters,progress:options.progress,ci:options.ci,rollback:options.rollback,hotswap:options.hotswap,hotswapPropertyOverrides:options.hotswapPropertyOverrides,extraUserAgent:options.extraUserAgent,resourcesToImport:options.resourcesToImport,overrideTemplate:options.overrideTemplate,assetParallelism:options.assetParallelism})}async rollbackStack(options){var _a;let resourcesToSkip=options.orphanLogicalIds??[];if(options.force&&resourcesToSkip.length>0){throw new Error("Cannot combine --force with --orphan")}const env2=await this.envs.accessStackForMutableStackOperations(options.stack);if(options.validateBootstrapStackVersion??true){await this.validateBootstrapStackVersion(options.stack.stackName,BOOTSTRAP_STACK_VERSION_FOR_ROLLBACK,options.stack.bootstrapStackVersionSsmParameter,env2.resources)}const cfn=env2.sdk.cloudFormation();const deployName=options.stack.stackName;let maxLoops=10;while(maxLoops--){let cloudFormationStack=await CloudFormationStack.lookup(cfn,deployName);const executionRoleArn=await env2.replacePlaceholders(options.roleArn??options.stack.cloudFormationExecutionRoleArn);switch(cloudFormationStack.stackStatus.rollbackChoice){case 3:warning(`Stack ${deployName} does not need a rollback: ${cloudFormationStack.stackStatus}`);return{notInRollbackableState:true};case 0:debug(`Initiating rollback of stack ${deployName}`);await cfn.rollbackStack({StackName:deployName,RoleARN:executionRoleArn,ClientRequestToken:(0,import_crypto38.randomUUID)(),RetainExceptOnCreate:true});break;case 1:if(options.force){const poller=new StackEventPoller(cfn,{stackName:deployName,stackStatuses:["ROLLBACK_IN_PROGRESS","UPDATE_ROLLBACK_IN_PROGRESS"]});await poller.poll();resourcesToSkip=poller.resourceErrors.filter(r=>!r.isStackEvent&&r.parentStackLogicalIds.length===0).map(r=>r.event.LogicalResourceId??"")}const skipDescription=resourcesToSkip.length>0?` (orphaning: ${resourcesToSkip.join(", ")})`:"";warning(`Continuing rollback of stack ${deployName}${skipDescription}`);await cfn.continueUpdateRollback({StackName:deployName,ClientRequestToken:(0,import_crypto38.randomUUID)(),RoleARN:executionRoleArn,ResourcesToSkip:resourcesToSkip});break;case 2:warning(`Stack ${deployName} failed creation and rollback. This state cannot be rolled back. You can recreate this stack by running 'cdk deploy'.`);return{notInRollbackableState:true};default:throw new Error(`Unexpected rollback choice: ${cloudFormationStack.stackStatus.rollbackChoice}`)}const monitor=options.quiet?void 0:StackActivityMonitor.withDefaultPrinter(cfn,deployName,options.stack,{ci:options.ci}).start();let stackErrorMessage=void 0;let finalStackState=cloudFormationStack;try{const successStack=await stabilizeStack(cfn,deployName);if(!successStack){throw new Error("Stack deploy failed (the stack disappeared while we were rolling it back)")}finalStackState=successStack;const errors=(_a=monitor==null?void 0:monitor.errors)==null?void 0:_a.join(", ");if(errors){stackErrorMessage=errors}}catch(e){stackErrorMessage=suffixWithErrors2(e.message,monitor==null?void 0:monitor.errors)}finally{await(monitor==null?void 0:monitor.stop())}if(finalStackState.stackStatus.isRollbackSuccess||!stackErrorMessage){return{success:true}}if(finalStackState.stackStatus.rollbackChoice===1&&options.force){continue}throw new Error(`${stackErrorMessage} (fix problem and retry, or orphan these resources using --orphan or --force)`)}throw new Error("Rollback did not finish after a large number of iterations; stopping because it looks like we're not making progress anymore. You can retry if rollback was progressing as expected.")}async destroyStack(options){const env2=await this.envs.accessStackForMutableStackOperations(options.stack);const executionRoleArn=await env2.replacePlaceholders(options.roleArn??options.stack.cloudFormationExecutionRoleArn);return destroyStack({sdk:env2.sdk,roleArn:executionRoleArn,stack:options.stack,deployName:options.deployName,quiet:options.quiet,ci:options.ci})}async stackExists(options){let env2;if(options.tryLookupRole){env2=await this.envs.accessStackForLookupBestEffort(options.stack)}else{env2=await this.envs.accessStackForReadOnlyStackOperations(options.stack)}const stack=await CloudFormationStack.lookup(env2.sdk.cloudFormation(),options.deployName??options.stack.stackName);return stack.exists}async prepareAndValidateAssets(asset,options){const env2=await this.envs.accessStackForMutableStackOperations(options.stack);await this.validateBootstrapStackVersion(options.stack.stackName,asset.requiresBootstrapStackVersion,asset.bootstrapStackVersionSsmParameter,env2.resources);const manifest=import_cdk_assets3.AssetManifest.fromFile(asset.file);return{manifest,stackEnv:env2.resolvedEnvironment}}async buildAssets(asset,options){const{manifest,stackEnv}=await this.prepareAndValidateAssets(asset,options);await buildAssets(manifest,this.assetSdkProvider,stackEnv,options.buildOptions)}async publishAssets(asset,options){const{manifest,stackEnv}=await this.prepareAndValidateAssets(asset,options);await publishAssets(manifest,this.assetSdkProvider,stackEnv,{...options.publishOptions,allowCrossAccount:await this.allowCrossAccountAssetPublishingForEnv(options.stack)})}async buildSingleAsset(assetArtifact,assetManifest,asset,options){if(assetArtifact!=="no-version-validation"){const env2=await this.envs.accessStackForReadOnlyStackOperations(options.stack);await this.validateBootstrapStackVersion(options.stack.stackName,assetArtifact.requiresBootstrapStackVersion,assetArtifact.bootstrapStackVersionSsmParameter,env2.resources)}const resolvedEnvironment=await this.envs.resolveStackEnvironment(options.stack);const publisher=this.cachedPublisher(assetManifest,resolvedEnvironment,options.stackName);await publisher.buildEntry(asset);if(publisher.hasFailures){throw new Error(`Failed to build asset ${asset.id}`)}}async publishSingleAsset(assetManifest,asset,options){const stackEnv=await this.envs.resolveStackEnvironment(options.stack);const publisher=this.cachedPublisher(assetManifest,stackEnv,options.stackName);await publisher.publishEntry(asset,{allowCrossAccount:await this.allowCrossAccountAssetPublishingForEnv(options.stack)});if(publisher.hasFailures){throw new Error(`Failed to publish asset ${asset.id}`)}}async allowCrossAccountAssetPublishingForEnv(stack){if(this._allowCrossAccountAssetPublishing===void 0){const env2=await this.envs.accessStackForReadOnlyStackOperations(stack);this._allowCrossAccountAssetPublishing=await determineAllowCrossAccountAssetPublishing(env2.sdk,this.props.toolkitStackName)}return this._allowCrossAccountAssetPublishing}async isSingleAssetPublished(assetManifest,asset,options){const stackEnv=await this.envs.resolveStackEnvironment(options.stack);const publisher=this.cachedPublisher(assetManifest,stackEnv,options.stackName);return publisher.isEntryPublished(asset)}async validateBootstrapStackVersion(stackName,requiresBootstrapStackVersion,bootstrapStackVersionSsmParameter,envResources){try{await envResources.validateVersion(requiresBootstrapStackVersion,bootstrapStackVersionSsmParameter)}catch(e){throw new Error(`${stackName}: ${e.message}`)}}cachedPublisher(assetManifest,env2,stackName){const existing=this.publisherCache.get(assetManifest);if(existing){return existing}const prefix=stackName?`${chalk17.bold(stackName)}: `:"";const publisher=new cdk_assets2.AssetPublishing(assetManifest,{aws:new PublishingAws(this.assetSdkProvider,env2),progressListener:new ParallelSafeAssetProgress(prefix,this.props.quiet??false)});this.publisherCache.set(assetManifest,publisher);return publisher}};ParallelSafeAssetProgress=class{constructor(prefix,quiet){this.prefix=prefix;this.quiet=quiet}onPublishEvent(type,event){const handler=this.quiet&&type!=="fail"?debug:EVENT_TO_LOGGER[type];handler(`${this.prefix}${type}: ${event.message}`)}}}});var require_constants8=__commonJS({"../../node_modules/picomatch/lib/constants.js"(exports2,module2){"use strict";var path24=require("path");var WIN_SLASH="\\\\/";var WIN_NO_SLASH=`[^${WIN_SLASH}]`;var DOT_LITERAL="\\.";var PLUS_LITERAL="\\+";var QMARK_LITERAL="\\?";var SLASH_LITERAL="\\/";var ONE_CHAR="(?=.)";var QMARK="[^/]";var END_ANCHOR=`(?:${SLASH_LITERAL}|$)`;var START_ANCHOR=`(?:^|${SLASH_LITERAL})`;var DOTS_SLASH=`${DOT_LITERAL}{1,2}${END_ANCHOR}`;var NO_DOT=`(?!${DOT_LITERAL})`;var NO_DOTS=`(?!${START_ANCHOR}${DOTS_SLASH})`;var NO_DOT_SLASH=`(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;var NO_DOTS_SLASH=`(?!${DOTS_SLASH})`;var QMARK_NO_DOT=`[^.${SLASH_LITERAL}]`;var STAR=`${QMARK}*?`;var POSIX_CHARS={DOT_LITERAL,PLUS_LITERAL,QMARK_LITERAL,SLASH_LITERAL,ONE_CHAR,QMARK,END_ANCHOR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK_NO_DOT,STAR,START_ANCHOR};var WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:`[${WIN_SLASH}]`,QMARK:WIN_NO_SLASH,STAR:`${WIN_NO_SLASH}*?`,DOTS_SLASH:`${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,NO_DOT:`(?!${DOT_LITERAL})`,NO_DOTS:`(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,NO_DOT_SLASH:`(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,NO_DOTS_SLASH:`(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,QMARK_NO_DOT:`[^.${WIN_SLASH}]`,START_ANCHOR:`(?:^|[${WIN_SLASH}])`,END_ANCHOR:`(?:[${WIN_SLASH}]|$)`};var POSIX_REGEX_SOURCE={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module2.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:path24.sep,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win32){return win32===true?WINDOWS_CHARS:POSIX_CHARS}}}});var require_utils6=__commonJS({"../../node_modules/picomatch/lib/utils.js"(exports2){"use strict";var path24=require("path");var win32=process.platform==="win32";var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants8();exports2.isObject=val2=>val2!==null&&typeof val2==="object"&&!Array.isArray(val2);exports2.hasRegexChars=str=>REGEX_SPECIAL_CHARS.test(str);exports2.isRegexChar=str=>str.length===1&&exports2.hasRegexChars(str);exports2.escapeRegex=str=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports2.toPosixSlashes=str=>str.replace(REGEX_BACKSLASH,"/");exports2.removeBackslashes=str=>{return str.replace(REGEX_REMOVE_BACKSLASH,match2=>{return match2==="\\"?"":match2})};exports2.supportsLookbehinds=()=>{const segs=process.version.slice(1).split(".").map(Number);if(segs.length===3&&segs[0]>=9||segs[0]===8&&segs[1]>=10){return true}return false};exports2.isWindows=options=>{if(options&&typeof options.windows==="boolean"){return options.windows}return win32===true||path24.sep==="\\"};exports2.escapeLast=(input,char,lastIdx)=>{const idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports2.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports2.removePrefix=(input,state6={})=>{let output=input;if(output.startsWith("./")){output=output.slice(2);state6.prefix="./"}return output};exports2.wrapOutput=(input,state6={},options={})=>{const prepend=options.contains?"":"^";const append=options.contains?"":"$";let output=`${prepend}(?:${input})${append}`;if(state6.negated===true){output=`(?:^(?!${output}).*$)`}return output}}});var require_scan2=__commonJS({"../../node_modules/picomatch/lib/scan.js"(exports2,module2){"use strict";var utils=require_utils6();var{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants8();var isPathSeparator=code=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH};var depth=token=>{if(token.isPrefix!==true){token.depth=token.isGlobstar?Infinity:1}};var scan=(input,options)=>{const opts=options||{};const length=input.length-1;const scanToEnd=opts.parts===true||opts.scanToEnd===true;const slashes=[];const tokens=[];const parts=[];let str=input;let index=-1;let start=0;let lastIndex=0;let isBrace=false;let isBracket=false;let isGlob=false;let isExtglob=false;let isGlobstar=false;let braceEscaped=false;let backslashes=false;let negated=false;let negatedExtglob=false;let finished=false;let braces=0;let prev;let code;let token={value:"",depth:0,isGlob:false};const eos=()=>index>=length;const peek=()=>str.charCodeAt(index+1);const advance=()=>{prev=code;return str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;code=advance();if(code===CHAR_LEFT_CURLY_BRACE){braceEscaped=true}continue}if(braceEscaped===true||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==true&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==true&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){isBrace=token.isBrace=true;isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(braceEscaped!==true&&code===CHAR_COMMA){isBrace=token.isBrace=true;isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(code===CHAR_RIGHT_CURLY_BRACE){braces--;if(braces===0){braceEscaped=false;isBrace=token.isBrace=true;finished=true;break}}}if(scanToEnd===true){continue}break}if(code===CHAR_FORWARD_SLASH){slashes.push(index);tokens.push(token);token={value:"",depth:0,isGlob:false};if(finished===true)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==true){const isExtglobChar=code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK;if(isExtglobChar===true&&peek()===CHAR_LEFT_PARENTHESES){isGlob=token.isGlob=true;isExtglob=token.isExtglob=true;finished=true;if(code===CHAR_EXCLAMATION_MARK&&index===start){negatedExtglob=true}if(scanToEnd===true){while(eos()!==true&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=true;finished=true;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=true;isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(code===CHAR_QUESTION_MARK){isGlob=token.isGlob=true;finished=true;if(scanToEnd===true){continue}break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==true&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=true;advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=true;isGlob=token.isGlob=true;finished=true;break}}if(scanToEnd===true){continue}break}if(opts.nonegate!==true&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=true;start++;continue}if(opts.noparen!==true&&code===CHAR_LEFT_PARENTHESES){isGlob=token.isGlob=true;if(scanToEnd===true){while(eos()!==true&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=true;code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=true;break}}continue}break}if(isGlob===true){finished=true;if(scanToEnd===true){continue}break}}if(opts.noext===true){isExtglob=false;isGlob=false}let base=str;let prefix="";let glob2="";if(start>0){prefix=str.slice(0,start);str=str.slice(start);lastIndex-=start}if(base&&isGlob===true&&lastIndex>0){base=str.slice(0,lastIndex);glob2=str.slice(lastIndex)}else if(isGlob===true){base="";glob2=str}else{base=str}if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1))){base=base.slice(0,-1)}}if(opts.unescape===true){if(glob2)glob2=utils.removeBackslashes(glob2);if(base&&backslashes===true){base=utils.removeBackslashes(base)}}const state6={prefix,input,start,base,glob:glob2,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===true){state6.maxDepth=0;if(!isPathSeparator(code)){tokens.push(token)}state6.tokens=tokens}if(opts.parts===true||opts.tokens===true){let prevIndex;for(let idx=0;idx<slashes.length;idx++){const n=prevIndex?prevIndex+1:start;const i=slashes[idx];const value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0){tokens[idx].isPrefix=true;tokens[idx].value=prefix}else{tokens[idx].value=value}depth(tokens[idx]);state6.maxDepth+=tokens[idx].depth}if(idx!==0||value!==""){parts.push(value)}prevIndex=i}if(prevIndex&&prevIndex+1<input.length){const value=input.slice(prevIndex+1);parts.push(value);if(opts.tokens){tokens[tokens.length-1].value=value;depth(tokens[tokens.length-1]);state6.maxDepth+=tokens[tokens.length-1].depth}}state6.slashes=slashes;state6.parts=parts}return state6};module2.exports=scan}});var require_parse4=__commonJS({"../../node_modules/picomatch/lib/parse.js"(exports2,module2){"use strict";var constants3=require_constants8();var utils=require_utils6();var{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants3;var expandRange=(args,options)=>{if(typeof options.expandRange==="function"){return options.expandRange(...args,options)}args.sort();const value=`[${args.join("-")}]`;try{new RegExp(value)}catch(ex){return args.map(v=>utils.escapeRegex(v)).join("..")}return value};var syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`};var parse11=(input,options)=>{if(typeof input!=="string"){throw new TypeError("Expected a string")}input=REPLACEMENTS[input]||input;const opts={...options};const max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH;let len=input.length;if(len>max){throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`)}const bos={type:"bos",value:"",output:opts.prepend||""};const tokens=[bos];const capture=opts.capture?"":"?:";const win32=utils.isWindows(options);const PLATFORM_CHARS=constants3.globChars(win32);const EXTGLOB_CHARS=constants3.extglobChars(PLATFORM_CHARS);const{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS;const globstar=opts2=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`};const nodot=opts.dot?"":NO_DOT;const qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT;let star3=opts.bash===true?globstar(opts):STAR;if(opts.capture){star3=`(${star3})`}if(typeof opts.noext==="boolean"){opts.noextglob=opts.noext}const state6={input,index:-1,start:0,dot:opts.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens};input=utils.removePrefix(input,state6);len=input.length;const extglobs=[];const braces=[];const stack=[];let prev=bos;let value;const eos=()=>state6.index===len-1;const peek=state6.peek=(n=1)=>input[state6.index+n];const advance=state6.advance=()=>input[++state6.index]||"";const remaining=()=>input.slice(state6.index+1);const consume=(value2="",num=0)=>{state6.consumed+=value2;state6.index+=num};const append=token=>{state6.output+=token.output!=null?token.output:token.value;consume(token.value)};const negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?")){advance();state6.start++;count++}if(count%2===0){return false}state6.negated=true;state6.start++;return true};const increment=type=>{state6[type]++;stack.push(type)};const decrement=type=>{state6[type]--;stack.pop()};const push=tok=>{if(prev.type==="globstar"){const isBrace=state6.braces>0&&(tok.type==="comma"||tok.type==="brace");const isExtglob=tok.extglob===true||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob){state6.output=state6.output.slice(0,-prev.output.length);prev.type="star";prev.value="*";prev.output=star3;state6.output+=prev.output}}if(extglobs.length&&tok.type!=="paren"){extglobs[extglobs.length-1].inner+=tok.value}if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.value+=tok.value;prev.output=(prev.output||"")+tok.value;return}tok.prev=prev;tokens.push(tok);prev=tok};const extglobOpen=(type,value2)=>{const token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev;token.parens=state6.parens;token.output=state6.output;const output=(opts.capture?"(":"")+token.open;increment("parens");push({type,value:value2,output:state6.output?"":ONE_CHAR});push({type:"paren",extglob:true,value:advance(),output});extglobs.push(token)};const extglobClose=token=>{let output=token.close+(opts.capture?")":"");let rest;if(token.type==="negate"){let extglobStar=star3;if(token.inner&&token.inner.length>1&&token.inner.includes("/")){extglobStar=globstar(opts)}if(extglobStar!==star3||eos()||/^\)+$/.test(remaining())){output=token.close=`)$))${extglobStar}`}if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){const expression=parse11(rest,{...options,fastpaths:false}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos"){state6.negatedExtglob=true}}push({type:"paren",extglob:true,value,output});decrement("parens")};if(opts.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=false;let output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc,chars,first,rest,index)=>{if(first==="\\"){backslashes=true;return m}if(first==="?"){if(esc){return esc+first+(rest?QMARK.repeat(rest.length):"")}if(index===0){return qmarkNoDot+(rest?QMARK.repeat(rest.length):"")}return QMARK.repeat(chars.length)}if(first==="."){return DOT_LITERAL.repeat(chars.length)}if(first==="*"){if(esc){return esc+first+(rest?star3:"")}return star3}return esc?m:`\\${m}`});if(backslashes===true){if(opts.unescape===true){output=output.replace(/\\/g,"")}else{output=output.replace(/\\+/g,m=>{return m.length%2===0?"\\\\":m?"\\":""})}}if(output===input&&opts.contains===true){state6.output=input;return state6}state6.output=utils.wrapOutput(output,state6,options);return state6}while(!eos()){value=advance();if(value==="\0"){continue}if(value==="\\"){const next=peek();if(next==="/"&&opts.bash!==true){continue}if(next==="."||next===";"){continue}if(!next){value+="\\";push({type:"text",value});continue}const match2=/^\\+/.exec(remaining());let slashes=0;if(match2&&match2[0].length>2){slashes=match2[0].length;state6.index+=slashes;if(slashes%2!==0){value+="\\"}}if(opts.unescape===true){value=advance()}else{value+=advance()}if(state6.brackets===0){push({type:"text",value});continue}}if(state6.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==false&&value===":"){const inner=prev.value.slice(1);if(inner.includes("[")){prev.posix=true;if(inner.includes(":")){const idx=prev.value.lastIndexOf("[");const pre=prev.value.slice(0,idx);const rest2=prev.value.slice(idx+2);const posix=POSIX_REGEX_SOURCE[rest2];if(posix){prev.value=pre+posix;state6.backtrack=true;advance();if(!bos.output&&tokens.indexOf(prev)===1){bos.output=ONE_CHAR}continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]"){value=`\\${value}`}if(value==="]"&&(prev.value==="["||prev.value==="[^")){value=`\\${value}`}if(opts.posix===true&&value==="!"&&prev.value==="["){value="^"}prev.value+=value;append({value});continue}if(state6.quotes===1&&value!=='"'){value=utils.escapeRegex(value);prev.value+=value;append({value});continue}if(value==='"'){state6.quotes=state6.quotes===1?0:1;if(opts.keepQuotes===true){push({type:"text",value})}continue}if(value==="("){increment("parens");push({type:"paren",value});continue}if(value===")"){if(state6.parens===0&&opts.strictBrackets===true){throw new SyntaxError(syntaxError("opening","("))}const extglob=extglobs[extglobs.length-1];if(extglob&&state6.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state6.parens?")":"\\)"});decrement("parens");continue}if(value==="["){if(opts.nobracket===true||!remaining().includes("]")){if(opts.nobracket!==true&&opts.strictBrackets===true){throw new SyntaxError(syntaxError("closing","]"))}value=`\\${value}`}else{increment("brackets")}push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===true||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state6.brackets===0){if(opts.strictBrackets===true){throw new SyntaxError(syntaxError("opening","["))}push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");const prevValue=prev.value.slice(1);if(prev.posix!==true&&prevValue[0]==="^"&&!prevValue.includes("/")){value=`/${value}`}prev.value+=value;append({value});if(opts.literalBrackets===false||utils.hasRegexChars(prevValue)){continue}const escaped=utils.escapeRegex(prev.value);state6.output=state6.output.slice(0,-prev.value.length);if(opts.literalBrackets===true){state6.output+=escaped;prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`;state6.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==true){increment("braces");const open={type:"brace",value,output:"(",outputIndex:state6.output.length,tokensIndex:state6.tokens.length};braces.push(open);push(open);continue}if(value==="}"){const brace=braces[braces.length-1];if(opts.nobrace===true||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===true){const arr=tokens.slice();const range=[];for(let i=arr.length-1;i>=0;i--){tokens.pop();if(arr[i].type==="brace"){break}if(arr[i].type!=="dots"){range.unshift(arr[i].value)}}output=expandRange(range,opts);state6.backtrack=true}if(brace.comma!==true&&brace.dots!==true){const out=state6.output.slice(0,brace.outputIndex);const toks=state6.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{";value=output="\\}";state6.output=out;for(const t of toks){state6.output+=t.output||t.value}}push({type:"brace",value,output});decrement("braces");braces.pop();continue}if(value==="|"){if(extglobs.length>0){extglobs[extglobs.length-1].conditions++}push({type:"text",value});continue}if(value===","){let output=value;const brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces"){brace.comma=true;output="|"}push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state6.index===state6.start+1){state6.start=state6.index+1;state6.consumed="";state6.output="";tokens.pop();prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state6.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;const brace=braces[braces.length-1];prev.type="dots";prev.output+=value;prev.value+=value;brace.dots=true;continue}if(state6.braces+state6.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){const isGroup=prev&&prev.value==="(";if(!isGroup&&opts.noextglob!==true&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){const next=peek();let output=value;if(next==="<"&&!utils.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining())){output=`\\${value}`}push({type:"text",value,output});continue}if(opts.dot!==true&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==true&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==true&&state6.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==true&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===false){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state6.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==true&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:true,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^"){value=`\\${value}`}const match2=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match2){value+=match2[0];state6.index+=match2[0].length}push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===true)){prev.type="star";prev.star=true;prev.value+=value;prev.output=star3;state6.backtrack=true;state6.globstar=true;consume(value);continue}let rest=remaining();if(opts.noextglob!==true&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===true){consume(value);continue}const prior=prev.prev;const before=prior.prev;const isStart=prior.type==="slash"||prior.type==="bos";const afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===true&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}const isBrace=state6.braces>0&&(prior.type==="comma"||prior.type==="brace");const isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){const after=input[state6.index+4];if(after&&after!=="/"){break}rest=rest.slice(3);consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar";prev.value+=value;prev.output=globstar(opts);state6.output=prev.output;state6.globstar=true;consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state6.output=state6.output.slice(0,-(prior.output+prev.output).length);prior.output=`(?:${prior.output}`;prev.type="globstar";prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)");prev.value+=value;state6.globstar=true;state6.output+=prior.output+prev.output;consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){const end=rest[1]!==void 0?"|$":"";state6.output=state6.output.slice(0,-(prior.output+prev.output).length);prior.output=`(?:${prior.output}`;prev.type="globstar";prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;prev.value+=value;state6.output+=prior.output+prev.output;state6.globstar=true;consume(value+advance());push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar";prev.value+=value;prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;state6.output=prev.output;state6.globstar=true;consume(value+advance());push({type:"slash",value:"/",output:""});continue}state6.output=state6.output.slice(0,-prev.output.length);prev.type="globstar";prev.output=globstar(opts);prev.value+=value;state6.output+=prev.output;state6.globstar=true;consume(value);continue}const token={type:"star",value,output:star3};if(opts.bash===true){token.output=".*?";if(prev.type==="bos"||prev.type==="slash"){token.output=nodot+token.output}push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===true){token.output=value;push(token);continue}if(state6.index===state6.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot"){state6.output+=NO_DOT_SLASH;prev.output+=NO_DOT_SLASH}else if(opts.dot===true){state6.output+=NO_DOTS_SLASH;prev.output+=NO_DOTS_SLASH}else{state6.output+=nodot;prev.output+=nodot}if(peek()!=="*"){state6.output+=ONE_CHAR;prev.output+=ONE_CHAR}}push(token)}while(state6.brackets>0){if(opts.strictBrackets===true)throw new SyntaxError(syntaxError("closing","]"));state6.output=utils.escapeLast(state6.output,"[");decrement("brackets")}while(state6.parens>0){if(opts.strictBrackets===true)throw new SyntaxError(syntaxError("closing",")"));state6.output=utils.escapeLast(state6.output,"(");decrement("parens")}while(state6.braces>0){if(opts.strictBrackets===true)throw new SyntaxError(syntaxError("closing","}"));state6.output=utils.escapeLast(state6.output,"{");decrement("braces")}if(opts.strictSlashes!==true&&(prev.type==="star"||prev.type==="bracket")){push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`})}if(state6.backtrack===true){state6.output="";for(const token of state6.tokens){state6.output+=token.output!=null?token.output:token.value;if(token.suffix){state6.output+=token.suffix}}}return state6};parse11.fastpaths=(input,options)=>{const opts={...options};const max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH;const len=input.length;if(len>max){throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`)}input=REPLACEMENTS[input]||input;const win32=utils.isWindows(options);const{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants3.globChars(win32);const nodot=opts.dot?NO_DOTS:NO_DOT;const slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT;const capture=opts.capture?"":"?:";const state6={negated:false,prefix:""};let star3=opts.bash===true?".*?":STAR;if(opts.capture){star3=`(${star3})`}const globstar=opts2=>{if(opts2.noglobstar===true)return star3;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`};const create=str=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star3}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star3}`;case"*.*":return`${nodot}${star3}${DOT_LITERAL}${ONE_CHAR}${star3}`;case"*/*":return`${nodot}${star3}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star3}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star3}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star3}${DOT_LITERAL}${ONE_CHAR}${star3}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star3}`;default:{const match2=/^(.*?)\.(\w+)$/.exec(str);if(!match2)return;const source2=create(match2[1]);if(!source2)return;return source2+DOT_LITERAL+match2[2]}}};const output=utils.removePrefix(input,state6);let source=create(output);if(source&&opts.strictSlashes!==true){source+=`${SLASH_LITERAL}?`}return source};module2.exports=parse11}});var require_picomatch=__commonJS({"../../node_modules/picomatch/lib/picomatch.js"(exports2,module2){"use strict";var path24=require("path");var scan=require_scan2();var parse11=require_parse4();var utils=require_utils6();var constants3=require_constants8();var isObject2=val2=>val2&&typeof val2==="object"&&!Array.isArray(val2);var picomatch=(glob2,options,returnState=false)=>{if(Array.isArray(glob2)){const fns=glob2.map(input=>picomatch(input,options,returnState));const arrayMatcher=str=>{for(const isMatch of fns){const state7=isMatch(str);if(state7)return state7}return false};return arrayMatcher}const isState=isObject2(glob2)&&glob2.tokens&&glob2.input;if(glob2===""||typeof glob2!=="string"&&!isState){throw new TypeError("Expected pattern to be a non-empty string")}const opts=options||{};const posix=utils.isWindows(options);const regex=isState?picomatch.compileRe(glob2,options):picomatch.makeRe(glob2,options,false,true);const state6=regex.state;delete regex.state;let isIgnored=()=>false;if(opts.ignore){const ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}const matcher=(input,returnObject=false)=>{const{isMatch,match:match2,output}=picomatch.test(input,regex,options,{glob:glob2,posix});const result={glob:glob2,state:state6,regex,posix,input,output,match:match2,isMatch};if(typeof opts.onResult==="function"){opts.onResult(result)}if(isMatch===false){result.isMatch=false;return returnObject?result:false}if(isIgnored(input)){if(typeof opts.onIgnore==="function"){opts.onIgnore(result)}result.isMatch=false;return returnObject?result:false}if(typeof opts.onMatch==="function"){opts.onMatch(result)}return returnObject?result:true};if(returnState){matcher.state=state6}return matcher};picomatch.test=(input,regex,options,{glob:glob2,posix}={})=>{if(typeof input!=="string"){throw new TypeError("Expected input to be a string")}if(input===""){return{isMatch:false,output:""}}const opts=options||{};const format7=opts.format||(posix?utils.toPosixSlashes:null);let match2=input===glob2;let output=match2&&format7?format7(input):input;if(match2===false){output=format7?format7(input):input;match2=output===glob2}if(match2===false||opts.capture===true){if(opts.matchBase===true||opts.basename===true){match2=picomatch.matchBase(input,regex,options,posix)}else{match2=regex.exec(output)}}return{isMatch:Boolean(match2),match:match2,output}};picomatch.matchBase=(input,glob2,options,posix=utils.isWindows(options))=>{const regex=glob2 instanceof RegExp?glob2:picomatch.makeRe(glob2,options);return regex.test(path24.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map(p=>picomatch.parse(p,options));return parse11(pattern,{...options,fastpaths:false})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state6,options,returnOutput=false,returnState=false)=>{if(returnOutput===true){return state6.output}const opts=options||{};const prepend=opts.contains?"":"^";const append=opts.contains?"":"$";let source=`${prepend}(?:${state6.output})${append}`;if(state6&&state6.negated===true){source=`^(?!${source}).*$`}const regex=picomatch.toRegex(source,options);if(returnState===true){regex.state=state6}return regex};picomatch.makeRe=(input,options={},returnOutput=false,returnState=false)=>{if(!input||typeof input!=="string"){throw new TypeError("Expected a non-empty string")}let parsed={negated:false,fastpaths:true};if(options.fastpaths!==false&&(input[0]==="."||input[0]==="*")){parsed.output=parse11.fastpaths(input,options)}if(!parsed.output){parsed=parse11(input,options)}return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{const opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===true)throw err;return/$^/}};picomatch.constants=constants3;module2.exports=picomatch}});var require_picomatch2=__commonJS({"../../node_modules/picomatch/index.js"(exports2,module2){"use strict";module2.exports=require_picomatch()}});var require_readdirp=__commonJS({"../../node_modules/readdirp/index.js"(exports2,module2){"use strict";var fs23=require("fs");var{Readable}=require("stream");var sysPath=require("path");var{promisify:promisify2}=require("util");var picomatch=require_picomatch2();var readdir2=promisify2(fs23.readdir);var stat4=promisify2(fs23.stat);var lstat=promisify2(fs23.lstat);var realpath=promisify2(fs23.realpath);var BANG="!";var RECURSIVE_ERROR_CODE="READDIRP_RECURSIVE_ERROR";var NORMAL_FLOW_ERRORS=new Set(["ENOENT","EPERM","EACCES","ELOOP",RECURSIVE_ERROR_CODE]);var FILE_TYPE="files";var DIR_TYPE="directories";var FILE_DIR_TYPE="files_directories";var EVERYTHING_TYPE="all";var ALL_TYPES=[FILE_TYPE,DIR_TYPE,FILE_DIR_TYPE,EVERYTHING_TYPE];var isNormalFlowError=error3=>NORMAL_FLOW_ERRORS.has(error3.code);var[maj,min]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10));var wantBigintFsStats=process.platform==="win32"&&(maj>10||maj===10&&min>=5);var normalizeFilter=filter2=>{if(filter2===void 0)return;if(typeof filter2==="function")return filter2;if(typeof filter2==="string"){const glob2=picomatch(filter2.trim());return entry=>glob2(entry.basename)}if(Array.isArray(filter2)){const positive=[];const negative=[];for(const item of filter2){const trimmed=item.trim();if(trimmed.charAt(0)===BANG){negative.push(picomatch(trimmed.slice(1)))}else{positive.push(picomatch(trimmed))}}if(negative.length>0){if(positive.length>0){return entry=>positive.some(f=>f(entry.basename))&&!negative.some(f=>f(entry.basename))}return entry=>!negative.some(f=>f(entry.basename))}return entry=>positive.some(f=>f(entry.basename))}};var ReaddirpStream=class _ReaddirpStream extends Readable{static get defaultOptions(){return{root:".",fileFilter:path24=>true,directoryFilter:path24=>true,type:FILE_TYPE,lstat:false,depth:2147483648,alwaysStat:false}}constructor(options={}){super({objectMode:true,autoDestroy:true,highWaterMark:options.highWaterMark||4096});const opts={..._ReaddirpStream.defaultOptions,...options};const{root,type}=opts;this._fileFilter=normalizeFilter(opts.fileFilter);this._directoryFilter=normalizeFilter(opts.directoryFilter);const statMethod=opts.lstat?lstat:stat4;if(wantBigintFsStats){this._stat=path24=>statMethod(path24,{bigint:true})}else{this._stat=statMethod}this._maxDepth=opts.depth;this._wantsDir=[DIR_TYPE,FILE_DIR_TYPE,EVERYTHING_TYPE].includes(type);this._wantsFile=[FILE_TYPE,FILE_DIR_TYPE,EVERYTHING_TYPE].includes(type);this._wantsEverything=type===EVERYTHING_TYPE;this._root=sysPath.resolve(root);this._isDirent="Dirent"in fs23&&!opts.alwaysStat;this._statsProp=this._isDirent?"dirent":"stats";this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};this.parents=[this._exploreDir(root,1)];this.reading=false;this.parent=void 0}async _read(batch){if(this.reading)return;this.reading=true;try{while(!this.destroyed&&batch>0){const{path:path24,depth,files=[]}=this.parent||{};if(files.length>0){const slice=files.splice(0,batch).map(dirent=>this._formatEntry(dirent,path24));for(const entry of await Promise.all(slice)){if(this.destroyed)return;const entryType=await this._getEntryType(entry);if(entryType==="directory"&&this._directoryFilter(entry)){if(depth<=this._maxDepth){this.parents.push(this._exploreDir(entry.fullPath,depth+1))}if(this._wantsDir){this.push(entry);batch--}}else if((entryType==="file"||this._includeAsFile(entry))&&this._fileFilter(entry)){if(this._wantsFile){this.push(entry);batch--}}}}else{const parent=this.parents.pop();if(!parent){this.push(null);break}this.parent=await parent;if(this.destroyed)return}}}catch(error3){this.destroy(error3)}finally{this.reading=false}}async _exploreDir(path24,depth){let files;try{files=await readdir2(path24,this._rdOptions)}catch(error3){this._onError(error3)}return{files,depth,path:path24}}async _formatEntry(dirent,path24){let entry;try{const basename3=this._isDirent?dirent.name:dirent;const fullPath=sysPath.resolve(sysPath.join(path24,basename3));entry={path:sysPath.relative(this._root,fullPath),fullPath,basename:basename3};entry[this._statsProp]=this._isDirent?dirent:await this._stat(fullPath)}catch(err){this._onError(err)}return entry}_onError(err){if(isNormalFlowError(err)&&!this.destroyed){this.emit("warn",err)}else{this.destroy(err)}}async _getEntryType(entry){const stats=entry&&entry[this._statsProp];if(!stats){return}if(stats.isFile()){return"file"}if(stats.isDirectory()){return"directory"}if(stats&&stats.isSymbolicLink()){const full=entry.fullPath;try{const entryRealPath=await realpath(full);const entryRealPathStats=await lstat(entryRealPath);if(entryRealPathStats.isFile()){return"file"}if(entryRealPathStats.isDirectory()){const len=entryRealPath.length;if(full.startsWith(entryRealPath)&&full.substr(len,1)===sysPath.sep){const recursiveError=new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);recursiveError.code=RECURSIVE_ERROR_CODE;return this._onError(recursiveError)}return"directory"}}catch(error3){this._onError(error3)}}}_includeAsFile(entry){const stats=entry&&entry[this._statsProp];return stats&&this._wantsEverything&&!stats.isDirectory()}};var readdirp=(root,options={})=>{let type=options.entryType||options.type;if(type==="both")type=FILE_DIR_TYPE;if(type)options.type=type;if(!root){throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)")}else if(typeof root!=="string"){throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)")}else if(type&&!ALL_TYPES.includes(type)){throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`)}options.root=root;return new ReaddirpStream(options)};var readdirpPromise=(root,options={})=>{return new Promise((resolve7,reject)=>{const files=[];readdirp(root,options).on("data",entry=>files.push(entry)).on("end",()=>resolve7(files)).on("error",error3=>reject(error3))})};readdirp.promise=readdirpPromise;readdirp.ReaddirpStream=ReaddirpStream;readdirp.default=readdirp;module2.exports=readdirp}});var require_anymatch=__commonJS({"../../node_modules/anymatch/index.js"(exports2,module2){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var picomatch=require_picomatch2();var normalizePath=require_normalize_path();var BANG="!";var DEFAULT_OPTIONS={returnIndex:false};var arrify=item=>Array.isArray(item)?item:[item];var createPattern=(matcher,options)=>{if(typeof matcher==="function"){return matcher}if(typeof matcher==="string"){const glob2=picomatch(matcher,options);return string=>matcher===string||glob2(string)}if(matcher instanceof RegExp){return string=>matcher.test(string)}return string=>false};var matchPatterns=(patterns,negPatterns,args,returnIndex)=>{const isList=Array.isArray(args);const _path=isList?args[0]:args;if(!isList&&typeof _path!=="string"){throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(_path))}const path24=normalizePath(_path,false);for(let index=0;index<negPatterns.length;index++){const nglob=negPatterns[index];if(nglob(path24)){return returnIndex?-1:false}}const applied=isList&&[path24].concat(args.slice(1));for(let index=0;index<patterns.length;index++){const pattern=patterns[index];if(isList?pattern(...applied):pattern(path24)){return returnIndex?index:true}}return returnIndex?-1:false};var anymatch=(matchers,testString,options=DEFAULT_OPTIONS)=>{if(matchers==null){throw new TypeError("anymatch: specify first argument")}const opts=typeof options==="boolean"?{returnIndex:options}:options;const returnIndex=opts.returnIndex||false;const mtchers=arrify(matchers);const negatedGlobs=mtchers.filter(item=>typeof item==="string"&&item.charAt(0)===BANG).map(item=>item.slice(1)).map(item=>picomatch(item,opts));const patterns=mtchers.filter(item=>typeof item!=="string"||typeof item==="string"&&item.charAt(0)!==BANG).map(matcher=>createPattern(matcher,opts));if(testString==null){return(testString2,ri=false)=>{const returnIndex2=typeof ri==="boolean"?ri:false;return matchPatterns(patterns,negatedGlobs,testString2,returnIndex2)}}return matchPatterns(patterns,negatedGlobs,testString,returnIndex)};anymatch.default=anymatch;module2.exports=anymatch}});var require_is_extglob=__commonJS({"../../node_modules/is-extglob/index.js"(exports2,module2){module2.exports=function isExtglob(str){if(typeof str!=="string"||str===""){return false}var match2;while(match2=/(\\).|([@?!+*]\(.*\))/g.exec(str)){if(match2[2])return true;str=str.slice(match2.index+match2[0].length)}return false}}});var require_is_glob=__commonJS({"../../node_modules/is-glob/index.js"(exports2,module2){var isExtglob=require_is_extglob();var chars={"{":"}","(":")","[":"]"};var strictCheck=function(str){if(str[0]==="!"){return true}var index=0;var pipeIndex=-2;var closeSquareIndex=-2;var closeCurlyIndex=-2;var closeParenIndex=-2;var backSlashIndex=-2;while(index<str.length){if(str[index]==="*"){return true}if(str[index+1]==="?"&&/[\].+)]/.test(str[index])){return true}if(closeSquareIndex!==-1&&str[index]==="["&&str[index+1]!=="]"){if(closeSquareIndex<index){closeSquareIndex=str.indexOf("]",index)}if(closeSquareIndex>index){if(backSlashIndex===-1||backSlashIndex>closeSquareIndex){return true}backSlashIndex=str.indexOf("\\",index);if(backSlashIndex===-1||backSlashIndex>closeSquareIndex){return true}}}if(closeCurlyIndex!==-1&&str[index]==="{"&&str[index+1]!=="}"){closeCurlyIndex=str.indexOf("}",index);if(closeCurlyIndex>index){backSlashIndex=str.indexOf("\\",index);if(backSlashIndex===-1||backSlashIndex>closeCurlyIndex){return true}}}if(closeParenIndex!==-1&&str[index]==="("&&str[index+1]==="?"&&/[:!=]/.test(str[index+2])&&str[index+3]!==")"){closeParenIndex=str.indexOf(")",index);if(closeParenIndex>index){backSlashIndex=str.indexOf("\\",index);if(backSlashIndex===-1||backSlashIndex>closeParenIndex){return true}}}if(pipeIndex!==-1&&str[index]==="("&&str[index+1]!=="|"){if(pipeIndex<index){pipeIndex=str.indexOf("|",index)}if(pipeIndex!==-1&&str[pipeIndex+1]!==")"){closeParenIndex=str.indexOf(")",pipeIndex);if(closeParenIndex>pipeIndex){backSlashIndex=str.indexOf("\\",pipeIndex);if(backSlashIndex===-1||backSlashIndex>closeParenIndex){return true}}}}if(str[index]==="\\"){var open=str[index+1];index+=2;var close=chars[open];if(close){var n=str.indexOf(close,index);if(n!==-1){index=n+1}}if(str[index]==="!"){return true}}else{index++}}return false};var relaxedCheck=function(str){if(str[0]==="!"){return true}var index=0;while(index<str.length){if(/[*?{}()[\]]/.test(str[index])){return true}if(str[index]==="\\"){var open=str[index+1];index+=2;var close=chars[open];if(close){var n=str.indexOf(close,index);if(n!==-1){index=n+1}}if(str[index]==="!"){return true}}else{index++}}return false};module2.exports=function isGlob(str,options){if(typeof str!=="string"||str===""){return false}if(isExtglob(str)){return true}var check=strictCheck;if(options&&options.strict===false){check=relaxedCheck}return check(str)}}});var require_glob_parent=__commonJS({"../../node_modules/glob-parent/index.js"(exports2,module2){"use strict";var isGlob=require_is_glob();var pathPosixDirname=require("path").posix.dirname;var isWin32=require("os").platform()==="win32";var slash="/";var backslash=/\\/g;var enclosure=/[\{\[].*[\}\]]$/;var globby=/(^|[^\\])([\{\[]|\([^\)]+$)/;var escaped=/\\([\!\*\?\|\[\]\(\)\{\}])/g;module2.exports=function globParent(str,opts){var options=Object.assign({flipBackslashes:true},opts);if(options.flipBackslashes&&isWin32&&str.indexOf(slash)<0){str=str.replace(backslash,slash)}if(enclosure.test(str)){str+=slash}str+="a";do{str=pathPosixDirname(str)}while(isGlob(str)||globby.test(str));return str.replace(escaped,"$1")}}});var require_utils7=__commonJS({"../../node_modules/braces/lib/utils.js"(exports2){"use strict";exports2.isInteger=num=>{if(typeof num==="number"){return Number.isInteger(num)}if(typeof num==="string"&&num.trim()!==""){return Number.isInteger(Number(num))}return false};exports2.find=(node,type)=>node.nodes.find(node2=>node2.type===type);exports2.exceedsLimit=(min,max,step=1,limit)=>{if(limit===false)return false;if(!exports2.isInteger(min)||!exports2.isInteger(max))return false;return(Number(max)-Number(min))/Number(step)>=limit};exports2.escapeNode=(block,n=0,type)=>{const node=block.nodes[n];if(!node)return;if(type&&node.type===type||node.type==="open"||node.type==="close"){if(node.escaped!==true){node.value="\\"+node.value;node.escaped=true}}};exports2.encloseBrace=node=>{if(node.type!=="brace")return false;if(node.commas>>0+node.ranges>>0===0){node.invalid=true;return true}return false};exports2.isInvalidBrace=block=>{if(block.type!=="brace")return false;if(block.invalid===true||block.dollar)return true;if(block.commas>>0+block.ranges>>0===0){block.invalid=true;return true}if(block.open!==true||block.close!==true){block.invalid=true;return true}return false};exports2.isOpenOrClose=node=>{if(node.type==="open"||node.type==="close"){return true}return node.open===true||node.close===true};exports2.reduce=nodes=>nodes.reduce((acc,node)=>{if(node.type==="text")acc.push(node.value);if(node.type==="range")node.type="text";return acc},[]);exports2.flatten=(...args)=>{const result=[];const flat=arr=>{for(let i=0;i<arr.length;i++){const ele=arr[i];if(Array.isArray(ele)){flat(ele);continue}if(ele!==void 0){result.push(ele)}}return result};flat(args);return result}}});var require_stringify=__commonJS({"../../node_modules/braces/lib/stringify.js"(exports2,module2){"use strict";var utils=require_utils7();module2.exports=(ast,options={})=>{const stringify12=(node,parent={})=>{const invalidBlock=options.escapeInvalid&&utils.isInvalidBrace(parent);const invalidNode=node.invalid===true&&options.escapeInvalid===true;let output="";if(node.value){if((invalidBlock||invalidNode)&&utils.isOpenOrClose(node)){return"\\"+node.value}return node.value}if(node.value){return node.value}if(node.nodes){for(const child of node.nodes){output+=stringify12(child)}}return output};return stringify12(ast)}}});var require_is_number=__commonJS({"../../node_modules/is-number/index.js"(exports2,module2){"use strict";module2.exports=function(num){if(typeof num==="number"){return num-num===0}if(typeof num==="string"&&num.trim()!==""){return Number.isFinite?Number.isFinite(+num):isFinite(+num)}return false}}});var require_to_regex_range=__commonJS({"../../node_modules/to-regex-range/index.js"(exports2,module2){"use strict";var isNumber=require_is_number();var toRegexRange=(min,max,options)=>{if(isNumber(min)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(max===void 0||min===max){return String(min)}if(isNumber(max)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let opts={relaxZeros:true,...options};if(typeof opts.strictZeros==="boolean"){opts.relaxZeros=opts.strictZeros===false}let relax=String(opts.relaxZeros);let shorthand=String(opts.shorthand);let capture=String(opts.capture);let wrap=String(opts.wrap);let cacheKey=min+":"+max+"="+relax+shorthand+capture+wrap;if(toRegexRange.cache.hasOwnProperty(cacheKey)){return toRegexRange.cache[cacheKey].result}let a=Math.min(min,max);let b=Math.max(min,max);if(Math.abs(a-b)===1){let result=min+"|"+max;if(opts.capture){return`(${result})`}if(opts.wrap===false){return result}return`(?:${result})`}let isPadded=hasPadding(min)||hasPadding(max);let state6={min,max,a,b};let positives=[];let negatives=[];if(isPadded){state6.isPadded=isPadded;state6.maxLen=String(state6.max).length}if(a<0){let newMin=b<0?Math.abs(b):1;negatives=splitToPatterns(newMin,Math.abs(a),state6,opts);a=state6.a=0}if(b>=0){positives=splitToPatterns(a,b,state6,opts)}state6.negatives=negatives;state6.positives=positives;state6.result=collatePatterns(negatives,positives,opts);if(opts.capture===true){state6.result=`(${state6.result})`}else if(opts.wrap!==false&&positives.length+negatives.length>1){state6.result=`(?:${state6.result})`}toRegexRange.cache[cacheKey]=state6;return state6.result};function collatePatterns(neg,pos,options){let onlyNegative=filterPatterns(neg,pos,"-",false,options)||[];let onlyPositive=filterPatterns(pos,neg,"",false,options)||[];let intersected=filterPatterns(neg,pos,"-?",true,options)||[];let subpatterns=onlyNegative.concat(intersected).concat(onlyPositive);return subpatterns.join("|")}function splitToRanges(min,max){let nines=1;let zeros=1;let stop=countNines(min,nines);let stops=new Set([max]);while(min<=stop&&stop<=max){stops.add(stop);nines+=1;stop=countNines(min,nines)}stop=countZeros(max+1,zeros)-1;while(min<stop&&stop<=max){stops.add(stop);zeros+=1;stop=countZeros(max+1,zeros)-1}stops=[...stops];stops.sort(compare2);return stops}function rangeToPattern(start,stop,options){if(start===stop){return{pattern:start,count:[],digits:0}}let zipped=zip(start,stop);let digits=zipped.length;let pattern="";let count=0;for(let i=0;i<digits;i++){let[startDigit,stopDigit]=zipped[i];if(startDigit===stopDigit){pattern+=startDigit}else if(startDigit!=="0"||stopDigit!=="9"){pattern+=toCharacterClass(startDigit,stopDigit,options)}else{count++}}if(count){pattern+=options.shorthand===true?"\\d":"[0-9]"}return{pattern,count:[count],digits}}function splitToPatterns(min,max,tok,options){let ranges=splitToRanges(min,max);let tokens=[];let start=min;let prev;for(let i=0;i<ranges.length;i++){let max2=ranges[i];let obj=rangeToPattern(String(start),String(max2),options);let zeros="";if(!tok.isPadded&&prev&&prev.pattern===obj.pattern){if(prev.count.length>1){prev.count.pop()}prev.count.push(obj.count[0]);prev.string=prev.pattern+toQuantifier(prev.count);start=max2+1;continue}if(tok.isPadded){zeros=padZeros(max2,tok,options)}obj.string=zeros+obj.pattern+toQuantifier(obj.count);tokens.push(obj);start=max2+1;prev=obj}return tokens}function filterPatterns(arr,comparison,prefix,intersection,options){let result=[];for(let ele of arr){let{string}=ele;if(!intersection&&!contains2(comparison,"string",string)){result.push(prefix+string)}if(intersection&&contains2(comparison,"string",string)){result.push(prefix+string)}}return result}function zip(a,b){let arr=[];for(let i=0;i<a.length;i++)arr.push([a[i],b[i]]);return arr}function compare2(a,b){return a>b?1:b>a?-1:0}function contains2(arr,key,val2){return arr.some(ele=>ele[key]===val2)}function countNines(min,len){return Number(String(min).slice(0,-len)+"9".repeat(len))}function countZeros(integer,zeros){return integer-integer%Math.pow(10,zeros)}function toQuantifier(digits){let[start=0,stop=""]=digits;if(stop||start>1){return`{${start+(stop?","+stop:"")}}`}return""}function toCharacterClass(a,b,options){return`[${a}${b-a===1?"":"-"}${b}]`}function hasPadding(str){return/^-?(0+)\d/.test(str)}function padZeros(value,tok,options){if(!tok.isPadded){return value}let diff=Math.abs(tok.maxLen-String(value).length);let relax=options.relaxZeros!==false;switch(diff){case 0:return"";case 1:return relax?"0?":"0";case 2:return relax?"0{0,2}":"00";default:{return relax?`0{0,${diff}}`:`0{${diff}}`}}}toRegexRange.cache={};toRegexRange.clearCache=()=>toRegexRange.cache={};module2.exports=toRegexRange}});var require_fill_range=__commonJS({"../../node_modules/fill-range/index.js"(exports2,module2){"use strict";var util4=require("util");var toRegexRange=require_to_regex_range();var isObject2=val2=>val2!==null&&typeof val2==="object"&&!Array.isArray(val2);var transform=toNumber=>{return value=>toNumber===true?Number(value):String(value)};var isValidValue=value=>{return typeof value==="number"||typeof value==="string"&&value!==""};var isNumber=num=>Number.isInteger(+num);var zeros=input=>{let value=`${input}`;let index=-1;if(value[0]==="-")value=value.slice(1);if(value==="0")return false;while(value[++index]==="0");return index>0};var stringify12=(start,end,options)=>{if(typeof start==="string"||typeof end==="string"){return true}return options.stringify===true};var pad=(input,maxLength,toNumber)=>{if(maxLength>0){let dash=input[0]==="-"?"-":"";if(dash)input=input.slice(1);input=dash+input.padStart(dash?maxLength-1:maxLength,"0")}if(toNumber===false){return String(input)}return input};var toMaxLen=(input,maxLength)=>{let negative=input[0]==="-"?"-":"";if(negative){input=input.slice(1);maxLength--}while(input.length<maxLength)input="0"+input;return negative?"-"+input:input};var toSequence=(parts,options,maxLen)=>{parts.negatives.sort((a,b)=>a<b?-1:a>b?1:0);parts.positives.sort((a,b)=>a<b?-1:a>b?1:0);let prefix=options.capture?"":"?:";let positives="";let negatives="";let result;if(parts.positives.length){positives=parts.positives.map(v=>toMaxLen(String(v),maxLen)).join("|")}if(parts.negatives.length){negatives=`-(${prefix}${parts.negatives.map(v=>toMaxLen(String(v),maxLen)).join("|")})`}if(positives&&negatives){result=`${positives}|${negatives}`}else{result=positives||negatives}if(options.wrap){return`(${prefix}${result})`}return result};var toRange=(a,b,isNumbers,options)=>{if(isNumbers){return toRegexRange(a,b,{wrap:false,...options})}let start=String.fromCharCode(a);if(a===b)return start;let stop=String.fromCharCode(b);return`[${start}-${stop}]`};var toRegex=(start,end,options)=>{if(Array.isArray(start)){let wrap=options.wrap===true;let prefix=options.capture?"":"?:";return wrap?`(${prefix}${start.join("|")})`:start.join("|")}return toRegexRange(start,end,options)};var rangeError=(...args)=>{return new RangeError("Invalid range arguments: "+util4.inspect(...args))};var invalidRange=(start,end,options)=>{if(options.strictRanges===true)throw rangeError([start,end]);return[]};var invalidStep=(step,options)=>{if(options.strictRanges===true){throw new TypeError(`Expected step "${step}" to be a number`)}return[]};var fillNumbers=(start,end,step=1,options={})=>{let a=Number(start);let b=Number(end);if(!Number.isInteger(a)||!Number.isInteger(b)){if(options.strictRanges===true)throw rangeError([start,end]);return[]}if(a===0)a=0;if(b===0)b=0;let descending2=a>b;let startString=String(start);let endString=String(end);let stepString=String(step);step=Math.max(Math.abs(step),1);let padded=zeros(startString)||zeros(endString)||zeros(stepString);let maxLen=padded?Math.max(startString.length,endString.length,stepString.length):0;let toNumber=padded===false&&stringify12(start,end,options)===false;let format7=options.transform||transform(toNumber);if(options.toRegex&&step===1){return toRange(toMaxLen(start,maxLen),toMaxLen(end,maxLen),true,options)}let parts={negatives:[],positives:[]};let push=num=>parts[num<0?"negatives":"positives"].push(Math.abs(num));let range=[];let index=0;while(descending2?a>=b:a<=b){if(options.toRegex===true&&step>1){push(a)}else{range.push(pad(format7(a,index),maxLen,toNumber))}a=descending2?a-step:a+step;index++}if(options.toRegex===true){return step>1?toSequence(parts,options,maxLen):toRegex(range,null,{wrap:false,...options})}return range};var fillLetters=(start,end,step=1,options={})=>{if(!isNumber(start)&&start.length>1||!isNumber(end)&&end.length>1){return invalidRange(start,end,options)}let format7=options.transform||(val2=>String.fromCharCode(val2));let a=`${start}`.charCodeAt(0);let b=`${end}`.charCodeAt(0);let descending2=a>b;let min=Math.min(a,b);let max=Math.max(a,b);if(options.toRegex&&step===1){return toRange(min,max,false,options)}let range=[];let index=0;while(descending2?a>=b:a<=b){range.push(format7(a,index));a=descending2?a-step:a+step;index++}if(options.toRegex===true){return toRegex(range,null,{wrap:false,options})}return range};var fill=(start,end,step,options={})=>{if(end==null&&isValidValue(start)){return[start]}if(!isValidValue(start)||!isValidValue(end)){return invalidRange(start,end,options)}if(typeof step==="function"){return fill(start,end,1,{transform:step})}if(isObject2(step)){return fill(start,end,0,step)}let opts={...options};if(opts.capture===true)opts.wrap=true;step=step||opts.step||1;if(!isNumber(step)){if(step!=null&&!isObject2(step))return invalidStep(step,opts);return fill(start,end,1,step)}if(isNumber(start)&&isNumber(end)){return fillNumbers(start,end,step,opts)}return fillLetters(start,end,Math.max(Math.abs(step),1),opts)};module2.exports=fill}});var require_compile2=__commonJS({"../../node_modules/braces/lib/compile.js"(exports2,module2){"use strict";var fill=require_fill_range();var utils=require_utils7();var compile=(ast,options={})=>{const walk=(node,parent={})=>{const invalidBlock=utils.isInvalidBrace(parent);const invalidNode=node.invalid===true&&options.escapeInvalid===true;const invalid=invalidBlock===true||invalidNode===true;const prefix=options.escapeInvalid===true?"\\":"";let output="";if(node.isOpen===true){return prefix+node.value}if(node.isClose===true){console.log("node.isClose",prefix,node.value);return prefix+node.value}if(node.type==="open"){return invalid?prefix+node.value:"("}if(node.type==="close"){return invalid?prefix+node.value:")"}if(node.type==="comma"){return node.prev.type==="comma"?"":invalid?node.value:"|"}if(node.value){return node.value}if(node.nodes&&node.ranges>0){const args=utils.reduce(node.nodes);const range=fill(...args,{...options,wrap:false,toRegex:true,strictZeros:true});if(range.length!==0){return args.length>1&&range.length>1?`(${range})`:range}}if(node.nodes){for(const child of node.nodes){output+=walk(child,node)}}return output};return walk(ast)};module2.exports=compile}});var require_expand=__commonJS({"../../node_modules/braces/lib/expand.js"(exports2,module2){"use strict";var fill=require_fill_range();var stringify12=require_stringify();var utils=require_utils7();var append=(queue="",stash="",enclose=false)=>{const result=[];queue=[].concat(queue);stash=[].concat(stash);if(!stash.length)return queue;if(!queue.length){return enclose?utils.flatten(stash).map(ele=>`{${ele}}`):stash}for(const item of queue){if(Array.isArray(item)){for(const value of item){result.push(append(value,stash,enclose))}}else{for(let ele of stash){if(enclose===true&&typeof ele==="string")ele=`{${ele}}`;result.push(Array.isArray(ele)?append(item,ele,enclose):item+ele)}}}return utils.flatten(result)};var expand2=(ast,options={})=>{const rangeLimit=options.rangeLimit===void 0?1e3:options.rangeLimit;const walk=(node,parent={})=>{node.queue=[];let p=parent;let q=parent.queue;while(p.type!=="brace"&&p.type!=="root"&&p.parent){p=p.parent;q=p.queue}if(node.invalid||node.dollar){q.push(append(q.pop(),stringify12(node,options)));return}if(node.type==="brace"&&node.invalid!==true&&node.nodes.length===2){q.push(append(q.pop(),["{}"]));return}if(node.nodes&&node.ranges>0){const args=utils.reduce(node.nodes);if(utils.exceedsLimit(...args,options.step,rangeLimit)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let range=fill(...args,options);if(range.length===0){range=stringify12(node,options)}q.push(append(q.pop(),range));node.nodes=[];return}const enclose=utils.encloseBrace(node);let queue=node.queue;let block=node;while(block.type!=="brace"&&block.type!=="root"&&block.parent){block=block.parent;queue=block.queue}for(let i=0;i<node.nodes.length;i++){const child=node.nodes[i];if(child.type==="comma"&&node.type==="brace"){if(i===1)queue.push("");queue.push("");continue}if(child.type==="close"){q.push(append(q.pop(),queue,enclose));continue}if(child.value&&child.type!=="open"){queue.push(append(queue.pop(),child.value));continue}if(child.nodes){walk(child,node)}}return queue};return utils.flatten(walk(ast))};module2.exports=expand2}});var require_constants9=__commonJS({"../../node_modules/braces/lib/constants.js"(exports2,module2){"use strict";module2.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:"\n",CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}}});var require_parse5=__commonJS({"../../node_modules/braces/lib/parse.js"(exports2,module2){"use strict";var stringify12=require_stringify();var{MAX_LENGTH,CHAR_BACKSLASH,CHAR_BACKTICK,CHAR_COMMA,CHAR_DOT,CHAR_LEFT_PARENTHESES,CHAR_RIGHT_PARENTHESES,CHAR_LEFT_CURLY_BRACE,CHAR_RIGHT_CURLY_BRACE,CHAR_LEFT_SQUARE_BRACKET,CHAR_RIGHT_SQUARE_BRACKET,CHAR_DOUBLE_QUOTE,CHAR_SINGLE_QUOTE,CHAR_NO_BREAK_SPACE,CHAR_ZERO_WIDTH_NOBREAK_SPACE}=require_constants9();var parse11=(input,options={})=>{if(typeof input!=="string"){throw new TypeError("Expected a string")}const opts=options||{};const max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH;if(input.length>max){throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`)}const ast={type:"root",input,nodes:[]};const stack=[ast];let block=ast;let prev=ast;let brackets=0;const length=input.length;let index=0;let depth=0;let value;const advance=()=>input[index++];const push=node=>{if(node.type==="text"&&prev.type==="dot"){prev.type="text"}if(prev&&prev.type==="text"&&node.type==="text"){prev.value+=node.value;return}block.nodes.push(node);node.parent=block;node.prev=prev;prev=node;return node};push({type:"bos"});while(index<length){block=stack[stack.length-1];value=advance();if(value===CHAR_ZERO_WIDTH_NOBREAK_SPACE||value===CHAR_NO_BREAK_SPACE){continue}if(value===CHAR_BACKSLASH){push({type:"text",value:(options.keepEscaping?value:"")+advance()});continue}if(value===CHAR_RIGHT_SQUARE_BRACKET){push({type:"text",value:"\\"+value});continue}if(value===CHAR_LEFT_SQUARE_BRACKET){brackets++;let next;while(index<length&&(next=advance())){value+=next;if(next===CHAR_LEFT_SQUARE_BRACKET){brackets++;continue}if(next===CHAR_BACKSLASH){value+=advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){brackets--;if(brackets===0){break}}}push({type:"text",value});continue}if(value===CHAR_LEFT_PARENTHESES){block=push({type:"paren",nodes:[]});stack.push(block);push({type:"text",value});continue}if(value===CHAR_RIGHT_PARENTHESES){if(block.type!=="paren"){push({type:"text",value});continue}block=stack.pop();push({type:"text",value});block=stack[stack.length-1];continue}if(value===CHAR_DOUBLE_QUOTE||value===CHAR_SINGLE_QUOTE||value===CHAR_BACKTICK){const open=value;let next;if(options.keepQuotes!==true){value=""}while(index<length&&(next=advance())){if(next===CHAR_BACKSLASH){value+=next+advance();continue}if(next===open){if(options.keepQuotes===true)value+=next;break}value+=next}push({type:"text",value});continue}if(value===CHAR_LEFT_CURLY_BRACE){depth++;const dollar=prev.value&&prev.value.slice(-1)==="$"||block.dollar===true;const brace={type:"brace",open:true,close:false,dollar,depth,commas:0,ranges:0,nodes:[]};block=push(brace);stack.push(block);push({type:"open",value});continue}if(value===CHAR_RIGHT_CURLY_BRACE){if(block.type!=="brace"){push({type:"text",value});continue}const type="close";block=stack.pop();block.close=true;push({type,value});depth--;block=stack[stack.length-1];continue}if(value===CHAR_COMMA&&depth>0){if(block.ranges>0){block.ranges=0;const open=block.nodes.shift();block.nodes=[open,{type:"text",value:stringify12(block)}]}push({type:"comma",value});block.commas++;continue}if(value===CHAR_DOT&&depth>0&&block.commas===0){const siblings=block.nodes;if(depth===0||siblings.length===0){push({type:"text",value});continue}if(prev.type==="dot"){block.range=[];prev.value+=value;prev.type="range";if(block.nodes.length!==3&&block.nodes.length!==5){block.invalid=true;block.ranges=0;prev.type="text";continue}block.ranges++;block.args=[];continue}if(prev.type==="range"){siblings.pop();const before=siblings[siblings.length-1];before.value+=prev.value+value;prev=before;block.ranges--;continue}push({type:"dot",value});continue}push({type:"text",value})}do{block=stack.pop();if(block.type!=="root"){block.nodes.forEach(node=>{if(!node.nodes){if(node.type==="open")node.isOpen=true;if(node.type==="close")node.isClose=true;if(!node.nodes)node.type="text";node.invalid=true}});const parent=stack[stack.length-1];const index2=parent.nodes.indexOf(block);parent.nodes.splice(index2,1,...block.nodes)}}while(stack.length>0);push({type:"eos"});return ast};module2.exports=parse11}});var require_braces=__commonJS({"../../node_modules/braces/index.js"(exports2,module2){"use strict";var stringify12=require_stringify();var compile=require_compile2();var expand2=require_expand();var parse11=require_parse5();var braces=(input,options={})=>{let output=[];if(Array.isArray(input)){for(const pattern of input){const result=braces.create(pattern,options);if(Array.isArray(result)){output.push(...result)}else{output.push(result)}}}else{output=[].concat(braces.create(input,options))}if(options&&options.expand===true&&options.nodupes===true){output=[...new Set(output)]}return output};braces.parse=(input,options={})=>parse11(input,options);braces.stringify=(input,options={})=>{if(typeof input==="string"){return stringify12(braces.parse(input,options),options)}return stringify12(input,options)};braces.compile=(input,options={})=>{if(typeof input==="string"){input=braces.parse(input,options)}return compile(input,options)};braces.expand=(input,options={})=>{if(typeof input==="string"){input=braces.parse(input,options)}let result=expand2(input,options);if(options.noempty===true){result=result.filter(Boolean)}if(options.nodupes===true){result=[...new Set(result)]}return result};braces.create=(input,options={})=>{if(input===""||input.length<3){return[input]}return options.expand!==true?braces.compile(input,options):braces.expand(input,options)};module2.exports=braces}});var require_binary_extensions=__commonJS({"../../node_modules/binary-extensions/binary-extensions.json"(exports2,module2){module2.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]}});var require_binary_extensions2=__commonJS({"../../node_modules/binary-extensions/index.js"(exports2,module2){module2.exports=require_binary_extensions()}});var require_is_binary_path=__commonJS({"../../node_modules/is-binary-path/index.js"(exports2,module2){"use strict";var path24=require("path");var binaryExtensions=require_binary_extensions2();var extensions=new Set(binaryExtensions);module2.exports=filePath=>extensions.has(path24.extname(filePath).slice(1).toLowerCase())}});var require_constants10=__commonJS({"../../node_modules/chokidar/lib/constants.js"(exports2){"use strict";var{sep:sep2}=require("path");var{platform:platform3}=process;var os8=require("os");exports2.EV_ALL="all";exports2.EV_READY="ready";exports2.EV_ADD="add";exports2.EV_CHANGE="change";exports2.EV_ADD_DIR="addDir";exports2.EV_UNLINK="unlink";exports2.EV_UNLINK_DIR="unlinkDir";exports2.EV_RAW="raw";exports2.EV_ERROR="error";exports2.STR_DATA="data";exports2.STR_END="end";exports2.STR_CLOSE="close";exports2.FSEVENT_CREATED="created";exports2.FSEVENT_MODIFIED="modified";exports2.FSEVENT_DELETED="deleted";exports2.FSEVENT_MOVED="moved";exports2.FSEVENT_CLONED="cloned";exports2.FSEVENT_UNKNOWN="unknown";exports2.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;exports2.FSEVENT_TYPE_FILE="file";exports2.FSEVENT_TYPE_DIRECTORY="directory";exports2.FSEVENT_TYPE_SYMLINK="symlink";exports2.KEY_LISTENERS="listeners";exports2.KEY_ERR="errHandlers";exports2.KEY_RAW="rawEmitters";exports2.HANDLER_KEYS=[exports2.KEY_LISTENERS,exports2.KEY_ERR,exports2.KEY_RAW];exports2.DOT_SLASH=`.${sep2}`;exports2.BACK_SLASH_RE=/\\/g;exports2.DOUBLE_SLASH_RE=/\/\//;exports2.SLASH_OR_BACK_SLASH_RE=/[/\\]/;exports2.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;exports2.REPLACER_RE=/^\.[/\\]/;exports2.SLASH="/";exports2.SLASH_SLASH="//";exports2.BRACE_START="{";exports2.BANG="!";exports2.ONE_DOT=".";exports2.TWO_DOTS="..";exports2.STAR="*";exports2.GLOBSTAR="**";exports2.ROOT_GLOBSTAR="/**/*";exports2.SLASH_GLOBSTAR="/**";exports2.DIR_SUFFIX="Dir";exports2.ANYMATCH_OPTS={dot:true};exports2.STRING_TYPE="string";exports2.FUNCTION_TYPE="function";exports2.EMPTY_STR="";exports2.EMPTY_FN=()=>{};exports2.IDENTITY_FN=val2=>val2;exports2.isWindows=platform3==="win32";exports2.isMacos=platform3==="darwin";exports2.isLinux=platform3==="linux";exports2.isIBMi=os8.type()==="OS400"}});var require_nodefs_handler=__commonJS({"../../node_modules/chokidar/lib/nodefs-handler.js"(exports2,module2){"use strict";var fs23=require("fs");var sysPath=require("path");var{promisify:promisify2}=require("util");var isBinaryPath=require_is_binary_path();var{isWindows,isLinux,EMPTY_FN,EMPTY_STR,KEY_LISTENERS,KEY_ERR,KEY_RAW,HANDLER_KEYS,EV_CHANGE,EV_ADD,EV_ADD_DIR,EV_ERROR,STR_DATA,STR_END,BRACE_START,STAR}=require_constants10();var THROTTLE_MODE_WATCH="watch";var open=promisify2(fs23.open);var stat4=promisify2(fs23.stat);var lstat=promisify2(fs23.lstat);var close=promisify2(fs23.close);var fsrealpath=promisify2(fs23.realpath);var statMethods={lstat,stat:stat4};var foreach=(val2,fn)=>{if(val2 instanceof Set){val2.forEach(fn)}else{fn(val2)}};var addAndConvert=(main,prop,item)=>{let container=main[prop];if(!(container instanceof Set)){main[prop]=container=new Set([container])}container.add(item)};var clearItem=cont=>key=>{const set=cont[key];if(set instanceof Set){set.clear()}else{delete cont[key]}};var delFromSet=(main,prop,item)=>{const container=main[prop];if(container instanceof Set){container.delete(item)}else if(container===item){delete main[prop]}};var isEmptySet=val2=>val2 instanceof Set?val2.size===0:!val2;var FsWatchInstances=new Map;function createFsWatchInstance(path24,options,listener,errHandler,emitRaw){const handleEvent=(rawEvent,evPath)=>{listener(path24);emitRaw(rawEvent,evPath,{watchedPath:path24});if(evPath&&path24!==evPath){fsWatchBroadcast(sysPath.resolve(path24,evPath),KEY_LISTENERS,sysPath.join(path24,evPath))}};try{return fs23.watch(path24,options,handleEvent)}catch(error3){errHandler(error3)}}var fsWatchBroadcast=(fullPath,type,val1,val2,val3)=>{const cont=FsWatchInstances.get(fullPath);if(!cont)return;foreach(cont[type],listener=>{listener(val1,val2,val3)})};var setFsWatchListener=(path24,fullPath,options,handlers)=>{const{listener,errHandler,rawEmitter}=handlers;let cont=FsWatchInstances.get(fullPath);let watcher;if(!options.persistent){watcher=createFsWatchInstance(path24,options,listener,errHandler,rawEmitter);return watcher.close.bind(watcher)}if(cont){addAndConvert(cont,KEY_LISTENERS,listener);addAndConvert(cont,KEY_ERR,errHandler);addAndConvert(cont,KEY_RAW,rawEmitter)}else{watcher=createFsWatchInstance(path24,options,fsWatchBroadcast.bind(null,fullPath,KEY_LISTENERS),errHandler,fsWatchBroadcast.bind(null,fullPath,KEY_RAW));if(!watcher)return;watcher.on(EV_ERROR,async error3=>{const broadcastErr=fsWatchBroadcast.bind(null,fullPath,KEY_ERR);cont.watcherUnusable=true;if(isWindows&&error3.code==="EPERM"){try{const fd=await open(path24,"r");await close(fd);broadcastErr(error3)}catch(err){}}else{broadcastErr(error3)}});cont={listeners:listener,errHandlers:errHandler,rawEmitters:rawEmitter,watcher};FsWatchInstances.set(fullPath,cont)}return()=>{delFromSet(cont,KEY_LISTENERS,listener);delFromSet(cont,KEY_ERR,errHandler);delFromSet(cont,KEY_RAW,rawEmitter);if(isEmptySet(cont.listeners)){cont.watcher.close();FsWatchInstances.delete(fullPath);HANDLER_KEYS.forEach(clearItem(cont));cont.watcher=void 0;Object.freeze(cont)}}};var FsWatchFileInstances=new Map;var setFsWatchFileListener=(path24,fullPath,options,handlers)=>{const{listener,rawEmitter}=handlers;let cont=FsWatchFileInstances.get(fullPath);let listeners=new Set;let rawEmitters=new Set;const copts=cont&&cont.options;if(copts&&(copts.persistent<options.persistent||copts.interval>options.interval)){listeners=cont.listeners;rawEmitters=cont.rawEmitters;fs23.unwatchFile(fullPath);cont=void 0}if(cont){addAndConvert(cont,KEY_LISTENERS,listener);addAndConvert(cont,KEY_RAW,rawEmitter)}else{cont={listeners:listener,rawEmitters:rawEmitter,options,watcher:fs23.watchFile(fullPath,options,(curr,prev)=>{foreach(cont.rawEmitters,rawEmitter2=>{rawEmitter2(EV_CHANGE,fullPath,{curr,prev})});const currmtime=curr.mtimeMs;if(curr.size!==prev.size||currmtime>prev.mtimeMs||currmtime===0){foreach(cont.listeners,listener2=>listener2(path24,curr))}})};FsWatchFileInstances.set(fullPath,cont)}return()=>{delFromSet(cont,KEY_LISTENERS,listener);delFromSet(cont,KEY_RAW,rawEmitter);if(isEmptySet(cont.listeners)){FsWatchFileInstances.delete(fullPath);fs23.unwatchFile(fullPath);cont.options=cont.watcher=void 0;Object.freeze(cont)}}};var NodeFsHandler=class{constructor(fsW){this.fsw=fsW;this._boundHandleError=error3=>fsW._handleError(error3)}_watchWithNodeFs(path24,listener){const opts=this.fsw.options;const directory=sysPath.dirname(path24);const basename3=sysPath.basename(path24);const parent=this.fsw._getWatchedDir(directory);parent.add(basename3);const absolutePath=sysPath.resolve(path24);const options={persistent:opts.persistent};if(!listener)listener=EMPTY_FN;let closer;if(opts.usePolling){options.interval=opts.enableBinaryInterval&&isBinaryPath(basename3)?opts.binaryInterval:opts.interval;closer=setFsWatchFileListener(path24,absolutePath,options,{listener,rawEmitter:this.fsw._emitRaw})}else{closer=setFsWatchListener(path24,absolutePath,options,{listener,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw})}return closer}_handleFile(file,stats,initialAdd){if(this.fsw.closed){return}const dirname7=sysPath.dirname(file);const basename3=sysPath.basename(file);const parent=this.fsw._getWatchedDir(dirname7);let prevStats=stats;if(parent.has(basename3))return;const listener=async(path24,newStats)=>{if(!this.fsw._throttle(THROTTLE_MODE_WATCH,file,5))return;if(!newStats||newStats.mtimeMs===0){try{const newStats2=await stat4(file);if(this.fsw.closed)return;const at=newStats2.atimeMs;const mt=newStats2.mtimeMs;if(!at||at<=mt||mt!==prevStats.mtimeMs){this.fsw._emit(EV_CHANGE,file,newStats2)}if(isLinux&&prevStats.ino!==newStats2.ino){this.fsw._closeFile(path24);prevStats=newStats2;this.fsw._addPathCloser(path24,this._watchWithNodeFs(file,listener))}else{prevStats=newStats2}}catch(error3){this.fsw._remove(dirname7,basename3)}}else if(parent.has(basename3)){const at=newStats.atimeMs;const mt=newStats.mtimeMs;if(!at||at<=mt||mt!==prevStats.mtimeMs){this.fsw._emit(EV_CHANGE,file,newStats)}prevStats=newStats}};const closer=this._watchWithNodeFs(file,listener);if(!(initialAdd&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(file)){if(!this.fsw._throttle(EV_ADD,file,0))return;this.fsw._emit(EV_ADD,file,stats)}return closer}async _handleSymlink(entry,directory,path24,item){if(this.fsw.closed){return}const full=entry.fullPath;const dir=this.fsw._getWatchedDir(directory);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let linkPath;try{linkPath=await fsrealpath(path24)}catch(e){this.fsw._emitReady();return true}if(this.fsw.closed)return;if(dir.has(item)){if(this.fsw._symlinkPaths.get(full)!==linkPath){this.fsw._symlinkPaths.set(full,linkPath);this.fsw._emit(EV_CHANGE,path24,entry.stats)}}else{dir.add(item);this.fsw._symlinkPaths.set(full,linkPath);this.fsw._emit(EV_ADD,path24,entry.stats)}this.fsw._emitReady();return true}if(this.fsw._symlinkPaths.has(full)){return true}this.fsw._symlinkPaths.set(full,true)}_handleRead(directory,initialAdd,wh,target,dir,depth,throttler){directory=sysPath.join(directory,EMPTY_STR);if(!wh.hasGlob){throttler=this.fsw._throttle("readdir",directory,1e3);if(!throttler)return}const previous=this.fsw._getWatchedDir(wh.path);const current=new Set;let stream=this.fsw._readdirp(directory,{fileFilter:entry=>wh.filterPath(entry),directoryFilter:entry=>wh.filterDir(entry),depth:0}).on(STR_DATA,async entry=>{if(this.fsw.closed){stream=void 0;return}const item=entry.path;let path24=sysPath.join(directory,item);current.add(item);if(entry.stats.isSymbolicLink()&&await this._handleSymlink(entry,directory,path24,item)){return}if(this.fsw.closed){stream=void 0;return}if(item===target||!target&&!previous.has(item)){this.fsw._incrReadyCount();path24=sysPath.join(dir,sysPath.relative(dir,path24));this._addToNodeFs(path24,initialAdd,wh,depth+1)}}).on(EV_ERROR,this._boundHandleError);return new Promise(resolve7=>stream.once(STR_END,()=>{if(this.fsw.closed){stream=void 0;return}const wasThrottled=throttler?throttler.clear():false;resolve7();previous.getChildren().filter(item=>{return item!==directory&&!current.has(item)&&(!wh.hasGlob||wh.filterPath({fullPath:sysPath.resolve(directory,item)}))}).forEach(item=>{this.fsw._remove(directory,item)});stream=void 0;if(wasThrottled)this._handleRead(directory,false,wh,target,dir,depth,throttler)}))}async _handleDir(dir,stats,initialAdd,depth,target,wh,realpath){const parentDir=this.fsw._getWatchedDir(sysPath.dirname(dir));const tracked=parentDir.has(sysPath.basename(dir));if(!(initialAdd&&this.fsw.options.ignoreInitial)&&!target&&!tracked){if(!wh.hasGlob||wh.globFilter(dir))this.fsw._emit(EV_ADD_DIR,dir,stats)}parentDir.add(sysPath.basename(dir));this.fsw._getWatchedDir(dir);let throttler;let closer;const oDepth=this.fsw.options.depth;if((oDepth==null||depth<=oDepth)&&!this.fsw._symlinkPaths.has(realpath)){if(!target){await this._handleRead(dir,initialAdd,wh,target,dir,depth,throttler);if(this.fsw.closed)return}closer=this._watchWithNodeFs(dir,(dirPath,stats2)=>{if(stats2&&stats2.mtimeMs===0)return;this._handleRead(dirPath,false,wh,target,dir,depth,throttler)})}return closer}async _addToNodeFs(path24,initialAdd,priorWh,depth,target){const ready=this.fsw._emitReady;if(this.fsw._isIgnored(path24)||this.fsw.closed){ready();return false}const wh=this.fsw._getWatchHelpers(path24,depth);if(!wh.hasGlob&&priorWh){wh.hasGlob=priorWh.hasGlob;wh.globFilter=priorWh.globFilter;wh.filterPath=entry=>priorWh.filterPath(entry);wh.filterDir=entry=>priorWh.filterDir(entry)}try{const stats=await statMethods[wh.statMethod](wh.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(wh.watchPath,stats)){ready();return false}const follow=this.fsw.options.followSymlinks&&!path24.includes(STAR)&&!path24.includes(BRACE_START);let closer;if(stats.isDirectory()){const absPath=sysPath.resolve(path24);const targetPath=follow?await fsrealpath(path24):path24;if(this.fsw.closed)return;closer=await this._handleDir(wh.watchPath,stats,initialAdd,depth,target,wh,targetPath);if(this.fsw.closed)return;if(absPath!==targetPath&&targetPath!==void 0){this.fsw._symlinkPaths.set(absPath,targetPath)}}else if(stats.isSymbolicLink()){const targetPath=follow?await fsrealpath(path24):path24;if(this.fsw.closed)return;const parent=sysPath.dirname(wh.watchPath);this.fsw._getWatchedDir(parent).add(wh.watchPath);this.fsw._emit(EV_ADD,wh.watchPath,stats);closer=await this._handleDir(parent,stats,initialAdd,depth,path24,wh,targetPath);if(this.fsw.closed)return;if(targetPath!==void 0){this.fsw._symlinkPaths.set(sysPath.resolve(path24),targetPath)}}else{closer=this._handleFile(wh.watchPath,stats,initialAdd)}ready();this.fsw._addPathCloser(path24,closer);return false}catch(error3){if(this.fsw._handleError(error3)){ready();return path24}}}};module2.exports=NodeFsHandler}});var require_fsevents_handler=__commonJS({"../../node_modules/chokidar/lib/fsevents-handler.js"(exports2,module2){"use strict";var fs23=require("fs");var sysPath=require("path");var{promisify:promisify2}=require("util");var fsevents;try{fsevents=require("fsevents")}catch(error3){if(process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR)console.error(error3)}if(fsevents){const mtch=process.version.match(/v(\d+)\.(\d+)/);if(mtch&&mtch[1]&&mtch[2]){const maj=Number.parseInt(mtch[1],10);const min=Number.parseInt(mtch[2],10);if(maj===8&&min<16){fsevents=void 0}}}var{EV_ADD,EV_CHANGE,EV_ADD_DIR,EV_UNLINK,EV_ERROR,STR_DATA,STR_END,FSEVENT_CREATED,FSEVENT_MODIFIED,FSEVENT_DELETED,FSEVENT_MOVED,FSEVENT_UNKNOWN,FSEVENT_FLAG_MUST_SCAN_SUBDIRS,FSEVENT_TYPE_FILE,FSEVENT_TYPE_DIRECTORY,FSEVENT_TYPE_SYMLINK,ROOT_GLOBSTAR,DIR_SUFFIX,DOT_SLASH,FUNCTION_TYPE,EMPTY_FN,IDENTITY_FN}=require_constants10();var Depth=value=>isNaN(value)?{}:{depth:value};var stat4=promisify2(fs23.stat);var lstat=promisify2(fs23.lstat);var realpath=promisify2(fs23.realpath);var statMethods={stat:stat4,lstat};var FSEventsWatchers=new Map;var consolidateThreshhold=10;var wrongEventFlags=new Set([69888,70400,71424,72704,73472,131328,131840,262912]);var createFSEventsInstance=(path24,callback)=>{const stop=fsevents.watch(path24,callback);return{stop}};function setFSEventsListener(path24,realPath,listener,rawEmitter){let watchPath=sysPath.extname(realPath)?sysPath.dirname(realPath):realPath;const parentPath=sysPath.dirname(watchPath);let cont=FSEventsWatchers.get(watchPath);if(couldConsolidate(parentPath)){watchPath=parentPath}const resolvedPath7=sysPath.resolve(path24);const hasSymlink=resolvedPath7!==realPath;const filteredListener=(fullPath,flags,info2)=>{if(hasSymlink)fullPath=fullPath.replace(realPath,resolvedPath7);if(fullPath===resolvedPath7||!fullPath.indexOf(resolvedPath7+sysPath.sep))listener(fullPath,flags,info2)};let watchedParent=false;for(const watchedPath of FSEventsWatchers.keys()){if(realPath.indexOf(sysPath.resolve(watchedPath)+sysPath.sep)===0){watchPath=watchedPath;cont=FSEventsWatchers.get(watchPath);watchedParent=true;break}}if(cont||watchedParent){cont.listeners.add(filteredListener)}else{cont={listeners:new Set([filteredListener]),rawEmitter,watcher:createFSEventsInstance(watchPath,(fullPath,flags)=>{if(!cont.listeners.size)return;if(flags&FSEVENT_FLAG_MUST_SCAN_SUBDIRS)return;const info2=fsevents.getInfo(fullPath,flags);cont.listeners.forEach(list=>{list(fullPath,flags,info2)});cont.rawEmitter(info2.event,fullPath,info2)})};FSEventsWatchers.set(watchPath,cont)}return()=>{const lst=cont.listeners;lst.delete(filteredListener);if(!lst.size){FSEventsWatchers.delete(watchPath);if(cont.watcher)return cont.watcher.stop().then(()=>{cont.rawEmitter=cont.watcher=void 0;Object.freeze(cont)})}}}var couldConsolidate=path24=>{let count=0;for(const watchPath of FSEventsWatchers.keys()){if(watchPath.indexOf(path24)===0){count++;if(count>=consolidateThreshhold){return true}}}return false};var canUse=()=>fsevents&&FSEventsWatchers.size<128;var calcDepth=(path24,root)=>{let i=0;while(!path24.indexOf(root)&&(path24=sysPath.dirname(path24))!==root)i++;return i};var sameTypes=(info2,stats)=>info2.type===FSEVENT_TYPE_DIRECTORY&&stats.isDirectory()||info2.type===FSEVENT_TYPE_SYMLINK&&stats.isSymbolicLink()||info2.type===FSEVENT_TYPE_FILE&&stats.isFile();var FsEventsHandler=class{constructor(fsw){this.fsw=fsw}checkIgnored(path24,stats){const ipaths=this.fsw._ignoredPaths;if(this.fsw._isIgnored(path24,stats)){ipaths.add(path24);if(stats&&stats.isDirectory()){ipaths.add(path24+ROOT_GLOBSTAR)}return true}ipaths.delete(path24);ipaths.delete(path24+ROOT_GLOBSTAR)}addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts){const event=watchedDir.has(item)?EV_CHANGE:EV_ADD;this.handleEvent(event,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}async checkExists(path24,fullPath,realPath,parent,watchedDir,item,info2,opts){try{const stats=await stat4(path24);if(this.fsw.closed)return;if(sameTypes(info2,stats)){this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}else{this.handleEvent(EV_UNLINK,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}catch(error3){if(error3.code==="EACCES"){this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}else{this.handleEvent(EV_UNLINK,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}}handleEvent(event,path24,fullPath,realPath,parent,watchedDir,item,info2,opts){if(this.fsw.closed||this.checkIgnored(path24))return;if(event===EV_UNLINK){const isDirectory=info2.type===FSEVENT_TYPE_DIRECTORY;if(isDirectory||watchedDir.has(item)){this.fsw._remove(parent,item,isDirectory)}}else{if(event===EV_ADD){if(info2.type===FSEVENT_TYPE_DIRECTORY)this.fsw._getWatchedDir(path24);if(info2.type===FSEVENT_TYPE_SYMLINK&&opts.followSymlinks){const curDepth=opts.depth===void 0?void 0:calcDepth(fullPath,realPath)+1;return this._addToFsEvents(path24,false,true,curDepth)}this.fsw._getWatchedDir(parent).add(item)}const eventName=info2.type===FSEVENT_TYPE_DIRECTORY?event+DIR_SUFFIX:event;this.fsw._emit(eventName,path24);if(eventName===EV_ADD_DIR)this._addToFsEvents(path24,false,true)}}_watchWithFsEvents(watchPath,realPath,transform,globFilter){if(this.fsw.closed||this.fsw._isIgnored(watchPath))return;const opts=this.fsw.options;const watchCallback=async(fullPath,flags,info2)=>{if(this.fsw.closed)return;if(opts.depth!==void 0&&calcDepth(fullPath,realPath)>opts.depth)return;const path24=transform(sysPath.join(watchPath,sysPath.relative(watchPath,fullPath)));if(globFilter&&!globFilter(path24))return;const parent=sysPath.dirname(path24);const item=sysPath.basename(path24);const watchedDir=this.fsw._getWatchedDir(info2.type===FSEVENT_TYPE_DIRECTORY?path24:parent);if(wrongEventFlags.has(flags)||info2.event===FSEVENT_UNKNOWN){if(typeof opts.ignored===FUNCTION_TYPE){let stats;try{stats=await stat4(path24)}catch(error3){}if(this.fsw.closed)return;if(this.checkIgnored(path24,stats))return;if(sameTypes(info2,stats)){this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}else{this.handleEvent(EV_UNLINK,path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}else{this.checkExists(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}else{switch(info2.event){case FSEVENT_CREATED:case FSEVENT_MODIFIED:return this.addOrChange(path24,fullPath,realPath,parent,watchedDir,item,info2,opts);case FSEVENT_DELETED:case FSEVENT_MOVED:return this.checkExists(path24,fullPath,realPath,parent,watchedDir,item,info2,opts)}}};const closer=setFSEventsListener(watchPath,realPath,watchCallback,this.fsw._emitRaw);this.fsw._emitReady();return closer}async _handleFsEventsSymlink(linkPath,fullPath,transform,curDepth){if(this.fsw.closed||this.fsw._symlinkPaths.has(fullPath))return;this.fsw._symlinkPaths.set(fullPath,true);this.fsw._incrReadyCount();try{const linkTarget=await realpath(linkPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(linkTarget)){return this.fsw._emitReady()}this.fsw._incrReadyCount();this._addToFsEvents(linkTarget||linkPath,path24=>{let aliasedPath=linkPath;if(linkTarget&&linkTarget!==DOT_SLASH){aliasedPath=path24.replace(linkTarget,linkPath)}else if(path24!==DOT_SLASH){aliasedPath=sysPath.join(linkPath,path24)}return transform(aliasedPath)},false,curDepth)}catch(error3){if(this.fsw._handleError(error3)){return this.fsw._emitReady()}}}emitAdd(newPath,stats,processPath,opts,forceAdd){const pp=processPath(newPath);const isDir=stats.isDirectory();const dirObj=this.fsw._getWatchedDir(sysPath.dirname(pp));const base=sysPath.basename(pp);if(isDir)this.fsw._getWatchedDir(pp);if(dirObj.has(base))return;dirObj.add(base);if(!opts.ignoreInitial||forceAdd===true){this.fsw._emit(isDir?EV_ADD_DIR:EV_ADD,pp,stats)}}initWatch(realPath,path24,wh,processPath){if(this.fsw.closed)return;const closer=this._watchWithFsEvents(wh.watchPath,sysPath.resolve(realPath||wh.watchPath),processPath,wh.globFilter);this.fsw._addPathCloser(path24,closer)}async _addToFsEvents(path24,transform,forceAdd,priorDepth){if(this.fsw.closed){return}const opts=this.fsw.options;const processPath=typeof transform===FUNCTION_TYPE?transform:IDENTITY_FN;const wh=this.fsw._getWatchHelpers(path24);try{const stats=await statMethods[wh.statMethod](wh.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(wh.watchPath,stats)){throw null}if(stats.isDirectory()){if(!wh.globFilter)this.emitAdd(processPath(path24),stats,processPath,opts,forceAdd);if(priorDepth&&priorDepth>opts.depth)return;this.fsw._readdirp(wh.watchPath,{fileFilter:entry=>wh.filterPath(entry),directoryFilter:entry=>wh.filterDir(entry),...Depth(opts.depth-(priorDepth||0))}).on(STR_DATA,entry=>{if(this.fsw.closed){return}if(entry.stats.isDirectory()&&!wh.filterPath(entry))return;const joinedPath=sysPath.join(wh.watchPath,entry.path);const{fullPath}=entry;if(wh.followSymlinks&&entry.stats.isSymbolicLink()){const curDepth=opts.depth===void 0?void 0:calcDepth(joinedPath,sysPath.resolve(wh.watchPath))+1;this._handleFsEventsSymlink(joinedPath,fullPath,processPath,curDepth)}else{this.emitAdd(joinedPath,entry.stats,processPath,opts,forceAdd)}}).on(EV_ERROR,EMPTY_FN).on(STR_END,()=>{this.fsw._emitReady()})}else{this.emitAdd(wh.watchPath,stats,processPath,opts,forceAdd);this.fsw._emitReady()}}catch(error3){if(!error3||this.fsw._handleError(error3)){this.fsw._emitReady();this.fsw._emitReady()}}if(opts.persistent&&forceAdd!==true){if(typeof transform===FUNCTION_TYPE){this.initWatch(void 0,path24,wh,processPath)}else{let realPath;try{realPath=await realpath(wh.watchPath)}catch(e){}this.initWatch(realPath,path24,wh,processPath)}}}};module2.exports=FsEventsHandler;module2.exports.canUse=canUse}});var require_chokidar=__commonJS({"../../node_modules/chokidar/index.js"(exports2){"use strict";var{EventEmitter}=require("events");var fs23=require("fs");var sysPath=require("path");var{promisify:promisify2}=require("util");var readdirp=require_readdirp();var anymatch=require_anymatch().default;var globParent=require_glob_parent();var isGlob=require_is_glob();var braces=require_braces();var normalizePath=require_normalize_path();var NodeFsHandler=require_nodefs_handler();var FsEventsHandler=require_fsevents_handler();var{EV_ALL,EV_READY,EV_ADD,EV_CHANGE,EV_UNLINK,EV_ADD_DIR,EV_UNLINK_DIR,EV_RAW,EV_ERROR,STR_CLOSE,STR_END,BACK_SLASH_RE,DOUBLE_SLASH_RE,SLASH_OR_BACK_SLASH_RE,DOT_RE,REPLACER_RE,SLASH,SLASH_SLASH,BRACE_START,BANG,ONE_DOT,TWO_DOTS,GLOBSTAR:GLOBSTAR2,SLASH_GLOBSTAR,ANYMATCH_OPTS,STRING_TYPE,FUNCTION_TYPE,EMPTY_STR,EMPTY_FN,isWindows,isMacos,isIBMi}=require_constants10();var stat4=promisify2(fs23.stat);var readdir2=promisify2(fs23.readdir);var arrify=(value=[])=>Array.isArray(value)?value:[value];var flatten2=(list,result=[])=>{list.forEach(item=>{if(Array.isArray(item)){flatten2(item,result)}else{result.push(item)}});return result};var unifyPaths=paths_=>{const paths=flatten2(arrify(paths_));if(!paths.every(p=>typeof p===STRING_TYPE)){throw new TypeError(`Non-string provided as watch path: ${paths}`)}return paths.map(normalizePathToUnix)};var toUnix=string=>{let str=string.replace(BACK_SLASH_RE,SLASH);let prepend=false;if(str.startsWith(SLASH_SLASH)){prepend=true}while(str.match(DOUBLE_SLASH_RE)){str=str.replace(DOUBLE_SLASH_RE,SLASH)}if(prepend){str=SLASH+str}return str};var normalizePathToUnix=path24=>toUnix(sysPath.normalize(toUnix(path24)));var normalizeIgnored=(cwd=EMPTY_STR)=>path24=>{if(typeof path24!==STRING_TYPE)return path24;return normalizePathToUnix(sysPath.isAbsolute(path24)?path24:sysPath.join(cwd,path24))};var getAbsolutePath=(path24,cwd)=>{if(sysPath.isAbsolute(path24)){return path24}if(path24.startsWith(BANG)){return BANG+sysPath.join(cwd,path24.slice(1))}return sysPath.join(cwd,path24)};var undef=(opts,key)=>opts[key]===void 0;var DirEntry=class{constructor(dir,removeWatcher){this.path=dir;this._removeWatcher=removeWatcher;this.items=new Set}add(item){const{items}=this;if(!items)return;if(item!==ONE_DOT&&item!==TWO_DOTS)items.add(item)}async remove(item){const{items}=this;if(!items)return;items.delete(item);if(items.size>0)return;const dir=this.path;try{await readdir2(dir)}catch(err){if(this._removeWatcher){this._removeWatcher(sysPath.dirname(dir),sysPath.basename(dir))}}}has(item){const{items}=this;if(!items)return;return items.has(item)}getChildren(){const{items}=this;if(!items)return;return[...items.values()]}dispose(){this.items.clear();delete this.path;delete this._removeWatcher;delete this.items;Object.freeze(this)}};var STAT_METHOD_F="stat";var STAT_METHOD_L="lstat";var WatchHelper=class{constructor(path24,watchPath,follow,fsw){this.fsw=fsw;this.path=path24=path24.replace(REPLACER_RE,EMPTY_STR);this.watchPath=watchPath;this.fullWatchPath=sysPath.resolve(watchPath);this.hasGlob=watchPath!==path24;if(path24===EMPTY_STR)this.hasGlob=false;this.globSymlink=this.hasGlob&&follow?void 0:false;this.globFilter=this.hasGlob?anymatch(path24,void 0,ANYMATCH_OPTS):false;this.dirParts=this.getDirParts(path24);this.dirParts.forEach(parts=>{if(parts.length>1)parts.pop()});this.followSymlinks=follow;this.statMethod=follow?STAT_METHOD_F:STAT_METHOD_L}checkGlobSymlink(entry){if(this.globSymlink===void 0){this.globSymlink=entry.fullParentDir===this.fullWatchPath?false:{realPath:entry.fullParentDir,linkPath:this.fullWatchPath}}if(this.globSymlink){return entry.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath)}return entry.fullPath}entryPath(entry){return sysPath.join(this.watchPath,sysPath.relative(this.watchPath,this.checkGlobSymlink(entry)))}filterPath(entry){const{stats}=entry;if(stats&&stats.isSymbolicLink())return this.filterDir(entry);const resolvedPath7=this.entryPath(entry);const matchesGlob=this.hasGlob&&typeof this.globFilter===FUNCTION_TYPE?this.globFilter(resolvedPath7):true;return matchesGlob&&this.fsw._isntIgnored(resolvedPath7,stats)&&this.fsw._hasReadPermissions(stats)}getDirParts(path24){if(!this.hasGlob)return[];const parts=[];const expandedPath=path24.includes(BRACE_START)?braces.expand(path24):[path24];expandedPath.forEach(path25=>{parts.push(sysPath.relative(this.watchPath,path25).split(SLASH_OR_BACK_SLASH_RE))});return parts}filterDir(entry){if(this.hasGlob){const entryParts=this.getDirParts(this.checkGlobSymlink(entry));let globstar=false;this.unmatchedGlob=!this.dirParts.some(parts=>{return parts.every((part,i)=>{if(part===GLOBSTAR2)globstar=true;return globstar||!entryParts[0][i]||anymatch(part,entryParts[0][i],ANYMATCH_OPTS)})})}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(entry),entry.stats)}};var FSWatcher=class extends EventEmitter{constructor(_opts){super();const opts={};if(_opts)Object.assign(opts,_opts);this._watched=new Map;this._closers=new Map;this._ignoredPaths=new Set;this._throttled=new Map;this._symlinkPaths=new Map;this._streams=new Set;this.closed=false;if(undef(opts,"persistent"))opts.persistent=true;if(undef(opts,"ignoreInitial"))opts.ignoreInitial=false;if(undef(opts,"ignorePermissionErrors"))opts.ignorePermissionErrors=false;if(undef(opts,"interval"))opts.interval=100;if(undef(opts,"binaryInterval"))opts.binaryInterval=300;if(undef(opts,"disableGlobbing"))opts.disableGlobbing=false;opts.enableBinaryInterval=opts.binaryInterval!==opts.interval;if(undef(opts,"useFsEvents"))opts.useFsEvents=!opts.usePolling;const canUseFsEvents=FsEventsHandler.canUse();if(!canUseFsEvents)opts.useFsEvents=false;if(undef(opts,"usePolling")&&!opts.useFsEvents){opts.usePolling=isMacos}if(isIBMi){opts.usePolling=true}const envPoll=process.env.CHOKIDAR_USEPOLLING;if(envPoll!==void 0){const envLower=envPoll.toLowerCase();if(envLower==="false"||envLower==="0"){opts.usePolling=false}else if(envLower==="true"||envLower==="1"){opts.usePolling=true}else{opts.usePolling=!!envLower}}const envInterval=process.env.CHOKIDAR_INTERVAL;if(envInterval){opts.interval=Number.parseInt(envInterval,10)}if(undef(opts,"atomic"))opts.atomic=!opts.usePolling&&!opts.useFsEvents;if(opts.atomic)this._pendingUnlinks=new Map;if(undef(opts,"followSymlinks"))opts.followSymlinks=true;if(undef(opts,"awaitWriteFinish"))opts.awaitWriteFinish=false;if(opts.awaitWriteFinish===true)opts.awaitWriteFinish={};const awf=opts.awaitWriteFinish;if(awf){if(!awf.stabilityThreshold)awf.stabilityThreshold=2e3;if(!awf.pollInterval)awf.pollInterval=100;this._pendingWrites=new Map}if(opts.ignored)opts.ignored=arrify(opts.ignored);let readyCalls=0;this._emitReady=()=>{readyCalls++;if(readyCalls>=this._readyCount){this._emitReady=EMPTY_FN;this._readyEmitted=true;process.nextTick(()=>this.emit(EV_READY))}};this._emitRaw=(...args)=>this.emit(EV_RAW,...args);this._readyEmitted=false;this.options=opts;if(opts.useFsEvents){this._fsEventsHandler=new FsEventsHandler(this)}else{this._nodeFsHandler=new NodeFsHandler(this)}Object.freeze(opts)}add(paths_,_origAdd,_internal){const{cwd,disableGlobbing}=this.options;this.closed=false;let paths=unifyPaths(paths_);if(cwd){paths=paths.map(path24=>{const absPath=getAbsolutePath(path24,cwd);if(disableGlobbing||!isGlob(path24)){return absPath}return normalizePath(absPath)})}paths=paths.filter(path24=>{if(path24.startsWith(BANG)){this._ignoredPaths.add(path24.slice(1));return false}this._ignoredPaths.delete(path24);this._ignoredPaths.delete(path24+SLASH_GLOBSTAR);this._userIgnored=void 0;return true});if(this.options.useFsEvents&&this._fsEventsHandler){if(!this._readyCount)this._readyCount=paths.length;if(this.options.persistent)this._readyCount+=paths.length;paths.forEach(path24=>this._fsEventsHandler._addToFsEvents(path24))}else{if(!this._readyCount)this._readyCount=0;this._readyCount+=paths.length;Promise.all(paths.map(async path24=>{const res=await this._nodeFsHandler._addToNodeFs(path24,!_internal,0,0,_origAdd);if(res)this._emitReady();return res})).then(results=>{if(this.closed)return;results.filter(item=>item).forEach(item=>{this.add(sysPath.dirname(item),sysPath.basename(_origAdd||item))})})}return this}unwatch(paths_){if(this.closed)return this;const paths=unifyPaths(paths_);const{cwd}=this.options;paths.forEach(path24=>{if(!sysPath.isAbsolute(path24)&&!this._closers.has(path24)){if(cwd)path24=sysPath.join(cwd,path24);path24=sysPath.resolve(path24)}this._closePath(path24);this._ignoredPaths.add(path24);if(this._watched.has(path24)){this._ignoredPaths.add(path24+SLASH_GLOBSTAR)}this._userIgnored=void 0});return this}close(){if(this.closed)return this._closePromise;this.closed=true;this.removeAllListeners();const closers=[];this._closers.forEach(closerList=>closerList.forEach(closer=>{const promise=closer();if(promise instanceof Promise)closers.push(promise)}));this._streams.forEach(stream=>stream.destroy());this._userIgnored=void 0;this._readyCount=0;this._readyEmitted=false;this._watched.forEach(dirent=>dirent.dispose());["closers","watched","streams","symlinkPaths","throttled"].forEach(key=>{this[`_${key}`].clear()});this._closePromise=closers.length?Promise.all(closers).then(()=>void 0):Promise.resolve();return this._closePromise}getWatched(){const watchList={};this._watched.forEach((entry,dir)=>{const key=this.options.cwd?sysPath.relative(this.options.cwd,dir):dir;watchList[key||ONE_DOT]=entry.getChildren().sort()});return watchList}emitWithAll(event,args){this.emit(...args);if(event!==EV_ERROR)this.emit(EV_ALL,...args)}async _emit(event,path24,val1,val2,val3){if(this.closed)return;const opts=this.options;if(isWindows)path24=sysPath.normalize(path24);if(opts.cwd)path24=sysPath.relative(opts.cwd,path24);const args=[event,path24];if(val3!==void 0)args.push(val1,val2,val3);else if(val2!==void 0)args.push(val1,val2);else if(val1!==void 0)args.push(val1);const awf=opts.awaitWriteFinish;let pw;if(awf&&(pw=this._pendingWrites.get(path24))){pw.lastChange=new Date;return this}if(opts.atomic){if(event===EV_UNLINK){this._pendingUnlinks.set(path24,args);setTimeout(()=>{this._pendingUnlinks.forEach((entry,path25)=>{this.emit(...entry);this.emit(EV_ALL,...entry);this._pendingUnlinks.delete(path25)})},typeof opts.atomic==="number"?opts.atomic:100);return this}if(event===EV_ADD&&this._pendingUnlinks.has(path24)){event=args[0]=EV_CHANGE;this._pendingUnlinks.delete(path24)}}if(awf&&(event===EV_ADD||event===EV_CHANGE)&&this._readyEmitted){const awfEmit=(err,stats)=>{if(err){event=args[0]=EV_ERROR;args[1]=err;this.emitWithAll(event,args)}else if(stats){if(args.length>2){args[2]=stats}else{args.push(stats)}this.emitWithAll(event,args)}};this._awaitWriteFinish(path24,awf.stabilityThreshold,event,awfEmit);return this}if(event===EV_CHANGE){const isThrottled=!this._throttle(EV_CHANGE,path24,50);if(isThrottled)return this}if(opts.alwaysStat&&val1===void 0&&(event===EV_ADD||event===EV_ADD_DIR||event===EV_CHANGE)){const fullPath=opts.cwd?sysPath.join(opts.cwd,path24):path24;let stats;try{stats=await stat4(fullPath)}catch(err){}if(!stats||this.closed)return;args.push(stats)}this.emitWithAll(event,args);return this}_handleError(error3){const code=error3&&error3.code;if(error3&&code!=="ENOENT"&&code!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||code!=="EPERM"&&code!=="EACCES")){this.emit(EV_ERROR,error3)}return error3||this.closed}_throttle(actionType,path24,timeout){if(!this._throttled.has(actionType)){this._throttled.set(actionType,new Map)}const action=this._throttled.get(actionType);const actionPath=action.get(path24);if(actionPath){actionPath.count++;return false}let timeoutObject;const clear=()=>{const item=action.get(path24);const count=item?item.count:0;action.delete(path24);clearTimeout(timeoutObject);if(item)clearTimeout(item.timeoutObject);return count};timeoutObject=setTimeout(clear,timeout);const thr={timeoutObject,clear,count:0};action.set(path24,thr);return thr}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(path24,threshold,event,awfEmit){let timeoutHandler;let fullPath=path24;if(this.options.cwd&&!sysPath.isAbsolute(path24)){fullPath=sysPath.join(this.options.cwd,path24)}const now=new Date;const awaitWriteFinish=prevStat=>{fs23.stat(fullPath,(err,curStat)=>{if(err||!this._pendingWrites.has(path24)){if(err&&err.code!=="ENOENT")awfEmit(err);return}const now2=Number(new Date);if(prevStat&&curStat.size!==prevStat.size){this._pendingWrites.get(path24).lastChange=now2}const pw=this._pendingWrites.get(path24);const df=now2-pw.lastChange;if(df>=threshold){this._pendingWrites.delete(path24);awfEmit(void 0,curStat)}else{timeoutHandler=setTimeout(awaitWriteFinish,this.options.awaitWriteFinish.pollInterval,curStat)}})};if(!this._pendingWrites.has(path24)){this._pendingWrites.set(path24,{lastChange:now,cancelWait:()=>{this._pendingWrites.delete(path24);clearTimeout(timeoutHandler);return event}});timeoutHandler=setTimeout(awaitWriteFinish,this.options.awaitWriteFinish.pollInterval)}}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(path24,stats){if(this.options.atomic&&DOT_RE.test(path24))return true;if(!this._userIgnored){const{cwd}=this.options;const ign=this.options.ignored;const ignored=ign&&ign.map(normalizeIgnored(cwd));const paths=arrify(ignored).filter(path25=>typeof path25===STRING_TYPE&&!isGlob(path25)).map(path25=>path25+SLASH_GLOBSTAR);const list=this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored,paths);this._userIgnored=anymatch(list,void 0,ANYMATCH_OPTS)}return this._userIgnored([path24,stats])}_isntIgnored(path24,stat5){return!this._isIgnored(path24,stat5)}_getWatchHelpers(path24,depth){const watchPath=depth||this.options.disableGlobbing||!isGlob(path24)?path24:globParent(path24);const follow=this.options.followSymlinks;return new WatchHelper(path24,watchPath,follow,this)}_getWatchedDir(directory){if(!this._boundRemove)this._boundRemove=this._remove.bind(this);const dir=sysPath.resolve(directory);if(!this._watched.has(dir))this._watched.set(dir,new DirEntry(dir,this._boundRemove));return this._watched.get(dir)}_hasReadPermissions(stats){if(this.options.ignorePermissionErrors)return true;const md=stats&&Number.parseInt(stats.mode,10);const st=md&511;const it=Number.parseInt(st.toString(8)[0],10);return Boolean(4&it)}_remove(directory,item,isDirectory){const path24=sysPath.join(directory,item);const fullPath=sysPath.resolve(path24);isDirectory=isDirectory!=null?isDirectory:this._watched.has(path24)||this._watched.has(fullPath);if(!this._throttle("remove",path24,100))return;if(!isDirectory&&!this.options.useFsEvents&&this._watched.size===1){this.add(directory,item,true)}const wp=this._getWatchedDir(path24);const nestedDirectoryChildren=wp.getChildren();nestedDirectoryChildren.forEach(nested=>this._remove(path24,nested));const parent=this._getWatchedDir(directory);const wasTracked=parent.has(item);parent.remove(item);if(this._symlinkPaths.has(fullPath)){this._symlinkPaths.delete(fullPath)}let relPath=path24;if(this.options.cwd)relPath=sysPath.relative(this.options.cwd,path24);if(this.options.awaitWriteFinish&&this._pendingWrites.has(relPath)){const event=this._pendingWrites.get(relPath).cancelWait();if(event===EV_ADD)return}this._watched.delete(path24);this._watched.delete(fullPath);const eventName=isDirectory?EV_UNLINK_DIR:EV_UNLINK;if(wasTracked&&!this._isIgnored(path24))this._emit(eventName,path24);if(!this.options.useFsEvents){this._closePath(path24)}}_closePath(path24){this._closeFile(path24);const dir=sysPath.dirname(path24);this._getWatchedDir(dir).remove(sysPath.basename(path24))}_closeFile(path24){const closers=this._closers.get(path24);if(!closers)return;closers.forEach(closer=>closer());this._closers.delete(path24)}_addPathCloser(path24,closer){if(!closer)return;let list=this._closers.get(path24);if(!list){list=[];this._closers.set(path24,list)}list.push(closer)}_readdirp(root,opts){if(this.closed)return;const options={type:EV_ALL,alwaysStat:true,lstat:true,...opts};let stream=readdirp(root,options);this._streams.add(stream);stream.once(STR_CLOSE,()=>{stream=void 0});stream.once(STR_END,()=>{if(stream){this._streams.delete(stream);stream=void 0}});return stream}};exports2.FSWatcher=FSWatcher;var watch2=(paths,options)=>{const watcher=new FSWatcher(options);watcher.add(paths);return watcher};exports2.watch=watch2}});async function findCloudWatchLogGroups(sdkProvider,stackArtifact){let sdk;const resolvedEnv=await sdkProvider.resolveEnvironment(stackArtifact.environment);try{sdk=(await new EnvironmentAccess(sdkProvider,DEFAULT_TOOLKIT_STACK_NAME).accessStackForLookup(stackArtifact)).sdk}catch(e){debug(`Failed to access SDK environment: ${e.message}`);sdk=(await sdkProvider.forEnvironment(resolvedEnv,0)).sdk}const listStackResources=new LazyListStackResources(sdk,stackArtifact.stackName);const evaluateCfnTemplate=new EvaluateCloudFormationTemplate({stackName:stackArtifact.stackName,template:stackArtifact.template,parameters:{},account:resolvedEnv.account,region:resolvedEnv.region,partition:(await sdk.currentAccount()).partition,sdk});const stackResources=await listStackResources.listStackResources();const logGroupNames=findAllLogGroupNames(stackResources,evaluateCfnTemplate);return{env:resolvedEnv,sdk,logGroupNames}}function isReferencedFromIgnoredResource(logGroupResource,evaluateCfnTemplate){const resourcesReferencingLogGroup=evaluateCfnTemplate.findReferencesTo(logGroupResource.LogicalResourceId);return resourcesReferencingLogGroup.some(reference=>{return IGNORE_LOGS_RESOURCE_TYPES.includes(reference.Type)})}function findAllLogGroupNames(stackResources,evaluateCfnTemplate){const logGroupNames=[];for(const resource of stackResources){const logGroupResolver=cloudWatchLogsResolvers[resource.ResourceType];if(logGroupResolver){const logGroupName=logGroupResolver(resource,evaluateCfnTemplate);if(logGroupName){logGroupNames.push(logGroupName)}}}return logGroupNames}var IGNORE_LOGS_RESOURCE_TYPES,cloudWatchLogsResolvers;var init_find_cloudwatch_logs=__esm({"lib/api/logs/find-cloudwatch-logs.ts"(){"use strict";init_logging();init_environment_access();init_evaluate_cloudformation_template();init_mode();init_toolkit_info();IGNORE_LOGS_RESOURCE_TYPES=["AWS::EC2::FlowLog","AWS::CloudTrail::Trail","AWS::CodeBuild::Project"];cloudWatchLogsResolvers={"AWS::Logs::LogGroup":(resource,evaluateCfnTemplate)=>{var _a;if(isReferencedFromIgnoredResource(resource,evaluateCfnTemplate)){return void 0}return(_a=resource.PhysicalResourceId)==null?void 0:_a.toString()},"AWS::Lambda::Function":(resource,evaluateCfnTemplate)=>{const loggingConfig=evaluateCfnTemplate.getResourceProperty(resource.LogicalResourceId,"LoggingConfig");if(loggingConfig==null?void 0:loggingConfig.LogGroup){if(typeof loggingConfig.LogGroup==="string"){return loggingConfig.LogGroup}if(typeof loggingConfig.LogGroup==="object"){if(loggingConfig.LogGroup.Ref){return evaluateCfnTemplate.getResourceProperty(loggingConfig.LogGroup.Ref,"LogGroupName")}}}return`/aws/lambda/${resource.PhysicalResourceId}`}}}});var util3,chalk18,SLEEP,CloudWatchLogEventMonitor;var init_logs_monitor=__esm({"lib/api/logs/logs-monitor.ts"(){"use strict";util3=__toESM(require("util"));chalk18=__toESM(require_source());init_logging();init_arrays();SLEEP=2e3;CloudWatchLogEventMonitor=class{constructor(startTime){this.envsLogGroupsAccessSettings=new Map;this.active=false;this.startTime=(startTime==null?void 0:startTime.getTime())??Date.now()}activate(){this.active=true;this.scheduleNextTick(0)}deactivate(){this.active=false;this.startTime=Date.now();this.envsLogGroupsAccessSettings.clear()}addLogGroups(env2,sdk,logGroupNames){var _a;const awsEnv=`${env2.account}:${env2.region}`;const logGroupsStartTimes=logGroupNames.reduce((acc,groupName)=>{acc[groupName]=this.startTime;return acc},{});this.envsLogGroupsAccessSettings.set(awsEnv,{sdk,logGroupsStartTimes:{...(_a=this.envsLogGroupsAccessSettings.get(awsEnv))==null?void 0:_a.logGroupsStartTimes,...logGroupsStartTimes}})}scheduleNextTick(sleep3){setTimeout(()=>void this.tick(),sleep3)}async tick(){if(!this.active){return}try{const events=flatten(await this.readNewEvents());events.forEach(event=>{this.print(event)})}catch(e){error("Error occurred while monitoring logs: %s",e)}this.scheduleNextTick(SLEEP)}async readNewEvents(){const promises=[];for(const settings of this.envsLogGroupsAccessSettings.values()){for(const group of Object.keys(settings.logGroupsStartTimes)){promises.push(this.readEventsFromLogGroup(settings,group))}}return Promise.all(promises)}print(event){print(util3.format("[%s] %s %s",chalk18.blue(event.logGroupName),chalk18.yellow(event.timestamp.toLocaleTimeString()),event.message.trim()))}async readEventsFromLogGroup(logGroupsAccessSettings,logGroupName){const events=[];const startTime=logGroupsAccessSettings.logGroupsStartTimes[logGroupName]??this.startTime;let endTime=startTime;try{const response=await logGroupsAccessSettings.sdk.cloudWatchLogs().filterLogEvents({logGroupName,limit:100,startTime});const filteredEvents=response.events??[];for(const event of filteredEvents){if(event.message){events.push({message:event.message,logGroupName,timestamp:event.timestamp?new Date(event.timestamp):new Date});if(event.timestamp&&endTime<event.timestamp){endTime=event.timestamp}}}if(filteredEvents.length===100&&response.nextToken){events.push({message:">>> `watch` shows only the first 100 log messages - the rest have been truncated...",logGroupName,timestamp:new Date(endTime)})}}catch(e){if(e.name==="ResourceNotFoundException"){return[]}throw e}logGroupsAccessSettings.logGroupsStartTimes[logGroupName]=endTime+1;return events}}}});var require_cdk_from_cfn=__commonJS({"../../node_modules/cdk-from-cfn/index.js"(exports2,module2){var imports={};imports["__wbindgen_placeholder__"]=module2.exports;var wasm;var{TextDecoder:TextDecoder2,TextEncoder}=require("util");var cachedTextDecoder=new TextDecoder2("utf-8",{ignoreBOM:true,fatal:true});cachedTextDecoder.decode();var cachedUint8Memory0=null;function getUint8Memory0(){if(cachedUint8Memory0===null||cachedUint8Memory0.byteLength===0){cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)}return cachedUint8Memory0}function getStringFromWasm0(ptr,len){ptr=ptr>>>0;return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr,ptr+len))}var heap=new Array(128).fill(void 0);heap.push(void 0,null,true,false);var heap_next=heap.length;function addHeapObject(obj){if(heap_next===heap.length)heap.push(heap.length+1);const idx=heap_next;heap_next=heap[idx];heap[idx]=obj;return idx}var cachedInt32Memory0=null;function getInt32Memory0(){if(cachedInt32Memory0===null||cachedInt32Memory0.byteLength===0){cachedInt32Memory0=new Int32Array(wasm.memory.buffer)}return cachedInt32Memory0}var cachedUint32Memory0=null;function getUint32Memory0(){if(cachedUint32Memory0===null||cachedUint32Memory0.byteLength===0){cachedUint32Memory0=new Uint32Array(wasm.memory.buffer)}return cachedUint32Memory0}function getObject(idx){return heap[idx]}function dropObject(idx){if(idx<132)return;heap[idx]=heap_next;heap_next=idx}function takeObject(idx){const ret=getObject(idx);dropObject(idx);return ret}function getArrayJsValueFromWasm0(ptr,len){ptr=ptr>>>0;const mem=getUint32Memory0();const slice=mem.subarray(ptr/4,ptr/4+len);const result=[];for(let i=0;i<slice.length;i++){result.push(takeObject(slice[i]))}return result}module2.exports.supported_languages=function(){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.supported_languages(retptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var v110=getArrayJsValueFromWasm0(r0,r1).slice();wasm.__wbindgen_free(r0,r1*4,4);return v110}finally{wasm.__wbindgen_add_to_stack_pointer(16)}};var WASM_VECTOR_LEN=0;var cachedTextEncoder=new TextEncoder("utf-8");var encodeString=typeof cachedTextEncoder.encodeInto==="function"?function(arg,view){return cachedTextEncoder.encodeInto(arg,view)}:function(arg,view){const buf=cachedTextEncoder.encode(arg);view.set(buf);return{read:arg.length,written:buf.length}};function passStringToWasm0(arg,malloc,realloc){if(realloc===void 0){const buf=cachedTextEncoder.encode(arg);const ptr2=malloc(buf.length,1)>>>0;getUint8Memory0().subarray(ptr2,ptr2+buf.length).set(buf);WASM_VECTOR_LEN=buf.length;return ptr2}let len=arg.length;let ptr=malloc(len,1)>>>0;const mem=getUint8Memory0();let offset=0;for(;offset<len;offset++){const code=arg.charCodeAt(offset);if(code>127)break;mem[ptr+offset]=code}if(offset!==len){if(offset!==0){arg=arg.slice(offset)}ptr=realloc(ptr,len,len=offset+arg.length*3,1)>>>0;const view=getUint8Memory0().subarray(ptr+offset,ptr+len);const ret=encodeString(arg,view);offset+=ret.written;ptr=realloc(ptr,len,offset,1)>>>0}WASM_VECTOR_LEN=offset;return ptr}module2.exports.transmute=function(template,language,stack_name){let deferred5_0;let deferred5_1;try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);const ptr0=passStringToWasm0(template,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;const ptr1=passStringToWasm0(language,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;const ptr2=passStringToWasm0(stack_name,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len2=WASM_VECTOR_LEN;wasm.transmute(retptr,ptr0,len0,ptr1,len1,ptr2,len2);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];var r2=getInt32Memory0()[retptr/4+2];var r3=getInt32Memory0()[retptr/4+3];var ptr4=r0;var len4=r1;if(r3){ptr4=0;len4=0;throw takeObject(r2)}deferred5_0=ptr4;deferred5_1=len4;return getStringFromWasm0(ptr4,len4)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(deferred5_0,deferred5_1,1)}};module2.exports.__wbindgen_error_new=function(arg0,arg1){const ret=new Error(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)};module2.exports.__wbindgen_string_new=function(arg0,arg1){const ret=getStringFromWasm0(arg0,arg1);return addHeapObject(ret)};var path24=require("path").join(__dirname,"index_bg.wasm");var bytes=require("fs").readFileSync(path24);var wasmModule=new WebAssembly.Module(bytes);var wasmInstance=new WebAssembly.Instance(wasmModule,imports);wasm=wasmInstance.exports;module2.exports.__wasm=wasm}});async function shell(command){const commandLine=renderCommandLine(command);debug(`Executing ${chalk19.blue(commandLine)}`);const child=child_process.spawn(command[0],renderArguments(command.slice(1)),{shell:true,stdio:["ignore","pipe","inherit"]});return new Promise((resolve7,reject)=>{const stdout2=new Array;child.stdout.on("data",chunk=>{process.stdout.write(chunk);stdout2.push(chunk)});child.once("error",reject);child.once("exit",code=>{if(code===0){resolve7(Buffer.from(stdout2).toString("utf-8"))}else{reject(new ToolkitError(`${commandLine} exited with error code ${code}`))}})})}function renderCommandLine(cmd){return renderArguments(cmd).join(" ")}function renderArguments(cmd){if(process.platform!=="win32"){return doRender(cmd,hasAnyChars(" ","\\","!",'"',"'","&","$"),posixEscape)}else{return doRender(cmd,hasAnyChars(" ",'"',"&","^","%"),windowsEscape)}}function doRender(cmd,needsEscaping,doEscape){return cmd.map(x=>needsEscaping(x)?doEscape(x):x)}function hasAnyChars(...chars){return str=>{return chars.some(c=>str.indexOf(c)!==-1)}}function posixEscape(x){x=x.replace(/'/g,`'"'"'`);return`'${x}'`}function windowsEscape(x){x=`"${x}"`;const shellMeta=new Set(['"',"&","^","%"]);return x.split("").map(c=>shellMeta.has(x)?"^"+c:c).join("")}var child_process,chalk19;var init_os=__esm({"lib/os.ts"(){"use strict";child_process=__toESM(require("child_process"));chalk19=__toESM(require_source());init_logging();init_error()}});async function invokeBuiltinHooks(target,context){switch(target.language){case"csharp":if(["app","sample-app"].includes(target.templateName)){return dotnetAddProject(target.targetDirectory,context)}break;case"fsharp":if(["app","sample-app"].includes(target.templateName)){return dotnetAddProject(target.targetDirectory,context,"fsproj")}break;case"python":await context.substitutePlaceholdersIn("requirements.txt");break;case"java":await context.substitutePlaceholdersIn("pom.xml");break;case"javascript":case"typescript":await context.substitutePlaceholdersIn("package.json")}}async function dotnetAddProject(targetDirectory,context,ext2="csproj"){const pname=context.placeholder("name.PascalCased");const slnPath=path19.join(targetDirectory,"src",`${pname}.sln`);const csprojPath=path19.join(targetDirectory,"src",pname,`${pname}.${ext2}`);try{await shell(["dotnet","sln",slnPath,"add",csprojPath])}catch(e){throw new ToolkitError(`Could not add project ${pname}.${ext2} to solution ${pname}.sln. ${e.message}`)}}var path19;var init_init_hooks=__esm({"lib/init-hooks.ts"(){"use strict";path19=__toESM(require("path"));init_os();init_error()}});function rangeFromSemver(ver,targetType){const re=ver.match(/^([^\d]*)([\d.]*)$/);if(!re||!semver6.valid(re[2])){throw new Error("not a semver or unsupported range syntax")}const prefixPart=re[1];const verPart=re[2];switch(targetType){case"bracket":switch(prefixPart){case"":return ver;case"^":return`[${verPart},${semver6.major(verPart)+1}.0.0)`;default:throw new Error(`unsupported range syntax - ${prefixPart}`)}case"pep":switch(prefixPart){case"":return`==${ver}`;case"^":return`>=${verPart},<${semver6.major(verPart)+1}.0.0`;default:throw new Error(`unsupported range syntax - ${prefixPart}`)}}}var semver6;var init_version_range=__esm({"lib/util/version-range.ts"(){"use strict";semver6=__toESM(require_semver4())}});var require_camelcase=__commonJS({"../../node_modules/camelcase/index.js"(exports2,module2){"use strict";var UPPERCASE=/[\p{Lu}]/u;var LOWERCASE=/[\p{Ll}]/u;var LEADING_CAPITAL=/^[\p{Lu}](?![\p{Lu}])/gu;var IDENTIFIER=/([\p{Alpha}\p{N}_]|$)/u;var SEPARATORS=/[_.\- ]+/;var LEADING_SEPARATORS=new RegExp("^"+SEPARATORS.source);var SEPARATORS_AND_IDENTIFIER=new RegExp(SEPARATORS.source+IDENTIFIER.source,"gu");var NUMBERS_AND_IDENTIFIER=new RegExp("\\d+"+IDENTIFIER.source,"gu");var preserveCamelCase=(string,toLowerCase,toUpperCase)=>{let isLastCharLower=false;let isLastCharUpper=false;let isLastLastCharUpper=false;for(let i=0;i<string.length;i++){const character=string[i];if(isLastCharLower&&UPPERCASE.test(character)){string=string.slice(0,i)+"-"+string.slice(i);isLastCharLower=false;isLastLastCharUpper=isLastCharUpper;isLastCharUpper=true;i++}else if(isLastCharUpper&&isLastLastCharUpper&&LOWERCASE.test(character)){string=string.slice(0,i-1)+"-"+string.slice(i-1);isLastLastCharUpper=isLastCharUpper;isLastCharUpper=false;isLastCharLower=true}else{isLastCharLower=toLowerCase(character)===character&&toUpperCase(character)!==character;isLastLastCharUpper=isLastCharUpper;isLastCharUpper=toUpperCase(character)===character&&toLowerCase(character)!==character}}return string};var preserveConsecutiveUppercase=(input,toLowerCase)=>{LEADING_CAPITAL.lastIndex=0;return input.replace(LEADING_CAPITAL,m1=>toLowerCase(m1))};var postProcess=(input,toUpperCase)=>{SEPARATORS_AND_IDENTIFIER.lastIndex=0;NUMBERS_AND_IDENTIFIER.lastIndex=0;return input.replace(SEPARATORS_AND_IDENTIFIER,(_2,identifier)=>toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER,m=>toUpperCase(m))};var camelCase3=(input,options)=>{if(!(typeof input==="string"||Array.isArray(input))){throw new TypeError("Expected the input to be `string | string[]`")}options={pascalCase:false,preserveConsecutiveUppercase:false,...options};if(Array.isArray(input)){input=input.map(x=>x.trim()).filter(x=>x.length).join("-")}else{input=input.trim()}if(input.length===0){return""}const toLowerCase=options.locale===false?string=>string.toLowerCase():string=>string.toLocaleLowerCase(options.locale);const toUpperCase=options.locale===false?string=>string.toUpperCase():string=>string.toLocaleUpperCase(options.locale);if(input.length===1){return options.pascalCase?toUpperCase(input):toLowerCase(input)}const hasUpperCase=input!==toLowerCase(input);if(hasUpperCase){input=preserveCamelCase(input,toLowerCase,toUpperCase)}input=input.replace(LEADING_SEPARATORS,"");if(options.preserveConsecutiveUppercase){input=preserveConsecutiveUppercase(input,toLowerCase)}else{input=toLowerCase(input)}if(options.pascalCase){input=toUpperCase(input.charAt(0))+input.slice(1)}return postProcess(input,toUpperCase)};module2.exports=camelCase3;module2.exports.default=camelCase3}});var require_decamelize=__commonJS({"node_modules/decamelize/index.js"(exports2,module2){"use strict";var handlePreserveConsecutiveUppercase=(decamelized,separator)=>{decamelized=decamelized.replace(/((?<![\p{Uppercase_Letter}\d])[\p{Uppercase_Letter}\d](?![\p{Uppercase_Letter}\d]))/gu,$0=>{return $0.toLowerCase()});return decamelized.replace(new RegExp("(\\p{Uppercase_Letter}+)(\\p{Uppercase_Letter}\\p{Lowercase_Letter}+)","gu"),(_2,$1,$2)=>{return $1+separator+$2.toLowerCase()})};module2.exports=(text,{separator="_",preserveConsecutiveUppercase=false}={})=>{if(!(typeof text==="string"&&typeof separator==="string")){throw new TypeError("The `text` and `separator` arguments should be of type `string`")}if(text.length<2){return preserveConsecutiveUppercase?text:text.toLowerCase()}const replacement=`$1${separator}$2`;const decamelized=text.replace(new RegExp("([\\p{Lowercase_Letter}\\d])(\\p{Uppercase_Letter})","gu"),replacement);if(preserveConsecutiveUppercase){return handlePreserveConsecutiveUppercase(decamelized,separator)}return decamelized.replace(new RegExp("(\\p{Uppercase_Letter})(\\p{Uppercase_Letter}\\p{Lowercase_Letter}+)","gu"),replacement).toLowerCase()}}});async function cliInit(options){const canUseNetwork=options.canUseNetwork??true;const generateOnly=options.generateOnly??false;const workDir=options.workDir??process.cwd();if(!options.type&&!options.language){await printAvailableTemplates();return}const type=options.type||"default";const template=(await availableInitTemplates()).find(t=>t.hasName(type));if(!template){await printAvailableTemplates(options.language);throw new ToolkitError(`Unknown init template: ${type}`)}if(!options.language&&template.languages.length===1){const language=template.languages[0];warning(`No --language was provided, but '${type}' supports only '${language}', so defaulting to --language=${language}`)}if(!options.language){print(`Available languages for ${chalk20.green(type)}: ${template.languages.map(l=>chalk20.blue(l)).join(", ")}`);throw new ToolkitError("No language was selected")}await initializeProject(template,options.language,canUseNetwork,generateOnly,workDir,options.stackName,options.migrate)}function pythonExecutable(){let python="python3";if(process.platform==="win32"){python="python"}return python}async function availableInitTemplates(){return new Promise(async resolve7=>{try{const templatesDir=path20.join(rootDir(),"lib","init-templates");const templateNames=await listDirectory(templatesDir);const templates=new Array;for(const templateName of templateNames){templates.push(await InitTemplate.fromName(templatesDir,templateName))}resolve7(templates)}catch{resolve7([])}})}async function listDirectory(dirPath){return(await fs18.readdir(dirPath)).filter(p=>!p.startsWith(".")).filter(p=>!(p==="LICENSE")).filter(p=>!(p===INFO_DOT_JSON)).sort()}async function printAvailableTemplates(language){print("Available templates:");for(const template of await availableInitTemplates()){if(language&&template.languages.indexOf(language)===-1){continue}print(`* ${chalk20.green(template.name)}: ${template.description}`);const languageArg=language?chalk20.bold(language):template.languages.length>1?`[${template.languages.map(t=>chalk20.bold(t)).join("|")}]`:chalk20.bold(template.languages[0]);print(` \u2514\u2500 ${chalk20.blue(`cdk init ${chalk20.bold(template.name)} --language=${languageArg}`)}`)}}async function initializeProject(template,language,canUseNetwork,generateOnly,workDir,stackName,migrate){await assertIsEmptyDirectory(workDir);print(`Applying project template ${chalk20.green(template.name)} for ${chalk20.blue(language)}`);await template.install(language,workDir,stackName);if(migrate){await template.addMigrateContext(workDir)}if(await fs18.pathExists(`${workDir}/README.md`)){const readme=await fs18.readFile(`${workDir}/README.md`,{encoding:"utf-8"});print(chalk20.green(readme))}if(!generateOnly){await initializeGitRepository(workDir);await postInstall(language,canUseNetwork,workDir)}print("\u2705 All done!")}async function assertIsEmptyDirectory(workDir){const files=await fs18.readdir(workDir);if(files.filter(f=>!f.startsWith(".")).length!==0){throw new ToolkitError("`cdk init` cannot be run in a non-empty directory!")}}async function initializeGitRepository(workDir){if(await isInGitRepository(workDir)){return}print("Initializing a new git repository...");try{await execute("git",["init"],{cwd:workDir});await execute("git",["add","."],{cwd:workDir});await execute("git",["commit",'--message="Initial commit"',"--no-gpg-sign"],{cwd:workDir})}catch{warning("Unable to initialize git repository for your project.")}}async function postInstall(language,canUseNetwork,workDir){switch(language){case"javascript":return postInstallJavascript(canUseNetwork,workDir);case"typescript":return postInstallTypescript(canUseNetwork,workDir);case"java":return postInstallJava(canUseNetwork,workDir);case"python":return postInstallPython(workDir)}}async function postInstallJavascript(canUseNetwork,cwd){return postInstallTypescript(canUseNetwork,cwd)}async function postInstallTypescript(canUseNetwork,cwd){const command="npm";if(!canUseNetwork){warning(`Please run '${command} install'!`);return}print(`Executing ${chalk20.green(`${command} install`)}...`);try{await execute(command,["install"],{cwd})}catch(e){warning(`${command} install failed: `+e.message)}}async function postInstallJava(canUseNetwork,cwd){const mvnPackageWarning="Please run 'mvn package'!";if(!canUseNetwork){warning(mvnPackageWarning);return}print("Executing 'mvn package'");try{await execute("mvn",["package"],{cwd})}catch{warning("Unable to package compiled code as JAR");warning(mvnPackageWarning)}}async function postInstallPython(cwd){const python=pythonExecutable();warning(`Please run '${python} -m venv .venv'!`);print(`Executing ${chalk20.green("Creating virtualenv...")}`);try{await execute(python,["-m venv",".venv"],{cwd})}catch{warning("Unable to create virtualenv automatically");warning(`Please run '${python} -m venv .venv'!`)}}async function isInGitRepository(dir){while(true){if(await fs18.pathExists(path20.join(dir,".git"))){return true}if(isRoot(dir)){return false}dir=path20.dirname(dir)}}function isRoot(dir){return path20.dirname(dir)===dir}async function execute(cmd,args,{cwd}){const child=childProcess2.spawn(cmd,args,{cwd,shell:true,stdio:["ignore","pipe","inherit"]});let stdout2="";child.stdout.on("data",chunk=>stdout2+=chunk.toString());return new Promise((ok,fail)=>{child.once("error",err=>fail(err));child.once("exit",status=>{if(status===0){return ok(stdout2)}else{process.stderr.write(stdout2);return fail(new ToolkitError(`${cmd} exited with status ${status}`))}})})}async function loadInitVersions(){const recommendedFlagsFile=path20.join(__dirname,"./init-templates/.init-version.json");const contents=JSON.parse(await fs18.readFile(recommendedFlagsFile,{encoding:"utf-8"}));const ret={"aws-cdk-lib":contents["aws-cdk-lib"],"constructs":contents.constructs};for(const[key,value]of Object.entries(ret)){if(!value){throw new Error(`Missing init version from ${recommendedFlagsFile}: ${key}`)}}return ret}async function currentlyRecommendedAwsCdkLibFlags(){const recommendedFlagsFile=path20.join(__dirname,"./init-templates/.recommended-feature-flags.json");return JSON.parse(await fs18.readFile(recommendedFlagsFile,{encoding:"utf-8"}))}var childProcess2,path20,chalk20,fs18,camelCase,decamelize,INFO_DOT_JSON,InitTemplate;var init_init=__esm({"lib/init.ts"(){"use strict";childProcess2=__toESM(require("child_process"));path20=__toESM(require("path"));chalk20=__toESM(require_source());fs18=__toESM(require_lib4());init_init_hooks();init_logging();init_error();init_directories();init_version_range();camelCase=require_camelcase();decamelize=require_decamelize();INFO_DOT_JSON="info.json";InitTemplate=class _InitTemplate{constructor(basePath,name,languages,info2){this.basePath=basePath;this.name=name;this.languages=languages;this.aliases=new Set;this.description=info2.description;for(const alias of info2.aliases||[]){this.aliases.add(alias)}}static async fromName(templatesDir,name){const basePath=path20.join(templatesDir,name);const languages=await listDirectory(basePath);const info2=await fs18.readJson(path20.join(basePath,INFO_DOT_JSON));return new _InitTemplate(basePath,name,languages,info2)}hasName(name){return name===this.name||this.aliases.has(name)}async install(language,targetDirectory,stackName){if(this.languages.indexOf(language)===-1){error(`The ${chalk20.blue(language)} language is not supported for ${chalk20.green(this.name)} (it supports: ${this.languages.map(l=>chalk20.blue(l)).join(", ")})`);throw new ToolkitError(`Unsupported language: ${language}`)}const projectInfo={name:decamelize(path20.basename(path20.resolve(targetDirectory))),stackName,versions:await loadInitVersions()};const sourceDirectory=path20.join(this.basePath,language);await this.installFiles(sourceDirectory,targetDirectory,language,projectInfo);await this.applyFutureFlags(targetDirectory);await invokeBuiltinHooks({targetDirectory,language,templateName:this.name},{substitutePlaceholdersIn:async(...fileNames)=>{for(const fileName of fileNames){const fullPath=path20.join(targetDirectory,fileName);const template=await fs18.readFile(fullPath,{encoding:"utf-8"});await fs18.writeFile(fullPath,this.expand(template,language,projectInfo))}},placeholder:ph=>this.expand(`%${ph}%`,language,projectInfo)})}async installFiles(sourceDirectory,targetDirectory,language,project){for(const file of await fs18.readdir(sourceDirectory)){const fromFile=path20.join(sourceDirectory,file);const toFile=path20.join(targetDirectory,this.expand(file,language,project));if((await fs18.stat(fromFile)).isDirectory()){await fs18.mkdir(toFile);await this.installFiles(fromFile,toFile,language,project);continue}else if(file.match(/^.*\.template\.[^.]+$/)){await this.installProcessed(fromFile,toFile.replace(/\.template(\.[^.]+)$/,"$1"),language,project);continue}else if(file.match(/^.*\.hook\.(d.)?[^.]+$/)){continue}else{await fs18.copy(fromFile,toFile)}}}async installProcessed(templatePath,toFile,language,project){const template=await fs18.readFile(templatePath,{encoding:"utf-8"});await fs18.writeFile(toFile,this.expand(template,language,project))}expand(template,language,project){const cdkVersion=project.versions["aws-cdk-lib"];let constructsVersion=project.versions.constructs;switch(language){case"java":case"csharp":case"fsharp":constructsVersion=rangeFromSemver(constructsVersion,"bracket");break;case"python":constructsVersion=rangeFromSemver(constructsVersion,"pep");break}return template.replace(/%name%/g,project.name).replace(/%stackname%/,project.stackName??"%name.PascalCased%Stack").replace(/%PascalNameSpace%/,project.stackName?camelCase(project.stackName+"Stack",{pascalCase:true}):"%name.PascalCased%").replace(/%PascalStackProps%/,project.stackName?camelCase(project.stackName,{pascalCase:true})+"StackProps":"StackProps").replace(/%name\.camelCased%/g,camelCase(project.name)).replace(/%name\.PascalCased%/g,camelCase(project.name,{pascalCase:true})).replace(/%cdk-version%/g,cdkVersion).replace(/%constructs-version%/g,constructsVersion).replace(/%cdk-home%/g,cdkHomeDir()).replace(/%name\.PythonModule%/g,project.name.replace(/-/g,"_")).replace(/%python-executable%/g,pythonExecutable()).replace(/%name\.StackName%/g,project.name.replace(/[^A-Za-z0-9-]/g,"-"))}async applyFutureFlags(projectDir){const cdkJson=path20.join(projectDir,"cdk.json");if(!await fs18.pathExists(cdkJson)){return}const config=await fs18.readJson(cdkJson);config.context={...config.context,...await currentlyRecommendedAwsCdkLibFlags()};await fs18.writeJson(cdkJson,config,{spaces:2})}async addMigrateContext(projectDir){const cdkJson=path20.join(projectDir,"cdk.json");if(!await fs18.pathExists(cdkJson)){return}const config=await fs18.readJson(cdkJson);config.context={...config.context,"cdk-migrate":true};await fs18.writeJson(cdkJson,config,{spaces:2})}}}});async function zipDirectory(directory,outputFile){const temporaryOutputFile=`${outputFile}.${randomString()}._tmp`;await writeZipFile(directory,temporaryOutputFile);await moveIntoPlace(temporaryOutputFile,outputFile)}function writeZipFile(directory,outputFile){return new Promise(async(ok,fail)=>{const globOptions={dot:true,nodir:true,follow:true,cwd:directory};const files=glob.sync("**",globOptions);const output=(0,import_fs2.createWriteStream)(outputFile);const archive=archiver2("zip");archive.on("warning",fail);archive.on("error",fail);output.once("close",ok);archive.pipe(output);for(const file of files){const fullPath=path21.resolve(directory,file);const[data2,stat4]=await Promise.all([import_fs2.promises.readFile(fullPath),import_fs2.promises.stat(fullPath)]);archive.append(data2,{name:file,mode:stat4.mode})}await archive.finalize()})}async function moveIntoPlace(source,target){let delay=100;let attempts=5;while(true){try{await import_fs2.promises.rename(source,target);return}catch(e){if(e.code!=="EPERM"||attempts--<=0){throw e}(0,import_console2.error)(e.message);await sleep2(Math.floor(Math.random()*delay));delay*=2}}}function sleep2(ms){return new Promise(ok=>setTimeout(ok,ms))}function randomString(){return Math.random().toString(36).replace(/[^a-z0-9]+/g,"")}var import_console2,import_fs2,path21,glob,archiver2;var init_archive=__esm({"lib/util/archive.ts"(){"use strict";import_console2=require("console");import_fs2=require("fs");path21=__toESM(require("path"));glob=__toESM(require_glob());archiver2=require_archiver()}});async function generateCdkApp(stackName,stack,language,outputPath,compress){const resolvedOutputPath=path22.join(outputPath??process.cwd(),stackName);const formattedStackName=decamelize2(stackName);try{fs20.rmSync(resolvedOutputPath,{recursive:true,force:true});fs20.mkdirSync(resolvedOutputPath,{recursive:true});const generateOnly=compress;await cliInit({type:"app",language,canUseNetwork:true,generateOnly,workDir:resolvedOutputPath,stackName,migrate:true});let stackFileName;switch(language){case"typescript":stackFileName=`${resolvedOutputPath}/lib/${formattedStackName}-stack.ts`;break;case"java":stackFileName=`${resolvedOutputPath}/src/main/java/com/myorg/${camelCase2(formattedStackName,{pascalCase:true})}Stack.java`;break;case"python":stackFileName=`${resolvedOutputPath}/${formattedStackName.replace(/-/g,"_")}/${formattedStackName.replace(/-/g,"_")}_stack.py`;break;case"csharp":stackFileName=`${resolvedOutputPath}/src/${camelCase2(formattedStackName,{pascalCase:true})}/${camelCase2(formattedStackName,{pascalCase:true})}Stack.cs`;break;case"go":stackFileName=`${resolvedOutputPath}/${formattedStackName}.go`;break;default:throw new Error(`${language} is not supported by CDK Migrate. Please choose from: ${MIGRATE_SUPPORTED_LANGUAGES.join(", ")}`)}fs20.writeFileSync(stackFileName,stack);if(compress){await zipDirectory(resolvedOutputPath,`${resolvedOutputPath}.zip`);fs20.rmSync(resolvedOutputPath,{recursive:true,force:true})}}catch(error3){fs20.rmSync(resolvedOutputPath,{recursive:true,force:true});throw error3}}function generateStack(template,stackName,language){const formattedStackName=`${camelCase2(decamelize2(stackName),{pascalCase:true})}Stack`;try{return cdk_from_cfn.transmute(template,language,formattedStackName)}catch(e){throw new Error(`${formattedStackName} could not be generated because ${e.message}`)}}function readFromPath(inputPath){let readFile4;try{readFile4=fs20.readFileSync(inputPath,"utf8")}catch(e){throw new Error(`'${inputPath}' is not a valid path.`)}if(readFile4==""){throw new Error(`Cloudformation template filepath: '${inputPath}' is an empty file.`)}return readFile4}async function readFromStack(stackName,sdkProvider,environment){const cloudFormation=(await sdkProvider.forEnvironment(environment,0)).sdk.cloudFormation();const stack=await CloudFormationStack.lookup(cloudFormation,stackName,true);if(stack.stackStatus.isDeploySuccess||stack.stackStatus.isRollbackSuccess){return JSON.stringify(await stack.template())}else{throw new Error(`Stack '${stackName}' in account ${environment.account} and region ${environment.region} has a status of '${stack.stackStatus.name}' due to '${stack.stackStatus.reason}'. The stack cannot be migrated until it is in a healthy state.`)}}async function generateTemplate(options){const cfn=new CfnTemplateGeneratorProvider(await buildCfnClient(options.sdkProvider,options.environment));const scanId=await findLastSuccessfulScan(cfn,options);const curScan=await cfn.describeResourceScan(scanId);if(curScan.Status=="IN_PROGRESS"){print("Resource scan in progress. Please wait, this can take 10 minutes or longer.");await scanProgressBar(scanId,cfn)}displayTimeDiff(new Date,new Date(curScan.StartTime));let resources=await cfn.listResourceScanResources(scanId,options.filters);print("finding related resources.");let relatedResources=await cfn.getResourceScanRelatedResources(scanId,resources);print(`Found ${relatedResources.length} resources.`);print("Generating CFN template from scanned resources.");const templateArn=(await cfn.createGeneratedTemplate(options.stackName,relatedResources)).GeneratedTemplateId;let generatedTemplate=await cfn.describeGeneratedTemplate(templateArn);print("Please wait, template creation in progress. This may take a couple minutes.");while(generatedTemplate.Status!=="COMPLETE"&&generatedTemplate.Status!=="FAILED"){await printDots(`[${generatedTemplate.Status}] Template Creation in Progress`,400);generatedTemplate=await cfn.describeGeneratedTemplate(templateArn)}print("");print("Template successfully generated!");return buildGenertedTemplateOutput(generatedTemplate,(await cfn.getGeneratedTemplate(templateArn)).TemplateBody,templateArn)}async function findLastSuccessfulScan(cfn,options){let resourceScanSummaries=[];const clientRequestToken=`cdk-migrate-${options.environment.account}-${options.environment.region}`;if(options.fromScan===0){print(`Starting new scan for account ${options.environment.account} in region ${options.environment.region}`);try{await cfn.startResourceScan(clientRequestToken);resourceScanSummaries=(await cfn.listResourceScans()).ResourceScanSummaries}catch(e){print(`Scan failed to start due to error '${e.message}', defaulting to latest scan.`)}}else{resourceScanSummaries=(await cfn.listResourceScans()).ResourceScanSummaries;await cfn.checkForResourceScan(resourceScanSummaries,options,clientRequestToken)}resourceScanSummaries=(await cfn.listResourceScans()).ResourceScanSummaries;let scanId=resourceScanSummaries[0].ResourceScanId;for(const summary of resourceScanSummaries){if(summary.Status!=="FAILED"){scanId=summary.ResourceScanId;break}}return scanId}function parseFilters(filters){if(!filters){return{"resource-identifier":void 0,"resource-type-prefix":void 0,"tag-key":void 0,"tag-value":void 0}}const filterShorthands={"identifier":"resource-identifier","id":"resource-identifier","type":"resource-type-prefix","type-prefix":"resource-type-prefix"};const filterList=filters.split(",");let filterMap={["resource-identifier"]:void 0,["resource-type-prefix"]:void 0,["tag-key"]:void 0,["tag-value"]:void 0};for(const fil of filterList){const filter2=fil.split("=");let filterKey=filter2[0];const filterValue=filter2[1];if(filterKey in filterShorthands){filterKey=filterShorthands[filterKey]}if(Object.values(FilterType).includes(filterKey)){filterMap[filterKey]=filterValue}else{throw new Error(`Invalid filter: ${filterKey}`)}}return filterMap}function chunks(list,chunkSize){const chunkedList=[];for(let i=0;i<list.length;i+=chunkSize){chunkedList.push(list.slice(i,i+chunkSize))}return chunkedList}function setEnvironment(account,region){return{account:account??import_cx_api9.UNKNOWN_ACCOUNT,region:region??import_cx_api9.UNKNOWN_REGION,name:"cdk-migrate-env"}}function parseSourceOptions(fromPath,fromStack,stackName){if(fromPath&&fromStack){throw new Error("Only one of `--from-path` or `--from-stack` may be provided.")}if(!stackName){throw new Error("`--stack-name` is a required field.")}if(!fromPath&&!fromStack){return{source:"scan"}}if(fromPath){return{source:"path",templatePath:fromPath}}return{source:"stack",stackName}}function excludeManaged(resourceList){return resourceList.filter(r=>!r.ManagedByStack).map(r=>({ResourceType:r.ResourceType,ResourceIdentifier:r.ResourceIdentifier}))}function resourceIdentifiers(resourceList){const identifiers=[];resourceList.forEach(r=>{const identifier={ResourceType:r.ResourceType,ResourceIdentifier:r.ResourceIdentifier};identifiers.push(identifier)});return identifiers}async function scanProgressBar(scanId,cfn){let curProgress=.5;let curScan={Status:"IN_PROGRESS",$metadata:{}};while(curScan.Status=="IN_PROGRESS"){curScan=await cfn.describeResourceScan(scanId);curProgress=curScan.PercentageCompleted??curProgress;printBar(30,curProgress);await new Promise(resolve7=>setTimeout(resolve7,2e3))}print("");print("\u2705 Scan Complete!")}function printBar(width,progress){if(!process.env.MIGRATE_INTEG_TEST){const FULL_BLOCK2="\u2588";const PARTIAL_BLOCK2=["","\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589"];const fraction=Math.min(progress/100,1);const innerWidth=Math.max(1,width-2);const chars=innerWidth*fraction;const remainder=chars-Math.floor(chars);const fullChars=FULL_BLOCK2.repeat(Math.floor(chars));const partialChar=PARTIAL_BLOCK2[Math.floor(remainder*PARTIAL_BLOCK2.length)];const filler="\xB7".repeat(innerWidth-Math.floor(chars)-(partialChar?1:0));const color=chalk21.green;rewriteLine("["+color(fullChars+partialChar)+filler+`] (${progress}%)`)}}async function printDots(message,timeoutx4){if(!process.env.MIGRATE_INTEG_TEST){rewriteLine(message+" .");await new Promise(resolve7=>setTimeout(resolve7,timeoutx4));rewriteLine(message+" ..");await new Promise(resolve7=>setTimeout(resolve7,timeoutx4));rewriteLine(message+" ...");await new Promise(resolve7=>setTimeout(resolve7,timeoutx4));rewriteLine(message);await new Promise(resolve7=>setTimeout(resolve7,timeoutx4))}}function rewriteLine(message){process.stdout.clearLine(0);process.stdout.cursorTo(0);process.stdout.write(message)}function displayTimeDiff(time1,time2){const diff=Math.abs(time1.getTime()-time2.getTime());const days=Math.floor(diff/(1e3*60*60*24));const hours=Math.floor(diff%(1e3*60*60*24)/(1e3*60*60));const minutes=Math.floor(diff%(1e3*60*60)/(1e3*60));print(`Using the latest successful scan which is ${days} days, ${hours} hours, and ${minutes} minutes old.`)}function writeMigrateJsonFile(outputPath,stackName,migrateJson){const outputToJson={"//":"This file is generated by cdk migrate. It will be automatically deleted after the first successful deployment of this app to the environment of the original resources.","Source":migrateJson.source,"Resources":migrateJson.resources};fs20.writeFileSync(`${path22.join(outputPath??process.cwd(),stackName)}/migrate.json`,JSON.stringify(outputToJson,null,2))}function getMigrateScanType(scanType){switch(scanType){case"new":return 0;case"most-recent":return 1;case"":return 2;case void 0:return 2;default:throw new Error(`Unknown scan type: ${scanType}`)}}function isThereAWarning(generatedTemplateOutput){if(generatedTemplateOutput.resources){for(const resource of generatedTemplateOutput.resources){if(resource.Warnings&&resource.Warnings.length>0){return true}}}return false}function buildGenertedTemplateOutput(generatedTemplateSummary,templateBody,source){const resources=generatedTemplateSummary.Resources;const migrateJson={templateBody,source,resources:generatedTemplateSummary.Resources.map(r=>({ResourceType:r.ResourceType,LogicalResourceId:r.LogicalResourceId,ResourceIdentifier:r.ResourceIdentifier}))};const templateId=generatedTemplateSummary.GeneratedTemplateId;return{migrateJson,resources,templateId}}async function buildCfnClient(sdkProvider,environment){const sdk=(await sdkProvider.forEnvironment(environment,0)).sdk;sdk.appendCustomUserAgent("cdk-migrate");return sdk.cloudFormation()}function appendWarningsToReadme(filepath,resources){const readme=fs20.readFileSync(filepath,"utf8");const lines=readme.split("\n");const index=lines.findIndex(line=>line.trim()==="Enjoy!");let linesToAdd=["\n## Warnings"];linesToAdd.push("### Write-only properties");linesToAdd.push("Write-only properties are resource property values that can be written to but can't be read by AWS CloudFormation or CDK Migrate. For more information, see [IaC generator and write-only properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC-write-only-properties.html).");linesToAdd.push("\n");linesToAdd.push("Write-only properties discovered during migration are organized here by resource ID and categorized by write-only property type. Resolve write-only properties by providing property values in your CDK app. For guidance, see [Resolve write-only properties](https://docs.aws.amazon.com/cdk/v2/guide/migrate.html#migrate-resources-writeonly).");for(const resource of resources){if(resource.Warnings&&resource.Warnings.length>0){linesToAdd.push(`### ${resource.LogicalResourceId}`);for(const warning2 of resource.Warnings){linesToAdd.push(`- **${warning2.Type}**: `);for(const property of warning2.Properties){linesToAdd.push(` - ${property.PropertyPath}: ${property.Description}`)}}}}lines.splice(index,0,...linesToAdd);fs20.writeFileSync(filepath,lines.join("\n"))}function deduplicateResources(resources){let uniqueResources={};for(const resource of resources){const key=Object.keys(resource.ResourceIdentifier)[0];const uniqueIdentifer=`${resource.ResourceType}:${key}:${resource.ResourceIdentifier[key]}`;uniqueResources[uniqueIdentifer]=resource}return Object.values(uniqueResources)}var fs20,path22,import_cx_api9,cdk_from_cfn,chalk21,camelCase2,decamelize2,MIGRATE_SUPPORTED_LANGUAGES,FilterType,CfnTemplateGeneratorProvider;var init_migrate=__esm({"lib/commands/migrate.ts"(){"use strict";fs20=__toESM(require("fs"));path22=__toESM(require("path"));import_cx_api9=__toESM(require_lib3());cdk_from_cfn=__toESM(require_cdk_from_cfn());chalk21=__toESM(require_source());init_init();init_logging();init_cloudformation();init_archive();camelCase2=require_camelcase();decamelize2=require_decamelize();MIGRATE_SUPPORTED_LANGUAGES=cdk_from_cfn.supported_languages();FilterType=(FilterType2=>{FilterType2["RESOURCE_IDENTIFIER"]="resource-identifier";FilterType2["RESOURCE_TYPE_PREFIX"]="resource-type-prefix";FilterType2["TAG_KEY"]="tag-key";FilterType2["TAG_VALUE"]="tag-value";return FilterType2})(FilterType||{});CfnTemplateGeneratorProvider=class{constructor(cfn){this.cfn=cfn}async checkForResourceScan(resourceScanSummaries,options,clientRequestToken){if(!resourceScanSummaries||resourceScanSummaries.length===0){if(options.fromScan===1){throw new Error("No scans found. Please either start a new scan with the `--from-scan` new or do not specify a `--from-scan` option.")}else{print("No scans found. Initiating a new resource scan.");await this.startResourceScan(clientRequestToken)}}}async getResourceScanRelatedResources(scanId,resources){let relatedResourceList=resources;for(const chunk of chunks(resources,100)){const res=await this.cfn.listResourceScanRelatedResources({ResourceScanId:scanId,Resources:chunk});relatedResourceList.push(...res.RelatedResources??[]);let nextToken=res.NextToken;while(nextToken){const nextRelatedResources=await this.cfn.listResourceScanRelatedResources({ResourceScanId:scanId,Resources:resourceIdentifiers(resources),NextToken:nextToken});nextToken=nextRelatedResources.NextToken;relatedResourceList.push(...nextRelatedResources.RelatedResources??[])}}relatedResourceList=deduplicateResources(relatedResourceList);return process.env.MIGRATE_INTEG_TEST?resourceIdentifiers(relatedResourceList):resourceIdentifiers(excludeManaged(relatedResourceList))}async startResourceScan(requestToken){return(await this.cfn.startResourceScan({ClientRequestToken:requestToken})).ResourceScanId}async listResourceScans(){return this.cfn.listResourceScans()}async listResourceScanResources(scanId,filters=[]){let resourceList=[];let resourceScanInputs;if(filters.length>0){print("Applying filters to resource scan.");for(const filter2 of filters){const filterList=parseFilters(filter2);resourceScanInputs={ResourceScanId:scanId,ResourceIdentifier:filterList["resource-identifier"],ResourceTypePrefix:filterList["resource-type-prefix"],TagKey:filterList["tag-key"],TagValue:filterList["tag-value"]};const resources=await this.cfn.listResourceScanResources(resourceScanInputs);resourceList=resourceList.concat(resources.Resources??[]);let nextToken=resources.NextToken;while(nextToken){resourceScanInputs.NextToken=nextToken;const nextResources=await this.cfn.listResourceScanResources(resourceScanInputs);nextToken=nextResources.NextToken;resourceList=resourceList.concat(nextResources.Resources??[])}}}else{print("No filters provided. Retrieving all resources from scan.");resourceScanInputs={ResourceScanId:scanId};const resources=await this.cfn.listResourceScanResources(resourceScanInputs);resourceList=resourceList.concat(resources.Resources??[]);let nextToken=resources.NextToken;while(nextToken){resourceScanInputs.NextToken=nextToken;const nextResources=await this.cfn.listResourceScanResources(resourceScanInputs);nextToken=nextResources.NextToken;resourceList=resourceList.concat(nextResources.Resources??[])}}if(resourceList.length===0){throw new Error(`No resources found with filters ${filters.join(" ")}. Please try again with different filters.`)}resourceList=deduplicateResources(resourceList);return process.env.MIGRATE_INTEG_TEST?resourceIdentifiers(resourceList):resourceIdentifiers(excludeManaged(resourceList))}async describeResourceScan(scanId){return this.cfn.describeResourceScan({ResourceScanId:scanId})}async describeGeneratedTemplate(templateId){const generatedTemplate=await this.cfn.describeGeneratedTemplate({GeneratedTemplateName:templateId});if(generatedTemplate.Status=="FAILED"){throw new Error(generatedTemplate.StatusReason)}return generatedTemplate}async getGeneratedTemplate(templateId){return this.cfn.getGeneratedTemplate({GeneratedTemplateName:templateId})}async createGeneratedTemplate(stackName,resources){const createTemplateOutput=await this.cfn.createGeneratedTemplate({Resources:resources,GeneratedTemplateName:stackName});if(createTemplateOutput.GeneratedTemplateId===void 0){throw new Error("CreateGeneratedTemplate failed to return an Arn.")}return createTemplateOutput}async deleteGeneratedTemplate(templateArn){await this.cfn.deleteGeneratedTemplate({GeneratedTemplateName:templateArn})}}}});function printStackDiff(oldTemplate,newTemplate,strict,context,quiet,stackName,changeSet,isImport,stream=process.stderr,nestedStackTemplates){let diff=(0,import_cloudformation_diff.fullDiff)(oldTemplate,newTemplate.template,changeSet,isImport);if(stackName&&(!quiet||!diff.isEmpty)){stream.write((0,import_util17.format)("Stack %s\n",chalk22.bold(stackName)))}if(!quiet&&isImport){stream.write("Parameters and rules created during migration do not affect resource configuration.\n")}let filteredChangesCount=0;if(diff.differenceCount&&!strict){const mangledNewTemplate=JSON.parse((0,import_cloudformation_diff.mangleLikeCloudFormation)(JSON.stringify(newTemplate.template)));const mangledDiff=(0,import_cloudformation_diff.fullDiff)(oldTemplate,mangledNewTemplate,changeSet);filteredChangesCount=Math.max(0,diff.differenceCount-mangledDiff.differenceCount);if(filteredChangesCount>0){diff=mangledDiff}}if(!strict){obscureDiff(diff)}let stackDiffCount=0;if(!diff.isEmpty){stackDiffCount++;(0,import_cloudformation_diff.formatDifferences)(stream,diff,{...logicalIdMapFromTemplate(oldTemplate),...buildLogicalToPathMap(newTemplate)},context)}else if(!quiet){print(chalk22.green("There were no differences"))}if(filteredChangesCount>0){print(chalk22.yellow(`Omitted ${filteredChangesCount} changes because they are likely mangled non-ASCII characters. Use --strict to print them.`))}for(const nestedStackLogicalId of Object.keys(nestedStackTemplates??{})){if(!nestedStackTemplates){break}const nestedStack=nestedStackTemplates[nestedStackLogicalId];newTemplate._template=nestedStack.generatedTemplate;stackDiffCount+=printStackDiff(nestedStack.deployedTemplate,newTemplate,strict,context,quiet,nestedStack.physicalName??nestedStackLogicalId,void 0,isImport,stream,nestedStack.nestedStackTemplates)}return stackDiffCount}function printSecurityDiff(oldTemplate,newTemplate,requireApproval,_quiet,stackName,changeSet,stream=process.stderr){const diff=(0,import_cloudformation_diff.fullDiff)(oldTemplate,newTemplate.template,changeSet);if(diffRequiresApproval(diff,requireApproval)){stream.write((0,import_util17.format)("Stack %s\n",chalk22.bold(stackName)));warning(`This deployment will make potentially sensitive changes according to your current security approval level (--require-approval ${requireApproval}).`);warning("Please confirm you intend to make the following modifications:\n");(0,import_cloudformation_diff.formatSecurityChanges)(process.stdout,diff,buildLogicalToPathMap(newTemplate));return true}return false}function diffRequiresApproval(diff,requireApproval){switch(requireApproval){case"never":return false;case"any-change":return diff.permissionsAnyChanges;case"broadening":return diff.permissionsBroadened;default:throw new ToolkitError(`Unrecognized approval level: ${requireApproval}`)}}function buildLogicalToPathMap(stack){const map={};for(const md of stack.findMetadataByType(cxschema9.ArtifactMetadataEntryType.LOGICAL_ID)){map[md.data]=md.path}return map}function logicalIdMapFromTemplate(template){var _a;const ret={};for(const[logicalId,resource]of Object.entries(template.Resources??{})){const path24=(_a=resource==null?void 0:resource.Metadata)==null?void 0:_a["aws:cdk:path"];if(path24){ret[logicalId]=path24}}return ret}function obscureDiff(diff){if(diff.unknown){diff.unknown=diff.unknown.filter(change=>{var _a,_b;if(!change){return true}if((_a=change.newValue)==null?void 0:_a.CheckBootstrapVersion){return false}if((_b=change.oldValue)==null?void 0:_b.CheckBootstrapVersion){return false}return true})}if(diff.resources){diff.resources=diff.resources.filter(change=>{if(!change){return true}if(change.newResourceType==="AWS::CDK::Metadata"){return false}if(change.oldResourceType==="AWS::CDK::Metadata"){return false}return true})}}var import_util17,cxschema9,import_cloudformation_diff,chalk22;var init_diff2=__esm({"lib/diff.ts"(){"use strict";import_util17=require("util");cxschema9=__toESM(require_lib2());import_cloudformation_diff=__toESM(require_lib9());chalk22=__toESM(require_source());init_logging();init_error()}});function removeNonImportResources(stack){const template=stack.template;delete template.Resources.CDKMetadata;delete template.Outputs;return template}function fmtdict(xs){return Object.entries(xs).map(([k,v])=>`${k}=${v}`).join(", ")}function addDefaultDeletionPolicy(resource){if(resource.DeletionPolicy){return resource}return{...resource,DeletionPolicy:"Retain"}}var cfnDiff2,chalk23,fs21,promptly3,ResourceImporter;var init_import=__esm({"lib/import.ts"(){"use strict";cfnDiff2=__toESM(require_lib9());chalk23=__toESM(require_source());fs21=__toESM(require_lib4());promptly3=__toESM(require_promptly());init_deploy_stack();init_logging();init_error();ResourceImporter=class{constructor(stack,cfn){this.stack=stack;this.cfn=cfn}async askForResourceIdentifiers(available){const ret={importResources:[],resourceMap:{}};const resourceIdentifiers2=await this.resourceIdentifiers();for(const resource of available){const identifier=await this.askForResourceIdentifier(resourceIdentifiers2,resource);if(!identifier){continue}ret.importResources.push(resource);ret.resourceMap[resource.logicalId]=identifier}return ret}async loadResourceIdentifiers(available,filename){const contents=await fs21.readJson(filename);const ret={importResources:[],resourceMap:{}};for(const resource of available){const descr=this.describeResource(resource.logicalId);const idProps=contents[resource.logicalId];if(idProps){print("%s: importing using %s",chalk23.blue(descr),chalk23.blue(fmtdict(idProps)));ret.importResources.push(resource);ret.resourceMap[resource.logicalId]=idProps;delete contents[resource.logicalId]}else{print("%s: skipping",chalk23.blue(descr))}}const unknown=Object.keys(contents);if(unknown.length>0){warning(`Unrecognized resource identifiers in mapping file: ${unknown.join(", ")}`)}return ret}async importResourcesFromMap(importMap,options){const resourcesToImport=await this.makeResourcesToImport(importMap);const updatedTemplate=await this.currentTemplateWithAdditions(importMap.importResources);await this.importResources(updatedTemplate,resourcesToImport,options)}async importResourcesFromMigrate(resourcesToImport,options){const updatedTemplate=this.removeNonImportResources();await this.importResources(updatedTemplate,resourcesToImport,options)}async importResources(overrideTemplate,resourcesToImport,options){try{const result=await this.cfn.deployStack({stack:this.stack,deployName:this.stack.stackName,...options,overrideTemplate,resourcesToImport});assertIsSuccessfulDeployStackResult(result);const message=result.noOp?" \u2705 %s (no changes)":" \u2705 %s";success("\n"+message,this.stack.displayName)}catch(e){error("\n \u274C %s failed: %s",chalk23.bold(this.stack.displayName),e);throw e}}async discoverImportableResources(allowNonAdditions=false){const currentTemplate=await this.currentTemplate();const diff=cfnDiff2.fullDiff(currentTemplate,this.stack.template);const resourceChanges=Object.entries(diff.resources.changes).filter(([logicalId,_2])=>logicalId!=="CDKMetadata");const nonAdditions=resourceChanges.filter(([_2,dif])=>!dif.isAddition);const additions=resourceChanges.filter(([_2,dif])=>dif.isAddition);if(nonAdditions.length){const offendingResources=nonAdditions.map(([logId,_2])=>this.describeResource(logId));if(allowNonAdditions){warning(`Ignoring updated/deleted resources (--force): ${offendingResources.join(", ")}`)}else{throw new ToolkitError(`No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(", ")} (--force to override)`)}}return{additions:additions.map(([logicalId,resourceDiff])=>{var _a,_b;return{logicalId,resourceDiff,resourceDefinition:addDefaultDeletionPolicy(((_b=(_a=this.stack.template)==null?void 0:_a.Resources)==null?void 0:_b[logicalId])??{})}}),hasNonAdditions:nonAdditions.length>0}}async resolveEnvironment(){return this.cfn.resolveEnvironment(this.stack)}async currentTemplate(){if(!this._currentTemplate){this._currentTemplate=await this.cfn.readCurrentTemplate(this.stack)}return this._currentTemplate}async currentTemplateWithAdditions(additions){const template=await this.currentTemplate();if(!template.Resources){template.Resources={}}for(const add of additions){template.Resources[add.logicalId]=add.resourceDefinition}return template}async resourceIdentifiers(){var _a;const ret={};const resourceIdentifierSummaries=await this.cfn.resourceIdentifierSummaries(this.stack);for(const summary of resourceIdentifierSummaries){if("ResourceType"in summary&&summary.ResourceType&&"ResourceIdentifiers"in summary&&summary.ResourceIdentifiers){ret[summary.ResourceType]=(_a=summary.ResourceIdentifiers??[])==null?void 0:_a.map(x=>x.split(","))}}return ret}async askForResourceIdentifier(resourceIdentifiers2,chg){const resourceName=this.describeResource(chg.logicalId);const resourceType=chg.resourceDiff.newResourceType;if(resourceType===void 0||!(resourceType in resourceIdentifiers2)){warning(`${resourceName}: unsupported resource type ${resourceType}, skipping import.`);return void 0}const idPropSets=resourceIdentifiers2[resourceType];const resourceProps=Object.fromEntries(Object.entries(chg.resourceDefinition.Properties??{}).filter(([_2,v])=>typeof v==="string"));const satisfiedPropSets=idPropSets.filter(ps=>ps.every(p=>resourceProps[p]));for(const satisfiedPropSet of satisfiedPropSets){const candidateProps=Object.fromEntries(satisfiedPropSet.map(p=>[p,resourceProps[p]]));const displayCandidateProps=fmtdict(candidateProps);if(await promptly3.confirm(`${chalk23.blue(resourceName)} (${resourceType}): import with ${chalk23.yellow(displayCandidateProps)} (yes/no) [default: yes]? `,{default:"yes"})){return candidateProps}}if(satisfiedPropSets.length>0){print(chalk23.grey(`Skipping import of ${resourceName}`));return void 0}const prefix=`${chalk23.blue(resourceName)} (${resourceType})`;let preamble;let promptPattern;if(idPropSets.length>1){preamble=`${prefix}: enter one of ${idPropSets.map(x=>chalk23.blue(x.join("+"))).join(", ")} to import (all empty to skip)`;promptPattern=`${prefix}: enter %`}else{promptPattern=`${prefix}: enter %`}if(preamble){print(preamble)}for(const idProps of idPropSets){const input={};for(const idProp of idProps){const defaultValue=resourceProps[idProp]??"";const prompt4=[promptPattern.replace(/%/g,chalk23.blue(idProp)),defaultValue?`[${defaultValue}]`:"(empty to skip)"].join(" ")+":";const response=await promptly3.prompt(prompt4,{default:defaultValue,trim:true});if(!response){break}input[idProp]=response;resourceProps[idProp]=response}if(Object.keys(input).length===idProps.length){return input}}print(chalk23.grey(`Skipping import of ${resourceName}`));return void 0}async makeResourcesToImport(resourceMap){return resourceMap.importResources.map(res=>({LogicalResourceId:res.logicalId,ResourceType:res.resourceDiff.newResourceType,ResourceIdentifier:resourceMap.resourceMap[res.logicalId]}))}describeResource(logicalId){var _a,_b,_c,_d;return((_d=(_c=(_b=(_a=this.stack.template)==null?void 0:_a.Resources)==null?void 0:_b[logicalId])==null?void 0:_c.Metadata)==null?void 0:_d["aws:cdk:path"])??logicalId}removeNonImportResources(){return removeNonImportResources(this.stack)}}}});async function listStacks(toolkit,options){const assembly=await toolkit.assembly();const stacks=await assembly.selectStacks({patterns:options.selectors},{extend:1,defaultBehavior:"all"});function calculateStackDependencies(collectionOfStacks){const allData=[];for(const stack of collectionOfStacks.stackArtifacts){const data2={id:stack.displayName??stack.id,name:stack.stackName,environment:stack.environment,dependencies:[]};for(const dependencyId of stack.dependencies.map(x=>x.id)){if(dependencyId.includes(".assets")){continue}const depStack=assembly.stackById(dependencyId);if(depStack.stackArtifacts[0].dependencies.length>0&&depStack.stackArtifacts[0].dependencies.filter(dep=>!dep.id.includes(".assets")).length>0){const stackWithDeps=calculateStackDependencies(depStack);for(const stackDetail of stackWithDeps){data2.dependencies.push({id:stackDetail.id,dependencies:stackDetail.dependencies})}}else{data2.dependencies.push({id:depStack.stackArtifacts[0].displayName??depStack.stackArtifacts[0].id,dependencies:[]})}}allData.push(data2)}return allData}return calculateStackDependencies(stacks)}var import_run;var init_list_stacks=__esm({"lib/list-stacks.ts"(){"use strict";import_run=__toESM(require_run());init_cloud_assembly2()}});function validateSnsTopicArn(arn){return/^arn:aws:sns:[a-z0-9\-]+:[0-9]+:[a-z0-9\-\_]+$/i.test(arn)}var init_validate_notification_arn=__esm({"lib/util/validate-notification-arn.ts"(){"use strict"}});async function parallelPromises(n,promises){const ret=new Array;let count=0;let error3;const queue=[...promises];return new Promise((ok,ko)=>{tick();function tick(){if(count===0&&error3){ko(error3);return}if(count===0&&queue.length===0){ok(ret);return}while(count<n&&queue.length>0&&!error3){const next=queue.shift();if(next!==void 0){start(next)}}}function start(fn){count+=1;fn().then(result=>{ret.push(result)}).catch(e=>{error3=e}).finally(()=>{count-=1;tick()})}})}var init_parallel=__esm({"lib/util/parallel.ts"(){"use strict"}});var init_work_graph_types=__esm({"lib/util/work-graph-types.ts"(){"use strict"}});function sum2(xs){let ret=0;for(const x of xs){ret+=x}return ret}function retainOnly(xs,pred){xs.splice(0,xs.length,...xs.filter(pred))}function gv(id,attrs){const attrString=Object.entries(attrs??{}).flatMap(([k,v])=>v!==void 0?[`${k}="${v}"`]:[]).join(",");return attrString?`"${simplifyId(id)}" [${attrString}]`:`"${simplifyId(id)}"`}function simplifyId(id){return id.replace(/([0-9a-f]{6})[0-9a-f]{6,}/g,"$1")}var WorkGraph;var init_work_graph=__esm({"lib/util/work-graph.ts"(){"use strict";init_parallel();init_work_graph_types();init_logging();WorkGraph=class{constructor(nodes={}){this.readyPool=[];this.lazyDependencies=new Map;this.nodes={...nodes}}addNodes(...nodes){for(const node of nodes){if(this.nodes[node.id]){throw new Error(`Duplicate use of node id: ${node.id}`)}const ld=this.lazyDependencies.get(node.id);if(ld){for(const x of ld){node.dependencies.add(x)}this.lazyDependencies.delete(node.id)}this.nodes[node.id]=node}}removeNode(nodeId){const id=typeof nodeId==="string"?nodeId:nodeId.id;const removedNode=this.nodes[id];this.lazyDependencies.delete(id);delete this.nodes[id];if(removedNode){for(const node of Object.values(this.nodes)){node.dependencies.delete(removedNode.id)}}}nodesOfType(type){return Object.values(this.nodes).filter(n=>n.type===type)}dependees(nodeId){const id=typeof nodeId==="string"?nodeId:nodeId.id;return Object.values(this.nodes).filter(n=>n.dependencies.has(id))}addDependency(fromId,toId){const node=this.nodes[fromId];if(node){node.dependencies.add(toId);return}let lazyDeps=this.lazyDependencies.get(fromId);if(!lazyDeps){lazyDeps=[];this.lazyDependencies.set(fromId,lazyDeps)}lazyDeps.push(toId)}tryGetNode(id){return this.nodes[id]}node(id){const ret=this.nodes[id];if(!ret){throw new Error(`No node with id ${id} among ${Object.keys(this.nodes)}`)}return ret}absorb(graph){this.addNodes(...Object.values(graph.nodes))}hasFailed(){return Object.values(this.nodes).some(n=>n.deploymentState==="failed")}doParallel(concurrency,actions){return this.forAllArtifacts(concurrency,async x=>{switch(x.type){case"stack":await actions.deployStack(x);break;case"asset-build":await actions.buildAsset(x);break;case"asset-publish":await actions.publishAsset(x);break}})}ready(){this.updateReadyPool();return this.readyPool}forAllArtifacts(n,fn){const graph=this;const max=typeof n==="number"?{"asset-build":n,"asset-publish":n,"stack":n}:n;const totalMax=typeof n==="number"?n:sum2(Object.values(n));return new Promise((ok,fail)=>{let active={"asset-build":0,"asset-publish":0,"stack":0};function totalActive(){return sum2(Object.values(active))}start();function start(){graph.updateReadyPool();for(let i=0;i<graph.readyPool.length;){const node=graph.readyPool[i];if(active[node.type]<max[node.type]&&totalActive()<totalMax){graph.readyPool.splice(i,1);startOne(node)}else{i+=1}}if(totalActive()===0){if(graph.done()){ok()}if(graph.hasFailed()){fail(graph.error)}}}function startOne(x){x.deploymentState="deploying";active[x.type]++;void fn(x).finally(()=>{active[x.type]--}).then(()=>{graph.deployed(x);start()}).catch(err=>{graph.failed(x,err);start()})}})}done(){return Object.values(this.nodes).every(n=>"completed"===n.deploymentState)}deployed(node){node.deploymentState="completed"}failed(node,error3){this.error=error3;node.deploymentState="failed";this.skipRest();this.readyPool.splice(0)}toString(){return["digraph D {",...Object.entries(this.nodes).flatMap(([id,node])=>renderNode(id,node)),"}"].join("\n");function renderNode(id,node){const ret=[];if(node.deploymentState==="completed"){ret.push(` ${gv(id,{style:"filled",fillcolor:"yellow",comment:node.note})};`)}else{ret.push(` ${gv(id,{comment:node.note})};`)}for(const dep of node.dependencies){ret.push(` ${gv(id)} -> ${gv(dep)};`)}return ret}}removeUnavailableDependencies(){for(const node of Object.values(this.nodes)){const removeDeps=Array.from(node.dependencies).filter(dep=>this.nodes[dep]===void 0);removeDeps.forEach(d=>{node.dependencies.delete(d)})}}async removeUnnecessaryAssets(isUnnecessary){debug("Checking for previously published assets");const publishes=this.nodesOfType("asset-publish");const classifiedNodes=await parallelPromises(8,publishes.map(assetNode=>async()=>[assetNode,await isUnnecessary(assetNode)]));const alreadyPublished=classifiedNodes.filter(([_2,unnecessary])=>unnecessary).map(([assetNode,_2])=>assetNode);for(const assetNode of alreadyPublished){this.removeNode(assetNode)}debug(`${publishes.length} total assets, ${publishes.length-alreadyPublished.length} still need to be published`);const unusedBuilds=this.nodesOfType("asset-build").filter(build=>this.dependees(build).length===0);for(const unusedBuild of unusedBuilds){this.removeNode(unusedBuild)}}updateReadyPool(){const activeCount=Object.values(this.nodes).filter(x=>x.deploymentState==="deploying").length;const pendingCount=Object.values(this.nodes).filter(x=>x.deploymentState==="pending").length;const newlyReady=Object.values(this.nodes).filter(x=>x.deploymentState==="pending"&&Array.from(x.dependencies).every(id=>this.node(id).deploymentState==="completed"));for(const node of newlyReady){node.deploymentState="queued";this.readyPool.push(node)}retainOnly(this.readyPool,node=>node.deploymentState==="queued");this.readyPool.sort((a,b)=>(b.priority??0)-(a.priority??0));if(this.readyPool.length===0&&activeCount===0&&pendingCount>0){const cycle=this.findCycle()??["No cycle found!"];trace(`Cycle ${cycle.join(" -> ")} in graph ${this}`);throw new Error(`Unable to make progress anymore, dependency cycle between remaining artifacts: ${cycle.join(" -> ")} (run with -vv for full graph)`)}}skipRest(){for(const node of Object.values(this.nodes)){if(["queued","pending"].includes(node.deploymentState)){node.deploymentState="skipped"}}}findCycle(){const seen=new Set;const self2=this;for(const nodeId of Object.keys(this.nodes)){const cycle=recurse(nodeId,[nodeId]);if(cycle){return cycle}}return void 0;function recurse(nodeId,path24){if(seen.has(nodeId)){return void 0}try{for(const dep of self2.nodes[nodeId].dependencies??[]){const index=path24.indexOf(dep);if(index>-1){return[...path24.slice(index),dep]}const cycle=recurse(dep,[...path24,dep]);if(cycle){return cycle}}return void 0}finally{seen.add(nodeId)}}}reachable(start,end){const seen=new Set;const self2=this;return recurse(start);function recurse(current){if(seen.has(current)){return false}seen.add(current);if(current===end){return true}for(const dep of self2.nodes[current].dependencies){if(recurse(dep)){return true}}return false}}}}});function stacksFromAssets(artifacts){const ret=new Map;for(const stack of artifacts.filter(cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact)){const assetArtifacts=stack.dependencies.filter(cxapi6.AssetManifestArtifact.isAssetManifestArtifact);for(const art of assetArtifacts){ret.set(art,stack)}}return ret}function onlyStacks(artifacts){return artifacts.filter(cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact)}var cxapi6,import_cdk_assets4,_WorkGraphBuilder,WorkGraphBuilder;var init_work_graph_builder=__esm({"lib/util/work-graph-builder.ts"(){"use strict";cxapi6=__toESM(require_lib3());import_cdk_assets4=__toESM(require_lib11());init_content_hash();init_work_graph();init_work_graph_types();_WorkGraphBuilder=class _WorkGraphBuilder{constructor(prebuildAssets,idPrefix=""){this.prebuildAssets=prebuildAssets;this.idPrefix=idPrefix;this.graph=new WorkGraph}addStack(artifact){this.graph.addNodes({type:"stack",id:`${this.idPrefix}${artifact.id}`,dependencies:new Set(this.stackArtifactIds(onlyStacks(artifact.dependencies))),stack:artifact,deploymentState:"pending",priority:_WorkGraphBuilder.PRIORITIES.stack})}addAsset(parentStack,assetManifestArtifact,assetManifest,asset){const assetId=asset.id.assetId;const buildId=`build-${assetId}-${contentHashAny([assetId,asset.genericSource]).substring(0,10)}`;const publishId=`publish-${assetId}-${contentHashAny([assetId,asset.genericDestination]).substring(0,10)}`;if(!this.graph.tryGetNode(buildId)){const node={type:"asset-build",id:buildId,note:assetId,dependencies:new Set([...this.stackArtifactIds(assetManifestArtifact.dependencies),...!this.prebuildAssets?this.stackArtifactIds(onlyStacks(parentStack.dependencies)):[]]),parentStack,assetManifestArtifact,assetManifest,asset,deploymentState:"pending",priority:_WorkGraphBuilder.PRIORITIES["asset-build"]};this.graph.addNodes(node)}const publishNode=this.graph.tryGetNode(publishId);if(!publishNode){this.graph.addNodes({type:"asset-publish",id:publishId,note:`${asset.id}`,dependencies:new Set([buildId]),parentStack,assetManifestArtifact,assetManifest,asset,deploymentState:"pending",priority:_WorkGraphBuilder.PRIORITIES["asset-publish"]})}for(const inheritedDep of this.stackArtifactIds(onlyStacks(parentStack.dependencies))){this.graph.addDependency(publishId,inheritedDep)}this.graph.addDependency(`${this.idPrefix}${parentStack.id}`,publishId)}build(artifacts){const parentStacks=stacksFromAssets(artifacts);for(const artifact of artifacts){if(cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)){this.addStack(artifact)}else if(cxapi6.AssetManifestArtifact.isAssetManifestArtifact(artifact)){const manifest=import_cdk_assets4.AssetManifest.fromFile(artifact.file);for(const entry of manifest.entries){const parentStack=parentStacks.get(artifact);if(parentStack===void 0){throw new Error("Found an asset manifest that is not associated with a stack")}this.addAsset(parentStack,artifact,manifest,entry)}}else if(cxapi6.NestedCloudAssemblyArtifact.isNestedCloudAssemblyArtifact(artifact)){const assembly=new cxapi6.CloudAssembly(artifact.fullPath,{topoSort:false});const nestedGraph=new _WorkGraphBuilder(this.prebuildAssets,`${this.idPrefix}${artifact.id}.`).build(assembly.artifacts);this.graph.absorb(nestedGraph)}else{}}this.graph.removeUnavailableDependencies();this.removeStackPublishCycles();return this.graph}stackArtifactIds(deps){return deps.flatMap(d=>cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact(d)?[this.stackArtifactId(d)]:[])}stackArtifactId(artifact){if(!cxapi6.CloudFormationStackArtifact.isCloudFormationStackArtifact(artifact)){throw new Error(`Can only call this on CloudFormationStackArtifact, got: ${artifact.constructor.name}`)}return`${this.idPrefix}${artifact.id}`}removeStackPublishCycles(){const publishSteps=this.graph.nodesOfType("asset-publish");for(const publishStep of publishSteps){for(const dep of publishStep.dependencies){if(this.graph.reachable(dep,publishStep.id)){publishStep.dependencies.delete(dep)}}}}};_WorkGraphBuilder.PRIORITIES={"asset-build":10,"asset-publish":0,"stack":5};WorkGraphBuilder=_WorkGraphBuilder}});function looksLikeGlob(environment){return environment.indexOf("*")>-1}async function globEnvironmentsFromStacks(stacks,environmentGlobs,sdk){if(environmentGlobs.length===0){return[]}const availableEnvironments=new Array;for(const stack of stacks.stackArtifacts){const actual=await sdk.resolveEnvironment(stack.environment);availableEnvironments.push(actual)}const environments=distinct(availableEnvironments).filter(env2=>environmentGlobs.find(glob2=>minimatch(env2.name,glob2)));if(environments.length===0){const globs=JSON.stringify(environmentGlobs);const envList=availableEnvironments.length>0?availableEnvironments.map(env2=>env2.name).join(", "):"<none>";throw new ToolkitError(`No environments were found when selecting across ${globs} (available: ${envList})`)}return environments}function environmentsFromDescriptors(envSpecs){const ret=new Array;for(const spec of envSpecs){const parts=spec.replace(/^aws:\/\//,"").split("/");if(parts.length!==2){throw new ToolkitError(`Expected environment name in format 'aws://<account>/<region>', got: ${spec}`)}ret.push({name:spec,account:parts[0],region:parts[1]})}return ret}function distinct(envs){const unique={};for(const env2 of envs){const id=`${env2.account||"default"}/${env2.region||"default"}`;if(id in unique){continue}unique[id]=env2}return Object.values(unique)}var init_environments=__esm({"lib/api/cxapp/environments.ts"(){"use strict";init_esm();init_error()}});function printSerializedObject(obj,json){data(serializeStructure(obj,json))}function tagsForStack(stack){return Object.entries(stack.tags).map(([Key,Value])=>({Key,Value}))}function formatTime2(num){return roundPercentage(millisecondsToSeconds(num))}function roundPercentage(num){return Math.round(100*num)/100}function millisecondsToSeconds(num){return num/1e3}function buildParameterMap(parameters){const parameterMap={"*":{}};for(const key in parameters){if(parameters.hasOwnProperty(key)){const[stack,parameter]=key.split(":",2);if(!parameter){parameterMap["*"][stack]=parameters[key]}else{if(!parameterMap[stack]){parameterMap[stack]={}}parameterMap[stack][parameter]=parameters[key]}}}return parameterMap}function obscureTemplate(template={}){if(template.Rules){if(template.Rules.CheckBootstrapVersion){if(Object.keys(template.Rules).length>1){delete template.Rules.CheckBootstrapVersion}else{delete template.Rules}}}return template}async function askUserConfirmation(concurrency,motivation,question){await withCorkedLogging(async()=>{if(!TESTING2&&!process.stdin.isTTY){throw new ToolkitError(`${motivation}, but terminal (TTY) is not attached so we are unable to get a confirmation from the user`)}if(concurrency>1){throw new ToolkitError(`${motivation}, but concurrency is greater than 1 so we are unable to get a confirmation from the user`)}const confirmed=await promptly4.confirm(`${chalk24.cyan(question)} (y/n)?`);if(!confirmed){throw new ToolkitError("Aborted by user")}})}var path23,import_util18,cxapi7,chalk24,chokidar,fs22,promptly4,pLimit3,TESTING2,CdkToolkit;var init_cdk_toolkit=__esm({"lib/cdk-toolkit.ts"(){"use strict";path23=__toESM(require("path"));import_util18=require("util");cxapi7=__toESM(require_lib3());chalk24=__toESM(require_source());chokidar=__toESM(require_chokidar());fs22=__toESM(require_lib4());promptly4=__toESM(require_promptly());init_esm_node();init_bootstrap();init_cloud_assembly2();init_garbage_collector();init_common();init_find_cloudwatch_logs();init_logs_monitor();init_cloudformation();init_stack_activity_monitor();init_migrate();init_diff2();init_import();init_list_stacks();init_logging();init_serialize();init_settings();init_error();init_util3();init_validate_notification_arn();init_work_graph_builder();init_environments();pLimit3=require_p_limit2();TESTING2=false;CdkToolkit=class{constructor(props){this.props=props}async metadata(stackName,json){const stacks=await this.selectSingleStackByName(stackName);printSerializedObject(stacks.firstStack.manifest.metadata??{},json)}async acknowledge(noticeId){const acks=this.props.configuration.context.get("acknowledged-issue-numbers")??[];acks.push(Number(noticeId));this.props.configuration.context.set("acknowledged-issue-numbers",acks);await this.props.configuration.saveContext()}async diff(options){const stacks=await this.selectStacksForDiff(options.stackNames,options.exclusively);const strict=!!options.strict;const contextLines=options.contextLines||3;const stream=options.stream||process.stderr;const quiet=options.quiet||false;let diffs=0;const parameterMap=buildParameterMap(options.parameters);if(options.templatePath!==void 0){if(stacks.stackCount!==1){throw new ToolkitError("Can only select one stack when comparing to fixed template. Use --exclusively to avoid selecting multiple stacks.")}if(!await fs22.pathExists(options.templatePath)){throw new ToolkitError(`There is no file at ${options.templatePath}`)}const template=deserializeStructure(await fs22.readFile(options.templatePath,{encoding:"UTF-8"}));diffs=options.securityOnly?numberFromBool(printSecurityDiff(template,stacks.firstStack,"broadening",quiet)):printStackDiff(template,stacks.firstStack,strict,contextLines,quiet,void 0,void 0,false,stream)}else{for(const stack of stacks.stackArtifacts){const templateWithNestedStacks=await this.props.deployments.readCurrentTemplateWithNestedStacks(stack,options.compareAgainstProcessedTemplate);const currentTemplate=templateWithNestedStacks.deployedRootTemplate;const nestedStacks=templateWithNestedStacks.nestedStacks;const resourcesToImport=await this.tryGetResources(await this.props.deployments.resolveEnvironment(stack));if(resourcesToImport){removeNonImportResources(stack)}let changeSet=void 0;if(options.changeSet){let stackExists=false;try{stackExists=await this.props.deployments.stackExists({stack,deployName:stack.stackName,tryLookupRole:true})}catch(e){debug(e.message);if(!quiet){stream.write(`Checking if the stack ${stack.stackName} exists before creating the changeset has failed, will base the diff on template differences (run again with -v to see the reason)
|
|
849
|
+
`)}stackExists=false}if(stackExists){changeSet=await createDiffChangeSet({stack,uuid:v4_default(),deployments:this.props.deployments,willExecute:false,sdkProvider:this.props.sdkProvider,parameters:Object.assign({},parameterMap["*"],parameterMap[stack.stackName]),resourcesToImport,stream})}else{debug(`the stack '${stack.stackName}' has not been deployed to CloudFormation or describeStacks call failed, skipping changeset creation.`)}}const stackCount=options.securityOnly?numberFromBool(printSecurityDiff(currentTemplate,stack,"broadening",quiet,stack.displayName,changeSet)):printStackDiff(currentTemplate,stack,strict,contextLines,quiet,stack.displayName,changeSet,!!resourcesToImport,stream,nestedStacks);diffs+=stackCount}}stream.write((0,import_util18.format)("\n\u2728 Number of stacks with differences: %s\n",diffs));return diffs&&options.fail?1:0}async deploy(options){var _a,_b;if(options.watch){return this.watch(options)}const startSynthTime=new Date().getTime();const stackCollection=await this.selectStacksForDeploy(options.selector,options.exclusively,options.cacheCloudAssembly,options.ignoreNoStacks);const elapsedSynthTime=new Date().getTime()-startSynthTime;print("\n\u2728 Synthesis time: %ss\n",formatTime2(elapsedSynthTime));if(stackCollection.stackCount===0){console.error("This app contains no stacks");return}await this.tryMigrateResources(stackCollection,options);const requireApproval=options.requireApproval??"broadening";const parameterMap=buildParameterMap(options.parameters);if(options.hotswap!=="full-deployment"){warning("\u26A0\uFE0F The --hotswap and --hotswap-fallback flags deliberately introduce CloudFormation drift to speed up deployments");warning("\u26A0\uFE0F They should only be used for development - never use them for your production Stacks!\n")}let hotswapPropertiesFromSettings=this.props.configuration.settings.get(["hotswap"])||{};let hotswapPropertyOverrides=new HotswapPropertyOverrides;hotswapPropertyOverrides.ecsHotswapProperties=new EcsHotswapProperties((_a=hotswapPropertiesFromSettings.ecs)==null?void 0:_a.minimumHealthyPercent,(_b=hotswapPropertiesFromSettings.ecs)==null?void 0:_b.maximumHealthyPercent);const stacks=stackCollection.stackArtifacts;const stackOutputs={};const outputsFile=options.outputsFile;const buildAsset=async assetNode=>{await this.props.deployments.buildSingleAsset(assetNode.assetManifestArtifact,assetNode.assetManifest,assetNode.asset,{stack:assetNode.parentStack,roleArn:options.roleArn,stackName:assetNode.parentStack.stackName})};const publishAsset=async assetNode=>{await this.props.deployments.publishSingleAsset(assetNode.assetManifest,assetNode.asset,{stack:assetNode.parentStack,roleArn:options.roleArn,stackName:assetNode.parentStack.stackName})};const deployStack2=async stackNode=>{const stack=stackNode.stack;if(stackCollection.stackCount!==1){highlight(stack.displayName)}if(!stack.environment){throw new ToolkitError(`Stack ${stack.displayName} does not define an environment, and AWS credentials could not be obtained from standard locations or no region was configured.`)}if(Object.keys(stack.template.Resources||{}).length===0){if(!await this.props.deployments.stackExists({stack})){warning("%s: stack has no resources, skipping deployment.",chalk24.bold(stack.displayName))}else{warning("%s: stack has no resources, deleting existing stack.",chalk24.bold(stack.displayName));await this.destroy({selector:{patterns:[stack.hierarchicalId]},exclusively:true,force:true,roleArn:options.roleArn,fromDeploy:true,ci:options.ci})}return}if(requireApproval!=="never"){const currentTemplate=await this.props.deployments.readCurrentTemplate(stack);if(printSecurityDiff(currentTemplate,stack,requireApproval)){await askUserConfirmation(concurrency,'"--require-approval" is enabled and stack includes security-sensitive updates',"Do you wish to deploy these changes")}}const notificationArns=!!options.notificationArns||!!stack.notificationArns?(options.notificationArns??[]).concat(stack.notificationArns??[]):void 0;for(const notificationArn of notificationArns??[]){if(!validateSnsTopicArn(notificationArn)){throw new ToolkitError(`Notification arn ${notificationArn} is not a valid arn for an SNS topic`)}}const stackIndex=stacks.indexOf(stack)+1;print("%s: deploying... [%s/%s]",chalk24.bold(stack.displayName),stackIndex,stackCollection.stackCount);const startDeployTime=new Date().getTime();let tags=options.tags;if(!tags||tags.length===0){tags=tagsForStack(stack)}let elapsedDeployTime=0;try{let deployResult;let rollback=options.rollback;let iteration=0;while(!deployResult){if(++iteration>2){throw new ToolkitError("This loop should have stabilized in 2 iterations, but didn't. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose")}const r=await this.props.deployments.deployStack({stack,deployName:stack.stackName,roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,reuseAssets:options.reuseAssets,notificationArns,tags,execute:options.execute,changeSetName:options.changeSetName,deploymentMethod:options.deploymentMethod,force:options.force,parameters:Object.assign({},parameterMap["*"],parameterMap[stack.stackName]),usePreviousParameters:options.usePreviousParameters,progress,ci:options.ci,rollback,hotswap:options.hotswap,hotswapPropertyOverrides,extraUserAgent:options.extraUserAgent,assetParallelism:options.assetParallelism,ignoreNoStacks:options.ignoreNoStacks});switch(r.type){case"did-deploy-stack":deployResult=r;break;case"failpaused-need-rollback-first":{const motivation=r.reason==="replacement"?`Stack is in a paused fail state (${r.status}) and change includes a replacement which cannot be deployed with "--no-rollback"`:`Stack is in a paused fail state (${r.status}) and command line arguments do not include "--no-rollback"`;if(options.force){warning(`${motivation}. Rolling back first (--force).`)}else{await askUserConfirmation(concurrency,motivation,`${motivation}. Roll back first and then proceed with deployment`)}await this.rollback({selector:{patterns:[stack.hierarchicalId]},toolkitStackName:options.toolkitStackName,force:options.force});rollback=true;break}case"replacement-requires-rollback":{const motivation='Change includes a replacement which cannot be deployed with "--no-rollback"';if(options.force){warning(`${motivation}. Proceeding with regular deployment (--force).`)}else{await askUserConfirmation(concurrency,motivation,`${motivation}. Perform a regular deployment`)}rollback=true;break}default:throw new ToolkitError(`Unexpected result type from deployStack: ${JSON.stringify(r)}. If you are seeing this error, please report it at https://github.com/aws/aws-cdk/issues/new/choose`)}}const message=deployResult.noOp?" \u2705 %s (no changes)":" \u2705 %s";success("\n"+message,stack.displayName);elapsedDeployTime=new Date().getTime()-startDeployTime;print("\n\u2728 Deployment time: %ss\n",formatTime2(elapsedDeployTime));if(Object.keys(deployResult.outputs).length>0){print("Outputs:");stackOutputs[stack.stackName]=deployResult.outputs}for(const name of Object.keys(deployResult.outputs).sort()){const value=deployResult.outputs[name];print("%s.%s = %s",chalk24.cyan(stack.id),chalk24.cyan(name),chalk24.underline(chalk24.cyan(value)))}print("Stack ARN:");data(deployResult.stackArn)}catch(e){throw new ToolkitError([`\u274C ${chalk24.bold(stack.stackName)} failed:`,...e.name?[`${e.name}:`]:[],e.message].join(" "))}finally{if(options.cloudWatchLogMonitor){const foundLogGroupsResult=await findCloudWatchLogGroups(this.props.sdkProvider,stack);options.cloudWatchLogMonitor.addLogGroups(foundLogGroupsResult.env,foundLogGroupsResult.sdk,foundLogGroupsResult.logGroupNames)}if(outputsFile){fs22.ensureFileSync(outputsFile);await fs22.writeJson(outputsFile,stackOutputs,{spaces:2,encoding:"utf8"})}}print("\n\u2728 Total time: %ss\n",formatTime2(elapsedSynthTime+elapsedDeployTime))};const assetBuildTime=options.assetBuildTime??0;const prebuildAssets=assetBuildTime===0;const concurrency=options.concurrency||1;const progress=concurrency>1?"events":options.progress;if(concurrency>1&&options.progress&&options.progress!="events"){warning('\u26A0\uFE0F The --concurrency flag only supports --progress "events". Switching to "events".')}const stacksAndTheirAssetManifests=stacks.flatMap(stack=>[stack,...stack.dependencies.filter(cxapi7.AssetManifestArtifact.isAssetManifestArtifact)]);const workGraph=new WorkGraphBuilder(prebuildAssets).build(stacksAndTheirAssetManifests);if(!options.force){await this.removePublishedAssets(workGraph,options)}const graphConcurrency={"stack":concurrency,"asset-build":1,"asset-publish":options.assetParallelism??true?8:1};await workGraph.doParallel(graphConcurrency,{deployStack:deployStack2,buildAsset,publishAsset})}async rollback(options){const startSynthTime=new Date().getTime();const stackCollection=await this.selectStacksForDeploy(options.selector,true);const elapsedSynthTime=new Date().getTime()-startSynthTime;print("\n\u2728 Synthesis time: %ss\n",formatTime2(elapsedSynthTime));if(stackCollection.stackCount===0){console.error("No stacks selected");return}let anyRollbackable=false;for(const stack of stackCollection.stackArtifacts){print("Rolling back %s",chalk24.bold(stack.displayName));const startRollbackTime=new Date().getTime();try{const result=await this.props.deployments.rollbackStack({stack,roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,force:options.force,validateBootstrapStackVersion:options.validateBootstrapStackVersion,orphanLogicalIds:options.orphanLogicalIds});if(!result.notInRollbackableState){anyRollbackable=true}const elapsedRollbackTime=new Date().getTime()-startRollbackTime;print("\n\u2728 Rollback time: %ss\n",formatTime2(elapsedRollbackTime))}catch(e){error("\n \u274C %s failed: %s",chalk24.bold(stack.displayName),e.message);throw new ToolkitError("Rollback failed (use --force to orphan failing resources)")}}if(!anyRollbackable){throw new ToolkitError("No stacks were in a state that could be rolled back")}}async watch(options){const rootDir2=path23.dirname(path23.resolve(PROJECT_CONFIG));debug("root directory used for 'watch' is: %s",rootDir2);const watchSettings=this.props.configuration.settings.get(["watch"]);if(!watchSettings){throw new ToolkitError(`Cannot use the 'watch' command without specifying at least one directory to monitor. Make sure to add a "watch" key to your cdk.json`)}const watchIncludes=this.patternsArrayForWatch(watchSettings.include,{rootDir:rootDir2,returnRootDirIfEmpty:true});debug("'include' patterns for 'watch': %s",watchIncludes);const outputDir=this.props.configuration.settings.get(["output"]);const watchExcludes=this.patternsArrayForWatch(watchSettings.exclude,{rootDir:rootDir2,returnRootDirIfEmpty:false}).concat(`${outputDir}/**`,"**/.*","**/.*/**","**/node_modules/**");debug("'exclude' patterns for 'watch': %s",watchExcludes);let latch="pre-ready";const cloudWatchLogMonitor=options.traceLogs?new CloudWatchLogEventMonitor:void 0;const deployAndWatch=async()=>{latch="deploying";cloudWatchLogMonitor==null?void 0:cloudWatchLogMonitor.deactivate();await this.invokeDeployFromWatch(options,cloudWatchLogMonitor);while(latch==="queued"){latch="deploying";print("Detected file changes during deployment. Invoking 'cdk deploy' again");await this.invokeDeployFromWatch(options,cloudWatchLogMonitor)}latch="open";cloudWatchLogMonitor==null?void 0:cloudWatchLogMonitor.activate()};chokidar.watch(watchIncludes,{ignored:watchExcludes,cwd:rootDir2}).on("ready",async()=>{latch="open";debug("'watch' received the 'ready' event. From now on, all file changes will trigger a deployment");print("Triggering initial 'cdk deploy'");await deployAndWatch()}).on("all",async(event,filePath)=>{if(latch==="pre-ready"){print(`'watch' is observing ${event==="addDir"?"directory":"the file"} '%s' for changes`,filePath)}else if(latch==="open"){print("Detected change to '%s' (type: %s). Triggering 'cdk deploy'",filePath,event);await deployAndWatch()}else{latch="queued";print("Detected change to '%s' (type: %s) while 'cdk deploy' is still running. Will queue for another deployment after this one finishes",filePath,event)}})}async import(options){const stacks=await this.selectStacksForDeploy(options.selector,true,true,false);if(stacks.stackCount>1){throw new ToolkitError(`Stack selection is ambiguous, please choose a specific stack for import [${stacks.stackArtifacts.map(x=>x.id).join(", ")}]`)}if(!process.stdout.isTTY&&!options.resourceMappingFile){throw new ToolkitError("--resource-mapping is required when input is not a terminal")}const stack=stacks.stackArtifacts[0];highlight(stack.displayName);const resourceImporter=new ResourceImporter(stack,this.props.deployments);const{additions,hasNonAdditions}=await resourceImporter.discoverImportableResources(options.force);if(additions.length===0){warning("%s: no new resources compared to the currently deployed stack, skipping import.",chalk24.bold(stack.displayName));return}const actualImport=!options.resourceMappingFile?await resourceImporter.askForResourceIdentifiers(additions):await resourceImporter.loadResourceIdentifiers(additions,options.resourceMappingFile);if(actualImport.importResources.length===0){warning("No resources selected for import.");return}if(options.recordResourceMapping){const outputFile=options.recordResourceMapping;fs22.ensureFileSync(outputFile);await fs22.writeJson(outputFile,actualImport.resourceMap,{spaces:2,encoding:"utf8"});print("%s: mapping file written.",outputFile);return}print("%s: importing resources into stack...",chalk24.bold(stack.displayName));const tags=tagsForStack(stack);await resourceImporter.importResourcesFromMap(actualImport,{roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,tags,deploymentMethod:options.deploymentMethod,usePreviousParameters:true,progress:options.progress,rollback:options.rollback});print(`Import operation complete. We recommend you run a ${chalk24.blueBright("drift detection")} operation to confirm your CDK app resource definitions are up-to-date. Read more here: `+chalk24.underline.blueBright("https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/detect-drift-stack.html"));if(actualImport.importResources.length<additions.length){print("");warning(`Some resources were skipped. Run another ${chalk24.blueBright("cdk import")} or a ${chalk24.blueBright("cdk deploy")} to bring the stack up-to-date with your CDK app definition.`)}else if(hasNonAdditions){print("");warning(`Your app has pending updates or deletes excluded from this import operation. Run a ${chalk24.blueBright("cdk deploy")} to bring the stack up-to-date with your CDK app definition.`)}}async destroy(options){let stacks=await this.selectStacksForDestroy(options.selector,options.exclusively);stacks=stacks.reversed();if(!options.force){const confirmed=await promptly4.confirm(`Are you sure you want to delete: ${chalk24.blue(stacks.stackArtifacts.map(s=>s.hierarchicalId).join(", "))} (y/n)?`);if(!confirmed){return}}const action=options.fromDeploy?"deploy":"destroy";for(const[index,stack]of stacks.stackArtifacts.entries()){success("%s: destroying... [%s/%s]",chalk24.blue(stack.displayName),index+1,stacks.stackCount);try{await this.props.deployments.destroyStack({stack,deployName:stack.stackName,roleArn:options.roleArn,ci:options.ci});success(`
|
|
850
850
|
\u2705 %s: ${action}ed`,chalk24.blue(stack.displayName))}catch(e){error(`
|
|
851
|
-
\u274C %s: ${action} failed`,chalk24.blue(stack.displayName),e);throw e}}}async list(selectors,options={}){const stacks=await listStacks(this,{selectors});if(options.long&&options.showDeps){printSerializedObject(stacks,options.json??false);return 0}if(options.showDeps){const stackDeps=[];for(const stack of stacks){stackDeps.push({id:stack.id,dependencies:stack.dependencies})}printSerializedObject(stackDeps,options.json??false);return 0}if(options.long){const long=[];for(const stack of stacks){long.push({id:stack.id,name:stack.name,environment:stack.environment})}printSerializedObject(long,options.json??false);return 0}for(const stack of stacks){data(stack.id)}return 0}async synth(stackNames,exclusively,quiet,autoValidate,json){const stacks=await this.selectStacksForDiff(stackNames,exclusively,autoValidate);if(stacks.stackCount===1){if(!quiet){printSerializedObject(obscureTemplate(stacks.firstStack.template),json??false)}return void 0}success(`Successfully synthesized to ${chalk24.blue(path23.resolve(stacks.assembly.directory))}`);print(`Supply a stack id (${stacks.stackArtifacts.map(s=>chalk24.green(s.hierarchicalId)).join(", ")}) to display its template.`);return void 0}async bootstrap(userEnvironmentSpecs,options){const bootstrapper=new Bootstrapper(options.source);const environments=await this.defineEnvironments(userEnvironmentSpecs);const limit=pLimit3(20);await Promise.all(environments.map(environment=>limit(async()=>{success(" \u23F3 Bootstrapping environment %s...",chalk24.blue(environment.name));try{const result=await bootstrapper.bootstrapEnvironment(environment,this.props.sdkProvider,options);const message=result.noOp?" \u2705 Environment %s bootstrapped (no changes).":" \u2705 Environment %s bootstrapped.";success(message,chalk24.blue(environment.name))}catch(e){error(" \u274C Environment %s failed bootstrapping: %s",chalk24.blue(environment.name),e);throw e}})))}async garbageCollect(userEnvironmentSpecs,options){const environments=await this.defineEnvironments(userEnvironmentSpecs);for(const environment of environments){success(" \u23F3 Garbage Collecting environment %s...",chalk24.blue(environment.name));const gc=new GarbageCollector({sdkProvider:this.props.sdkProvider,resolvedEnvironment:environment,bootstrapStackName:options.bootstrapStackName,rollbackBufferDays:options.rollbackBufferDays,createdBufferDays:options.createdBufferDays,action:options.action??"full",type:options.type??"all",confirm:options.confirm??true});await gc.garbageCollect()};}async defineEnvironments(userEnvironmentSpecs){const environmentSpecs=userEnvironmentSpecs.length>0?[...userEnvironmentSpecs]:["**"];const globSpecs=partition(environmentSpecs,looksLikeGlob);if(globSpecs.length>0&&!this.props.cloudExecutable.hasApp){if(userEnvironmentSpecs.length>0){throw new ToolkitError(`'${globSpecs}' is not an environment name. Specify an environment name like 'aws://123456789012/us-east-1', or run in a directory with 'cdk.json' to use wildcards.`)}else{throw new ToolkitError("Specify an environment name like 'aws://123456789012/us-east-1', or run in a directory with 'cdk.json'.")}}const environments=[...environmentsFromDescriptors(environmentSpecs)];if(this.props.cloudExecutable.hasApp){environments.push(...await globEnvironmentsFromStacks(await this.selectStacksForList([]),globSpecs,this.props.sdkProvider))}return environments}async migrate(options){var _a,_b,_c;warning("This command is an experimental feature.");const language=((_a=options.language)==null?void 0:_a.toLowerCase())??"typescript";const environment=setEnvironment(options.account,options.region);let generateTemplateOutput;let cfn;let templateToDelete;try{const scanType=parseSourceOptions(options.fromPath,options.fromStack,options.stackName).source;if(scanType=="scan"){generateTemplateOutput=await generateTemplate({stackName:options.stackName,filters:options.filter,fromScan:options.fromScan,sdkProvider:this.props.sdkProvider,environment});templateToDelete=generateTemplateOutput.templateId}else if(scanType=="path"){const templateBody=readFromPath(options.fromPath);const parsedTemplate=deserializeStructure(templateBody);const templateId=(_c=(_b=parsedTemplate.Metadata)==null?void 0:_b.TemplateId)==null?void 0:_c.toString();if(templateId){cfn=new CfnTemplateGeneratorProvider(await buildCfnClient(this.props.sdkProvider,environment));const generatedTemplateSummary=await cfn.describeGeneratedTemplate(templateId);generateTemplateOutput=buildGenertedTemplateOutput(generatedTemplateSummary,templateBody,generatedTemplateSummary.GeneratedTemplateId)}else{generateTemplateOutput={migrateJson:{templateBody,source:"localfile"}}}}else if(scanType=="stack"){const template=await readFromStack(options.stackName,this.props.sdkProvider,environment);if(!template){throw new ToolkitError(`No template found for stack-name: ${options.stackName}`)}generateTemplateOutput={migrateJson:{templateBody:template,source:options.stackName}}}else{throw new ToolkitError(`Invalid source option provided: ${scanType}`)}const stack=generateStack(generateTemplateOutput.migrateJson.templateBody,options.stackName,language);success(" \u23F3 Generating CDK app for %s...",chalk24.blue(options.stackName));await generateCdkApp(options.stackName,stack,language,options.outputPath,options.compress);if(generateTemplateOutput){writeMigrateJsonFile(options.outputPath,options.stackName,generateTemplateOutput.migrateJson)}if(isThereAWarning(generateTemplateOutput)){warning(" \u26A0\uFE0F Some resources could not be migrated completely. Please review the README.md file for more information.");appendWarningsToReadme(`${path23.join(options.outputPath??process.cwd(),options.stackName)}/README.md`,generateTemplateOutput.resources)}}catch(e){error(" \u274C Migrate failed for `%s`: %s",options.stackName,e.message);throw e}finally{if(templateToDelete){if(!cfn){cfn=new CfnTemplateGeneratorProvider(await buildCfnClient(this.props.sdkProvider,environment))}if(!process.env.MIGRATE_INTEG_TEST){await cfn.deleteGeneratedTemplate(templateToDelete)}}}}async selectStacksForList(patterns){const assembly=await this.assembly();const stacks=await assembly.selectStacks({patterns},{defaultBehavior:"all"});return stacks}async selectStacksForDeploy(selector,exclusively,cacheCloudAssembly,ignoreNoStacks){const assembly=await this.assembly(cacheCloudAssembly);const stacks=await assembly.selectStacks(selector,{extend:exclusively?0:1,defaultBehavior:"single",ignoreNoStacks});this.validateStacksSelected(stacks,selector.patterns);this.validateStacks(stacks);return stacks}async selectStacksForDiff(stackNames,exclusively,autoValidate){const assembly=await this.assembly();const selectedForDiff=await assembly.selectStacks({patterns:stackNames},{extend:exclusively?0:1,defaultBehavior:"main"});const allStacks=await this.selectStacksForList([]);const autoValidateStacks=autoValidate?allStacks.filter(art=>art.validateOnSynth??false):new StackCollection(assembly,[]);this.validateStacksSelected(selectedForDiff.concat(autoValidateStacks),stackNames);this.validateStacks(selectedForDiff.concat(autoValidateStacks));return selectedForDiff}async selectStacksForDestroy(selector,exclusively){const assembly=await this.assembly();const stacks=await assembly.selectStacks(selector,{extend:exclusively?0:2,defaultBehavior:"single"});return stacks}async suggestStacks(props){const assembly=await this.assembly();const selectorWithoutPatterns={...props.selector,allTopLevel:true,patterns:[]};const stacksWithoutPatterns=await assembly.selectStacks(selectorWithoutPatterns,{extend:props.exclusively?0:2,defaultBehavior:"single"});const patterns=props.selector.patterns.map(pattern=>{const notExist=!props.stacks.stackArtifacts.find(stack=>minimatch(stack.hierarchicalId,pattern));const closelyMatched=notExist?stacksWithoutPatterns.stackArtifacts.map(stack=>{if(minimatch(stack.hierarchicalId.toLowerCase(),pattern.toLowerCase())){return stack.hierarchicalId}return}).filter(stack=>stack!==void 0):[];return{pattern,notExist,closelyMatched}});for(const pattern of patterns){if(pattern.notExist){const closelyMatched=pattern.closelyMatched.length>0?` Do you mean ${chalk24.blue(pattern.closelyMatched.join(", "))}?`:"";warning(`${chalk24.red(pattern.pattern)} does not exist.${closelyMatched}`)}};}validateStacks(stacks){stacks.processMetadataMessages({ignoreErrors:this.props.ignoreErrors,strict:this.props.strict,verbose:this.props.verbose})}validateStacksSelected(stacks,stackNames){if(stackNames.length!=0&&stacks.stackCount==0){throw new ToolkitError(`No stacks match the name(s) ${stackNames}`)}}async selectSingleStackByName(stackName){const assembly=await this.assembly();const stacks=await assembly.selectStacks({patterns:[stackName]},{extend:0,defaultBehavior:"none"});if(stacks.stackCount>1){throw new ToolkitError(`This command requires exactly one stack and we matched more than one: ${stacks.stackIds}`)}return assembly.stackById(stacks.firstStack.id)}assembly(cacheCloudAssembly){return this.props.cloudExecutable.synthesize(cacheCloudAssembly)}patternsArrayForWatch(patterns,options){const patternsArray=patterns!==void 0?Array.isArray(patterns)?patterns:[patterns]:[];return patternsArray.length>0?patternsArray:options.returnRootDirIfEmpty?[options.rootDir]:[]}async invokeDeployFromWatch(options,cloudWatchLogMonitor){const deployOptions={...options,requireApproval:"never",watch:false,cloudWatchLogMonitor,cacheCloudAssembly:false,hotswap:options.hotswap,extraUserAgent:`cdk-watch/hotswap-${options.hotswap!=="fall-back"?"on":"off"}`,concurrency:options.concurrency};try{await this.deploy(deployOptions)}catch{}}async removePublishedAssets(graph,options){await graph.removeUnnecessaryAssets(assetNode=>this.props.deployments.isSingleAssetPublished(assetNode.assetManifest,assetNode.asset,{stack:assetNode.parentStack,roleArn:options.roleArn,stackName:assetNode.parentStack.stackName}))}async tryMigrateResources(stacks,options){const stack=stacks.stackArtifacts[0];const migrateDeployment=new ResourceImporter(stack,this.props.deployments);const resourcesToImport=await this.tryGetResources(await migrateDeployment.resolveEnvironment());if(resourcesToImport){print("%s: creating stack for resource migration...",chalk24.bold(stack.displayName));print("%s: importing resources into stack...",chalk24.bold(stack.displayName));await this.performResourceMigration(migrateDeployment,resourcesToImport,options);fs22.rmSync("migrate.json");print("%s: applying CDKMetadata and Outputs to stack (if applicable)...",chalk24.bold(stack.displayName))}}async performResourceMigration(migrateDeployment,resourcesToImport,options){const startDeployTime=new Date().getTime();let elapsedDeployTime=0;await migrateDeployment.importResourcesFromMigrate(resourcesToImport,{roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,deploymentMethod:options.deploymentMethod,usePreviousParameters:true,progress:options.progress,rollback:options.rollback});elapsedDeployTime=new Date().getTime()-startDeployTime;print("\n\u2728 Resource migration time: %ss\n",formatTime2(elapsedDeployTime))}async tryGetResources(environment){try{const migrateFile=fs22.readJsonSync("migrate.json",{encoding:"utf-8"});const sourceEnv=migrateFile.Source.split(":");if(sourceEnv[0]==="localfile"||sourceEnv[4]===environment.account&&sourceEnv[3]===environment.region){return migrateFile.Resources}}catch(e){}return void 0}}}});async function contextHandler(options){if(options.clear){options.context.clear();await options.context.save(PROJECT_CONTEXT);print("All context values cleared.")}else if(options.reset){invalidateContext(options.context,options.reset,options.force??false);await options.context.save(PROJECT_CONTEXT)}else{if(options.json){const contextValues=options.context.all;process.stdout.write(JSON.stringify(contextValues,void 0,2))}else{listContext(options.context)}}await displayVersionMessage();return 0}function listContext(context){const keys=contextKeys(context);if(keys.length===0){print("This CDK application does not have any saved context values yet.");print("");print("Context will automatically be saved when you synthesize CDK apps");print("that use environment context information like AZ information, VPCs,");print("SSM parameters, and so on.");return}const data2=[[chalk25.green("#"),chalk25.green("Key"),chalk25.green("Value")]];for(const[i,key]of keys){const jsonWithoutNewlines=JSON.stringify(context.all[key],void 0,2).replace(/\s+/g," ");data2.push([i,key,jsonWithoutNewlines])}print("Context found in %s:",chalk25.blue(PROJECT_CONFIG));print("");print(renderTable(data2,process.stdout.columns));print(`Run ${chalk25.blue("cdk context --reset KEY_OR_NUMBER")} to remove a context key. It will be refreshed on the next CDK synthesis run.`)}function invalidateContext(context,key,force){const i=parseInt(key,10);if(`${i}`===key){key=keyByNumber(context,i)}if(context.has(key)){context.unset(key);if(!context.has(key)){print("Context value %s reset. It will be refreshed on next synthesis",chalk25.blue(key));return}error("Only context values specified in %s can be reset through the CLI",chalk25.blue(PROJECT_CONTEXT));if(!force){throw new Error(`Cannot reset readonly context value with key: ${key}`)}}const matches=keysByExpression(context,key);if(matches.length>0){matches.forEach(match2=>{context.unset(match2)});const{unset,readonly}=getUnsetAndReadonly(context,matches);printUnset(unset);printReadonly(readonly);if(!force&&unset.length===0){throw new Error("None of the matched context values could be reset")}return}if(!force){throw new Error(`No context value matching key: ${key}`)}}function printUnset(unset){if(unset.length===0)return;print("The following matched context values reset. They will be refreshed on next synthesis");unset.forEach(match2=>{print(" %s",match2)})}function printReadonly(readonly){if(readonly.length===0)return;warning("The following matched context values could not be reset through the CLI");readonly.forEach(match2=>{print(" %s",match2)});print("");print("This usually means they are configured in %s or %s",chalk25.blue(PROJECT_CONFIG),chalk25.blue(USER_DEFAULTS))}function keysByExpression(context,expression){return context.keys.filter(minimatch.filter(expression))}function getUnsetAndReadonly(context,matches){return matches.reduce((acc,match2)=>{if(context.has(match2)){acc.readonly.push(match2)}else{acc.unset.push(match2)}return acc},{unset:[],readonly:[]})}function keyByNumber(context,n){for(const[i,key]of contextKeys(context)){if(n===i){return key}}throw new Error(`No context key with number: ${n}`)}function contextKeys(context){const keys=context.keys;keys.sort();return enumerate1(keys)}function enumerate1(xs){const ret=new Array;let i=1;for(const x of xs){ret.push([i,x]);i+=1}return ret}var chalk25;var init_context=__esm({"lib/commands/context.ts"(){"use strict";chalk25=__toESM(require_source());init_esm();init_version4();init_logging();init_settings();init_util3()}});async function docs(options){const url="https://docs.aws.amazon.com/cdk/api/v2/";print(chalk26.green(url));const browserCommand=options.browser.replace(/%u/g,url);debug(`Opening documentation ${chalk26.green(browserCommand)}`);return new Promise((resolve7,_reject)=>{childProcess3.exec(browserCommand,(err,stdout2,stderr2)=>{if(err){debug(`An error occurred when trying to open a browser: ${err.stack||err.message}`);return resolve7(0)}if(stdout2){debug(stdout2)}if(stderr2){warning(stderr2)}resolve7(0)})})}var childProcess3,chalk26;var init_docs=__esm({"lib/commands/docs.ts"(){"use strict";childProcess3=__toESM(require("child_process"));chalk26=__toESM(require_source());init_logging()}});async function doctor(){let exitStatus=0;for(const verification of verifications){if(!await verification()){exitStatus=-1}}await displayVersionMessage();return exitStatus}function displayVersionInformation(){print(`\u2139\uFE0F CDK Version: ${chalk27.green(DISPLAY_VERSION)}`);return true}function displayAwsEnvironmentVariables(){const keys=Object.keys(process2.env).filter(s=>s.startsWith("AWS_"));if(keys.length===0){print("\u2139\uFE0F No AWS environment variables");return true}print("\u2139\uFE0F AWS environment variables:");for(const key of keys){print(` - ${chalk27.blue(key)} = ${chalk27.green(anonymizeAwsVariable(key,process2.env[key]))}`)}return true}function displayCdkEnvironmentVariables(){const keys=Object.keys(process2.env).filter(s=>s.startsWith("CDK_"));if(keys.length===0){print("\u2139\uFE0F No CDK environment variables");return true}print("\u2139\uFE0F CDK environment variables:");let healthy=true;for(const key of keys.sort()){if(key===cxapi8.CONTEXT_ENV||key===cxapi8.CONTEXT_OVERFLOW_LOCATION_ENV||key===cxapi8.OUTDIR_ENV){print(` - ${chalk27.red(key)} = ${chalk27.green(process2.env[key])} (\u26A0\uFE0F reserved for use by the CDK toolkit)`);healthy=false}else{print(` - ${chalk27.blue(key)} = ${chalk27.green(process2.env[key])}`)}}return healthy}function anonymizeAwsVariable(name,value){if(name==="AWS_ACCESS_KEY_ID"){return value.slice(0,4)+"<redacted>"}if(name==="AWS_SECRET_ACCESS_KEY"||name==="AWS_SESSION_TOKEN"||name==="AWS_SECURITY_TOKEN"){return"<redacted>"}return value}var process2,cxapi8,chalk27,verifications;var init_doctor=__esm({"lib/commands/doctor.ts"(){"use strict";process2=__toESM(require("process"));cxapi8=__toESM(require_lib3());chalk27=__toESM(require_source());init_logging();init_version4();verifications=[displayVersionInformation,displayAwsEnvironmentVariables,displayCdkEnvironmentVariables]}});function formatSdkLoggerContent(content){if(content.length===1){const apiFmt=formatApiCall(content[0]);if(apiFmt){return apiFmt}}return content.map(x=>typeof x==="string"?x:(0,import_util21.inspect)(x)).join("")}function formatApiCall(content){var _a,_b,_c;if(!isSdkApiCallSuccess(content)&&!isSdkApiCallError(content)){return void 0}const service=content.clientName.replace(/Client$/,"");const api=content.commandName.replace(/Command$/,"");const parts=[];if((((_a=content.metadata)==null?void 0:_a.attempts)??0)>1){parts.push(`[${(_b=content.metadata)==null?void 0:_b.attempts} attempts, ${(_c=content.metadata)==null?void 0:_c.totalRetryDelay}ms retry]`)}parts.push(`${service}.${api}(${JSON.stringify(content.input)})`);if(isSdkApiCallSuccess(content)){parts.push("-> OK")}else{parts.push(`-> ${content.error}`)}return parts.join(" ")}function isSdkApiCallSuccess(x){return x&&typeof x==="object"&&x.commandName&&x.output}function isSdkApiCallError(x){return x&&typeof x==="object"&&x.commandName&&x.error}var import_util21,SdkToCliLogger;var init_sdk_logger=__esm({"lib/api/aws-auth/sdk-logger.ts"(){"use strict";import_util21=require("util");init_logging();SdkToCliLogger=class{trace(..._content){}debug(..._content){}info(...content){trace("[sdk info] %s",formatSdkLoggerContent(content))}warn(...content){trace("[sdk warn] %s",formatSdkLoggerContent(content))}error(...content){trace("[sdk error] %s",formatSdkLoggerContent(content))}}}});var cli_exports={};__export(cli_exports,{cli:()=>cli,exec:()=>exec3});async function exec3(args,synthesizer){const argv=await parseCommandLineArguments(args);if(argv.verbose){let logLevel;switch(argv.verbose){case 1:logLevel="debug";break;case 2:default:logLevel="trace";break}setLogLevel(logLevel)}if(argv.debug||argv.verbose>2){enableTracing(true)}if(argv.ci){setCI(true)}try{await checkForPlatformWarnings()}catch(e){debug(`Error while checking for platform warnings: ${e}`)}debug("CDK toolkit version:",DISPLAY_VERSION);debug("Command line arguments:",argv);const configuration=new Configuration({commandLineArguments:{...argv,_:argv._}});await configuration.load();const cmd=argv._[0];const notices=Notices.create({context:configuration.context,output:configuration.settings.get(["outdir"]),shouldDisplay:configuration.settings.get(["notices"]),includeAcknowledged:cmd==="notices"?!argv.unacknowledged:false,httpOptions:{proxyAddress:configuration.settings.get(["proxy"]),caBundlePath:configuration.settings.get(["caBundlePath"])}});await notices.refresh();const sdkProvider=await SdkProvider.withAwsCliCompatibleDefaults({profile:configuration.settings.get(["profile"]),httpOptions:{proxyAddress:argv.proxy,caBundlePath:argv["ca-bundle-path"]},logger:new SdkToCliLogger});let outDirLock;const cloudExecutable=new CloudExecutable({configuration,sdkProvider,synthesizer:synthesizer??(async(aws,config)=>{await(outDirLock==null?void 0:outDirLock.release());const{assembly,lock}=await execProgram(aws,config);outDirLock=lock;return assembly})});function loadPlugins(...settings){const loaded=new Set;for(const source of settings){const plugins=source.get(["plugin"])||[];for(const plugin of plugins){const resolved=tryResolve(plugin);if(loaded.has(resolved)){continue}debug(`Loading plug-in: ${chalk28.green(plugin)} from ${chalk28.blue(resolved)}`);PluginHost.instance.load(plugin);loaded.add(resolved)}}function tryResolve(plugin){try{return require.resolve(plugin)}catch(e){error(`Unable to resolve plugin ${chalk28.green(plugin)}: ${e.stack}`);throw new ToolkitError(`Unable to resolve plug-in: ${plugin}`)}}}loadPlugins(configuration.settings);if(typeof cmd!=="string"){throw new ToolkitError(`First argument should be a string. Got: ${cmd} (${typeof cmd})`)}try{return await main(cmd,argv)}finally{await(outDirLock==null?void 0:outDirLock.release());await displayVersionMessage();if(cmd==="notices"){await notices.refresh({force:true});notices.display({showTotal:argv.unacknowledged})}else if(cmd!=="version"){await notices.refresh();notices.display()}}async function main(command,args2){const toolkitStackName=ToolkitInfo.determineName(configuration.settings.get(["toolkitStackName"]));debug(`Toolkit stack: ${chalk28.bold(toolkitStackName)}`);const cloudFormation=new Deployments({sdkProvider,toolkitStackName});if(args2.all&&args2.STACKS){throw new ToolkitError("You must either specify a list of Stacks or the `--all` argument")}args2.STACKS=args2.STACKS??(args2.STACK?[args2.STACK]:[]);args2.ENVIRONMENTS=args2.ENVIRONMENTS??[];const selector={allTopLevel:args2.all,patterns:args2.STACKS};const cli2=new CdkToolkit({cloudExecutable,deployments:cloudFormation,verbose:argv.trace||argv.verbose>0,ignoreErrors:argv["ignore-errors"],strict:argv.strict,configuration,sdkProvider});switch(command){case"context":return contextHandler({context:configuration.context,clear:argv.clear,json:argv.json,force:argv.force,reset:argv.reset});case"docs":return docs({browser:configuration.settings.get(["browser"])});case"doctor":return doctor();case"ls":case"list":return cli2.list(args2.STACKS,{long:args2.long,json:argv.json,showDeps:args2.showDependencies});case"diff":const enableDiffNoFail=isFeatureEnabled(configuration,cxapi9.ENABLE_DIFF_NO_FAIL_CONTEXT);return cli2.diff({stackNames:args2.STACKS,exclusively:args2.exclusively,templatePath:args2.template,strict:args2.strict,contextLines:args2.contextLines,securityOnly:args2.securityOnly,fail:args2.fail!=null?args2.fail:!enableDiffNoFail,stream:args2.ci?process.stdout:void 0,compareAgainstProcessedTemplate:args2.processed,quiet:args2.quiet,changeSet:args2["change-set"],toolkitStackName});case"bootstrap":const source=determineBootstrapVersion(args2);if(args2.showTemplate){const bootstrapper=new Bootstrapper(source);return bootstrapper.showTemplate(args2.json)}return cli2.bootstrap(args2.ENVIRONMENTS,{source,roleArn:args2.roleArn,force:argv.force,toolkitStackName,execute:args2.execute,tags:configuration.settings.get(["tags"]),terminationProtection:args2.terminationProtection,usePreviousParameters:args2["previous-parameters"],parameters:{bucketName:configuration.settings.get(["toolkitBucket","bucketName"]),kmsKeyId:configuration.settings.get(["toolkitBucket","kmsKeyId"]),createCustomerMasterKey:args2.bootstrapCustomerKey,qualifier:args2.qualifier??configuration.context.get("@aws-cdk/core:bootstrapQualifier"),publicAccessBlockConfiguration:args2.publicAccessBlockConfiguration,examplePermissionsBoundary:argv.examplePermissionsBoundary,customPermissionsBoundary:argv.customPermissionsBoundary,trustedAccounts:arrayFromYargs(args2.trust),trustedAccountsForLookup:arrayFromYargs(args2.trustForLookup),cloudFormationExecutionPolicies:arrayFromYargs(args2.cloudformationExecutionPolicies)}});case"deploy":const parameterMap={};for(const parameter of args2.parameters){if(typeof parameter==="string"){const keyValue=parameter.split("=");parameterMap[keyValue[0]]=keyValue.slice(1).join("=")}}if(args2.execute!==void 0&&args2.method!==void 0){throw new ToolkitError("Can not supply both --[no-]execute and --method at the same time")}let deploymentMethod;switch(args2.method){case"direct":if(args2.changeSetName){throw new ToolkitError("--change-set-name cannot be used with method=direct")}if(args2.importExistingResources){throw new Error("--import-existing-resources cannot be enabled with method=direct")}deploymentMethod={method:"direct"};break;case"change-set":deploymentMethod={method:"change-set",execute:true,changeSetName:args2.changeSetName,importExistingResources:args2.importExistingResources};break;case"prepare-change-set":deploymentMethod={method:"change-set",execute:false,changeSetName:args2.changeSetName,importExistingResources:args2.importExistingResources};break;case void 0:deploymentMethod={method:"change-set",execute:args2.execute??true,changeSetName:args2.changeSetName,importExistingResources:args2.importExistingResources};break}return cli2.deploy({selector,exclusively:args2.exclusively,toolkitStackName,roleArn:args2.roleArn,notificationArns:args2.notificationArns,requireApproval:configuration.settings.get(["requireApproval"]),reuseAssets:args2["build-exclude"],tags:configuration.settings.get(["tags"]),deploymentMethod,force:args2.force,parameters:parameterMap,usePreviousParameters:args2["previous-parameters"],outputsFile:configuration.settings.get(["outputsFile"]),progress:configuration.settings.get(["progress"]),ci:args2.ci,rollback:configuration.settings.get(["rollback"]),hotswap:determineHotswapMode(args2.hotswap,args2.hotswapFallback),watch:args2.watch,traceLogs:args2.logs,concurrency:args2.concurrency,assetParallelism:configuration.settings.get(["assetParallelism"]),assetBuildTime:configuration.settings.get(["assetPrebuild"])?0:1,ignoreNoStacks:args2.ignoreNoStacks});case"rollback":return cli2.rollback({selector,toolkitStackName,roleArn:args2.roleArn,force:args2.force,validateBootstrapStackVersion:args2["validate-bootstrap-version"],orphanLogicalIds:args2.orphan});case"import":return cli2.import({selector,toolkitStackName,roleArn:args2.roleArn,deploymentMethod:{method:"change-set",execute:args2.execute,changeSetName:args2.changeSetName},progress:configuration.settings.get(["progress"]),rollback:configuration.settings.get(["rollback"]),recordResourceMapping:args2["record-resource-mapping"],resourceMappingFile:args2["resource-mapping"],force:args2.force});case"watch":return cli2.watch({selector,exclusively:args2.exclusively,toolkitStackName,roleArn:args2.roleArn,reuseAssets:args2["build-exclude"],deploymentMethod:{method:"change-set",changeSetName:args2.changeSetName},force:args2.force,progress:configuration.settings.get(["progress"]),rollback:configuration.settings.get(["rollback"]),hotswap:determineHotswapMode(args2.hotswap,args2.hotswapFallback,true),traceLogs:args2.logs,concurrency:args2.concurrency});case"destroy":return cli2.destroy({selector,exclusively:args2.exclusively,force:args2.force,roleArn:args2.roleArn,ci:args2.ci});case"gc":if(!configuration.settings.get(["unstable"]).includes("gc")){throw new ToolkitError("Unstable feature use: 'gc' is unstable. It must be opted in via '--unstable', e.g. 'cdk gc --unstable=gc'")}return cli2.garbageCollect(args2.ENVIRONMENTS,{action:args2.action,type:args2.type,rollbackBufferDays:args2["rollback-buffer-days"],createdBufferDays:args2["created-buffer-days"],bootstrapStackName:args2.bootstrapStackName,confirm:args2.confirm});case"synthesize":case"synth":const quiet=configuration.settings.get(["quiet"])??args2.quiet;if(args2.exclusively){return cli2.synth(args2.STACKS,args2.exclusively,quiet,args2.validation,argv.json)}else{return cli2.synth(args2.STACKS,true,quiet,args2.validation,argv.json)}case"notices":return;case"metadata":return cli2.metadata(args2.STACK,argv.json);case"acknowledge":case"ack":return cli2.acknowledge(args2.ID);case"init":const language=configuration.settings.get(["language"]);if(args2.list){return printAvailableTemplates(language)}else{return cliInit({type:args2.TEMPLATE,language,canUseNetwork:void 0,generateOnly:args2.generateOnly})}case"migrate":return cli2.migrate({stackName:args2["stack-name"],fromPath:args2["from-path"],fromStack:args2["from-stack"],language:args2.language,outputPath:args2["output-path"],fromScan:getMigrateScanType(args2["from-scan"]),filter:args2.filter,account:args2.account,region:args2.region,compress:args2.compress});case"version":return data(DISPLAY_VERSION);default:throw new ToolkitError("Unknown command: "+command)}}}function determineBootstrapVersion(args){let source;if(args.template){print(`Using bootstrapping template from ${args.template}`);source={source:"custom",templateFile:args.template}}else if(process.env.CDK_LEGACY_BOOTSTRAP){print("CDK_LEGACY_BOOTSTRAP set, using legacy-style bootstrapping");source={source:"legacy"}}else{source={source:"default"}}return source}function isFeatureEnabled(configuration,featureFlag){return configuration.context.get(featureFlag)??cxapi9.futureFlagDefault(featureFlag)}function arrayFromYargs(xs){if(xs.length===0){return void 0}return xs.filter(x=>x!=="")}function determineHotswapMode(hotswap,hotswapFallback,watch2){if(hotswap&&hotswapFallback){throw new ToolkitError("Can not supply both --hotswap and --hotswap-fallback at the same time")}else if(!hotswap&&!hotswapFallback){if(hotswap===void 0&&hotswapFallback===void 0){return watch2?"hotswap-only":"full-deployment"}else if(hotswap===false||hotswapFallback===false){return"full-deployment"}}let hotswapMode;if(hotswap){hotswapMode="hotswap-only"}else{hotswapMode="fall-back"}return hotswapMode}function cli(args=process.argv.slice(2)){exec3(args).then(async value=>{if(typeof value==="number"){process.exitCode=value}}).catch(err=>{error(err.message);if(err.stack&&isDeveloperBuild()){debug(err.stack)}process.exitCode=1})}var cxapi9,import_run2,chalk28;var init_cli=__esm({"lib/cli.ts"(){"use strict";cxapi9=__toESM(require_lib3());import_run2=__toESM(require_run());chalk28=__toESM(require_source());init_common();init_parse_command_line_arguments();init_platform_warnings();init_tracing();init_aws_auth();init_bootstrap();init_cloud_executable();init_exec();init_deployments();init_plugin2();init_toolkit_info();init_cdk_toolkit();init_context();init_docs();init_doctor();init_migrate();init_init();init_logging();init_notices();init_settings();init_version4();init_sdk_logger();init_error();if(!process.stdout.isTTY){process.env.FORCE_COLOR="0"}}});var __createBinding2=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]});var __exportStar2=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding2(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.exec=exports.cli=void 0;__exportStar2((init_api(),__toCommonJS(api_exports)),exports);var cli_1=(init_cli(),__toCommonJS(cli_exports));Object.defineProperty(exports,"cli",{enumerable:true,get:function(){return cli_1.cli}});Object.defineProperty(exports,"exec",{enumerable:true,get:function(){return cli_1.exec}});
|
|
851
|
+
\u274C %s: ${action} failed`,chalk24.blue(stack.displayName),e);throw e}}}async list(selectors,options={}){const stacks=await listStacks(this,{selectors});if(options.long&&options.showDeps){printSerializedObject(stacks,options.json??false);return 0}if(options.showDeps){const stackDeps=[];for(const stack of stacks){stackDeps.push({id:stack.id,dependencies:stack.dependencies})}printSerializedObject(stackDeps,options.json??false);return 0}if(options.long){const long=[];for(const stack of stacks){long.push({id:stack.id,name:stack.name,environment:stack.environment})}printSerializedObject(long,options.json??false);return 0}for(const stack of stacks){data(stack.id)}return 0}async synth(stackNames,exclusively,quiet,autoValidate,json){const stacks=await this.selectStacksForDiff(stackNames,exclusively,autoValidate);if(stacks.stackCount===1){if(!quiet){printSerializedObject(obscureTemplate(stacks.firstStack.template),json??false)}return void 0}success(`Successfully synthesized to ${chalk24.blue(path23.resolve(stacks.assembly.directory))}`);print(`Supply a stack id (${stacks.stackArtifacts.map(s=>chalk24.green(s.hierarchicalId)).join(", ")}) to display its template.`);return void 0}async bootstrap(userEnvironmentSpecs,options){const bootstrapper=new Bootstrapper(options.source);const environments=await this.defineEnvironments(userEnvironmentSpecs);const limit=pLimit3(20);await Promise.all(environments.map(environment=>limit(async()=>{success(" \u23F3 Bootstrapping environment %s...",chalk24.blue(environment.name));try{const result=await bootstrapper.bootstrapEnvironment(environment,this.props.sdkProvider,options);const message=result.noOp?" \u2705 Environment %s bootstrapped (no changes).":" \u2705 Environment %s bootstrapped.";success(message,chalk24.blue(environment.name))}catch(e){error(" \u274C Environment %s failed bootstrapping: %s",chalk24.blue(environment.name),e);throw e}})))}async garbageCollect(userEnvironmentSpecs,options){const environments=await this.defineEnvironments(userEnvironmentSpecs);for(const environment of environments){success(" \u23F3 Garbage Collecting environment %s...",chalk24.blue(environment.name));const gc=new GarbageCollector({sdkProvider:this.props.sdkProvider,resolvedEnvironment:environment,bootstrapStackName:options.bootstrapStackName,rollbackBufferDays:options.rollbackBufferDays,createdBufferDays:options.createdBufferDays,action:options.action??"full",type:options.type??"all",confirm:options.confirm??true});await gc.garbageCollect()};}async defineEnvironments(userEnvironmentSpecs){const environmentSpecs=userEnvironmentSpecs.length>0?[...userEnvironmentSpecs]:["**"];const globSpecs=partition(environmentSpecs,looksLikeGlob);if(globSpecs.length>0&&!this.props.cloudExecutable.hasApp){if(userEnvironmentSpecs.length>0){throw new ToolkitError(`'${globSpecs}' is not an environment name. Specify an environment name like 'aws://123456789012/us-east-1', or run in a directory with 'cdk.json' to use wildcards.`)}else{throw new ToolkitError("Specify an environment name like 'aws://123456789012/us-east-1', or run in a directory with 'cdk.json'.")}}const environments=[...environmentsFromDescriptors(environmentSpecs)];if(this.props.cloudExecutable.hasApp){environments.push(...await globEnvironmentsFromStacks(await this.selectStacksForList([]),globSpecs,this.props.sdkProvider))}return environments}async migrate(options){var _a,_b,_c;warning("This command is an experimental feature.");const language=((_a=options.language)==null?void 0:_a.toLowerCase())??"typescript";const environment=setEnvironment(options.account,options.region);let generateTemplateOutput;let cfn;let templateToDelete;try{const scanType=parseSourceOptions(options.fromPath,options.fromStack,options.stackName).source;if(scanType=="scan"){generateTemplateOutput=await generateTemplate({stackName:options.stackName,filters:options.filter,fromScan:options.fromScan,sdkProvider:this.props.sdkProvider,environment});templateToDelete=generateTemplateOutput.templateId}else if(scanType=="path"){const templateBody=readFromPath(options.fromPath);const parsedTemplate=deserializeStructure(templateBody);const templateId=(_c=(_b=parsedTemplate.Metadata)==null?void 0:_b.TemplateId)==null?void 0:_c.toString();if(templateId){cfn=new CfnTemplateGeneratorProvider(await buildCfnClient(this.props.sdkProvider,environment));const generatedTemplateSummary=await cfn.describeGeneratedTemplate(templateId);generateTemplateOutput=buildGenertedTemplateOutput(generatedTemplateSummary,templateBody,generatedTemplateSummary.GeneratedTemplateId)}else{generateTemplateOutput={migrateJson:{templateBody,source:"localfile"}}}}else if(scanType=="stack"){const template=await readFromStack(options.stackName,this.props.sdkProvider,environment);if(!template){throw new ToolkitError(`No template found for stack-name: ${options.stackName}`)}generateTemplateOutput={migrateJson:{templateBody:template,source:options.stackName}}}else{throw new ToolkitError(`Invalid source option provided: ${scanType}`)}const stack=generateStack(generateTemplateOutput.migrateJson.templateBody,options.stackName,language);success(" \u23F3 Generating CDK app for %s...",chalk24.blue(options.stackName));await generateCdkApp(options.stackName,stack,language,options.outputPath,options.compress);if(generateTemplateOutput){writeMigrateJsonFile(options.outputPath,options.stackName,generateTemplateOutput.migrateJson)}if(isThereAWarning(generateTemplateOutput)){warning(" \u26A0\uFE0F Some resources could not be migrated completely. Please review the README.md file for more information.");appendWarningsToReadme(`${path23.join(options.outputPath??process.cwd(),options.stackName)}/README.md`,generateTemplateOutput.resources)}}catch(e){error(" \u274C Migrate failed for `%s`: %s",options.stackName,e.message);throw e}finally{if(templateToDelete){if(!cfn){cfn=new CfnTemplateGeneratorProvider(await buildCfnClient(this.props.sdkProvider,environment))}if(!process.env.MIGRATE_INTEG_TEST){await cfn.deleteGeneratedTemplate(templateToDelete)}}}}async selectStacksForList(patterns){const assembly=await this.assembly();const stacks=await assembly.selectStacks({patterns},{defaultBehavior:"all"});return stacks}async selectStacksForDeploy(selector,exclusively,cacheCloudAssembly,ignoreNoStacks){const assembly=await this.assembly(cacheCloudAssembly);const stacks=await assembly.selectStacks(selector,{extend:exclusively?0:1,defaultBehavior:"single",ignoreNoStacks});this.validateStacksSelected(stacks,selector.patterns);this.validateStacks(stacks);return stacks}async selectStacksForDiff(stackNames,exclusively,autoValidate){const assembly=await this.assembly();const selectedForDiff=await assembly.selectStacks({patterns:stackNames},{extend:exclusively?0:1,defaultBehavior:"main"});const allStacks=await this.selectStacksForList([]);const autoValidateStacks=autoValidate?allStacks.filter(art=>art.validateOnSynth??false):new StackCollection(assembly,[]);this.validateStacksSelected(selectedForDiff.concat(autoValidateStacks),stackNames);this.validateStacks(selectedForDiff.concat(autoValidateStacks));return selectedForDiff}async selectStacksForDestroy(selector,exclusively){const assembly=await this.assembly();const stacks=await assembly.selectStacks(selector,{extend:exclusively?0:2,defaultBehavior:"single"});return stacks}validateStacks(stacks){stacks.processMetadataMessages({ignoreErrors:this.props.ignoreErrors,strict:this.props.strict,verbose:this.props.verbose})}validateStacksSelected(stacks,stackNames){if(stackNames.length!=0&&stacks.stackCount==0){throw new ToolkitError(`No stacks match the name(s) ${stackNames}`)}}async selectSingleStackByName(stackName){const assembly=await this.assembly();const stacks=await assembly.selectStacks({patterns:[stackName]},{extend:0,defaultBehavior:"none"});if(stacks.stackCount>1){throw new ToolkitError(`This command requires exactly one stack and we matched more than one: ${stacks.stackIds}`)}return assembly.stackById(stacks.firstStack.id)}assembly(cacheCloudAssembly){return this.props.cloudExecutable.synthesize(cacheCloudAssembly)}patternsArrayForWatch(patterns,options){const patternsArray=patterns!==void 0?Array.isArray(patterns)?patterns:[patterns]:[];return patternsArray.length>0?patternsArray:options.returnRootDirIfEmpty?[options.rootDir]:[]}async invokeDeployFromWatch(options,cloudWatchLogMonitor){const deployOptions={...options,requireApproval:"never",watch:false,cloudWatchLogMonitor,cacheCloudAssembly:false,hotswap:options.hotswap,extraUserAgent:`cdk-watch/hotswap-${options.hotswap!=="fall-back"?"on":"off"}`,concurrency:options.concurrency};try{await this.deploy(deployOptions)}catch{}}async removePublishedAssets(graph,options){await graph.removeUnnecessaryAssets(assetNode=>this.props.deployments.isSingleAssetPublished(assetNode.assetManifest,assetNode.asset,{stack:assetNode.parentStack,roleArn:options.roleArn,stackName:assetNode.parentStack.stackName}))}async tryMigrateResources(stacks,options){const stack=stacks.stackArtifacts[0];const migrateDeployment=new ResourceImporter(stack,this.props.deployments);const resourcesToImport=await this.tryGetResources(await migrateDeployment.resolveEnvironment());if(resourcesToImport){print("%s: creating stack for resource migration...",chalk24.bold(stack.displayName));print("%s: importing resources into stack...",chalk24.bold(stack.displayName));await this.performResourceMigration(migrateDeployment,resourcesToImport,options);fs22.rmSync("migrate.json");print("%s: applying CDKMetadata and Outputs to stack (if applicable)...",chalk24.bold(stack.displayName))}}async performResourceMigration(migrateDeployment,resourcesToImport,options){const startDeployTime=new Date().getTime();let elapsedDeployTime=0;await migrateDeployment.importResourcesFromMigrate(resourcesToImport,{roleArn:options.roleArn,toolkitStackName:options.toolkitStackName,deploymentMethod:options.deploymentMethod,usePreviousParameters:true,progress:options.progress,rollback:options.rollback});elapsedDeployTime=new Date().getTime()-startDeployTime;print("\n\u2728 Resource migration time: %ss\n",formatTime2(elapsedDeployTime))}async tryGetResources(environment){try{const migrateFile=fs22.readJsonSync("migrate.json",{encoding:"utf-8"});const sourceEnv=migrateFile.Source.split(":");if(sourceEnv[0]==="localfile"||sourceEnv[4]===environment.account&&sourceEnv[3]===environment.region){return migrateFile.Resources}}catch(e){}return void 0}}}});async function contextHandler(options){if(options.clear){options.context.clear();await options.context.save(PROJECT_CONTEXT);print("All context values cleared.")}else if(options.reset){invalidateContext(options.context,options.reset,options.force??false);await options.context.save(PROJECT_CONTEXT)}else{if(options.json){const contextValues=options.context.all;process.stdout.write(JSON.stringify(contextValues,void 0,2))}else{listContext(options.context)}}await displayVersionMessage();return 0}function listContext(context){const keys=contextKeys(context);if(keys.length===0){print("This CDK application does not have any saved context values yet.");print("");print("Context will automatically be saved when you synthesize CDK apps");print("that use environment context information like AZ information, VPCs,");print("SSM parameters, and so on.");return}const data2=[[chalk25.green("#"),chalk25.green("Key"),chalk25.green("Value")]];for(const[i,key]of keys){const jsonWithoutNewlines=JSON.stringify(context.all[key],void 0,2).replace(/\s+/g," ");data2.push([i,key,jsonWithoutNewlines])}print("Context found in %s:",chalk25.blue(PROJECT_CONFIG));print("");print(renderTable(data2,process.stdout.columns));print(`Run ${chalk25.blue("cdk context --reset KEY_OR_NUMBER")} to remove a context key. It will be refreshed on the next CDK synthesis run.`)}function invalidateContext(context,key,force){const i=parseInt(key,10);if(`${i}`===key){key=keyByNumber(context,i)}if(context.has(key)){context.unset(key);if(!context.has(key)){print("Context value %s reset. It will be refreshed on next synthesis",chalk25.blue(key));return}error("Only context values specified in %s can be reset through the CLI",chalk25.blue(PROJECT_CONTEXT));if(!force){throw new Error(`Cannot reset readonly context value with key: ${key}`)}}const matches=keysByExpression(context,key);if(matches.length>0){matches.forEach(match2=>{context.unset(match2)});const{unset,readonly}=getUnsetAndReadonly(context,matches);printUnset(unset);printReadonly(readonly);if(!force&&unset.length===0){throw new Error("None of the matched context values could be reset")}return}if(!force){throw new Error(`No context value matching key: ${key}`)}}function printUnset(unset){if(unset.length===0)return;print("The following matched context values reset. They will be refreshed on next synthesis");unset.forEach(match2=>{print(" %s",match2)})}function printReadonly(readonly){if(readonly.length===0)return;warning("The following matched context values could not be reset through the CLI");readonly.forEach(match2=>{print(" %s",match2)});print("");print("This usually means they are configured in %s or %s",chalk25.blue(PROJECT_CONFIG),chalk25.blue(USER_DEFAULTS))}function keysByExpression(context,expression){return context.keys.filter(minimatch.filter(expression))}function getUnsetAndReadonly(context,matches){return matches.reduce((acc,match2)=>{if(context.has(match2)){acc.readonly.push(match2)}else{acc.unset.push(match2)}return acc},{unset:[],readonly:[]})}function keyByNumber(context,n){for(const[i,key]of contextKeys(context)){if(n===i){return key}}throw new Error(`No context key with number: ${n}`)}function contextKeys(context){const keys=context.keys;keys.sort();return enumerate1(keys)}function enumerate1(xs){const ret=new Array;let i=1;for(const x of xs){ret.push([i,x]);i+=1}return ret}var chalk25;var init_context=__esm({"lib/commands/context.ts"(){"use strict";chalk25=__toESM(require_source());init_esm();init_version4();init_logging();init_settings();init_util3()}});async function docs(options){const url="https://docs.aws.amazon.com/cdk/api/v2/";print(chalk26.green(url));const browserCommand=options.browser.replace(/%u/g,url);debug(`Opening documentation ${chalk26.green(browserCommand)}`);return new Promise((resolve7,_reject)=>{childProcess3.exec(browserCommand,(err,stdout2,stderr2)=>{if(err){debug(`An error occurred when trying to open a browser: ${err.stack||err.message}`);return resolve7(0)}if(stdout2){debug(stdout2)}if(stderr2){warning(stderr2)}resolve7(0)})})}var childProcess3,chalk26;var init_docs=__esm({"lib/commands/docs.ts"(){"use strict";childProcess3=__toESM(require("child_process"));chalk26=__toESM(require_source());init_logging()}});async function doctor(){let exitStatus=0;for(const verification of verifications){if(!await verification()){exitStatus=-1}}await displayVersionMessage();return exitStatus}function displayVersionInformation(){print(`\u2139\uFE0F CDK Version: ${chalk27.green(DISPLAY_VERSION)}`);return true}function displayAwsEnvironmentVariables(){const keys=Object.keys(process2.env).filter(s=>s.startsWith("AWS_"));if(keys.length===0){print("\u2139\uFE0F No AWS environment variables");return true}print("\u2139\uFE0F AWS environment variables:");for(const key of keys){print(` - ${chalk27.blue(key)} = ${chalk27.green(anonymizeAwsVariable(key,process2.env[key]))}`)}return true}function displayCdkEnvironmentVariables(){const keys=Object.keys(process2.env).filter(s=>s.startsWith("CDK_"));if(keys.length===0){print("\u2139\uFE0F No CDK environment variables");return true}print("\u2139\uFE0F CDK environment variables:");let healthy=true;for(const key of keys.sort()){if(key===cxapi8.CONTEXT_ENV||key===cxapi8.CONTEXT_OVERFLOW_LOCATION_ENV||key===cxapi8.OUTDIR_ENV){print(` - ${chalk27.red(key)} = ${chalk27.green(process2.env[key])} (\u26A0\uFE0F reserved for use by the CDK toolkit)`);healthy=false}else{print(` - ${chalk27.blue(key)} = ${chalk27.green(process2.env[key])}`)}}return healthy}function anonymizeAwsVariable(name,value){if(name==="AWS_ACCESS_KEY_ID"){return value.slice(0,4)+"<redacted>"}if(name==="AWS_SECRET_ACCESS_KEY"||name==="AWS_SESSION_TOKEN"||name==="AWS_SECURITY_TOKEN"){return"<redacted>"}return value}var process2,cxapi8,chalk27,verifications;var init_doctor=__esm({"lib/commands/doctor.ts"(){"use strict";process2=__toESM(require("process"));cxapi8=__toESM(require_lib3());chalk27=__toESM(require_source());init_logging();init_version4();verifications=[displayVersionInformation,displayAwsEnvironmentVariables,displayCdkEnvironmentVariables]}});function formatSdkLoggerContent(content){if(content.length===1){const apiFmt=formatApiCall(content[0]);if(apiFmt){return apiFmt}}return content.map(x=>typeof x==="string"?x:(0,import_util21.inspect)(x)).join("")}function formatApiCall(content){var _a,_b,_c;if(!isSdkApiCallSuccess(content)&&!isSdkApiCallError(content)){return void 0}const service=content.clientName.replace(/Client$/,"");const api=content.commandName.replace(/Command$/,"");const parts=[];if((((_a=content.metadata)==null?void 0:_a.attempts)??0)>1){parts.push(`[${(_b=content.metadata)==null?void 0:_b.attempts} attempts, ${(_c=content.metadata)==null?void 0:_c.totalRetryDelay}ms retry]`)}parts.push(`${service}.${api}(${JSON.stringify(content.input)})`);if(isSdkApiCallSuccess(content)){parts.push("-> OK")}else{parts.push(`-> ${content.error}`)}return parts.join(" ")}function isSdkApiCallSuccess(x){return x&&typeof x==="object"&&x.commandName&&x.output}function isSdkApiCallError(x){return x&&typeof x==="object"&&x.commandName&&x.error}var import_util21,SdkToCliLogger;var init_sdk_logger=__esm({"lib/api/aws-auth/sdk-logger.ts"(){"use strict";import_util21=require("util");init_logging();SdkToCliLogger=class{trace(..._content){}debug(..._content){}info(...content){trace("[sdk info] %s",formatSdkLoggerContent(content))}warn(...content){trace("[sdk warn] %s",formatSdkLoggerContent(content))}error(...content){trace("[sdk error] %s",formatSdkLoggerContent(content))}}}});var cli_exports={};__export(cli_exports,{cli:()=>cli,exec:()=>exec3});async function exec3(args,synthesizer){const argv=await parseCommandLineArguments(args);if(argv.verbose){let logLevel;switch(argv.verbose){case 1:logLevel="debug";break;case 2:default:logLevel="trace";break}setLogLevel(logLevel)}if(argv.debug||argv.verbose>2){enableTracing(true)}if(argv.ci){setCI(true)}try{await checkForPlatformWarnings()}catch(e){debug(`Error while checking for platform warnings: ${e}`)}debug("CDK toolkit version:",DISPLAY_VERSION);debug("Command line arguments:",argv);const configuration=new Configuration({commandLineArguments:{...argv,_:argv._}});await configuration.load();const cmd=argv._[0];const notices=Notices.create({context:configuration.context,output:configuration.settings.get(["outdir"]),shouldDisplay:configuration.settings.get(["notices"]),includeAcknowledged:cmd==="notices"?!argv.unacknowledged:false,httpOptions:{proxyAddress:configuration.settings.get(["proxy"]),caBundlePath:configuration.settings.get(["caBundlePath"])}});await notices.refresh();const sdkProvider=await SdkProvider.withAwsCliCompatibleDefaults({profile:configuration.settings.get(["profile"]),httpOptions:{proxyAddress:argv.proxy,caBundlePath:argv["ca-bundle-path"]},logger:new SdkToCliLogger});let outDirLock;const cloudExecutable=new CloudExecutable({configuration,sdkProvider,synthesizer:synthesizer??(async(aws,config)=>{await(outDirLock==null?void 0:outDirLock.release());const{assembly,lock}=await execProgram(aws,config);outDirLock=lock;return assembly})});function loadPlugins(...settings){const loaded=new Set;for(const source of settings){const plugins=source.get(["plugin"])||[];for(const plugin of plugins){const resolved=tryResolve(plugin);if(loaded.has(resolved)){continue}debug(`Loading plug-in: ${chalk28.green(plugin)} from ${chalk28.blue(resolved)}`);PluginHost.instance.load(plugin);loaded.add(resolved)}}function tryResolve(plugin){try{return require.resolve(plugin)}catch(e){error(`Unable to resolve plugin ${chalk28.green(plugin)}: ${e.stack}`);throw new ToolkitError(`Unable to resolve plug-in: ${plugin}`)}}}loadPlugins(configuration.settings);if(typeof cmd!=="string"){throw new ToolkitError(`First argument should be a string. Got: ${cmd} (${typeof cmd})`)}try{return await main(cmd,argv)}finally{await(outDirLock==null?void 0:outDirLock.release());await displayVersionMessage();if(cmd==="notices"){await notices.refresh({force:true});notices.display({showTotal:argv.unacknowledged})}else if(cmd!=="version"){await notices.refresh();notices.display()}}async function main(command,args2){const toolkitStackName=ToolkitInfo.determineName(configuration.settings.get(["toolkitStackName"]));debug(`Toolkit stack: ${chalk28.bold(toolkitStackName)}`);const cloudFormation=new Deployments({sdkProvider,toolkitStackName});if(args2.all&&args2.STACKS){throw new ToolkitError("You must either specify a list of Stacks or the `--all` argument")}args2.STACKS=args2.STACKS??(args2.STACK?[args2.STACK]:[]);args2.ENVIRONMENTS=args2.ENVIRONMENTS??[];const selector={allTopLevel:args2.all,patterns:args2.STACKS};const cli2=new CdkToolkit({cloudExecutable,deployments:cloudFormation,verbose:argv.trace||argv.verbose>0,ignoreErrors:argv["ignore-errors"],strict:argv.strict,configuration,sdkProvider});switch(command){case"context":return contextHandler({context:configuration.context,clear:argv.clear,json:argv.json,force:argv.force,reset:argv.reset});case"docs":return docs({browser:configuration.settings.get(["browser"])});case"doctor":return doctor();case"ls":case"list":return cli2.list(args2.STACKS,{long:args2.long,json:argv.json,showDeps:args2.showDependencies});case"diff":const enableDiffNoFail=isFeatureEnabled(configuration,cxapi9.ENABLE_DIFF_NO_FAIL_CONTEXT);return cli2.diff({stackNames:args2.STACKS,exclusively:args2.exclusively,templatePath:args2.template,strict:args2.strict,contextLines:args2.contextLines,securityOnly:args2.securityOnly,fail:args2.fail!=null?args2.fail:!enableDiffNoFail,stream:args2.ci?process.stdout:void 0,compareAgainstProcessedTemplate:args2.processed,quiet:args2.quiet,changeSet:args2["change-set"],toolkitStackName});case"bootstrap":const source=determineBootstrapVersion(args2);if(args2.showTemplate){const bootstrapper=new Bootstrapper(source);return bootstrapper.showTemplate(args2.json)}return cli2.bootstrap(args2.ENVIRONMENTS,{source,roleArn:args2.roleArn,force:argv.force,toolkitStackName,execute:args2.execute,tags:configuration.settings.get(["tags"]),terminationProtection:args2.terminationProtection,usePreviousParameters:args2["previous-parameters"],parameters:{bucketName:configuration.settings.get(["toolkitBucket","bucketName"]),kmsKeyId:configuration.settings.get(["toolkitBucket","kmsKeyId"]),createCustomerMasterKey:args2.bootstrapCustomerKey,qualifier:args2.qualifier??configuration.context.get("@aws-cdk/core:bootstrapQualifier"),publicAccessBlockConfiguration:args2.publicAccessBlockConfiguration,examplePermissionsBoundary:argv.examplePermissionsBoundary,customPermissionsBoundary:argv.customPermissionsBoundary,trustedAccounts:arrayFromYargs(args2.trust),trustedAccountsForLookup:arrayFromYargs(args2.trustForLookup),cloudFormationExecutionPolicies:arrayFromYargs(args2.cloudformationExecutionPolicies)}});case"deploy":const parameterMap={};for(const parameter of args2.parameters){if(typeof parameter==="string"){const keyValue=parameter.split("=");parameterMap[keyValue[0]]=keyValue.slice(1).join("=")}}if(args2.execute!==void 0&&args2.method!==void 0){throw new ToolkitError("Can not supply both --[no-]execute and --method at the same time")}let deploymentMethod;switch(args2.method){case"direct":if(args2.changeSetName){throw new ToolkitError("--change-set-name cannot be used with method=direct")}if(args2.importExistingResources){throw new Error("--import-existing-resources cannot be enabled with method=direct")}deploymentMethod={method:"direct"};break;case"change-set":deploymentMethod={method:"change-set",execute:true,changeSetName:args2.changeSetName,importExistingResources:args2.importExistingResources};break;case"prepare-change-set":deploymentMethod={method:"change-set",execute:false,changeSetName:args2.changeSetName,importExistingResources:args2.importExistingResources};break;case void 0:deploymentMethod={method:"change-set",execute:args2.execute??true,changeSetName:args2.changeSetName,importExistingResources:args2.importExistingResources};break}return cli2.deploy({selector,exclusively:args2.exclusively,toolkitStackName,roleArn:args2.roleArn,notificationArns:args2.notificationArns,requireApproval:configuration.settings.get(["requireApproval"]),reuseAssets:args2["build-exclude"],tags:configuration.settings.get(["tags"]),deploymentMethod,force:args2.force,parameters:parameterMap,usePreviousParameters:args2["previous-parameters"],outputsFile:configuration.settings.get(["outputsFile"]),progress:configuration.settings.get(["progress"]),ci:args2.ci,rollback:configuration.settings.get(["rollback"]),hotswap:determineHotswapMode(args2.hotswap,args2.hotswapFallback),watch:args2.watch,traceLogs:args2.logs,concurrency:args2.concurrency,assetParallelism:configuration.settings.get(["assetParallelism"]),assetBuildTime:configuration.settings.get(["assetPrebuild"])?0:1,ignoreNoStacks:args2.ignoreNoStacks});case"rollback":return cli2.rollback({selector,toolkitStackName,roleArn:args2.roleArn,force:args2.force,validateBootstrapStackVersion:args2["validate-bootstrap-version"],orphanLogicalIds:args2.orphan});case"import":return cli2.import({selector,toolkitStackName,roleArn:args2.roleArn,deploymentMethod:{method:"change-set",execute:args2.execute,changeSetName:args2.changeSetName},progress:configuration.settings.get(["progress"]),rollback:configuration.settings.get(["rollback"]),recordResourceMapping:args2["record-resource-mapping"],resourceMappingFile:args2["resource-mapping"],force:args2.force});case"watch":return cli2.watch({selector,exclusively:args2.exclusively,toolkitStackName,roleArn:args2.roleArn,reuseAssets:args2["build-exclude"],deploymentMethod:{method:"change-set",changeSetName:args2.changeSetName},force:args2.force,progress:configuration.settings.get(["progress"]),rollback:configuration.settings.get(["rollback"]),hotswap:determineHotswapMode(args2.hotswap,args2.hotswapFallback,true),traceLogs:args2.logs,concurrency:args2.concurrency});case"destroy":return cli2.destroy({selector,exclusively:args2.exclusively,force:args2.force,roleArn:args2.roleArn,ci:args2.ci});case"gc":if(!configuration.settings.get(["unstable"]).includes("gc")){throw new ToolkitError("Unstable feature use: 'gc' is unstable. It must be opted in via '--unstable', e.g. 'cdk gc --unstable=gc'")}return cli2.garbageCollect(args2.ENVIRONMENTS,{action:args2.action,type:args2.type,rollbackBufferDays:args2["rollback-buffer-days"],createdBufferDays:args2["created-buffer-days"],bootstrapStackName:args2.bootstrapStackName,confirm:args2.confirm});case"synthesize":case"synth":const quiet=configuration.settings.get(["quiet"])??args2.quiet;if(args2.exclusively){return cli2.synth(args2.STACKS,args2.exclusively,quiet,args2.validation,argv.json)}else{return cli2.synth(args2.STACKS,true,quiet,args2.validation,argv.json)}case"notices":return;case"metadata":return cli2.metadata(args2.STACK,argv.json);case"acknowledge":case"ack":return cli2.acknowledge(args2.ID);case"init":const language=configuration.settings.get(["language"]);if(args2.list){return printAvailableTemplates(language)}else{return cliInit({type:args2.TEMPLATE,language,canUseNetwork:void 0,generateOnly:args2.generateOnly})}case"migrate":return cli2.migrate({stackName:args2["stack-name"],fromPath:args2["from-path"],fromStack:args2["from-stack"],language:args2.language,outputPath:args2["output-path"],fromScan:getMigrateScanType(args2["from-scan"]),filter:args2.filter,account:args2.account,region:args2.region,compress:args2.compress});case"version":return data(DISPLAY_VERSION);default:throw new ToolkitError("Unknown command: "+command)}}}function determineBootstrapVersion(args){let source;if(args.template){print(`Using bootstrapping template from ${args.template}`);source={source:"custom",templateFile:args.template}}else if(process.env.CDK_LEGACY_BOOTSTRAP){print("CDK_LEGACY_BOOTSTRAP set, using legacy-style bootstrapping");source={source:"legacy"}}else{source={source:"default"}}return source}function isFeatureEnabled(configuration,featureFlag){return configuration.context.get(featureFlag)??cxapi9.futureFlagDefault(featureFlag)}function arrayFromYargs(xs){if(xs.length===0){return void 0}return xs.filter(x=>x!=="")}function determineHotswapMode(hotswap,hotswapFallback,watch2){if(hotswap&&hotswapFallback){throw new ToolkitError("Can not supply both --hotswap and --hotswap-fallback at the same time")}else if(!hotswap&&!hotswapFallback){if(hotswap===void 0&&hotswapFallback===void 0){return watch2?"hotswap-only":"full-deployment"}else if(hotswap===false||hotswapFallback===false){return"full-deployment"}}let hotswapMode;if(hotswap){hotswapMode="hotswap-only"}else{hotswapMode="fall-back"}return hotswapMode}function cli(args=process.argv.slice(2)){exec3(args).then(async value=>{if(typeof value==="number"){process.exitCode=value}}).catch(err=>{error(err.message);if(err.stack&&isDeveloperBuild()){debug(err.stack)}process.exitCode=1})}var cxapi9,import_run2,chalk28;var init_cli=__esm({"lib/cli.ts"(){"use strict";cxapi9=__toESM(require_lib3());import_run2=__toESM(require_run());chalk28=__toESM(require_source());init_common();init_parse_command_line_arguments();init_platform_warnings();init_tracing();init_aws_auth();init_bootstrap();init_cloud_executable();init_exec();init_deployments();init_plugin2();init_toolkit_info();init_cdk_toolkit();init_context();init_docs();init_doctor();init_migrate();init_init();init_logging();init_notices();init_settings();init_version4();init_sdk_logger();init_error();if(!process.stdout.isTTY){process.env.FORCE_COLOR="0"}}});var __createBinding2=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]});var __exportStar2=exports&&exports.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding2(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.exec=exports.cli=void 0;__exportStar2((init_api(),__toCommonJS(api_exports)),exports);var cli_1=(init_cli(),__toCommonJS(cli_exports));Object.defineProperty(exports,"cli",{enumerable:true,get:function(){return cli_1.cli}});Object.defineProperty(exports,"exec",{enumerable:true,get:function(){return cli_1.exec}});
|
|
852
852
|
/*! Bundled license information:
|
|
853
853
|
|
|
854
854
|
normalize-path/index.js:
|