cdk-insights 1.42.2 → 1.42.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/entry.js +5 -5
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/entry.js
CHANGED
|
@@ -88,7 +88,7 @@ ${JSON.stringify(S)}`}).join(`
|
|
|
88
88
|
`),s.info("Mixed approach - conventional createLogger with branded transports")};Os.demonstrateMixedUsage=Tq;var Pq=()=>{console.log(`\u{1F3A8} Running Branded API Examples
|
|
89
89
|
`);try{(0,Os.demonstrateBrandedAPI)(),(0,Os.demonstrateAPIComparison)(),(0,Os.demonstrateMixedUsage)(),console.log(`
|
|
90
90
|
\u2705 All branded API examples completed!`),console.log(`
|
|
91
|
-
\u{1F4A1} Benefits of Branded API:`),console.log(" \u2022 Clear brand ownership"),console.log(" \u2022 Consistent naming convention"),console.log(" \u2022 Easy to identify Strogger functions"),console.log(" \u2022 No breaking changes - conventional API still works")}catch(t){console.error("\u274C Error running branded API examples:",t)}};Os.runBrandedAPIExamples=Pq;require.main===ok&&(0,Os.runBrandedAPIExamples)()});var Lr=M(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.demonstrateAutomaticInstanceId=ce.runCloudWatchTransportExamples=ce.runFileTransportExamples=ce.createCloudWatchTransportExample=ce.createFileTransportExample=ce.createBatchedLogger=ce.createBatchedTransport=ce.generateLoggerInstanceId=ce.generateSpanId=ce.generateTraceId=ce.generateCorrelationId=ce.createLoggerInstanceEnricher=ce.createUserEnricher=ce.createEnvironmentEnricher=ce.createSessionEnricher=ce.createCorrelationEnricher=ce.createEnrichmentMiddleware=ce.createDefaultEnrichmentMiddleware=ce.createSampler=ce.createRateLimiter=ce.createLogFilter=ce.validateTransportConfig=ce.validateEnvironmentVariable=ce.handleTransportError=ce.createDetailedError=ce.ERROR_MESSAGES=ce.ValidationError=ce.ConfigurationError=ce.TransportError=ce.LoggerError=ce.createPerformanceMonitor=ce.getEnvironment=ce.createStroggerCloudWatchTransport=ce.createStroggerNewRelicTransport=ce.createStroggerElasticsearchTransport=ce.createStroggerSplunkTransport=ce.createStroggerDataDogTransport=ce.createStroggerConsoleTransport=ce.createCloudWatchTransport=ce.createFileTransport=ce.createNewRelicTransport=ce.createElasticsearchTransport=ce.createSplunkTransport=ce.createDataDogTransport=ce.createConsoleTransport=ce.createJsonFormatter=ce.LogLevel=ce.strogger=ce.createStrogger=ce.createLogger=void 0;ce.printLoggerConfig=ce.shouldLog=ce.runBrandedAPIExamples=ce.runStructuredLoggingDemo=ce.demonstrateManualGeneration=ce.demonstrateInstanceIdInContexts=ce.demonstrateMultipleInstances=ce.demonstrateCustomInstanceId=void 0;var cy=ty();Object.defineProperty(ce,"createLogger",{enumerable:!0,get:function(){return cy.createLogger}});Object.defineProperty(ce,"createStrogger",{enumerable:!0,get:function(){return cy.createStrogger}});Object.defineProperty(ce,"strogger",{enumerable:!0,get:function(){return cy.strogger}});var Lq=Hn();Object.defineProperty(ce,"LogLevel",{enumerable:!0,get:function(){return Lq.LogLevel}});var Oq=j0();Object.defineProperty(ce,"createJsonFormatter",{enumerable:!0,get:function(){return Oq.createJsonFormatter}});var Mq=xp();Object.defineProperty(ce,"createConsoleTransport",{enumerable:!0,get:function(){return Mq.createConsoleTransport}});var Bq=ny();Object.defineProperty(ce,"createDataDogTransport",{enumerable:!0,get:function(){return Bq.createDataDogTransport}});var Nq=ry();Object.defineProperty(ce,"createSplunkTransport",{enumerable:!0,get:function(){return Nq.createSplunkTransport}});var $q=iy();Object.defineProperty(ce,"createElasticsearchTransport",{enumerable:!0,get:function(){return $q.createElasticsearchTransport}});var Wq=oy();Object.defineProperty(ce,"createNewRelicTransport",{enumerable:!0,get:function(){return Wq.createNewRelicTransport}});var jq=II();Object.defineProperty(ce,"createFileTransport",{enumerable:!0,get:function(){return jq.createFileTransport}});var Uq=ay();Object.defineProperty(ce,"createCloudWatchTransport",{enumerable:!0,get:function(){return Uq.createCloudWatchTransport}});var Hq=xp();Object.defineProperty(ce,"createStroggerConsoleTransport",{enumerable:!0,get:function(){return Hq.createConsoleTransport}});var Gq=ny();Object.defineProperty(ce,"createStroggerDataDogTransport",{enumerable:!0,get:function(){return Gq.createDataDogTransport}});var zq=ry();Object.defineProperty(ce,"createStroggerSplunkTransport",{enumerable:!0,get:function(){return zq.createSplunkTransport}});var qq=iy();Object.defineProperty(ce,"createStroggerElasticsearchTransport",{enumerable:!0,get:function(){return qq.createElasticsearchTransport}});var Kq=oy();Object.defineProperty(ce,"createStroggerNewRelicTransport",{enumerable:!0,get:function(){return Kq.createNewRelicTransport}});var Vq=ay();Object.defineProperty(ce,"createStroggerCloudWatchTransport",{enumerable:!0,get:function(){return Vq.createCloudWatchTransport}});var Zq=X0();Object.defineProperty(ce,"getEnvironment",{enumerable:!0,get:function(){return Zq.getEnvironment}});var Yq=kI();Object.defineProperty(ce,"createPerformanceMonitor",{enumerable:!0,get:function(){return Yq.createPerformanceMonitor}});var Or=hi();Object.defineProperty(ce,"LoggerError",{enumerable:!0,get:function(){return Or.LoggerError}});Object.defineProperty(ce,"TransportError",{enumerable:!0,get:function(){return Or.TransportError}});Object.defineProperty(ce,"ConfigurationError",{enumerable:!0,get:function(){return Or.ConfigurationError}});Object.defineProperty(ce,"ValidationError",{enumerable:!0,get:function(){return Or.ValidationError}});Object.defineProperty(ce,"ERROR_MESSAGES",{enumerable:!0,get:function(){return Or.ERROR_MESSAGES}});Object.defineProperty(ce,"createDetailedError",{enumerable:!0,get:function(){return Or.createDetailedError}});Object.defineProperty(ce,"handleTransportError",{enumerable:!0,get:function(){return Or.handleTransportError}});Object.defineProperty(ce,"validateEnvironmentVariable",{enumerable:!0,get:function(){return Or.validateEnvironmentVariable}});Object.defineProperty(ce,"validateTransportConfig",{enumerable:!0,get:function(){return Or.validateTransportConfig}});var uy=ey();Object.defineProperty(ce,"createLogFilter",{enumerable:!0,get:function(){return uy.createLogFilter}});Object.defineProperty(ce,"createRateLimiter",{enumerable:!0,get:function(){return uy.createRateLimiter}});Object.defineProperty(ce,"createSampler",{enumerable:!0,get:function(){return uy.createSampler}});var zn=G0();Object.defineProperty(ce,"createDefaultEnrichmentMiddleware",{enumerable:!0,get:function(){return zn.createDefaultEnrichmentMiddleware}});Object.defineProperty(ce,"createEnrichmentMiddleware",{enumerable:!0,get:function(){return zn.createEnrichmentMiddleware}});Object.defineProperty(ce,"createCorrelationEnricher",{enumerable:!0,get:function(){return zn.createCorrelationEnricher}});Object.defineProperty(ce,"createSessionEnricher",{enumerable:!0,get:function(){return zn.createSessionEnricher}});Object.defineProperty(ce,"createEnvironmentEnricher",{enumerable:!0,get:function(){return zn.createEnvironmentEnricher}});Object.defineProperty(ce,"createUserEnricher",{enumerable:!0,get:function(){return zn.createUserEnricher}});Object.defineProperty(ce,"createLoggerInstanceEnricher",{enumerable:!0,get:function(){return zn.createLoggerInstanceEnricher}});Object.defineProperty(ce,"generateCorrelationId",{enumerable:!0,get:function(){return zn.generateCorrelationId}});Object.defineProperty(ce,"generateTraceId",{enumerable:!0,get:function(){return zn.generateTraceId}});Object.defineProperty(ce,"generateSpanId",{enumerable:!0,get:function(){return zn.generateSpanId}});Object.defineProperty(ce,"generateLoggerInstanceId",{enumerable:!0,get:function(){return zn.generateLoggerInstanceId}});var ck=H0();Object.defineProperty(ce,"createBatchedTransport",{enumerable:!0,get:function(){return ck.createBatchedTransport}});Object.defineProperty(ce,"createBatchedLogger",{enumerable:!0,get:function(){return ck.createBatchedLogger}});var Jq=_I();Object.defineProperty(ce,"createFileTransportExample",{enumerable:!0,get:function(){return Jq.createFileTransportExample}});var Qq=FI();Object.defineProperty(ce,"createCloudWatchTransportExample",{enumerable:!0,get:function(){return Qq.createCloudWatchTransportExample}});var Xq=$I();Object.defineProperty(ce,"runFileTransportExamples",{enumerable:!0,get:function(){return Xq.runFileTransportExamples}});var eK=VI();Object.defineProperty(ce,"runCloudWatchTransportExamples",{enumerable:!0,get:function(){return eK.runCloudWatchTransportExamples}});var Tu=ZI();Object.defineProperty(ce,"demonstrateAutomaticInstanceId",{enumerable:!0,get:function(){return Tu.demonstrateAutomaticInstanceId}});Object.defineProperty(ce,"demonstrateCustomInstanceId",{enumerable:!0,get:function(){return Tu.demonstrateCustomInstanceId}});Object.defineProperty(ce,"demonstrateMultipleInstances",{enumerable:!0,get:function(){return Tu.demonstrateMultipleInstances}});Object.defineProperty(ce,"demonstrateInstanceIdInContexts",{enumerable:!0,get:function(){return Tu.demonstrateInstanceIdInContexts}});Object.defineProperty(ce,"demonstrateManualGeneration",{enumerable:!0,get:function(){return Tu.demonstrateManualGeneration}});var tK=ik();Object.defineProperty(ce,"runStructuredLoggingDemo",{enumerable:!0,get:function(){return tK.runStructuredLoggingDemo}});var sK=ak();Object.defineProperty(ce,"runBrandedAPIExamples",{enumerable:!0,get:function(){return sK.runBrandedAPIExamples}});var nK=kr();Object.defineProperty(ce,"shouldLog",{enumerable:!0,get:function(){return nK.shouldLog}});var rK=ty();Object.defineProperty(ce,"printLoggerConfig",{enumerable:!0,get:function(){return rK.printLoggerConfig}})});var qn,Ya,ly,iK,uk,oK,Me,Ja,ie,et,Mp,bn,Bp,aK,dt=D(()=>{"use strict";qn=oe(Lr()),Ya=process.env.NODE_ENV==="development",ly=process.env.CDK_INSIGHTS_VERBOSE==="true",iK=Ya||ly||process.env.CDK_INSIGHTS_ENABLE_LOGGING==="true",uk=ly?qn.LogLevel.DEBUG:Ya?qn.LogLevel.INFO:qn.LogLevel.ERROR,oK=iK?[(0,qn.createConsoleTransport)({formatter:(0,qn.createJsonFormatter)(),level:uk,useColors:!Ya})]:[],Me=(0,qn.createLogger)({config:{level:uk,serviceName:"cdk-insights",stage:Ya?"dev":"prod"},formatter:(0,qn.createJsonFormatter)(),transports:oK,env:{STAGE:Ya?"dev":"prod",LOG_LEVEL:ly?"DEBUG":Ya?"INFO":"ERROR"}}),Ja=t=>({debug:(e,s,n)=>Me.debug(e,{component:t,...s},n),info:(e,s,n)=>Me.info(e,{component:t,...s},n),warn:(e,s,n,r)=>Me.warn(e,{component:t,...s},n,r),error:(e,s,n,r)=>Me.error(e,{component:t,...s},n,r)}),ie=Ja("cli"),et=Ja("analysis"),Mp=Ja("license"),bn=Ja("cache"),Bp=Ja("github"),aK=Ja("aspect")});var jt,lk,Wp,Mr,Np,dy,Kn,Qa,$p,cK,jp,dk,py,pk,fy,uK,fk,mk,Up,hk,my=D(()=>{"use strict";jt=oe(require("node:fs")),lk=oe(require("node:os")),Wp=oe(require("node:path"));pp();mp();dt();Mr=Wp.join(lk.homedir(),".cdk-insights","cache"),Np=Wp.join(Mr,"analysis-cache.json"),dy=Wp.join(Mr,"cache-stats.json"),Kn={totalHits:0,totalMisses:0,totalSets:0,totalClears:0,cacheSize:0,maxCacheSize:1e3},Qa=null,$p=!1,cK=()=>{try{if(jt.existsSync(dy)){let t=jt.readFileSync(dy,"utf-8");try{Kn={...Kn,...JSON.parse(t)}}catch(e){bn.warn("Could not parse cache statistics file",{error:e instanceof Error?e.message:String(e)})}}}catch(t){bn.warn("Could not load cache statistics",{error:t instanceof Error?t.message:String(t)})}},jp=()=>{$p=!0,!Qa&&(Qa=setTimeout(()=>{$p&&dk(),Qa=null},5e3))},dk=()=>{try{uK(),jt.writeFileSync(dy,JSON.stringify(Kn,null,2),"utf-8"),$p=!1}catch(t){bn.warn("Could not save cache statistics",{error:t instanceof Error?t.message:String(t)})}},py=()=>{Qa&&(clearTimeout(Qa),Qa=null),$p&&dk()};process.on("exit",py);process.on("SIGINT",()=>{py(),process.exit(0)});process.on("SIGTERM",()=>{py(),process.exit(0)});cK();pk=()=>{try{if(Oa()){bn.info("\u2139\uFE0F Cache clear skipped in CI environment (set CDK_INSIGHTS_ENABLE_CACHE_IN_CI=true to opt in)");return}jt.existsSync(Np)&&jt.unlinkSync(Np),jt.existsSync(Mr)&&jt.readdirSync(Mr).length===0&&jt.rmdirSync(Mr),Kn.totalClears++,Kn.lastClearTime=Date.now(),Kn.cacheSize=0,jp(),bn.info("\u2705 Analysis cache cleared successfully")}catch(t){bn.warn("\u26A0\uFE0F Could not clear cache files",{error:t instanceof Error?t.message:String(t)}),bn.info("\u2139\uFE0F Cache will be cleared on next process restart")}},fy=()=>{let t=jt.existsSync(Np),e=jt.existsSync(Mr),s;if(t)try{s=jt.statSync(Np).size}catch{}return{cacheDir:Mr,cacheFileExists:t,cacheDirExists:e,cacheSize:s,stats:Kn}},uK=()=>{jt.existsSync(Mr)||jt.mkdirSync(Mr,{recursive:!0})},fk=t=>{if(!t)return Ir.isFeatureEnabled("caching","free");let e=t==="enterprise"?"pro":t;return Ir.isFeatureEnabled("caching",e)},mk=()=>{Kn.totalHits++,jp()},Up=()=>{Kn.totalMisses++,jp()},hk=()=>{Kn.totalSets++,Kn.cacheSize++,jp()}});var lK,gk,dK,hy,Hp,yk,Pu,Xa,ec=D(()=>{"use strict";lK=["IAM","S3","Lambda","DynamoDB","RDS","EC2","SNS","SQS","StepFunctions","CloudTrail","ApiGateway","SecretsManager","KMS","EventBridge","CloudFront","ELB","ECS","Cognito","WAF","CloudWatch","Route53","ElastiCache","ECR","OpenSearch","ACM","Backup","VPC","Kinesis","AppSync","EKS","Redshift","MSK","Glue","EFS","AutoScaling"],gk={IAM:["iamPolicies","iamPermissionBoundary","iamCrossAccountTrust","iamUserPolicies"],S3:["s3Buckets","s3BucketLogging","s3BucketPolicySsl","s3BucketPolicySelfLockout","s3IntelligentTiering","s3LifecyclePolicy","s3Replication"],Lambda:["lambdaEnvironmentVariables","lambdaMemory","lambdaReservedConcurrency","lambdaDeadLetterQueue","lambdaRuntime","lambdaVpcNatWarning","lambdaPermission"],DynamoDB:["dynamoDBAutoScaling","dynamoDBStreams","dynamoDBPitr","dynamoDBEncryption"],RDS:["rdsEncryption","rdsMultiAZ","rdsPublicAccess","rdsBackupRetention","rdsDeletionProtection","rdsLogging","rdsEnhancedMonitoring"],EC2:["ec2InstanceType","natGatewayUsage","securityGroups","ebsVolumes","ec2PublicIp","ec2SubnetAutoPublicIp"],SNS:["sns","snsTopicPolicySelfLockout"],SQS:["sqs","sqsQueuePolicySelfLockout"],StepFunctions:["stepFunctions"],CloudTrail:["cloudTrailLogging"],ApiGateway:["apiGateway","apiGatewayMethodAuth"],SecretsManager:["secretsManager"],KMS:["kmsKeys","kmsKeyPolicySelfLockout"],EventBridge:["eventBridgeRules","eventBusPolicy"],CloudFront:["cloudFrontHttpsOnly","cloudFrontWafAssociation","cloudFrontLogging","cloudFrontTls"],ELB:["elbDeletionProtection","elbLogging","elbHttpsListeners","elbSecurityPolicy"],ECS:["ecsSecrets","ecsLogging","ecsServiceConnectLogs","ecsResources"],Cognito:["cognitoPasswordPolicy","cognitoMfa","cognitoAdvancedSecurity"],WAF:["wafWebAcl","wafLogging"],CloudWatch:["cloudWatchLogRetention","cloudWatchEncryption","cloudWatchAlarms"],Route53:["route53Dnssec","route53HealthChecks","route53QueryLogging"],ElastiCache:["elastiCacheEncryption","elastiCacheAuth","elastiCacheFailover"],ECR:["ecrScanning","ecrLifecycle","ecrImmutableTags"],OpenSearch:["openSearchEncryption","openSearchAccessControl","openSearchLogging"],ACM:["acmValidation"],Backup:["backupPlans","backupVault"],VPC:["vpcFlowLogs","vpcDefaultSecurityGroup"],Kinesis:["kinesisEncryption","kinesisRetention"],AppSync:["appSyncAuth","appSyncLogging","appSyncWaf"],EKS:["eksPublicEndpoint","eksEncryption","eksLogging"],Redshift:["redshiftEncryption","redshiftPublicAccess","redshiftLogging"],MSK:["mskEncryption","mskAuth","mskLogging"],Glue:["glueEncryption","glueConnections"],EFS:["efsEncryption"],AutoScaling:["autoScalingGroupHealthCheck","autoScalingLaunchConfigPublicIp"]},dK=Object.entries(gk).reduce((t,[e,s])=>{for(let n of s)t[n]=e;return t},{}),hy=t=>{let e=new Set,s=[];for(let n of t)e.has(n)||(e.add(n),s.push(n));return s},Hp=t=>{if(!t||t.length===0)return{services:["All services"],removedAllServices:!1,defaultedToAll:!0};let e=hy(t),s=e.includes("All services"),n=e.filter(r=>r!=="All services");return s&&n.length>0?{services:n,removedAllServices:!0,defaultedToAll:!1}:{services:s?["All services"]:e,removedAllServices:!1,defaultedToAll:!1}},yk=(t,e)=>{if(t.length===0||t.includes("All services"))return hy(e);let s=t.flatMap(n=>n==="All services"?e:gk[n]??[]);return hy(s)},Pu=t=>dK[t],Xa=t=>t==="All services"?!0:lK.includes(t)});var Gp,xi,zp,xk,tc=D(()=>{"use strict";Gp=t=>{if(!t)return;let e=t.trim();if(e)return e.replace(/\/+$/,"")},xi=t=>{let e=Gp(t);return e||(Gp("https://api.cdkinsights.dev/analysis/v1")??"")},zp=t=>{let e=Gp(process.env.CDK_INSIGHTS_LICENSE_API_URL);if(e)return e;let s=xi(t);return s?s.endsWith("/analysis")?`${s.slice(0,-9)}/license`:s:""},xk=t=>Gp(t)});async function Ck(t,e,s){let n=pK(t);if(n){let o=xi(),a=Sk(n.token),c=a?.fingerprint;ie.info("\u2705 Using cached auth token",{hasToken:!0,hasJwtFingerprint:!!c,apiUrl:o});let u=a?.tier||a?.licenseType?{tier:a.tier,licenseType:a.licenseType}:void 0;return{token:n.token,usageData:void 0,licenseInfo:u,fingerprint:c,apiUrl:o}}let r=xi();if(!r){ie.error("\u274C No API endpoint configured for authentication");return}ie.info("\u{1F510} Starting authentication process",{apiUrl:r,hasLicenseKey:!!t,hasFingerprint:!!e,hasProject:!!s});let i=`${r}/login`;ie.info("\u{1F4E1} Making authentication request",{url:i,method:"POST",headers:{"x-cdk-insights-fingerprint":e?"[REDACTED]":"undefined","x-cdk-insights-client":"cli"},body:{licenseKey:t?"[REDACTED]":"undefined",project:s||"undefined"}});try{let{data:o}=await Rt.post(i,{licenseKey:t,project:s},{headers:{"x-cdk-insights-fingerprint":e,"x-cdk-insights-client":"cli"},timeout:1e4});return ie.info("\u2705 Authentication successful",{hasToken:!!o.token,expiresIn:o.expiresIn,fingerprintStatus:o.fingerprintStatus,hasUsageData:!!o.usageData,hasLicenseInfo:!!o.licenseInfo,apiUrl:r}),fK(o.token,t,o.expiresIn||3600),{token:o.token,usageData:o.usageData,licenseInfo:o.licenseInfo,fingerprint:o.fingerprint,apiUrl:r}}catch(o){let a=Rt.isAxiosError(o)?o:void 0,c=xk(a?.config?.url?a.config.url.replace(/\/?login$/,""):r);if(ie.error("Authentication failed",{error:o instanceof Error?o.message:String(o),apiUrl:c}),a)if(a.code==="ECONNREFUSED")ie.error("Network error: Connection refused",{error:a.message,suggestion:"Check if the API server is running and accessible",apiUrl:c});else if(a.code==="ENOTFOUND")ie.error("Network error: Host not found",{error:a.message,apiUrl:c,suggestion:"Check if the API URL is correct"});else if(a.code==="ETIMEDOUT")ie.error("Network error: Request timed out",{error:a.message,suggestion:"The API server took too long to respond",apiUrl:c});else if(a.response){let u=a.response.status,l=a.response.data,d=typeof l?.error=="string"?l.error:l?.error?.message||l?.message||a.message;ie.error(`HTTP ${u} error`,{status:u,apiUrl:c,error:d,response:l}),u===401?ie.error("License key is invalid or expired",{status:u,apiUrl:c}):u===403?ie.error("Access denied - license key may be invalid or suspended",{status:u,apiUrl:c}):u===404?ie.error("API endpoint not found",{status:u,apiUrl:c,suggestion:"Check if the API URL is correct"}):u>=500&&ie.error("Server error",{status:u,apiUrl:c,suggestion:"The API server may be experiencing issues"})}else ie.error("Network error",{error:a.message,apiUrl:c});else ie.error("Unexpected error",{error:o.message||String(o),apiUrl:c});return}}var bk,hs,yy,gy,sc,Sk,vk,pK,fK,Dk,xy=D(()=>{"use strict";bk=oe(require("node:crypto")),hs=oe(require("node:fs")),yy=oe(require("node:path"));rr();tc();dt();gy=yy.join(process.env.HOME||process.env.USERPROFILE||"",".cdk-insights"),sc=yy.join(gy,"auth-token.json"),Sk=t=>{try{let e=t.split(".");return e.length!==3?null:JSON.parse(Buffer.from(e[1],"base64").toString())}catch{return null}},vk=t=>bk.createHash("sha256").update(t).digest("hex").slice(0,16),pK=t=>{try{if(!hs.existsSync(sc))return null;let e=JSON.parse(hs.readFileSync(sc,"utf-8")),s=vk(t);if(e.licenseKeyHash!==s)return null;let n=Sk(e.token),r=Math.floor(Date.now()/1e3),i=n?.exp||e.cachedAt+e.expiresIn;return r>=i?(hs.unlinkSync(sc),null):(ie.debug("Using cached auth token",{cachedAt:new Date(e.cachedAt*1e3).toISOString(),expiresAt:new Date(i*1e3).toISOString()}),e)}catch(e){return ie.debug("Failed to load cached auth token",{error:e instanceof Error?e.message:String(e)}),null}},fK=(t,e,s)=>{try{hs.existsSync(gy)||hs.mkdirSync(gy,{recursive:!0});let n={token:t,licenseKeyHash:vk(e),cachedAt:Math.floor(Date.now()/1e3),expiresIn:s},r=hs.openSync(sc,"w",process.platform!=="win32"?384:void 0);hs.writeSync(r,JSON.stringify(n),void 0,"utf-8"),hs.closeSync(r),ie.debug("Saved auth token to cache",{cachedAt:new Date(n.cachedAt*1e3).toISOString(),expiresIn:s})}catch(n){ie.debug("Failed to save auth token to cache",{error:n instanceof Error?n.message:String(n)})}};Dk=()=>{try{hs.existsSync(sc)?(hs.unlinkSync(sc),ie.info("\u{1F5D1}\uFE0F Cleared auth token cache")):ie.info("\u2139\uFE0F No auth token cache to clear")}catch(t){ie.warn("Failed to clear auth token cache",{error:t instanceof Error?t.message:String(t)})}}});var jr,Ho,Dy,Go,$u,Ht,Nk=D(()=>{jr=(t,e=[])=>t.name==="up"||e.includes("vim")&&t.name==="k"||e.includes("emacs")&&t.ctrl&&t.name==="p",Ho=(t,e=[])=>t.name==="down"||e.includes("vim")&&t.name==="j"||e.includes("emacs")&&t.ctrl&&t.name==="n",Dy=t=>t.name==="space",Go=t=>t.name==="backspace",$u=t=>"1234567890".includes(t.name),Ht=t=>t.name==="enter"||t.name==="return"});var Qp,Xp,Wu,ef,Di,tf=D(()=>{Qp=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}},Xp=class extends Error{name="CancelPromptError";message="Prompt was canceled"},Wu=class extends Error{name="ExitPromptError"},ef=class extends Error{name="HookError"},Di=class extends Error{name="ValidationError"}});function wV(t){return{rl:t,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Wk(t,e){let s=wV(t);return $k.run(s,()=>{function n(r){s.handleChange=()=>{s.index=0,r()},s.handleChange()}return e(n)})}function zo(){let t=$k.getStore();if(!t)throw new ef("[Inquirer] Hook functions can only be called from within a prompt");return t}function Ay(){return zo().rl}function wy(t){let e=(...s)=>{let n=zo(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let o=t(...s);return r&&i(),n.handleChange=i,o};return sf.AsyncResource.bind(e)}function dc(t){let e=zo(),{index:s}=e,n={get(){return e.hooks[s]},set(i){e.hooks[s]=i},initialized:s in e.hooks},r=t(n);return e.index++,r}function jk(){zo().handleChange()}var sf,$k,qo,Ko=D(()=>{sf=require("node:async_hooks");tf();$k=new sf.AsyncLocalStorage;qo={queue(t){let e=zo(),{index:s}=e;e.hooksEffect.push(()=>{e.hooksCleanup[s]?.();let n=t(Ay());if(n!=null&&typeof n!="function")throw new Di("useEffect return value must be a cleanup function or nothing.");e.hooksCleanup[s]=n})},run(){let t=zo();wy(()=>{t.hooksEffect.forEach(e=>{e()}),t.hooksEffect.length=0})()},clearAll(){let t=zo();t.hooksCleanup.forEach(e=>{e?.()}),t.hooksEffect.length=0,t.hooksCleanup.length=0}}});function $e(t){return dc(e=>{let s=Uk.AsyncResource.bind(function(i){e.get()!==i&&(e.set(i),jk())});if(e.initialized)return[e.get(),s];let n=typeof t=="function"?t():t;return e.set(n),[n,s]})}var Uk,nf=D(()=>{Uk=require("node:async_hooks");Ko()});function Zn(t,e){dc(s=>{let n=s.get();(!Array.isArray(n)||e.some((i,o)=>!Object.is(i,n[o])))&&qo.queue(t),s.set(e)})}var rf=D(()=>{Ko()});var Ai=M((ige,Hk)=>{var EV=require("node:tty"),RV=EV?.WriteStream?.prototype?.hasColors?.()??!1,Qe=(t,e)=>{if(!RV)return r=>r;let s=`\x1B[${t}m`,n=`\x1B[${e}m`;return r=>{let i=r+"",o=i.indexOf(n);if(o===-1)return s+i+n;let a=s,c=0,l=(e===22?n:"")+s;for(;o!==-1;)a+=i.slice(c,o)+l,c=o+n.length,o=i.indexOf(n,c);return a+=i.slice(c)+n,a}},Je={};Je.reset=Qe(0,0);Je.bold=Qe(1,22);Je.dim=Qe(2,22);Je.italic=Qe(3,23);Je.underline=Qe(4,24);Je.overline=Qe(53,55);Je.inverse=Qe(7,27);Je.hidden=Qe(8,28);Je.strikethrough=Qe(9,29);Je.black=Qe(30,39);Je.red=Qe(31,39);Je.green=Qe(32,39);Je.yellow=Qe(33,39);Je.blue=Qe(34,39);Je.magenta=Qe(35,39);Je.cyan=Qe(36,39);Je.white=Qe(37,39);Je.gray=Qe(90,39);Je.bgBlack=Qe(40,49);Je.bgRed=Qe(41,49);Je.bgGreen=Qe(42,49);Je.bgYellow=Qe(43,49);Je.bgBlue=Qe(44,49);Je.bgMagenta=Qe(45,49);Je.bgCyan=Qe(46,49);Je.bgWhite=Qe(47,49);Je.bgGray=Qe(100,49);Je.redBright=Qe(91,39);Je.greenBright=Qe(92,39);Je.yellowBright=Qe(93,39);Je.blueBright=Qe(94,39);Je.magentaBright=Qe(95,39);Je.cyanBright=Qe(96,39);Je.whiteBright=Qe(97,39);Je.bgRedBright=Qe(101,49);Je.bgGreenBright=Qe(102,49);Je.bgYellowBright=Qe(103,49);Je.bgBlueBright=Qe(104,49);Je.bgMagentaBright=Qe(105,49);Je.bgCyanBright=Qe(106,49);Je.bgWhiteBright=Qe(107,49);Hk.exports=Je});function IV(){return Yn.default.platform!=="win32"?Yn.default.env.TERM!=="linux":!!Yn.default.env.WT_SESSION||!!Yn.default.env.TERMINUS_SUBLIME||Yn.default.env.ConEmuTask==="{cmd::Cmder}"||Yn.default.env.TERM_PROGRAM==="Terminus-Sublime"||Yn.default.env.TERM_PROGRAM==="vscode"||Yn.default.env.TERM==="xterm-256color"||Yn.default.env.TERM==="alacritty"||Yn.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Yn,Gk,zk,kV,_V,FV,TV,PV,Dn,oge,pc=D(()=>{Yn=oe(require("node:process"),1);Gk={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},zk={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},kV={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},_V={...Gk,...zk},FV={...Gk,...kV},TV=IV(),PV=TV?_V:FV,Dn=PV,oge=Object.entries(zk)});var An,qk,Kk=D(()=>{An=oe(Ai(),1);pc();qk={prefix:{idle:An.default.blue("?"),done:An.default.green(Dn.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(t=>An.default.yellow(t))},style:{answer:An.default.cyan,message:An.default.bold,error:t=>An.default.red(`> ${t}`),defaultAnswer:t=>An.default.dim(`(${t})`),help:An.default.dim,highlight:An.default.cyan,key:t=>An.default.cyan(An.default.bold(`<${t}>`))}}});function Vk(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Zk(...t){let e={};for(let s of t)for(let[n,r]of Object.entries(s)){let i=e[n];e[n]=Vk(i)&&Vk(r)?Zk(i,r):r}return e}function Pt(...t){let e=[qk,...t.filter(s=>s!=null)];return Zk(...e)}var Ey=D(()=>{Kk()});function Gt({status:t="idle",theme:e}){let[s,n]=$e(!1),[r,i]=$e(0),{prefix:o,spinner:a}=Pt(e);return Zn(()=>{if(t==="loading"){let u,l=-1,d=setTimeout(()=>{n(!0),u=setInterval(()=>{l=l+1,i(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(u)}}else n(!1)},[t]),s?a.frames[r]:typeof o=="string"?o:o[t==="loading"?"idle":t]??o.idle}var Yk=D(()=>{nf();rf();Ey()});function en(t,e){return dc(s=>{let n=s.get();if(!n||n.dependencies.length!==e.length||n.dependencies.some((r,i)=>r!==e[i])){let r=t();return s.set({value:r,dependencies:e}),r}return n.value})}var Jk=D(()=>{Ko()});function wn(t){return $e({current:t})[0]}var of=D(()=>{nf()});function zt(t){let e=wn(t);e.current=t,Zn(s=>{let n=!1,r=wy((i,o)=>{n||e.current(o,s)});return s.input.on("keypress",r),()=>{n=!0,s.input.removeListener("keypress",r)}},[])}var Qk=D(()=>{of();rf();Ko()});var e_=M((Age,Xk)=>{"use strict";Xk.exports=OV;function LV(t){let e={defaultWidth:0,output:process.stdout,tty:require("tty")};return t?(Object.keys(e).forEach(function(s){t[s]||(t[s]=e[s])}),t):e}function OV(t){let e=LV(t);if(e.output.getWindowSize)return e.output.getWindowSize()[0]||e.defaultWidth;if(e.tty.getWindowSize)return e.tty.getWindowSize()[1]||e.defaultWidth;if(e.output.columns)return e.output.columns;if(process.env.CLI_WIDTH){let s=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(s)&&s!==0)return s}return e.defaultWidth}});var s_=M((wge,t_)=>{"use strict";t_.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Ry=M((Ege,r_)=>{var ju=s_(),n_={};for(let t of Object.keys(ju))n_[ju[t]]=t;var Te={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};r_.exports=Te;for(let t of Object.keys(Te)){if(!("channels"in Te[t]))throw new Error("missing channels property: "+t);if(!("labels"in Te[t]))throw new Error("missing channel labels property: "+t);if(Te[t].labels.length!==Te[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:s}=Te[t];delete Te[t].channels,delete Te[t].labels,Object.defineProperty(Te[t],"channels",{value:e}),Object.defineProperty(Te[t],"labels",{value:s})}Te.rgb.hsl=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.min(e,s,n),i=Math.max(e,s,n),o=i-r,a,c;i===r?a=0:e===i?a=(s-n)/o:s===i?a=2+(n-e)/o:n===i&&(a=4+(e-s)/o),a=Math.min(a*60,360),a<0&&(a+=360);let u=(r+i)/2;return i===r?c=0:u<=.5?c=o/(i+r):c=o/(2-i-r),[a,c*100,u*100]};Te.rgb.hsv=function(t){let e,s,n,r,i,o=t[0]/255,a=t[1]/255,c=t[2]/255,u=Math.max(o,a,c),l=u-Math.min(o,a,c),d=function(p){return(u-p)/6/l+1/2};return l===0?(r=0,i=0):(i=l/u,e=d(o),s=d(a),n=d(c),o===u?r=n-s:a===u?r=1/3+e-n:c===u&&(r=2/3+s-e),r<0?r+=1:r>1&&(r-=1)),[r*360,i*100,u*100]};Te.rgb.hwb=function(t){let e=t[0],s=t[1],n=t[2],r=Te.rgb.hsl(t)[0],i=1/255*Math.min(e,Math.min(s,n));return n=1-1/255*Math.max(e,Math.max(s,n)),[r,i*100,n*100]};Te.rgb.cmyk=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.min(1-e,1-s,1-n),i=(1-e-r)/(1-r)||0,o=(1-s-r)/(1-r)||0,a=(1-n-r)/(1-r)||0;return[i*100,o*100,a*100,r*100]};function MV(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}Te.rgb.keyword=function(t){let e=n_[t];if(e)return e;let s=1/0,n;for(let r of Object.keys(ju)){let i=ju[r],o=MV(t,i);o<s&&(s=o,n=r)}return n};Te.keyword.rgb=function(t){return ju[t]};Te.rgb.xyz=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,s=s>.04045?((s+.055)/1.055)**2.4:s/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let r=e*.4124+s*.3576+n*.1805,i=e*.2126+s*.7152+n*.0722,o=e*.0193+s*.1192+n*.9505;return[r*100,i*100,o*100]};Te.rgb.lab=function(t){let e=Te.rgb.xyz(t),s=e[0],n=e[1],r=e[2];s/=95.047,n/=100,r/=108.883,s=s>.008856?s**(1/3):7.787*s+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,o=500*(s-n),a=200*(n-r);return[i,o,a]};Te.hsl.rgb=function(t){let e=t[0]/360,s=t[1]/100,n=t[2]/100,r,i,o;if(s===0)return o=n*255,[o,o,o];n<.5?r=n*(1+s):r=n+s-n*s;let a=2*n-r,c=[0,0,0];for(let u=0;u<3;u++)i=e+1/3*-(u-1),i<0&&i++,i>1&&i--,6*i<1?o=a+(r-a)*6*i:2*i<1?o=r:3*i<2?o=a+(r-a)*(2/3-i)*6:o=a,c[u]=o*255;return c};Te.hsl.hsv=function(t){let e=t[0],s=t[1]/100,n=t[2]/100,r=s,i=Math.max(n,.01);n*=2,s*=n<=1?n:2-n,r*=i<=1?i:2-i;let o=(n+s)/2,a=n===0?2*r/(i+r):2*s/(n+s);return[e,a*100,o*100]};Te.hsv.rgb=function(t){let e=t[0]/60,s=t[1]/100,n=t[2]/100,r=Math.floor(e)%6,i=e-Math.floor(e),o=255*n*(1-s),a=255*n*(1-s*i),c=255*n*(1-s*(1-i));switch(n*=255,r){case 0:return[n,c,o];case 1:return[a,n,o];case 2:return[o,n,c];case 3:return[o,a,n];case 4:return[c,o,n];case 5:return[n,o,a]}};Te.hsv.hsl=function(t){let e=t[0],s=t[1]/100,n=t[2]/100,r=Math.max(n,.01),i,o;o=(2-s)*n;let a=(2-s)*r;return i=s*r,i/=a<=1?a:2-a,i=i||0,o/=2,[e,i*100,o*100]};Te.hwb.rgb=function(t){let e=t[0]/360,s=t[1]/100,n=t[2]/100,r=s+n,i;r>1&&(s/=r,n/=r);let o=Math.floor(6*e),a=1-n;i=6*e-o,(o&1)!==0&&(i=1-i);let c=s+i*(a-s),u,l,d;switch(o){default:case 6:case 0:u=a,l=c,d=s;break;case 1:u=c,l=a,d=s;break;case 2:u=s,l=a,d=c;break;case 3:u=s,l=c,d=a;break;case 4:u=c,l=s,d=a;break;case 5:u=a,l=s,d=c;break}return[u*255,l*255,d*255]};Te.cmyk.rgb=function(t){let e=t[0]/100,s=t[1]/100,n=t[2]/100,r=t[3]/100,i=1-Math.min(1,e*(1-r)+r),o=1-Math.min(1,s*(1-r)+r),a=1-Math.min(1,n*(1-r)+r);return[i*255,o*255,a*255]};Te.xyz.rgb=function(t){let e=t[0]/100,s=t[1]/100,n=t[2]/100,r,i,o;return r=e*3.2406+s*-1.5372+n*-.4986,i=e*-.9689+s*1.8758+n*.0415,o=e*.0557+s*-.204+n*1.057,r=r>.0031308?1.055*r**(1/2.4)-.055:r*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,r=Math.min(Math.max(0,r),1),i=Math.min(Math.max(0,i),1),o=Math.min(Math.max(0,o),1),[r*255,i*255,o*255]};Te.xyz.lab=function(t){let e=t[0],s=t[1],n=t[2];e/=95.047,s/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,s=s>.008856?s**(1/3):7.787*s+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let r=116*s-16,i=500*(e-s),o=200*(s-n);return[r,i,o]};Te.lab.xyz=function(t){let e=t[0],s=t[1],n=t[2],r,i,o;i=(e+16)/116,r=s/500+i,o=i-n/200;let a=i**3,c=r**3,u=o**3;return i=a>.008856?a:(i-16/116)/7.787,r=c>.008856?c:(r-16/116)/7.787,o=u>.008856?u:(o-16/116)/7.787,r*=95.047,i*=100,o*=108.883,[r,i,o]};Te.lab.lch=function(t){let e=t[0],s=t[1],n=t[2],r;r=Math.atan2(n,s)*360/2/Math.PI,r<0&&(r+=360);let o=Math.sqrt(s*s+n*n);return[e,o,r]};Te.lch.lab=function(t){let e=t[0],s=t[1],r=t[2]/360*2*Math.PI,i=s*Math.cos(r),o=s*Math.sin(r);return[e,i,o]};Te.rgb.ansi16=function(t,e=null){let[s,n,r]=t,i=e===null?Te.rgb.hsv(t)[2]:e;if(i=Math.round(i/50),i===0)return 30;let o=30+(Math.round(r/255)<<2|Math.round(n/255)<<1|Math.round(s/255));return i===2&&(o+=60),o};Te.hsv.ansi16=function(t){return Te.rgb.ansi16(Te.hsv.rgb(t),t[2])};Te.rgb.ansi256=function(t){let e=t[0],s=t[1],n=t[2];return e===s&&s===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(s/255*5)+Math.round(n/255*5)};Te.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let s=(~~(t>50)+1)*.5,n=(e&1)*s*255,r=(e>>1&1)*s*255,i=(e>>2&1)*s*255;return[n,r,i]};Te.ansi256.rgb=function(t){if(t>=232){let i=(t-232)*10+8;return[i,i,i]}t-=16;let e,s=Math.floor(t/36)/5*255,n=Math.floor((e=t%36)/6)/5*255,r=e%6/5*255;return[s,n,r]};Te.rgb.hex=function(t){let s=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(s.length)+s};Te.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let s=e[0];e[0].length===3&&(s=s.split("").map(a=>a+a).join(""));let n=parseInt(s,16),r=n>>16&255,i=n>>8&255,o=n&255;return[r,i,o]};Te.rgb.hcg=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.max(Math.max(e,s),n),i=Math.min(Math.min(e,s),n),o=r-i,a,c;return o<1?a=i/(1-o):a=0,o<=0?c=0:r===e?c=(s-n)/o%6:r===s?c=2+(n-e)/o:c=4+(e-s)/o,c/=6,c%=1,[c*360,o*100,a*100]};Te.hsl.hcg=function(t){let e=t[1]/100,s=t[2]/100,n=s<.5?2*e*s:2*e*(1-s),r=0;return n<1&&(r=(s-.5*n)/(1-n)),[t[0],n*100,r*100]};Te.hsv.hcg=function(t){let e=t[1]/100,s=t[2]/100,n=e*s,r=0;return n<1&&(r=(s-n)/(1-n)),[t[0],n*100,r*100]};Te.hcg.rgb=function(t){let e=t[0]/360,s=t[1]/100,n=t[2]/100;if(s===0)return[n*255,n*255,n*255];let r=[0,0,0],i=e%1*6,o=i%1,a=1-o,c=0;switch(Math.floor(i)){case 0:r[0]=1,r[1]=o,r[2]=0;break;case 1:r[0]=a,r[1]=1,r[2]=0;break;case 2:r[0]=0,r[1]=1,r[2]=o;break;case 3:r[0]=0,r[1]=a,r[2]=1;break;case 4:r[0]=o,r[1]=0,r[2]=1;break;default:r[0]=1,r[1]=0,r[2]=a}return c=(1-s)*n,[(s*r[0]+c)*255,(s*r[1]+c)*255,(s*r[2]+c)*255]};Te.hcg.hsv=function(t){let e=t[1]/100,s=t[2]/100,n=e+s*(1-e),r=0;return n>0&&(r=e/n),[t[0],r*100,n*100]};Te.hcg.hsl=function(t){let e=t[1]/100,n=t[2]/100*(1-e)+.5*e,r=0;return n>0&&n<.5?r=e/(2*n):n>=.5&&n<1&&(r=e/(2*(1-n))),[t[0],r*100,n*100]};Te.hcg.hwb=function(t){let e=t[1]/100,s=t[2]/100,n=e+s*(1-e);return[t[0],(n-e)*100,(1-n)*100]};Te.hwb.hcg=function(t){let e=t[1]/100,n=1-t[2]/100,r=n-e,i=0;return r<1&&(i=(n-r)/(1-r)),[t[0],r*100,i*100]};Te.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};Te.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};Te.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};Te.gray.hsl=function(t){return[0,0,t[0]]};Te.gray.hsv=Te.gray.hsl;Te.gray.hwb=function(t){return[0,100,t[0]]};Te.gray.cmyk=function(t){return[0,0,0,t[0]]};Te.gray.lab=function(t){return[t[0],0,0]};Te.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};Te.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var o_=M((Rge,i_)=>{var af=Ry();function BV(){let t={},e=Object.keys(af);for(let s=e.length,n=0;n<s;n++)t[e[n]]={distance:-1,parent:null};return t}function NV(t){let e=BV(),s=[t];for(e[t].distance=0;s.length;){let n=s.pop(),r=Object.keys(af[n]);for(let i=r.length,o=0;o<i;o++){let a=r[o],c=e[a];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,s.unshift(a))}}return e}function $V(t,e){return function(s){return e(t(s))}}function WV(t,e){let s=[e[t].parent,t],n=af[e[t].parent][t],r=e[t].parent;for(;e[r].parent;)s.unshift(e[r].parent),n=$V(af[e[r].parent][r],n),r=e[r].parent;return n.conversion=s,n}i_.exports=function(t){let e=NV(t),s={},n=Object.keys(e);for(let r=n.length,i=0;i<r;i++){let o=n[i];e[o].parent!==null&&(s[o]=WV(o,e))}return s}});var c_=M((Ige,a_)=>{var Iy=Ry(),jV=o_(),fc={},UV=Object.keys(Iy);function HV(t){let e=function(...s){let n=s[0];return n==null?n:(n.length>1&&(s=n),t(s))};return"conversion"in t&&(e.conversion=t.conversion),e}function GV(t){let e=function(...s){let n=s[0];if(n==null)return n;n.length>1&&(s=n);let r=t(s);if(typeof r=="object")for(let i=r.length,o=0;o<i;o++)r[o]=Math.round(r[o]);return r};return"conversion"in t&&(e.conversion=t.conversion),e}UV.forEach(t=>{fc[t]={},Object.defineProperty(fc[t],"channels",{value:Iy[t].channels}),Object.defineProperty(fc[t],"labels",{value:Iy[t].labels});let e=jV(t);Object.keys(e).forEach(n=>{let r=e[n];fc[t][n]=GV(r),fc[t][n].raw=HV(r)})});a_.exports=fc});var m_=M((kge,f_)=>{"use strict";var u_=(t,e)=>(...s)=>`\x1B[${t(...s)+e}m`,l_=(t,e)=>(...s)=>{let n=t(...s);return`\x1B[${38+e};5;${n}m`},d_=(t,e)=>(...s)=>{let n=t(...s);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},cf=t=>t,p_=(t,e,s)=>[t,e,s],mc=(t,e,s)=>{Object.defineProperty(t,e,{get:()=>{let n=s();return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},ky,hc=(t,e,s,n)=>{ky===void 0&&(ky=c_());let r=n?10:0,i={};for(let[o,a]of Object.entries(ky)){let c=o==="ansi16"?"ansi":o;o===e?i[c]=t(s,r):typeof a=="object"&&(i[c]=t(a[e],r))}return i};function zV(){let t=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[s,n]of Object.entries(e)){for(let[r,i]of Object.entries(n))e[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=e[r],t.set(i[0],i[1]);Object.defineProperty(e,s,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:t,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",mc(e.color,"ansi",()=>hc(u_,"ansi16",cf,!1)),mc(e.color,"ansi256",()=>hc(l_,"ansi256",cf,!1)),mc(e.color,"ansi16m",()=>hc(d_,"rgb",p_,!1)),mc(e.bgColor,"ansi",()=>hc(u_,"ansi16",cf,!0)),mc(e.bgColor,"ansi256",()=>hc(l_,"ansi256",cf,!0)),mc(e.bgColor,"ansi16m",()=>hc(d_,"rgb",p_,!0)),e}Object.defineProperty(f_,"exports",{enumerable:!0,get:zV})});var y_=M((_ge,g_)=>{"use strict";var Uu=jd(),qV=s0(),KV=m_(),Fy=new Set(["\x1B","\x9B"]),VV=39,h_=t=>`${Fy.values().next().value}[${t}m`,ZV=t=>t.split(" ").map(e=>Uu(e)),_y=(t,e,s)=>{let n=[...e],r=!1,i=Uu(qV(t[t.length-1]));for(let[o,a]of n.entries()){let c=Uu(a);if(i+c<=s?t[t.length-1]+=a:(t.push(a),i=0),Fy.has(a))r=!0;else if(r&&a==="m"){r=!1;continue}r||(i+=c,i===s&&o<n.length-1&&(t.push(""),i=0))}!i&&t[t.length-1].length>0&&t.length>1&&(t[t.length-2]+=t.pop())},YV=t=>{let e=t.split(" "),s=e.length;for(;s>0&&!(Uu(e[s-1])>0);)s--;return s===e.length?t:e.slice(0,s).join(" ")+e.slice(s).join("")},JV=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let n="",r="",i,o=ZV(t),a=[""];for(let[c,u]of t.split(" ").entries()){s.trim!==!1&&(a[a.length-1]=a[a.length-1].trimLeft());let l=Uu(a[a.length-1]);if(c!==0&&(l>=e&&(s.wordWrap===!1||s.trim===!1)&&(a.push(""),l=0),(l>0||s.trim===!1)&&(a[a.length-1]+=" ",l++)),s.hard&&o[c]>e){let d=e-l,p=1+Math.floor((o[c]-d-1)/e);Math.floor((o[c]-1)/e)<p&&a.push(""),_y(a,u,e);continue}if(l+o[c]>e&&l>0&&o[c]>0){if(s.wordWrap===!1&&l<e){_y(a,u,e);continue}a.push("")}if(l+o[c]>e&&s.wordWrap===!1){_y(a,u,e);continue}a[a.length-1]+=u}s.trim!==!1&&(a=a.map(YV)),n=a.join(`
|
|
91
|
+
\u{1F4A1} Benefits of Branded API:`),console.log(" \u2022 Clear brand ownership"),console.log(" \u2022 Consistent naming convention"),console.log(" \u2022 Easy to identify Strogger functions"),console.log(" \u2022 No breaking changes - conventional API still works")}catch(t){console.error("\u274C Error running branded API examples:",t)}};Os.runBrandedAPIExamples=Pq;require.main===ok&&(0,Os.runBrandedAPIExamples)()});var Lr=M(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.demonstrateAutomaticInstanceId=ce.runCloudWatchTransportExamples=ce.runFileTransportExamples=ce.createCloudWatchTransportExample=ce.createFileTransportExample=ce.createBatchedLogger=ce.createBatchedTransport=ce.generateLoggerInstanceId=ce.generateSpanId=ce.generateTraceId=ce.generateCorrelationId=ce.createLoggerInstanceEnricher=ce.createUserEnricher=ce.createEnvironmentEnricher=ce.createSessionEnricher=ce.createCorrelationEnricher=ce.createEnrichmentMiddleware=ce.createDefaultEnrichmentMiddleware=ce.createSampler=ce.createRateLimiter=ce.createLogFilter=ce.validateTransportConfig=ce.validateEnvironmentVariable=ce.handleTransportError=ce.createDetailedError=ce.ERROR_MESSAGES=ce.ValidationError=ce.ConfigurationError=ce.TransportError=ce.LoggerError=ce.createPerformanceMonitor=ce.getEnvironment=ce.createStroggerCloudWatchTransport=ce.createStroggerNewRelicTransport=ce.createStroggerElasticsearchTransport=ce.createStroggerSplunkTransport=ce.createStroggerDataDogTransport=ce.createStroggerConsoleTransport=ce.createCloudWatchTransport=ce.createFileTransport=ce.createNewRelicTransport=ce.createElasticsearchTransport=ce.createSplunkTransport=ce.createDataDogTransport=ce.createConsoleTransport=ce.createJsonFormatter=ce.LogLevel=ce.strogger=ce.createStrogger=ce.createLogger=void 0;ce.printLoggerConfig=ce.shouldLog=ce.runBrandedAPIExamples=ce.runStructuredLoggingDemo=ce.demonstrateManualGeneration=ce.demonstrateInstanceIdInContexts=ce.demonstrateMultipleInstances=ce.demonstrateCustomInstanceId=void 0;var cy=ty();Object.defineProperty(ce,"createLogger",{enumerable:!0,get:function(){return cy.createLogger}});Object.defineProperty(ce,"createStrogger",{enumerable:!0,get:function(){return cy.createStrogger}});Object.defineProperty(ce,"strogger",{enumerable:!0,get:function(){return cy.strogger}});var Lq=Hn();Object.defineProperty(ce,"LogLevel",{enumerable:!0,get:function(){return Lq.LogLevel}});var Oq=j0();Object.defineProperty(ce,"createJsonFormatter",{enumerable:!0,get:function(){return Oq.createJsonFormatter}});var Mq=xp();Object.defineProperty(ce,"createConsoleTransport",{enumerable:!0,get:function(){return Mq.createConsoleTransport}});var Bq=ny();Object.defineProperty(ce,"createDataDogTransport",{enumerable:!0,get:function(){return Bq.createDataDogTransport}});var Nq=ry();Object.defineProperty(ce,"createSplunkTransport",{enumerable:!0,get:function(){return Nq.createSplunkTransport}});var $q=iy();Object.defineProperty(ce,"createElasticsearchTransport",{enumerable:!0,get:function(){return $q.createElasticsearchTransport}});var Wq=oy();Object.defineProperty(ce,"createNewRelicTransport",{enumerable:!0,get:function(){return Wq.createNewRelicTransport}});var jq=II();Object.defineProperty(ce,"createFileTransport",{enumerable:!0,get:function(){return jq.createFileTransport}});var Uq=ay();Object.defineProperty(ce,"createCloudWatchTransport",{enumerable:!0,get:function(){return Uq.createCloudWatchTransport}});var Hq=xp();Object.defineProperty(ce,"createStroggerConsoleTransport",{enumerable:!0,get:function(){return Hq.createConsoleTransport}});var Gq=ny();Object.defineProperty(ce,"createStroggerDataDogTransport",{enumerable:!0,get:function(){return Gq.createDataDogTransport}});var zq=ry();Object.defineProperty(ce,"createStroggerSplunkTransport",{enumerable:!0,get:function(){return zq.createSplunkTransport}});var qq=iy();Object.defineProperty(ce,"createStroggerElasticsearchTransport",{enumerable:!0,get:function(){return qq.createElasticsearchTransport}});var Kq=oy();Object.defineProperty(ce,"createStroggerNewRelicTransport",{enumerable:!0,get:function(){return Kq.createNewRelicTransport}});var Vq=ay();Object.defineProperty(ce,"createStroggerCloudWatchTransport",{enumerable:!0,get:function(){return Vq.createCloudWatchTransport}});var Zq=X0();Object.defineProperty(ce,"getEnvironment",{enumerable:!0,get:function(){return Zq.getEnvironment}});var Yq=kI();Object.defineProperty(ce,"createPerformanceMonitor",{enumerable:!0,get:function(){return Yq.createPerformanceMonitor}});var Or=hi();Object.defineProperty(ce,"LoggerError",{enumerable:!0,get:function(){return Or.LoggerError}});Object.defineProperty(ce,"TransportError",{enumerable:!0,get:function(){return Or.TransportError}});Object.defineProperty(ce,"ConfigurationError",{enumerable:!0,get:function(){return Or.ConfigurationError}});Object.defineProperty(ce,"ValidationError",{enumerable:!0,get:function(){return Or.ValidationError}});Object.defineProperty(ce,"ERROR_MESSAGES",{enumerable:!0,get:function(){return Or.ERROR_MESSAGES}});Object.defineProperty(ce,"createDetailedError",{enumerable:!0,get:function(){return Or.createDetailedError}});Object.defineProperty(ce,"handleTransportError",{enumerable:!0,get:function(){return Or.handleTransportError}});Object.defineProperty(ce,"validateEnvironmentVariable",{enumerable:!0,get:function(){return Or.validateEnvironmentVariable}});Object.defineProperty(ce,"validateTransportConfig",{enumerable:!0,get:function(){return Or.validateTransportConfig}});var uy=ey();Object.defineProperty(ce,"createLogFilter",{enumerable:!0,get:function(){return uy.createLogFilter}});Object.defineProperty(ce,"createRateLimiter",{enumerable:!0,get:function(){return uy.createRateLimiter}});Object.defineProperty(ce,"createSampler",{enumerable:!0,get:function(){return uy.createSampler}});var zn=G0();Object.defineProperty(ce,"createDefaultEnrichmentMiddleware",{enumerable:!0,get:function(){return zn.createDefaultEnrichmentMiddleware}});Object.defineProperty(ce,"createEnrichmentMiddleware",{enumerable:!0,get:function(){return zn.createEnrichmentMiddleware}});Object.defineProperty(ce,"createCorrelationEnricher",{enumerable:!0,get:function(){return zn.createCorrelationEnricher}});Object.defineProperty(ce,"createSessionEnricher",{enumerable:!0,get:function(){return zn.createSessionEnricher}});Object.defineProperty(ce,"createEnvironmentEnricher",{enumerable:!0,get:function(){return zn.createEnvironmentEnricher}});Object.defineProperty(ce,"createUserEnricher",{enumerable:!0,get:function(){return zn.createUserEnricher}});Object.defineProperty(ce,"createLoggerInstanceEnricher",{enumerable:!0,get:function(){return zn.createLoggerInstanceEnricher}});Object.defineProperty(ce,"generateCorrelationId",{enumerable:!0,get:function(){return zn.generateCorrelationId}});Object.defineProperty(ce,"generateTraceId",{enumerable:!0,get:function(){return zn.generateTraceId}});Object.defineProperty(ce,"generateSpanId",{enumerable:!0,get:function(){return zn.generateSpanId}});Object.defineProperty(ce,"generateLoggerInstanceId",{enumerable:!0,get:function(){return zn.generateLoggerInstanceId}});var ck=H0();Object.defineProperty(ce,"createBatchedTransport",{enumerable:!0,get:function(){return ck.createBatchedTransport}});Object.defineProperty(ce,"createBatchedLogger",{enumerable:!0,get:function(){return ck.createBatchedLogger}});var Jq=_I();Object.defineProperty(ce,"createFileTransportExample",{enumerable:!0,get:function(){return Jq.createFileTransportExample}});var Qq=FI();Object.defineProperty(ce,"createCloudWatchTransportExample",{enumerable:!0,get:function(){return Qq.createCloudWatchTransportExample}});var Xq=$I();Object.defineProperty(ce,"runFileTransportExamples",{enumerable:!0,get:function(){return Xq.runFileTransportExamples}});var eK=VI();Object.defineProperty(ce,"runCloudWatchTransportExamples",{enumerable:!0,get:function(){return eK.runCloudWatchTransportExamples}});var Tu=ZI();Object.defineProperty(ce,"demonstrateAutomaticInstanceId",{enumerable:!0,get:function(){return Tu.demonstrateAutomaticInstanceId}});Object.defineProperty(ce,"demonstrateCustomInstanceId",{enumerable:!0,get:function(){return Tu.demonstrateCustomInstanceId}});Object.defineProperty(ce,"demonstrateMultipleInstances",{enumerable:!0,get:function(){return Tu.demonstrateMultipleInstances}});Object.defineProperty(ce,"demonstrateInstanceIdInContexts",{enumerable:!0,get:function(){return Tu.demonstrateInstanceIdInContexts}});Object.defineProperty(ce,"demonstrateManualGeneration",{enumerable:!0,get:function(){return Tu.demonstrateManualGeneration}});var tK=ik();Object.defineProperty(ce,"runStructuredLoggingDemo",{enumerable:!0,get:function(){return tK.runStructuredLoggingDemo}});var sK=ak();Object.defineProperty(ce,"runBrandedAPIExamples",{enumerable:!0,get:function(){return sK.runBrandedAPIExamples}});var nK=kr();Object.defineProperty(ce,"shouldLog",{enumerable:!0,get:function(){return nK.shouldLog}});var rK=ty();Object.defineProperty(ce,"printLoggerConfig",{enumerable:!0,get:function(){return rK.printLoggerConfig}})});var qn,Ya,ly,iK,uk,oK,Me,Ja,ie,et,Mp,bn,Bp,aK,dt=D(()=>{"use strict";qn=oe(Lr()),Ya=process.env.NODE_ENV==="development",ly=process.env.CDK_INSIGHTS_VERBOSE==="true",iK=Ya||ly||process.env.CDK_INSIGHTS_ENABLE_LOGGING==="true",uk=ly?qn.LogLevel.DEBUG:Ya?qn.LogLevel.INFO:qn.LogLevel.ERROR,oK=iK?[(0,qn.createConsoleTransport)({formatter:(0,qn.createJsonFormatter)(),level:uk,useColors:!Ya})]:[],Me=(0,qn.createLogger)({config:{level:uk,serviceName:"cdk-insights",stage:Ya?"dev":"prod"},formatter:(0,qn.createJsonFormatter)(),transports:oK,env:{STAGE:Ya?"dev":"prod",LOG_LEVEL:ly?"DEBUG":Ya?"INFO":"ERROR"}}),Ja=t=>({debug:(e,s,n)=>Me.debug(e,{component:t,...s},n),info:(e,s,n)=>Me.info(e,{component:t,...s},n),warn:(e,s,n,r)=>Me.warn(e,{component:t,...s},n,r),error:(e,s,n,r)=>Me.error(e,{component:t,...s},n,r)}),ie=Ja("cli"),et=Ja("analysis"),Mp=Ja("license"),bn=Ja("cache"),Bp=Ja("github"),aK=Ja("aspect")});var jt,lk,Wp,Mr,Np,dy,Kn,Qa,$p,cK,jp,dk,py,pk,fy,uK,fk,mk,Up,hk,my=D(()=>{"use strict";jt=oe(require("node:fs")),lk=oe(require("node:os")),Wp=oe(require("node:path"));pp();mp();dt();Mr=Wp.join(lk.homedir(),".cdk-insights","cache"),Np=Wp.join(Mr,"analysis-cache.json"),dy=Wp.join(Mr,"cache-stats.json"),Kn={totalHits:0,totalMisses:0,totalSets:0,totalClears:0,cacheSize:0,maxCacheSize:1e3},Qa=null,$p=!1,cK=()=>{try{if(jt.existsSync(dy)){let t=jt.readFileSync(dy,"utf-8");try{Kn={...Kn,...JSON.parse(t)}}catch(e){bn.warn("Could not parse cache statistics file",{error:e instanceof Error?e.message:String(e)})}}}catch(t){bn.warn("Could not load cache statistics",{error:t instanceof Error?t.message:String(t)})}},jp=()=>{$p=!0,!Qa&&(Qa=setTimeout(()=>{$p&&dk(),Qa=null},5e3))},dk=()=>{try{uK(),jt.writeFileSync(dy,JSON.stringify(Kn,null,2),"utf-8"),$p=!1}catch(t){bn.warn("Could not save cache statistics",{error:t instanceof Error?t.message:String(t)})}},py=()=>{Qa&&(clearTimeout(Qa),Qa=null),$p&&dk()};process.on("exit",py);process.on("SIGINT",()=>{py(),process.exit(0)});process.on("SIGTERM",()=>{py(),process.exit(0)});cK();pk=()=>{try{if(Oa()){bn.info("\u2139\uFE0F Cache clear skipped in CI environment (set CDK_INSIGHTS_ENABLE_CACHE_IN_CI=true to opt in)");return}jt.existsSync(Np)&&jt.unlinkSync(Np),jt.existsSync(Mr)&&jt.readdirSync(Mr).length===0&&jt.rmdirSync(Mr),Kn.totalClears++,Kn.lastClearTime=Date.now(),Kn.cacheSize=0,jp(),bn.info("\u2705 Analysis cache cleared successfully")}catch(t){bn.warn("\u26A0\uFE0F Could not clear cache files",{error:t instanceof Error?t.message:String(t)}),bn.info("\u2139\uFE0F Cache will be cleared on next process restart")}},fy=()=>{let t=jt.existsSync(Np),e=jt.existsSync(Mr),s;if(t)try{s=jt.statSync(Np).size}catch{}return{cacheDir:Mr,cacheFileExists:t,cacheDirExists:e,cacheSize:s,stats:Kn}},uK=()=>{jt.existsSync(Mr)||jt.mkdirSync(Mr,{recursive:!0})},fk=t=>{if(!t)return Ir.isFeatureEnabled("caching","free");let e=t==="enterprise"?"pro":t;return Ir.isFeatureEnabled("caching",e)},mk=()=>{Kn.totalHits++,jp()},Up=()=>{Kn.totalMisses++,jp()},hk=()=>{Kn.totalSets++,Kn.cacheSize++,jp()}});var lK,gk,dK,hy,Hp,yk,Pu,Xa,ec=D(()=>{"use strict";lK=["IAM","S3","Lambda","DynamoDB","RDS","EC2","SNS","SQS","StepFunctions","CloudTrail","ApiGateway","SecretsManager","KMS","EventBridge","CloudFront","ELB","ECS","Cognito","WAF","CloudWatch","Route53","ElastiCache","ECR","OpenSearch","ACM","Backup","VPC","Kinesis","AppSync","EKS","Redshift","MSK","Glue","EFS","AutoScaling"],gk={IAM:["iamPolicies","iamPermissionBoundary","iamCrossAccountTrust","iamUserPolicies"],S3:["s3Buckets","s3BucketLogging","s3BucketPolicySsl","s3BucketPolicySelfLockout","s3IntelligentTiering","s3LifecyclePolicy","s3Replication"],Lambda:["lambdaEnvironmentVariables","lambdaMemory","lambdaReservedConcurrency","lambdaDeadLetterQueue","lambdaRuntime","lambdaVpcNatWarning","lambdaPermission"],DynamoDB:["dynamoDBAutoScaling","dynamoDBStreams","dynamoDBPitr","dynamoDBEncryption"],RDS:["rdsEncryption","rdsMultiAZ","rdsPublicAccess","rdsBackupRetention","rdsDeletionProtection","rdsLogging","rdsEnhancedMonitoring"],EC2:["ec2InstanceType","natGatewayUsage","securityGroups","ebsVolumes","ec2PublicIp","ec2SubnetAutoPublicIp"],SNS:["sns","snsTopicPolicySelfLockout"],SQS:["sqs","sqsQueuePolicySelfLockout"],StepFunctions:["stepFunctions"],CloudTrail:["cloudTrailLogging"],ApiGateway:["apiGateway","apiGatewayMethodAuth"],SecretsManager:["secretsManager"],KMS:["kmsKeys","kmsKeyPolicySelfLockout"],EventBridge:["eventBridgeRules","eventBusPolicy"],CloudFront:["cloudFrontHttpsOnly","cloudFrontWafAssociation","cloudFrontLogging","cloudFrontTls"],ELB:["elbDeletionProtection","elbLogging","elbHttpsListeners","elbSecurityPolicy"],ECS:["ecsSecrets","ecsLogging","ecsServiceConnectLogs","ecsResources"],Cognito:["cognitoPasswordPolicy","cognitoMfa","cognitoAdvancedSecurity"],WAF:["wafWebAcl","wafLogging"],CloudWatch:["cloudWatchLogRetention","cloudWatchEncryption","cloudWatchAlarms"],Route53:["route53Dnssec","route53HealthChecks","route53QueryLogging"],ElastiCache:["elastiCacheEncryption","elastiCacheAuth","elastiCacheFailover"],ECR:["ecrScanning","ecrLifecycle","ecrImmutableTags"],OpenSearch:["openSearchEncryption","openSearchAccessControl","openSearchLogging"],ACM:["acmValidation"],Backup:["backupPlans","backupVault"],VPC:["vpcFlowLogs","vpcDefaultSecurityGroup"],Kinesis:["kinesisEncryption","kinesisRetention"],AppSync:["appSyncAuth","appSyncLogging","appSyncWaf"],EKS:["eksPublicEndpoint","eksEncryption","eksLogging"],Redshift:["redshiftEncryption","redshiftPublicAccess","redshiftLogging"],MSK:["mskEncryption","mskAuth","mskLogging"],Glue:["glueEncryption","glueConnections"],EFS:["efsEncryption"],AutoScaling:["autoScalingGroupHealthCheck","autoScalingLaunchConfigPublicIp"]},dK=Object.entries(gk).reduce((t,[e,s])=>{for(let n of s)t[n]=e;return t},{}),hy=t=>{let e=new Set,s=[];for(let n of t)e.has(n)||(e.add(n),s.push(n));return s},Hp=t=>{if(!t||t.length===0)return{services:["All services"],removedAllServices:!1,defaultedToAll:!0};let e=hy(t),s=e.includes("All services"),n=e.filter(r=>r!=="All services");return s&&n.length>0?{services:n,removedAllServices:!0,defaultedToAll:!1}:{services:s?["All services"]:e,removedAllServices:!1,defaultedToAll:!1}},yk=(t,e)=>{if(t.length===0||t.includes("All services"))return hy(e);let s=t.flatMap(n=>n==="All services"?e:gk[n]??[]);return hy(s)},Pu=t=>dK[t],Xa=t=>t==="All services"?!0:lK.includes(t)});var Gp,xi,zp,xk,tc=D(()=>{"use strict";Gp=t=>{if(!t)return;let e=t.trim();if(e)return e.replace(/\/+$/,"")},xi=t=>{let e=Gp(t);return e||(Gp("https://api.cdkinsights.dev/analysis/v1")??"")},zp=t=>{let e=Gp(process.env.CDK_INSIGHTS_LICENSE_API_URL);if(e)return e;let s=xi(t);return s?s.endsWith("/analysis/v1")?`${s.slice(0,-12)}/license`:s.endsWith("/analysis")?`${s.slice(0,-9)}/license`:s:""},xk=t=>Gp(t)});async function Ck(t,e,s){let n=pK(t);if(n){let o=xi(),a=Sk(n.token),c=a?.fingerprint;ie.info("\u2705 Using cached auth token",{hasToken:!0,hasJwtFingerprint:!!c,apiUrl:o});let u=a?.tier||a?.licenseType?{tier:a.tier,licenseType:a.licenseType}:void 0;return{token:n.token,usageData:void 0,licenseInfo:u,fingerprint:c,apiUrl:o}}let r=xi();if(!r){ie.error("\u274C No API endpoint configured for authentication");return}ie.info("\u{1F510} Starting authentication process",{apiUrl:r,hasLicenseKey:!!t,hasFingerprint:!!e,hasProject:!!s});let i=`${r}/login`;ie.info("\u{1F4E1} Making authentication request",{url:i,method:"POST",headers:{"x-cdk-insights-fingerprint":e?"[REDACTED]":"undefined","x-cdk-insights-client":"cli"},body:{licenseKey:t?"[REDACTED]":"undefined",project:s||"undefined"}});try{let{data:o}=await Rt.post(i,{licenseKey:t,project:s},{headers:{"x-cdk-insights-fingerprint":e,"x-cdk-insights-client":"cli"},timeout:1e4});return ie.info("\u2705 Authentication successful",{hasToken:!!o.token,expiresIn:o.expiresIn,fingerprintStatus:o.fingerprintStatus,hasUsageData:!!o.usageData,hasLicenseInfo:!!o.licenseInfo,apiUrl:r}),fK(o.token,t,o.expiresIn||3600),{token:o.token,usageData:o.usageData,licenseInfo:o.licenseInfo,fingerprint:o.fingerprint,apiUrl:r}}catch(o){let a=Rt.isAxiosError(o)?o:void 0,c=xk(a?.config?.url?a.config.url.replace(/\/?login$/,""):r);if(ie.error("Authentication failed",{error:o instanceof Error?o.message:String(o),apiUrl:c}),a)if(a.code==="ECONNREFUSED")ie.error("Network error: Connection refused",{error:a.message,suggestion:"Check if the API server is running and accessible",apiUrl:c});else if(a.code==="ENOTFOUND")ie.error("Network error: Host not found",{error:a.message,apiUrl:c,suggestion:"Check if the API URL is correct"});else if(a.code==="ETIMEDOUT")ie.error("Network error: Request timed out",{error:a.message,suggestion:"The API server took too long to respond",apiUrl:c});else if(a.response){let u=a.response.status,l=a.response.data,d=typeof l?.error=="string"?l.error:l?.error?.message||l?.message||a.message;ie.error(`HTTP ${u} error`,{status:u,apiUrl:c,error:d,response:l}),u===401?ie.error("License key is invalid or expired",{status:u,apiUrl:c}):u===403?ie.error("Access denied - license key may be invalid or suspended",{status:u,apiUrl:c}):u===404?ie.error("API endpoint not found",{status:u,apiUrl:c,suggestion:"Check if the API URL is correct"}):u>=500&&ie.error("Server error",{status:u,apiUrl:c,suggestion:"The API server may be experiencing issues"})}else ie.error("Network error",{error:a.message,apiUrl:c});else ie.error("Unexpected error",{error:o.message||String(o),apiUrl:c});return}}var bk,hs,yy,gy,sc,Sk,vk,pK,fK,Dk,xy=D(()=>{"use strict";bk=oe(require("node:crypto")),hs=oe(require("node:fs")),yy=oe(require("node:path"));rr();tc();dt();gy=yy.join(process.env.HOME||process.env.USERPROFILE||"",".cdk-insights"),sc=yy.join(gy,"auth-token.json"),Sk=t=>{try{let e=t.split(".");return e.length!==3?null:JSON.parse(Buffer.from(e[1],"base64").toString())}catch{return null}},vk=t=>bk.createHash("sha256").update(t).digest("hex").slice(0,16),pK=t=>{try{if(!hs.existsSync(sc))return null;let e=JSON.parse(hs.readFileSync(sc,"utf-8")),s=vk(t);if(e.licenseKeyHash!==s)return null;let n=Sk(e.token),r=Math.floor(Date.now()/1e3),i=n?.exp||e.cachedAt+e.expiresIn;return r>=i?(hs.unlinkSync(sc),null):(ie.debug("Using cached auth token",{cachedAt:new Date(e.cachedAt*1e3).toISOString(),expiresAt:new Date(i*1e3).toISOString()}),e)}catch(e){return ie.debug("Failed to load cached auth token",{error:e instanceof Error?e.message:String(e)}),null}},fK=(t,e,s)=>{try{hs.existsSync(gy)||hs.mkdirSync(gy,{recursive:!0});let n={token:t,licenseKeyHash:vk(e),cachedAt:Math.floor(Date.now()/1e3),expiresIn:s},r=hs.openSync(sc,"w",process.platform!=="win32"?384:void 0);hs.writeSync(r,JSON.stringify(n),void 0,"utf-8"),hs.closeSync(r),ie.debug("Saved auth token to cache",{cachedAt:new Date(n.cachedAt*1e3).toISOString(),expiresIn:s})}catch(n){ie.debug("Failed to save auth token to cache",{error:n instanceof Error?n.message:String(n)})}};Dk=()=>{try{hs.existsSync(sc)?(hs.unlinkSync(sc),ie.info("\u{1F5D1}\uFE0F Cleared auth token cache")):ie.info("\u2139\uFE0F No auth token cache to clear")}catch(t){ie.warn("Failed to clear auth token cache",{error:t instanceof Error?t.message:String(t)})}}});var jr,Ho,Dy,Go,$u,Ht,Nk=D(()=>{jr=(t,e=[])=>t.name==="up"||e.includes("vim")&&t.name==="k"||e.includes("emacs")&&t.ctrl&&t.name==="p",Ho=(t,e=[])=>t.name==="down"||e.includes("vim")&&t.name==="j"||e.includes("emacs")&&t.ctrl&&t.name==="n",Dy=t=>t.name==="space",Go=t=>t.name==="backspace",$u=t=>"1234567890".includes(t.name),Ht=t=>t.name==="enter"||t.name==="return"});var Qp,Xp,Wu,ef,Di,tf=D(()=>{Qp=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}},Xp=class extends Error{name="CancelPromptError";message="Prompt was canceled"},Wu=class extends Error{name="ExitPromptError"},ef=class extends Error{name="HookError"},Di=class extends Error{name="ValidationError"}});function wV(t){return{rl:t,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Wk(t,e){let s=wV(t);return $k.run(s,()=>{function n(r){s.handleChange=()=>{s.index=0,r()},s.handleChange()}return e(n)})}function zo(){let t=$k.getStore();if(!t)throw new ef("[Inquirer] Hook functions can only be called from within a prompt");return t}function Ay(){return zo().rl}function wy(t){let e=(...s)=>{let n=zo(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let o=t(...s);return r&&i(),n.handleChange=i,o};return sf.AsyncResource.bind(e)}function dc(t){let e=zo(),{index:s}=e,n={get(){return e.hooks[s]},set(i){e.hooks[s]=i},initialized:s in e.hooks},r=t(n);return e.index++,r}function jk(){zo().handleChange()}var sf,$k,qo,Ko=D(()=>{sf=require("node:async_hooks");tf();$k=new sf.AsyncLocalStorage;qo={queue(t){let e=zo(),{index:s}=e;e.hooksEffect.push(()=>{e.hooksCleanup[s]?.();let n=t(Ay());if(n!=null&&typeof n!="function")throw new Di("useEffect return value must be a cleanup function or nothing.");e.hooksCleanup[s]=n})},run(){let t=zo();wy(()=>{t.hooksEffect.forEach(e=>{e()}),t.hooksEffect.length=0})()},clearAll(){let t=zo();t.hooksCleanup.forEach(e=>{e?.()}),t.hooksEffect.length=0,t.hooksCleanup.length=0}}});function $e(t){return dc(e=>{let s=Uk.AsyncResource.bind(function(i){e.get()!==i&&(e.set(i),jk())});if(e.initialized)return[e.get(),s];let n=typeof t=="function"?t():t;return e.set(n),[n,s]})}var Uk,nf=D(()=>{Uk=require("node:async_hooks");Ko()});function Zn(t,e){dc(s=>{let n=s.get();(!Array.isArray(n)||e.some((i,o)=>!Object.is(i,n[o])))&&qo.queue(t),s.set(e)})}var rf=D(()=>{Ko()});var Ai=M((ige,Hk)=>{var EV=require("node:tty"),RV=EV?.WriteStream?.prototype?.hasColors?.()??!1,Qe=(t,e)=>{if(!RV)return r=>r;let s=`\x1B[${t}m`,n=`\x1B[${e}m`;return r=>{let i=r+"",o=i.indexOf(n);if(o===-1)return s+i+n;let a=s,c=0,l=(e===22?n:"")+s;for(;o!==-1;)a+=i.slice(c,o)+l,c=o+n.length,o=i.indexOf(n,c);return a+=i.slice(c)+n,a}},Je={};Je.reset=Qe(0,0);Je.bold=Qe(1,22);Je.dim=Qe(2,22);Je.italic=Qe(3,23);Je.underline=Qe(4,24);Je.overline=Qe(53,55);Je.inverse=Qe(7,27);Je.hidden=Qe(8,28);Je.strikethrough=Qe(9,29);Je.black=Qe(30,39);Je.red=Qe(31,39);Je.green=Qe(32,39);Je.yellow=Qe(33,39);Je.blue=Qe(34,39);Je.magenta=Qe(35,39);Je.cyan=Qe(36,39);Je.white=Qe(37,39);Je.gray=Qe(90,39);Je.bgBlack=Qe(40,49);Je.bgRed=Qe(41,49);Je.bgGreen=Qe(42,49);Je.bgYellow=Qe(43,49);Je.bgBlue=Qe(44,49);Je.bgMagenta=Qe(45,49);Je.bgCyan=Qe(46,49);Je.bgWhite=Qe(47,49);Je.bgGray=Qe(100,49);Je.redBright=Qe(91,39);Je.greenBright=Qe(92,39);Je.yellowBright=Qe(93,39);Je.blueBright=Qe(94,39);Je.magentaBright=Qe(95,39);Je.cyanBright=Qe(96,39);Je.whiteBright=Qe(97,39);Je.bgRedBright=Qe(101,49);Je.bgGreenBright=Qe(102,49);Je.bgYellowBright=Qe(103,49);Je.bgBlueBright=Qe(104,49);Je.bgMagentaBright=Qe(105,49);Je.bgCyanBright=Qe(106,49);Je.bgWhiteBright=Qe(107,49);Hk.exports=Je});function IV(){return Yn.default.platform!=="win32"?Yn.default.env.TERM!=="linux":!!Yn.default.env.WT_SESSION||!!Yn.default.env.TERMINUS_SUBLIME||Yn.default.env.ConEmuTask==="{cmd::Cmder}"||Yn.default.env.TERM_PROGRAM==="Terminus-Sublime"||Yn.default.env.TERM_PROGRAM==="vscode"||Yn.default.env.TERM==="xterm-256color"||Yn.default.env.TERM==="alacritty"||Yn.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Yn,Gk,zk,kV,_V,FV,TV,PV,Dn,oge,pc=D(()=>{Yn=oe(require("node:process"),1);Gk={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},zk={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},kV={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},_V={...Gk,...zk},FV={...Gk,...kV},TV=IV(),PV=TV?_V:FV,Dn=PV,oge=Object.entries(zk)});var An,qk,Kk=D(()=>{An=oe(Ai(),1);pc();qk={prefix:{idle:An.default.blue("?"),done:An.default.green(Dn.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(t=>An.default.yellow(t))},style:{answer:An.default.cyan,message:An.default.bold,error:t=>An.default.red(`> ${t}`),defaultAnswer:t=>An.default.dim(`(${t})`),help:An.default.dim,highlight:An.default.cyan,key:t=>An.default.cyan(An.default.bold(`<${t}>`))}}});function Vk(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Zk(...t){let e={};for(let s of t)for(let[n,r]of Object.entries(s)){let i=e[n];e[n]=Vk(i)&&Vk(r)?Zk(i,r):r}return e}function Pt(...t){let e=[qk,...t.filter(s=>s!=null)];return Zk(...e)}var Ey=D(()=>{Kk()});function Gt({status:t="idle",theme:e}){let[s,n]=$e(!1),[r,i]=$e(0),{prefix:o,spinner:a}=Pt(e);return Zn(()=>{if(t==="loading"){let u,l=-1,d=setTimeout(()=>{n(!0),u=setInterval(()=>{l=l+1,i(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(u)}}else n(!1)},[t]),s?a.frames[r]:typeof o=="string"?o:o[t==="loading"?"idle":t]??o.idle}var Yk=D(()=>{nf();rf();Ey()});function en(t,e){return dc(s=>{let n=s.get();if(!n||n.dependencies.length!==e.length||n.dependencies.some((r,i)=>r!==e[i])){let r=t();return s.set({value:r,dependencies:e}),r}return n.value})}var Jk=D(()=>{Ko()});function wn(t){return $e({current:t})[0]}var of=D(()=>{nf()});function zt(t){let e=wn(t);e.current=t,Zn(s=>{let n=!1,r=wy((i,o)=>{n||e.current(o,s)});return s.input.on("keypress",r),()=>{n=!0,s.input.removeListener("keypress",r)}},[])}var Qk=D(()=>{of();rf();Ko()});var e_=M((Age,Xk)=>{"use strict";Xk.exports=OV;function LV(t){let e={defaultWidth:0,output:process.stdout,tty:require("tty")};return t?(Object.keys(e).forEach(function(s){t[s]||(t[s]=e[s])}),t):e}function OV(t){let e=LV(t);if(e.output.getWindowSize)return e.output.getWindowSize()[0]||e.defaultWidth;if(e.tty.getWindowSize)return e.tty.getWindowSize()[1]||e.defaultWidth;if(e.output.columns)return e.output.columns;if(process.env.CLI_WIDTH){let s=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(s)&&s!==0)return s}return e.defaultWidth}});var s_=M((wge,t_)=>{"use strict";t_.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Ry=M((Ege,r_)=>{var ju=s_(),n_={};for(let t of Object.keys(ju))n_[ju[t]]=t;var Te={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};r_.exports=Te;for(let t of Object.keys(Te)){if(!("channels"in Te[t]))throw new Error("missing channels property: "+t);if(!("labels"in Te[t]))throw new Error("missing channel labels property: "+t);if(Te[t].labels.length!==Te[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:s}=Te[t];delete Te[t].channels,delete Te[t].labels,Object.defineProperty(Te[t],"channels",{value:e}),Object.defineProperty(Te[t],"labels",{value:s})}Te.rgb.hsl=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.min(e,s,n),i=Math.max(e,s,n),o=i-r,a,c;i===r?a=0:e===i?a=(s-n)/o:s===i?a=2+(n-e)/o:n===i&&(a=4+(e-s)/o),a=Math.min(a*60,360),a<0&&(a+=360);let u=(r+i)/2;return i===r?c=0:u<=.5?c=o/(i+r):c=o/(2-i-r),[a,c*100,u*100]};Te.rgb.hsv=function(t){let e,s,n,r,i,o=t[0]/255,a=t[1]/255,c=t[2]/255,u=Math.max(o,a,c),l=u-Math.min(o,a,c),d=function(p){return(u-p)/6/l+1/2};return l===0?(r=0,i=0):(i=l/u,e=d(o),s=d(a),n=d(c),o===u?r=n-s:a===u?r=1/3+e-n:c===u&&(r=2/3+s-e),r<0?r+=1:r>1&&(r-=1)),[r*360,i*100,u*100]};Te.rgb.hwb=function(t){let e=t[0],s=t[1],n=t[2],r=Te.rgb.hsl(t)[0],i=1/255*Math.min(e,Math.min(s,n));return n=1-1/255*Math.max(e,Math.max(s,n)),[r,i*100,n*100]};Te.rgb.cmyk=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.min(1-e,1-s,1-n),i=(1-e-r)/(1-r)||0,o=(1-s-r)/(1-r)||0,a=(1-n-r)/(1-r)||0;return[i*100,o*100,a*100,r*100]};function MV(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}Te.rgb.keyword=function(t){let e=n_[t];if(e)return e;let s=1/0,n;for(let r of Object.keys(ju)){let i=ju[r],o=MV(t,i);o<s&&(s=o,n=r)}return n};Te.keyword.rgb=function(t){return ju[t]};Te.rgb.xyz=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,s=s>.04045?((s+.055)/1.055)**2.4:s/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let r=e*.4124+s*.3576+n*.1805,i=e*.2126+s*.7152+n*.0722,o=e*.0193+s*.1192+n*.9505;return[r*100,i*100,o*100]};Te.rgb.lab=function(t){let e=Te.rgb.xyz(t),s=e[0],n=e[1],r=e[2];s/=95.047,n/=100,r/=108.883,s=s>.008856?s**(1/3):7.787*s+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,o=500*(s-n),a=200*(n-r);return[i,o,a]};Te.hsl.rgb=function(t){let e=t[0]/360,s=t[1]/100,n=t[2]/100,r,i,o;if(s===0)return o=n*255,[o,o,o];n<.5?r=n*(1+s):r=n+s-n*s;let a=2*n-r,c=[0,0,0];for(let u=0;u<3;u++)i=e+1/3*-(u-1),i<0&&i++,i>1&&i--,6*i<1?o=a+(r-a)*6*i:2*i<1?o=r:3*i<2?o=a+(r-a)*(2/3-i)*6:o=a,c[u]=o*255;return c};Te.hsl.hsv=function(t){let e=t[0],s=t[1]/100,n=t[2]/100,r=s,i=Math.max(n,.01);n*=2,s*=n<=1?n:2-n,r*=i<=1?i:2-i;let o=(n+s)/2,a=n===0?2*r/(i+r):2*s/(n+s);return[e,a*100,o*100]};Te.hsv.rgb=function(t){let e=t[0]/60,s=t[1]/100,n=t[2]/100,r=Math.floor(e)%6,i=e-Math.floor(e),o=255*n*(1-s),a=255*n*(1-s*i),c=255*n*(1-s*(1-i));switch(n*=255,r){case 0:return[n,c,o];case 1:return[a,n,o];case 2:return[o,n,c];case 3:return[o,a,n];case 4:return[c,o,n];case 5:return[n,o,a]}};Te.hsv.hsl=function(t){let e=t[0],s=t[1]/100,n=t[2]/100,r=Math.max(n,.01),i,o;o=(2-s)*n;let a=(2-s)*r;return i=s*r,i/=a<=1?a:2-a,i=i||0,o/=2,[e,i*100,o*100]};Te.hwb.rgb=function(t){let e=t[0]/360,s=t[1]/100,n=t[2]/100,r=s+n,i;r>1&&(s/=r,n/=r);let o=Math.floor(6*e),a=1-n;i=6*e-o,(o&1)!==0&&(i=1-i);let c=s+i*(a-s),u,l,d;switch(o){default:case 6:case 0:u=a,l=c,d=s;break;case 1:u=c,l=a,d=s;break;case 2:u=s,l=a,d=c;break;case 3:u=s,l=c,d=a;break;case 4:u=c,l=s,d=a;break;case 5:u=a,l=s,d=c;break}return[u*255,l*255,d*255]};Te.cmyk.rgb=function(t){let e=t[0]/100,s=t[1]/100,n=t[2]/100,r=t[3]/100,i=1-Math.min(1,e*(1-r)+r),o=1-Math.min(1,s*(1-r)+r),a=1-Math.min(1,n*(1-r)+r);return[i*255,o*255,a*255]};Te.xyz.rgb=function(t){let e=t[0]/100,s=t[1]/100,n=t[2]/100,r,i,o;return r=e*3.2406+s*-1.5372+n*-.4986,i=e*-.9689+s*1.8758+n*.0415,o=e*.0557+s*-.204+n*1.057,r=r>.0031308?1.055*r**(1/2.4)-.055:r*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,r=Math.min(Math.max(0,r),1),i=Math.min(Math.max(0,i),1),o=Math.min(Math.max(0,o),1),[r*255,i*255,o*255]};Te.xyz.lab=function(t){let e=t[0],s=t[1],n=t[2];e/=95.047,s/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,s=s>.008856?s**(1/3):7.787*s+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let r=116*s-16,i=500*(e-s),o=200*(s-n);return[r,i,o]};Te.lab.xyz=function(t){let e=t[0],s=t[1],n=t[2],r,i,o;i=(e+16)/116,r=s/500+i,o=i-n/200;let a=i**3,c=r**3,u=o**3;return i=a>.008856?a:(i-16/116)/7.787,r=c>.008856?c:(r-16/116)/7.787,o=u>.008856?u:(o-16/116)/7.787,r*=95.047,i*=100,o*=108.883,[r,i,o]};Te.lab.lch=function(t){let e=t[0],s=t[1],n=t[2],r;r=Math.atan2(n,s)*360/2/Math.PI,r<0&&(r+=360);let o=Math.sqrt(s*s+n*n);return[e,o,r]};Te.lch.lab=function(t){let e=t[0],s=t[1],r=t[2]/360*2*Math.PI,i=s*Math.cos(r),o=s*Math.sin(r);return[e,i,o]};Te.rgb.ansi16=function(t,e=null){let[s,n,r]=t,i=e===null?Te.rgb.hsv(t)[2]:e;if(i=Math.round(i/50),i===0)return 30;let o=30+(Math.round(r/255)<<2|Math.round(n/255)<<1|Math.round(s/255));return i===2&&(o+=60),o};Te.hsv.ansi16=function(t){return Te.rgb.ansi16(Te.hsv.rgb(t),t[2])};Te.rgb.ansi256=function(t){let e=t[0],s=t[1],n=t[2];return e===s&&s===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(s/255*5)+Math.round(n/255*5)};Te.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let s=(~~(t>50)+1)*.5,n=(e&1)*s*255,r=(e>>1&1)*s*255,i=(e>>2&1)*s*255;return[n,r,i]};Te.ansi256.rgb=function(t){if(t>=232){let i=(t-232)*10+8;return[i,i,i]}t-=16;let e,s=Math.floor(t/36)/5*255,n=Math.floor((e=t%36)/6)/5*255,r=e%6/5*255;return[s,n,r]};Te.rgb.hex=function(t){let s=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(s.length)+s};Te.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let s=e[0];e[0].length===3&&(s=s.split("").map(a=>a+a).join(""));let n=parseInt(s,16),r=n>>16&255,i=n>>8&255,o=n&255;return[r,i,o]};Te.rgb.hcg=function(t){let e=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.max(Math.max(e,s),n),i=Math.min(Math.min(e,s),n),o=r-i,a,c;return o<1?a=i/(1-o):a=0,o<=0?c=0:r===e?c=(s-n)/o%6:r===s?c=2+(n-e)/o:c=4+(e-s)/o,c/=6,c%=1,[c*360,o*100,a*100]};Te.hsl.hcg=function(t){let e=t[1]/100,s=t[2]/100,n=s<.5?2*e*s:2*e*(1-s),r=0;return n<1&&(r=(s-.5*n)/(1-n)),[t[0],n*100,r*100]};Te.hsv.hcg=function(t){let e=t[1]/100,s=t[2]/100,n=e*s,r=0;return n<1&&(r=(s-n)/(1-n)),[t[0],n*100,r*100]};Te.hcg.rgb=function(t){let e=t[0]/360,s=t[1]/100,n=t[2]/100;if(s===0)return[n*255,n*255,n*255];let r=[0,0,0],i=e%1*6,o=i%1,a=1-o,c=0;switch(Math.floor(i)){case 0:r[0]=1,r[1]=o,r[2]=0;break;case 1:r[0]=a,r[1]=1,r[2]=0;break;case 2:r[0]=0,r[1]=1,r[2]=o;break;case 3:r[0]=0,r[1]=a,r[2]=1;break;case 4:r[0]=o,r[1]=0,r[2]=1;break;default:r[0]=1,r[1]=0,r[2]=a}return c=(1-s)*n,[(s*r[0]+c)*255,(s*r[1]+c)*255,(s*r[2]+c)*255]};Te.hcg.hsv=function(t){let e=t[1]/100,s=t[2]/100,n=e+s*(1-e),r=0;return n>0&&(r=e/n),[t[0],r*100,n*100]};Te.hcg.hsl=function(t){let e=t[1]/100,n=t[2]/100*(1-e)+.5*e,r=0;return n>0&&n<.5?r=e/(2*n):n>=.5&&n<1&&(r=e/(2*(1-n))),[t[0],r*100,n*100]};Te.hcg.hwb=function(t){let e=t[1]/100,s=t[2]/100,n=e+s*(1-e);return[t[0],(n-e)*100,(1-n)*100]};Te.hwb.hcg=function(t){let e=t[1]/100,n=1-t[2]/100,r=n-e,i=0;return r<1&&(i=(n-r)/(1-r)),[t[0],r*100,i*100]};Te.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};Te.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};Te.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};Te.gray.hsl=function(t){return[0,0,t[0]]};Te.gray.hsv=Te.gray.hsl;Te.gray.hwb=function(t){return[0,100,t[0]]};Te.gray.cmyk=function(t){return[0,0,0,t[0]]};Te.gray.lab=function(t){return[t[0],0,0]};Te.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};Te.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var o_=M((Rge,i_)=>{var af=Ry();function BV(){let t={},e=Object.keys(af);for(let s=e.length,n=0;n<s;n++)t[e[n]]={distance:-1,parent:null};return t}function NV(t){let e=BV(),s=[t];for(e[t].distance=0;s.length;){let n=s.pop(),r=Object.keys(af[n]);for(let i=r.length,o=0;o<i;o++){let a=r[o],c=e[a];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,s.unshift(a))}}return e}function $V(t,e){return function(s){return e(t(s))}}function WV(t,e){let s=[e[t].parent,t],n=af[e[t].parent][t],r=e[t].parent;for(;e[r].parent;)s.unshift(e[r].parent),n=$V(af[e[r].parent][r],n),r=e[r].parent;return n.conversion=s,n}i_.exports=function(t){let e=NV(t),s={},n=Object.keys(e);for(let r=n.length,i=0;i<r;i++){let o=n[i];e[o].parent!==null&&(s[o]=WV(o,e))}return s}});var c_=M((Ige,a_)=>{var Iy=Ry(),jV=o_(),fc={},UV=Object.keys(Iy);function HV(t){let e=function(...s){let n=s[0];return n==null?n:(n.length>1&&(s=n),t(s))};return"conversion"in t&&(e.conversion=t.conversion),e}function GV(t){let e=function(...s){let n=s[0];if(n==null)return n;n.length>1&&(s=n);let r=t(s);if(typeof r=="object")for(let i=r.length,o=0;o<i;o++)r[o]=Math.round(r[o]);return r};return"conversion"in t&&(e.conversion=t.conversion),e}UV.forEach(t=>{fc[t]={},Object.defineProperty(fc[t],"channels",{value:Iy[t].channels}),Object.defineProperty(fc[t],"labels",{value:Iy[t].labels});let e=jV(t);Object.keys(e).forEach(n=>{let r=e[n];fc[t][n]=GV(r),fc[t][n].raw=HV(r)})});a_.exports=fc});var m_=M((kge,f_)=>{"use strict";var u_=(t,e)=>(...s)=>`\x1B[${t(...s)+e}m`,l_=(t,e)=>(...s)=>{let n=t(...s);return`\x1B[${38+e};5;${n}m`},d_=(t,e)=>(...s)=>{let n=t(...s);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},cf=t=>t,p_=(t,e,s)=>[t,e,s],mc=(t,e,s)=>{Object.defineProperty(t,e,{get:()=>{let n=s();return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},ky,hc=(t,e,s,n)=>{ky===void 0&&(ky=c_());let r=n?10:0,i={};for(let[o,a]of Object.entries(ky)){let c=o==="ansi16"?"ansi":o;o===e?i[c]=t(s,r):typeof a=="object"&&(i[c]=t(a[e],r))}return i};function zV(){let t=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[s,n]of Object.entries(e)){for(let[r,i]of Object.entries(n))e[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=e[r],t.set(i[0],i[1]);Object.defineProperty(e,s,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:t,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",mc(e.color,"ansi",()=>hc(u_,"ansi16",cf,!1)),mc(e.color,"ansi256",()=>hc(l_,"ansi256",cf,!1)),mc(e.color,"ansi16m",()=>hc(d_,"rgb",p_,!1)),mc(e.bgColor,"ansi",()=>hc(u_,"ansi16",cf,!0)),mc(e.bgColor,"ansi256",()=>hc(l_,"ansi256",cf,!0)),mc(e.bgColor,"ansi16m",()=>hc(d_,"rgb",p_,!0)),e}Object.defineProperty(f_,"exports",{enumerable:!0,get:zV})});var y_=M((_ge,g_)=>{"use strict";var Uu=jd(),qV=s0(),KV=m_(),Fy=new Set(["\x1B","\x9B"]),VV=39,h_=t=>`${Fy.values().next().value}[${t}m`,ZV=t=>t.split(" ").map(e=>Uu(e)),_y=(t,e,s)=>{let n=[...e],r=!1,i=Uu(qV(t[t.length-1]));for(let[o,a]of n.entries()){let c=Uu(a);if(i+c<=s?t[t.length-1]+=a:(t.push(a),i=0),Fy.has(a))r=!0;else if(r&&a==="m"){r=!1;continue}r||(i+=c,i===s&&o<n.length-1&&(t.push(""),i=0))}!i&&t[t.length-1].length>0&&t.length>1&&(t[t.length-2]+=t.pop())},YV=t=>{let e=t.split(" "),s=e.length;for(;s>0&&!(Uu(e[s-1])>0);)s--;return s===e.length?t:e.slice(0,s).join(" ")+e.slice(s).join("")},JV=(t,e,s={})=>{if(s.trim!==!1&&t.trim()==="")return"";let n="",r="",i,o=ZV(t),a=[""];for(let[c,u]of t.split(" ").entries()){s.trim!==!1&&(a[a.length-1]=a[a.length-1].trimLeft());let l=Uu(a[a.length-1]);if(c!==0&&(l>=e&&(s.wordWrap===!1||s.trim===!1)&&(a.push(""),l=0),(l>0||s.trim===!1)&&(a[a.length-1]+=" ",l++)),s.hard&&o[c]>e){let d=e-l,p=1+Math.floor((o[c]-d-1)/e);Math.floor((o[c]-1)/e)<p&&a.push(""),_y(a,u,e);continue}if(l+o[c]>e&&l>0&&o[c]>0){if(s.wordWrap===!1&&l<e){_y(a,u,e);continue}a.push("")}if(l+o[c]>e&&s.wordWrap===!1){_y(a,u,e);continue}a[a.length-1]+=u}s.trim!==!1&&(a=a.map(YV)),n=a.join(`
|
|
92
92
|
`);for(let[c,u]of[...n].entries()){if(r+=u,Fy.has(u)){let d=parseFloat(/\d[^m]*/.exec(n.slice(c,c+4)));i=d===VV?null:d}let l=KV.codes.get(Number(i));i&&l&&(n[c+1]===`
|
|
93
93
|
`?r+=h_(l):u===`
|
|
94
94
|
`&&(r+=h_(i)))}return r};g_.exports=(t,e,s)=>String(t).normalize().replace(/\r\n/g,`
|
|
@@ -174,7 +174,7 @@ ${gt.primary.bold(`${Xt.rocket} ${s}`)}`),console.log(`${gt.comment("\u2500".rep
|
|
|
174
174
|
${gt.primary.bold(`${Xt.chart} Analysis Complete!`)}`),console.log(gt.comment("\u2500".repeat(50))),console.log(gt.success(`\u2705 Completed: ${n}`)),i>0&&console.log(gt.error(`\u274C Failed: ${i}`)),o>0&&console.log(gt.warning(`\u23F0 Timed out: ${o}`)),console.log(gt.comment(`\u23F1\uFE0F Total time: ${y}s`))}}}createSpinner(e){let s=wm({text:e,color:"blue",spinner:"dots"}).start();return{stop:n=>{n?s.succeed(n):s.stop()},fail:n=>{s.fail(n||"Failed")},warn:n=>{s.warn(n||"Warning")},info:n=>{s.info(n||"Info")}}}showSummary(e){console.log(`
|
|
175
175
|
${gt.primary.bold(`${Xt.chart} Analysis Summary`)}`),console.log(gt.comment("\u2500".repeat(40))),console.log(gt.text(`Completed ${e.length} step${e.length===1?"":"s"} successfully!`))}header(e){console.log(`
|
|
176
176
|
${gt.primary.bold(`${Xt.rocket} ${e}`)}`),console.log(`${gt.comment("\u2500".repeat(60))}
|
|
177
|
-
`)}section(e,s=Xt.info){console.log(gt.primary.bold(`${s} ${e}`))}success(e,s=Xt.success){console.log(gt.success(`${s} ${e}`))}info(e,s=Xt.info){console.log(gt.info(`${s} ${e}`))}warning(e,s=Xt.warning){console.log(gt.warning(`${s} ${e}`))}error(e,s=Xt.error){console.log(gt.error(`${s} ${e}`))}comment(e,s=""){console.log(gt.comment(`${s} ${e}`))}phase1(e){console.log(gt.info(`${Xt.phase1} Phase 1: ${e}`))}phase2(e){console.log(gt.primary(`${Xt.phase2} Phase 2: ${e}`))}phase3(e){console.log(gt.secondary(`${Xt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return gt.severity.critical.bold(`${Xt.critical} CRITICAL`);case"HIGH":return gt.severity.high.bold(`${Xt.high} HIGH`);case"MEDIUM":return gt.severity.medium.bold(`${Xt.medium} MEDIUM`);case"LOW":return gt.severity.low.bold(`${Xt.low} LOW`);default:return gt.comment(e)}}divider(){console.log(gt.comment("\u2500".repeat(60)))}newline(){console.log("")}clearLine(){process.stdout.write(`\r${" ".repeat(process.stdout.columns)}\r`)}},Em=PS.getInstance()});var L8,O8=D(()=>{"use strict";L8=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var OS,M8,MS,B8=D(()=>{"use strict";dt();OS=null,M8=t=>{OS=t},MS=()=>{if(OS&&!process.env.CI)try{OS.saveToDisk(),ie.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){ie.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",MS);process.on("SIGINT",()=>{MS(),process.exit(0)});process.on("SIGTERM",()=>{MS(),process.exit(0)})});var wee,Eee,Rm,Ree,Iee,kee,_ee,N8,$8=D(()=>{"use strict";fS();QM();iS();xl();cm();n8();xS();LS();dt();Qn();O8();B8();wee={maxConcurrent:gl.DEFAULT_MAX_CONCURRENT,retryAttempts:gl.DEFAULT_RETRY_ATTEMPTS,retryDelay:gl.DEFAULT_RETRY_DELAY_MS,timeoutMs:gl.DEFAULT_TIMEOUT_MS},Eee=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},Rm=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${Lc(e,n)}${r}`},Ree=t=>{let e=pl({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=e.get(i)||0;return Eee(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},Iee=({analyzeResource:t,redactionMapping:e,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:c,originalResources:u,relationships:l,aiModelId:d})=>async({redactedId:p,redactedResources:f,findingsByResource:m,progressTracker:g})=>{let h=m.get(p)||[],y=f[p];if(!y)return{status:"skipped",redactedId:p};let C=mS(p,y,i,o,[]),A=hS(C),w=e[p];if(!w)return{status:"skipped",redactedId:p};let N=w,L=()=>(s[N]||(s[N]={issues:[]}),s[N]),R=c.get(A);if(R){let k=(R.issues||[]).map(x=>({...x,resource:N,resourceId:N})),K=L();return K.issues.push(...ra({existing:K.issues,incoming:k})),K.resourceName=R.resourceName,{status:"success",redactedId:p,resourceKey:N,remappedIssues:k,resourceName:R.resourceName}}let H=Lc(a,w),B=Lc("cdk-insights-stack",a),S=am(w,l,u),U={dependencies:S.dependencies.map(k=>Rm(k,a)),dependents:S.dependents.map(k=>Rm(k,a)),usageDescription:S.usageDescription};for(let k=1;k<=r.retryAttempts;k++)try{let K=await Promise.race([t(B,H,y,y.Type,i,o,h,g,U,d),new Promise((X,Z)=>setTimeout(()=>Z(new Error("Analysis timeout")),r.timeoutMs))]);K.resourceId=N;let x=(K.issues||[]).map(X=>({...X,resource:N,resourceId:N})),v=L();return v.issues.push(...ra({existing:v.issues,incoming:x})),v.resourceName=K.resourceName,c.set(A,K,C),{status:"success",redactedId:p,resourceKey:N,remappedIssues:x,resourceName:K.resourceName}}catch(K){if(k===r.retryAttempts)return n({analysisError:K,redactedId:p});await new Promise(x=>setTimeout(x,r.retryDelay*2**(k-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},kee=async(t,e,s)=>{let n=Math.max(1,Math.floor(e)),r=0,i=Array.from({length:Math.min(n,t.length)}).map(async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o];await s(a)}});await Promise.allSettled(i)},_ee=10,N8=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=wee})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:c,fingerprint:u,noCache:l=!1,cacheConfig:d,aiModelId:p,aiBatchSize:f})=>{let m={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:y,mapping:b}=s(i),C=i8(a,b,c),A=new Map;for(let J of C){let re=A.get(J.resourceId);re?re.push(J):A.set(J.resourceId,[J])}let w=Object.keys(y),N=w.length,L=sa(i),R=new bm({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});M8(R);let H=Ree(n),B=Iee({analyzeResource:t,redactionMapping:b,aggregatedResult:m,errorHandler:H,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:R,originalResources:i,relationships:L,aiModelId:p}),S=Em.createSingleLineProgressTracker(N,"Analyzing resources with AI"),U=Math.min(Math.max(1,Math.floor(f??1)),_ee);if(U>1&&!!e&&e){ie.debug("Batched analysis enabled",{batchSize:U,totalResources:N});let J=Lc("cdk-insights-stack",r),re=pe=>{let Ae=am(pe,L,i);return{dependencies:Ae.dependencies.map(we=>Rm(we,r)),dependents:Ae.dependents.map(we=>Rm(we,r)),usageDescription:Ae.usageDescription}};for(let pe=0;pe<w.length;pe+=U){let Ae=w.slice(pe,pe+U),we=async()=>{for(let z of Ae){let ae=await B({redactedId:z,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ae.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:z,resourceData:y[z],resourceType:y[z].Type,existingFindings:A.get(z)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},ue=new Map,Re=[];for(let z of Ae){let ae=y[z],q=b[z];if(!ae||!q){h.processedCount++,h.failureCount++;continue}let _=mS(z,ae,o,u,[]),le=hS(_),F=R.get(le);if(F){let ye=(F.issues||[]).map(I=>({...I,resource:q,resourceId:q}));m[q]||(m[q]={issues:[]});let Se=m[q];Se.issues.push(...ra({existing:Se.issues,incoming:ye})),Se.resourceName=F.resourceName,h.processedCount++,h.successCount++;continue}let te=Lc(r,q);ue.set(te,{redactedId:z,originalResourceId:q,cacheKey:le,cacheComponents:_}),Re.push({stableResourceId:te,resourceData:ae,resourceType:ae.Type,context:re(q),existingFindings:A.get(z)||[]})}if(Re.length!==0)try{let z=await Promise.race([e(J,Re,o,u,p),new Promise((ae,q)=>setTimeout(()=>q(new Error("Analysis timeout")),n.timeoutMs))]);for(let[ae,q]of ue){let _=z.get(ae);if(h.processedCount++,!_){ie.warn(`Batched response missing entry for resource ${q.originalResourceId}`,{stableResourceId:ae,redactedId:q.redactedId}),h.failureCount++;continue}let le=(_.issues||[]).map(te=>({...te,resource:q.originalResourceId,resourceId:q.originalResourceId}));m[q.originalResourceId]||(m[q.originalResourceId]={issues:[]});let F=m[q.originalResourceId];F.issues.push(...ra({existing:F.issues,incoming:le})),F.resourceName=_.resourceName,R.set(q.cacheKey,{resourceId:q.originalResourceId,issues:_.issues||[],resourceName:_.resourceName},q.cacheComponents),h.successCount++}}catch(z){ie.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:z instanceof Error?z.message:String(z),chunkSize:Ae.length}),await we()}}}else await kee(w,n.maxConcurrent,async J=>{ie.debug(`Starting analysis for resource ${J}`,{redactedId:J,maxConcurrent:n.maxConcurrent});let re=await B({redactedId:J,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ie.debug(`Resource ${J} analysis result: ${re.status}`,{redactedId:J,status:re.status,hasProgressTracker:!!S}),re.status){case"success":h.successCount++,ie.debug(`Resource ${J} completed successfully`,{redactedId:J,resourceKey:re.resourceKey});break;case"timeout":h.timeoutCount++,ie.warn(`Resource ${J} timed out`,{redactedId:J}),g.push({redactedId:J,resourceData:y[J],resourceType:y[J].Type,existingFindings:A.get(J)||[]});break;case"fail":case"skipped":h.failureCount++,ie.warn(`Resource ${J} failed or was skipped`,{redactedId:J,status:re.status});break}});let K=Date.now()-h.startTime,x=S.getStats();if(ie.debug("Analysis completed with progress tracker stats",{progressTrackerStats:x,performanceMetrics:h,totalTime:K,totalResources:N,maxConcurrent:n.maxConcurrent}),P.analysisComplete(K,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){P.newline(),P.info("\u{1F4CA} Performance Analysis:");let J=h.successCount>0?Math.round(K/1e3/h.successCount):0;P.comment(` \u23F1\uFE0F Average completion time: ${J}s`),P.comment(` \u{1F4CA} Success rate: ${(h.successCount/N*100).toFixed(1)}%`)}if(g.length>0){P.newline(),P.warning("\u23F0 Timed Out Resources:"),P.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let J of g){if(P.comment(` \u274C ${J.resourceType}: ${J.redactedId}`),J.resourceData?.Properties){let pe=J.resourceData.Properties,Ae=L8(pe);P.comment(` \u{1F4DD} Name: ${Ae}`)}J.existingFindings.length>0&&P.comment(` \u{1F50D} Existing findings: ${J.existingFindings.length}`),J.resourceData?.Metadata&&P.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(J.resourceType)&&P.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}P.newline(),P.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),P.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),P.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let v=new Set(Object.keys(m)),X=new Set(Object.values(b)),Z=Array.from(X).filter(J=>!v.has(J)||!m[J]?.issues?.length);if(Z.length>0){let J=R.getCachedResultsForResources(Z),re=0;for(let[pe,Ae]of Array.from(J.entries())){if(m[pe]?.issues?.length>0)continue;let we=(Ae.issues||[]).map(ue=>({...ue,resource:pe,resourceId:pe}));we.length>0&&(m[pe]||(m[pe]={issues:[]}),m[pe].issues.push(...we),m[pe].resourceName=Ae.resourceName,re+=we.length)}re>0}return m}});var j8,Fee,W8,Tee,Pee,BS,Mc,Bc,U8,H8,Lee,Oee,Mee,Nc,Im=D(()=>{"use strict";j8="1.42.2",Fee={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},W8=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Tee=(t,e)=>{let s=0;if(s+=2e3,e){let n=Object.values(t).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(t)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},Pee=t=>t?t.split(`
|
|
177
|
+
`)}section(e,s=Xt.info){console.log(gt.primary.bold(`${s} ${e}`))}success(e,s=Xt.success){console.log(gt.success(`${s} ${e}`))}info(e,s=Xt.info){console.log(gt.info(`${s} ${e}`))}warning(e,s=Xt.warning){console.log(gt.warning(`${s} ${e}`))}error(e,s=Xt.error){console.log(gt.error(`${s} ${e}`))}comment(e,s=""){console.log(gt.comment(`${s} ${e}`))}phase1(e){console.log(gt.info(`${Xt.phase1} Phase 1: ${e}`))}phase2(e){console.log(gt.primary(`${Xt.phase2} Phase 2: ${e}`))}phase3(e){console.log(gt.secondary(`${Xt.phase3} Phase 3: ${e}`))}severityBadge(e){switch(e.toUpperCase()){case"CRITICAL":return gt.severity.critical.bold(`${Xt.critical} CRITICAL`);case"HIGH":return gt.severity.high.bold(`${Xt.high} HIGH`);case"MEDIUM":return gt.severity.medium.bold(`${Xt.medium} MEDIUM`);case"LOW":return gt.severity.low.bold(`${Xt.low} LOW`);default:return gt.comment(e)}}divider(){console.log(gt.comment("\u2500".repeat(60)))}newline(){console.log("")}clearLine(){process.stdout.write(`\r${" ".repeat(process.stdout.columns)}\r`)}},Em=PS.getInstance()});var L8,O8=D(()=>{"use strict";L8=t=>t&&(t.Name||t.ResourceName||t.FunctionName)||"Unnamed"});var OS,M8,MS,B8=D(()=>{"use strict";dt();OS=null,M8=t=>{OS=t},MS=()=>{if(OS&&!process.env.CI)try{OS.saveToDisk(),ie.info("\u{1F4BE} Cache saved to disk on exit")}catch(t){ie.warn("\u26A0\uFE0F Could not save cache on exit",{error:t instanceof Error?t.message:String(t)})}};process.on("exit",MS);process.on("SIGINT",()=>{MS(),process.exit(0)});process.on("SIGTERM",()=>{MS(),process.exit(0)})});var wee,Eee,Rm,Ree,Iee,kee,_ee,N8,$8=D(()=>{"use strict";fS();QM();iS();xl();cm();n8();xS();LS();dt();Qn();O8();B8();wee={maxConcurrent:gl.DEFAULT_MAX_CONCURRENT,retryAttempts:gl.DEFAULT_RETRY_ATTEMPTS,retryDelay:gl.DEFAULT_RETRY_DELAY_MS,timeoutMs:gl.DEFAULT_TIMEOUT_MS},Eee=t=>{if(!(t instanceof Error))return!1;let e=t.message??"";return e.startsWith("Polling timed out")||e==="Analysis timeout"||e.toLowerCase().includes("timeout")},Rm=(t,e)=>{let s=t.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return t;let[,n,r=""]=s;return`${Lc(e,n)}${r}`},Ree=t=>{let e=pl({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=e.get(i)||0;return Eee(s)?{status:"timeout",redactedId:n}:(e.set(i,o+1),o>t.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},Iee=({analyzeResource:t,redactionMapping:e,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:c,originalResources:u,relationships:l,aiModelId:d})=>async({redactedId:p,redactedResources:f,findingsByResource:m,progressTracker:g})=>{let h=m.get(p)||[],y=f[p];if(!y)return{status:"skipped",redactedId:p};let C=mS(p,y,i,o,[]),A=hS(C),w=e[p];if(!w)return{status:"skipped",redactedId:p};let N=w,L=()=>(s[N]||(s[N]={issues:[]}),s[N]),R=c.get(A);if(R){let k=(R.issues||[]).map(x=>({...x,resource:N,resourceId:N})),K=L();return K.issues.push(...ra({existing:K.issues,incoming:k})),K.resourceName=R.resourceName,{status:"success",redactedId:p,resourceKey:N,remappedIssues:k,resourceName:R.resourceName}}let H=Lc(a,w),B=Lc("cdk-insights-stack",a),S=am(w,l,u),U={dependencies:S.dependencies.map(k=>Rm(k,a)),dependents:S.dependents.map(k=>Rm(k,a)),usageDescription:S.usageDescription};for(let k=1;k<=r.retryAttempts;k++)try{let K=await Promise.race([t(B,H,y,y.Type,i,o,h,g,U,d),new Promise((X,Z)=>setTimeout(()=>Z(new Error("Analysis timeout")),r.timeoutMs))]);K.resourceId=N;let x=(K.issues||[]).map(X=>({...X,resource:N,resourceId:N})),v=L();return v.issues.push(...ra({existing:v.issues,incoming:x})),v.resourceName=K.resourceName,c.set(A,K,C),{status:"success",redactedId:p,resourceKey:N,remappedIssues:x,resourceName:K.resourceName}}catch(K){if(k===r.retryAttempts)return n({analysisError:K,redactedId:p});await new Promise(x=>setTimeout(x,r.retryDelay*2**(k-1)))}return{status:"fail",redactedId:p,error:new Error("Max retries exceeded")}},kee=async(t,e,s)=>{let n=Math.max(1,Math.floor(e)),r=0,i=Array.from({length:Math.min(n,t.length)}).map(async()=>{for(;r<t.length;){let o=r;r+=1;let a=t[o];await s(a)}});await Promise.allSettled(i)},_ee=10,N8=({analyzeResource:t,analyzeResourcesBatch:e,redactResources:s,config:n=wee})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:c,fingerprint:u,noCache:l=!1,cacheConfig:d,aiModelId:p,aiBatchSize:f})=>{let m={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:y,mapping:b}=s(i),C=i8(a,b,c),A=new Map;for(let J of C){let re=A.get(J.resourceId);re?re.push(J):A.set(J.resourceId,[J])}let w=Object.keys(y),N=w.length,L=sa(i),R=new bm({ttl:d?.ttl||6*60*60*1e3,maxSize:d?.maxSize||5e3,disabled:l||!d?.enabled});M8(R);let H=Ree(n),B=Iee({analyzeResource:t,redactionMapping:b,aggregatedResult:m,errorHandler:H,config:n,authToken:o,fingerprint:u,stackName:r,analysisCache:R,originalResources:i,relationships:L,aiModelId:p}),S=Em.createSingleLineProgressTracker(N,"Analyzing resources with AI"),U=Math.min(Math.max(1,Math.floor(f??1)),_ee);if(U>1&&!!e&&e){ie.debug("Batched analysis enabled",{batchSize:U,totalResources:N});let J=Lc("cdk-insights-stack",r),re=pe=>{let Ae=am(pe,L,i);return{dependencies:Ae.dependencies.map(we=>Rm(we,r)),dependents:Ae.dependents.map(we=>Rm(we,r)),usageDescription:Ae.usageDescription}};for(let pe=0;pe<w.length;pe+=U){let Ae=w.slice(pe,pe+U),we=async()=>{for(let z of Ae){let ae=await B({redactedId:z,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ae.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:z,resourceData:y[z],resourceType:y[z].Type,existingFindings:A.get(z)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},ue=new Map,Re=[];for(let z of Ae){let ae=y[z],q=b[z];if(!ae||!q){h.processedCount++,h.failureCount++;continue}let _=mS(z,ae,o,u,[]),le=hS(_),F=R.get(le);if(F){let ye=(F.issues||[]).map(I=>({...I,resource:q,resourceId:q}));m[q]||(m[q]={issues:[]});let Se=m[q];Se.issues.push(...ra({existing:Se.issues,incoming:ye})),Se.resourceName=F.resourceName,h.processedCount++,h.successCount++;continue}let te=Lc(r,q);ue.set(te,{redactedId:z,originalResourceId:q,cacheKey:le,cacheComponents:_}),Re.push({stableResourceId:te,resourceData:ae,resourceType:ae.Type,context:re(q),existingFindings:A.get(z)||[]})}if(Re.length!==0)try{let z=await Promise.race([e(J,Re,o,u,p),new Promise((ae,q)=>setTimeout(()=>q(new Error("Analysis timeout")),n.timeoutMs))]);for(let[ae,q]of ue){let _=z.get(ae);if(h.processedCount++,!_){ie.warn(`Batched response missing entry for resource ${q.originalResourceId}`,{stableResourceId:ae,redactedId:q.redactedId}),h.failureCount++;continue}let le=(_.issues||[]).map(te=>({...te,resource:q.originalResourceId,resourceId:q.originalResourceId}));m[q.originalResourceId]||(m[q.originalResourceId]={issues:[]});let F=m[q.originalResourceId];F.issues.push(...ra({existing:F.issues,incoming:le})),F.resourceName=_.resourceName,R.set(q.cacheKey,{resourceId:q.originalResourceId,issues:_.issues||[],resourceName:_.resourceName},q.cacheComponents),h.successCount++}}catch(z){ie.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:z instanceof Error?z.message:String(z),chunkSize:Ae.length}),await we()}}}else await kee(w,n.maxConcurrent,async J=>{ie.debug(`Starting analysis for resource ${J}`,{redactedId:J,maxConcurrent:n.maxConcurrent});let re=await B({redactedId:J,redactedResources:y,findingsByResource:A,progressTracker:S});switch(h.processedCount++,ie.debug(`Resource ${J} analysis result: ${re.status}`,{redactedId:J,status:re.status,hasProgressTracker:!!S}),re.status){case"success":h.successCount++,ie.debug(`Resource ${J} completed successfully`,{redactedId:J,resourceKey:re.resourceKey});break;case"timeout":h.timeoutCount++,ie.warn(`Resource ${J} timed out`,{redactedId:J}),g.push({redactedId:J,resourceData:y[J],resourceType:y[J].Type,existingFindings:A.get(J)||[]});break;case"fail":case"skipped":h.failureCount++,ie.warn(`Resource ${J} failed or was skipped`,{redactedId:J,status:re.status});break}});let K=Date.now()-h.startTime,x=S.getStats();if(ie.debug("Analysis completed with progress tracker stats",{progressTrackerStats:x,performanceMetrics:h,totalTime:K,totalResources:N,maxConcurrent:n.maxConcurrent}),P.analysisComplete(K,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){P.newline(),P.info("\u{1F4CA} Performance Analysis:");let J=h.successCount>0?Math.round(K/1e3/h.successCount):0;P.comment(` \u23F1\uFE0F Average completion time: ${J}s`),P.comment(` \u{1F4CA} Success rate: ${(h.successCount/N*100).toFixed(1)}%`)}if(g.length>0){P.newline(),P.warning("\u23F0 Timed Out Resources:"),P.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let J of g){if(P.comment(` \u274C ${J.resourceType}: ${J.redactedId}`),J.resourceData?.Properties){let pe=J.resourceData.Properties,Ae=L8(pe);P.comment(` \u{1F4DD} Name: ${Ae}`)}J.existingFindings.length>0&&P.comment(` \u{1F50D} Existing findings: ${J.existingFindings.length}`),J.resourceData?.Metadata&&P.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(J.resourceType)&&P.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}P.newline(),P.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),P.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),P.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let v=new Set(Object.keys(m)),X=new Set(Object.values(b)),Z=Array.from(X).filter(J=>!v.has(J)||!m[J]?.issues?.length);if(Z.length>0){let J=R.getCachedResultsForResources(Z),re=0;for(let[pe,Ae]of Array.from(J.entries())){if(m[pe]?.issues?.length>0)continue;let we=(Ae.issues||[]).map(ue=>({...ue,resource:pe,resourceId:pe}));we.length>0&&(m[pe]||(m[pe]={issues:[]}),m[pe].issues.push(...we),m[pe].resourceName=Ae.resourceName,re+=we.length)}re>0}return m}});var j8,Fee,W8,Tee,Pee,BS,Mc,Bc,U8,H8,Lee,Oee,Mee,Nc,Im=D(()=>{"use strict";j8="1.42.3",Fee={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},W8=t=>t.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Tee=(t,e)=>{let s=0;if(s+=2e3,e){let n=Object.values(t).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(t)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},Pee=t=>t?t.split(`
|
|
178
178
|
`).map(e=>e.trim()).filter(Boolean).join(`
|
|
179
179
|
`):"",BS=t=>{let e=`- **Issue:** ${t.issue}`;return t.recommendation&&(e+=`
|
|
180
180
|
- **Recommendation:** ${Pee(t.recommendation)}`),t.context&&(t.context.property&&(e+=`
|
|
@@ -296,7 +296,7 @@ ${o}`)}});var Y8,J8,Q8=D(()=>{"use strict";Y8=require("node:child_process"),J8=(
|
|
|
296
296
|
`)}catch(a){console.error("Failed to write GitHub outputs:",a)}}});var Tm,m4,h4=D(()=>{"use strict";dt();Tm=t=>{switch(t.toUpperCase()){case"CRITICAL":return"\u{1F534}";case"HIGH":return"\u{1F7E0}";case"MEDIUM":return"\u{1F7E1}";case"LOW":return"\u{1F7E2}";default:return"\u26AA"}},m4=(t,e)=>{Me.info(`
|
|
297
297
|
\u{1F4DD} Analysis Summary for stack: ${t}`),Me.info(`Total Resources Scanned: ${e.totalResources}`),Me.info(`Resources with Issues: ${e.resourcesWithIssues} (${e.percentWithIssues}%)`),Me.info(`Total Issues Found: ${e.totalIssues}
|
|
298
298
|
`),Me.info("Severity Breakdown:"),Me.info(` ${Tm("CRITICAL")} Critical: ${e.severityCounts.CRITICAL}`),Me.info(` ${Tm("HIGH")} High: ${e.severityCounts.HIGH}`),Me.info(` ${Tm("MEDIUM")} Medium: ${e.severityCounts.MEDIUM}`),Me.info(` ${Tm("LOW")} Low: ${e.severityCounts.LOW}
|
|
299
|
-
`),Me.info("WAF Pillar Impact:");for(let[s,n]of Object.entries(e.wafIssues))Me.info(` ${s}: ${n}`);Me.info(""),Me.info("Top Priorities:"),e.severityCounts.CRITICAL>0&&Me.info(" \u{1F534} Address Critical issues immediately (highest risk)"),e.severityCounts.HIGH>0&&Me.info(" \u{1F7E0} Then handle High-severity issues"),e.severityCounts.MEDIUM>0&&Me.info(" \u{1F7E1} Schedule Medium-severity tasks soon"),e.severityCounts.LOW>0&&Me.info(" \u{1F7E2} Plan Low-severity enhancements at your convenience"),Me.info("")}});var tte,ste,nte,g4,El,GS=D(()=>{"use strict";tte=p0(),ste=t=>{switch(t){case"CRITICAL":return"\u{1F534}";case"HIGH":return"\u{1F536}";case"MEDIUM":return"\u{1F7E1}";case"LOW":return"\u{1F7E2}";default:return"\u26AA"}},nte=(t,e)=>{let s=t.sourceLocation||e?.sourceLocation;if(s){let{filePath:n,line:r,column:i,confidence:o}=s,a=o==="high"?"\u{1F3AF}":o==="medium"?"\u{1F4CD}":"\u2753",c=n.length>40?`...${n.slice(-37)}`:n;return`${a} ${c}:${r}:${i}`}if(e?.rootSourceLocation){let{filePath:n,line:r,column:i}=e.rootSourceLocation;return`\u{1F517} ${n.length>40?`...${n.slice(-37)}`:n}:${r}:${i}`}return e?.createdBy?`\u{1F517} ${e.createdBy.length>28?`${e.createdBy.slice(0,25)}...`:e.createdBy}`:""},g4={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},El=t=>{let e=new tte({head:["Resource","Stack","Severity","Service","Issue","Location"],colWidths:[20,15,10,15,40,30],wordWrap:!0}),s=[];for(let[,n]of Object.entries(t)){let r=[...n.sources?.cdkInsights?.issues??[],...n.sources?.cdkNag?.issues??[]];for(let i of r){let o=i.constructType||n.constructType||n.type||"Unknown",a=nte(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=g4[n.issue.severity]||0;return(g4[r.issue.severity]||0)-i});for(let{issue:n,group:r,service:i,sourceLocation:o}of s)e.push([r.friendlyName||r.resourceId,n.stackName||"Unknown",`${ste(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var Rl=M(($_e,rte)=>{rte.exports={name:"cdk-insights",version:"1.42.2",description:"AWS CDK security and cost analysis CLI. Free static scans via npm \u2014 no account needed. Sign up free to add AI-powered insights.",main:"dist/index.js",types:"dist/index.d.ts",bin:{"cdk-insights":"dist/entry.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.js"}},files:["dist/**/*","README.md","LICENSE"],scripts:{test:"vitest --run",lint:"biome lint src/",typecheck:"tsc --noEmit",format:"biome format --write src/",check:"biome check src/","check:schema-sync":"ts-node scripts/check-schema-sync.ts",build:"ts-node scripts/build.ts","build:dev":"CDK_INSIGHTS_ENVIRONMENT=dev CDK_INSIGHTS_API_URL=https://s2zhmjbwlj.execute-api.eu-west-2.amazonaws.com/v1 ts-node scripts/build.ts",start:"node dist/index.js",dev:"ts-node src/index.ts",prepare:"husky install && npm run build","start:dev":"CDK_ENV=local ts-node src/index.ts","ai-run":"ts-node src/index.ts",unlink:"npm unlink -g cdk-insights",link:"npm link","prepare:test":"npm run unlink && npm run build && npm run link","prepare:dev":"npm run unlink && npm run build:dev && npm run link","deploy:dev":"STAGE=dev cdk deploy","destroy:dev":"STAGE=dev cdk destroy","release:patch":"bumper release patch","release:minor":"bumper release minor","release:major":"bumper release major","release:dry-run":"bumper release patch --dry-run","changelog:preview":"bumper preview","changelog:generate":"bumper generate","validate:commits":"bumper validate","release:check":"npm run validate:commits && npm run test && npm run build","release:full":"npm run release:check && npm run changelog:generate","setup:bumper":"bumper setup","publish:beta":"npm run build && npm publish --tag beta && npm dist-tag add cdk-insights@$npm_package_version latest","publish:alpha":"npm run build && npm publish --tag alpha","publish:canary":"npm run build && npm publish --tag canary","publish:latest":"npm run build && npm publish --tag latest","version:beta":"npm version prerelease --preid=beta","version:alpha":"npm version prerelease --preid=alpha","version:rc":"npm version prerelease --preid=rc","cdk-insights":"node scripts/cdk-insights-wrapper.js",scan:"node scripts/cdk-insights-wrapper.js scan","scan:all":"node scripts/cdk-insights-wrapper.js scan --all","scan:json":"node scripts/cdk-insights-wrapper.js scan --format json","scan:markdown":"node scripts/cdk-insights-wrapper.js scan --format markdown","scan:summary":"node scripts/cdk-insights-wrapper.js scan --format summary","scan:with-issues":"node scripts/cdk-insights-wrapper.js scan --withIssue","cache:clear":"node scripts/cdk-insights-wrapper.js cache clear","cache:status":"node scripts/cdk-insights-wrapper.js cache status","demo:progress":"ts-node src/examples/progress-demo.ts","demo:single-line":"ts-node src/examples/single-line-progress-demo.ts","test:line-clearing":"ts-node src/examples/line-clearing-test.ts"},publishConfig:{access:"public"},keywords:["aws","cdk","cloudformation","analysis","security","cost-optimization","static-analysis","devops","infrastructure","aws-cdk","cloud-security","compliance"],author:"Lee Priest <lee@cdkinsights.dev>",license:"BUSL-1.1",homepage:"https://github.com/instancelabs/cdk-insights",bugs:"https://github.com/instancelabs/cdk-insights/issues",repository:{type:"git",url:"git+https://github.com/instancelabs/cdk-insights.git"},dependencies:{"@inquirer/prompts":"^7.4.1","@middy/core":"^6.1.6","@types/glob":"^8.1.0",axios:"^1.8.4",chalk:"^5.4.1",chokidar:"^3.6.0","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.5.0",envolution:"^1.4.1",glob:"^11.0.3",ora:"^8.2.0",strogger:"^2.0.3",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies:{"@aws-sdk/client-dynamodb":"^3.788.0","@biomejs/biome":"^2.0.6","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@types/cli-progress":"^3.11.6","@types/jsonwebtoken":"^9.0.9","@types/node":"^22.14.1","@types/yargs":"^17.0.33","aws-cdk":"^2.1010.0","bumper-cli":"^1.6.0",esbuild:"^0.25.2",husky:"^8.0.3","ts-node":"^10.9.2",typescript:"^5.8.3",vitest:"^3.1.1"},peerDependencies:{"@aws-solutions-constructs/aws-apigateway-lambda":"^2.0.0","@aws-solutions-constructs/aws-lambda-stepfunctions":"^2.0.0","@aws-solutions-constructs/aws-s3-lambda":"^2.0.0","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var x4,ite,y4,ote,b4,S4=D(()=>{"use strict";x4=oe(require("node:fs"));dt();xl();({version:ite}=Rl()),y4={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},ote=(t,e,s)=>{let n=Object.entries(s).map(([r,i])=>{let o=[...i.sources?.cdkInsights?.issues??[],...i.sources?.cdkNag?.issues??[],...i.sources?.validationReport?.issues??[]].slice().sort((c,u)=>y4[c.severity]-y4[u.severity]),a=vm(o,i.cdkPath);return{resourceId:i.resourceId,logicalId:i.logicalId,cdkName:i.friendlyName,resourceName:i.resourceName,cdkPath:i.cdkPath,githubUrl:i.githubUrl,docUrl:i.docUrl,constructType:i.constructType,parentPath:i.parentPath,childCount:i.childCount,tags:i.tags,sourceLocation:i.sourceLocation,constructHierarchy:i.constructHierarchy,serviceCategory:i.serviceCategory,dependencies:i.dependencies,sensitiveProperties:i.sensitiveProperties,usesDefaults:i.usesDefaults,l2ConstructType:i.l2ConstructType,l2ConstructId:i.l2ConstructId,createdBy:i.createdBy,rootSourceLocation:i.rootSourceLocation,searchHint:i.searchHint,issues:a.map(c=>({issue:c.issue,recommendation:c.recommendation,severity:c.severity,wafPillar:c.wafPillar,codeSnippet:c.codeSnippet,locationHint:c.locationHint,foundBy:c.foundBy,sourceLocation:c.sourceLocation,stackName:c.stackName,ruleId:c.ruleId,seenInSynth:c.seenInSynth,validationPluginName:c.validationPluginName}))}});return{stackName:t,generatedAt:new Date().toISOString(),version:ite,summary:e,recommendations:n}},b4=(t,e,s)=>{let n=ote(t,e,s),r=`${t}_analysis_report.json`;try{x4.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Me.info(`\u{1F4C4} JSON report written to ${r}`)}catch(i){let o=i instanceof Error?i.message:String(i);throw Me.error(`\u274C Failed to write JSON report to ${r}: ${o}`),new Error(`Failed to write analysis report: ${o}`)}return n}});var ate,cte,v4,Pm,ute,zS=D(()=>{"use strict";({version:ate}=Rl()),cte=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},v4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},Pm=(t,e)=>{let s=[],n=[],r=new Set;for(let[i,o]of Object.entries(e)){let a=[...o.sources?.cdkInsights?.issues||[],...o.sources?.cdkNag?.issues||[]];for(let c of a){let u=ute(c);r.has(u)||(r.add(u),s.push({id:u,name:c.issue.slice(0,100),shortDescription:{text:c.issue},fullDescription:c.recommendation?{text:c.recommendation}:void 0,helpUri:c.docUrl||c.githubUrl,properties:{"security-severity":v4(c.severity).toString(),tags:[c.wafPillar,c.severity,c.foundBy].filter(Boolean)}}));let d=(c.sourceLocation?.frames?.slice(1)??[]).map(p=>({physicalLocation:{artifactLocation:{uri:p.filePath,uriBaseId:"%SRCROOT%"},region:{startLine:p.line,startColumn:p.column}},message:{text:p.kind==="property"&&p.propertyName?`Property set: ${p.propertyName}`:p.kind==="creation"?"Construct created here":"Related call site"}}));n.push({ruleId:u,level:cte(c.severity),message:{text:c.recommendation||c.issue},locations:[{physicalLocation:{artifactLocation:{uri:c.sourceLocation?.filePath||`cdk.out/${t}.template.json`,uriBaseId:"%SRCROOT%"},region:c.sourceLocation?{startLine:c.sourceLocation.line,startColumn:c.sourceLocation.column}:void 0}}],...d.length>0?{relatedLocations:d}:{},properties:{"security-severity":v4(c.severity).toString(),wafPillar:c.wafPillar,recommendation:c.recommendation}})}}return{$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"cdk-insights",version:ate,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},ute=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var qS,C4,D4=D(()=>{"use strict";qS=oe(require("node:fs"));dt();Im();h4();GS();S4();zS();HS();C4=(t,e,s,n,r)=>{switch(Me.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Nc(e,s,r,n),o=`${e}_analysis_report.md`;try{qS.writeFileSync(o,i),Me.info(`\u{1F4C4} Saved Markdown report to ${o}`)}catch(a){let c=a instanceof Error?a.message:String(a);throw Me.error(`\u274C Failed to write Markdown report to ${o}: ${c}`),new Error(`Failed to write Markdown report: ${c}`)}break}case"table":{El(s);break}case"json":{let i=b4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
299
|
+
`),Me.info("WAF Pillar Impact:");for(let[s,n]of Object.entries(e.wafIssues))Me.info(` ${s}: ${n}`);Me.info(""),Me.info("Top Priorities:"),e.severityCounts.CRITICAL>0&&Me.info(" \u{1F534} Address Critical issues immediately (highest risk)"),e.severityCounts.HIGH>0&&Me.info(" \u{1F7E0} Then handle High-severity issues"),e.severityCounts.MEDIUM>0&&Me.info(" \u{1F7E1} Schedule Medium-severity tasks soon"),e.severityCounts.LOW>0&&Me.info(" \u{1F7E2} Plan Low-severity enhancements at your convenience"),Me.info("")}});var tte,ste,nte,g4,El,GS=D(()=>{"use strict";tte=p0(),ste=t=>{switch(t){case"CRITICAL":return"\u{1F534}";case"HIGH":return"\u{1F536}";case"MEDIUM":return"\u{1F7E1}";case"LOW":return"\u{1F7E2}";default:return"\u26AA"}},nte=(t,e)=>{let s=t.sourceLocation||e?.sourceLocation;if(s){let{filePath:n,line:r,column:i,confidence:o}=s,a=o==="high"?"\u{1F3AF}":o==="medium"?"\u{1F4CD}":"\u2753",c=n.length>40?`...${n.slice(-37)}`:n;return`${a} ${c}:${r}:${i}`}if(e?.rootSourceLocation){let{filePath:n,line:r,column:i}=e.rootSourceLocation;return`\u{1F517} ${n.length>40?`...${n.slice(-37)}`:n}:${r}:${i}`}return e?.createdBy?`\u{1F517} ${e.createdBy.length>28?`${e.createdBy.slice(0,25)}...`:e.createdBy}`:""},g4={CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1},El=t=>{let e=new tte({head:["Resource","Stack","Severity","Service","Issue","Location"],colWidths:[20,15,10,15,40,30],wordWrap:!0}),s=[];for(let[,n]of Object.entries(t)){let r=[...n.sources?.cdkInsights?.issues??[],...n.sources?.cdkNag?.issues??[]];for(let i of r){let o=i.constructType||n.constructType||n.type||"Unknown",a=nte(i,n);s.push({issue:i,group:n,service:o,sourceLocation:a})}}s.sort((n,r)=>{let i=g4[n.issue.severity]||0;return(g4[r.issue.severity]||0)-i});for(let{issue:n,group:r,service:i,sourceLocation:o}of s)e.push([r.friendlyName||r.resourceId,n.stackName||"Unknown",`${ste(n.severity)} ${n.severity}`,i,n.issue,o||n.locationHint||""]);console.log(e.toString())}});var Rl=M(($_e,rte)=>{rte.exports={name:"cdk-insights",version:"1.42.3",description:"AWS CDK security and cost analysis CLI. Free static scans via npm \u2014 no account needed. Sign up free to add AI-powered insights.",main:"dist/index.js",types:"dist/index.d.ts",bin:{"cdk-insights":"dist/entry.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.js"}},files:["dist/**/*","README.md","LICENSE"],scripts:{test:"vitest --run",lint:"biome lint src/",typecheck:"tsc --noEmit",format:"biome format --write src/",check:"biome check src/","check:schema-sync":"ts-node scripts/check-schema-sync.ts",build:"ts-node scripts/build.ts","build:dev":"CDK_INSIGHTS_ENVIRONMENT=dev CDK_INSIGHTS_API_URL=https://s2zhmjbwlj.execute-api.eu-west-2.amazonaws.com/v1 ts-node scripts/build.ts",start:"node dist/index.js",dev:"ts-node src/index.ts",prepare:"husky install && npm run build","start:dev":"CDK_ENV=local ts-node src/index.ts","ai-run":"ts-node src/index.ts",unlink:"npm unlink -g cdk-insights",link:"npm link","prepare:test":"npm run unlink && npm run build && npm run link","prepare:dev":"npm run unlink && npm run build:dev && npm run link","deploy:dev":"STAGE=dev cdk deploy","destroy:dev":"STAGE=dev cdk destroy","release:patch":"bumper release patch","release:minor":"bumper release minor","release:major":"bumper release major","release:dry-run":"bumper release patch --dry-run","changelog:preview":"bumper preview","changelog:generate":"bumper generate","validate:commits":"bumper validate","release:check":"npm run validate:commits && npm run test && npm run build","release:full":"npm run release:check && npm run changelog:generate","setup:bumper":"bumper setup","publish:beta":"npm run build && npm publish --tag beta && npm dist-tag add cdk-insights@$npm_package_version latest","publish:alpha":"npm run build && npm publish --tag alpha","publish:canary":"npm run build && npm publish --tag canary","publish:latest":"npm run build && npm publish --tag latest","version:beta":"npm version prerelease --preid=beta","version:alpha":"npm version prerelease --preid=alpha","version:rc":"npm version prerelease --preid=rc","cdk-insights":"node scripts/cdk-insights-wrapper.js",scan:"node scripts/cdk-insights-wrapper.js scan","scan:all":"node scripts/cdk-insights-wrapper.js scan --all","scan:json":"node scripts/cdk-insights-wrapper.js scan --format json","scan:markdown":"node scripts/cdk-insights-wrapper.js scan --format markdown","scan:summary":"node scripts/cdk-insights-wrapper.js scan --format summary","scan:with-issues":"node scripts/cdk-insights-wrapper.js scan --withIssue","cache:clear":"node scripts/cdk-insights-wrapper.js cache clear","cache:status":"node scripts/cdk-insights-wrapper.js cache status","demo:progress":"ts-node src/examples/progress-demo.ts","demo:single-line":"ts-node src/examples/single-line-progress-demo.ts","test:line-clearing":"ts-node src/examples/line-clearing-test.ts"},publishConfig:{access:"public"},keywords:["aws","cdk","cloudformation","analysis","security","cost-optimization","static-analysis","devops","infrastructure","aws-cdk","cloud-security","compliance"],author:"Lee Priest <lee@cdkinsights.dev>",license:"BUSL-1.1",homepage:"https://github.com/instancelabs/cdk-insights",bugs:"https://github.com/instancelabs/cdk-insights/issues",repository:{type:"git",url:"git+https://github.com/instancelabs/cdk-insights.git"},dependencies:{"@inquirer/prompts":"^7.4.1","@middy/core":"^6.1.6","@types/glob":"^8.1.0",axios:"^1.8.4",chalk:"^5.4.1",chokidar:"^3.6.0","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.5.0",envolution:"^1.4.1",glob:"^11.0.3",ora:"^8.2.0",strogger:"^2.0.3",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies:{"@aws-sdk/client-dynamodb":"^3.788.0","@biomejs/biome":"^2.0.6","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@types/cli-progress":"^3.11.6","@types/jsonwebtoken":"^9.0.9","@types/node":"^22.14.1","@types/yargs":"^17.0.33","aws-cdk":"^2.1010.0","bumper-cli":"^1.6.0",esbuild:"^0.25.2",husky:"^8.0.3","ts-node":"^10.9.2",typescript:"^5.8.3",vitest:"^3.1.1"},peerDependencies:{"@aws-solutions-constructs/aws-apigateway-lambda":"^2.0.0","@aws-solutions-constructs/aws-lambda-stepfunctions":"^2.0.0","@aws-solutions-constructs/aws-s3-lambda":"^2.0.0","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var x4,ite,y4,ote,b4,S4=D(()=>{"use strict";x4=oe(require("node:fs"));dt();xl();({version:ite}=Rl()),y4={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},ote=(t,e,s)=>{let n=Object.entries(s).map(([r,i])=>{let o=[...i.sources?.cdkInsights?.issues??[],...i.sources?.cdkNag?.issues??[],...i.sources?.validationReport?.issues??[]].slice().sort((c,u)=>y4[c.severity]-y4[u.severity]),a=vm(o,i.cdkPath);return{resourceId:i.resourceId,logicalId:i.logicalId,cdkName:i.friendlyName,resourceName:i.resourceName,cdkPath:i.cdkPath,githubUrl:i.githubUrl,docUrl:i.docUrl,constructType:i.constructType,parentPath:i.parentPath,childCount:i.childCount,tags:i.tags,sourceLocation:i.sourceLocation,constructHierarchy:i.constructHierarchy,serviceCategory:i.serviceCategory,dependencies:i.dependencies,sensitiveProperties:i.sensitiveProperties,usesDefaults:i.usesDefaults,l2ConstructType:i.l2ConstructType,l2ConstructId:i.l2ConstructId,createdBy:i.createdBy,rootSourceLocation:i.rootSourceLocation,searchHint:i.searchHint,issues:a.map(c=>({issue:c.issue,recommendation:c.recommendation,severity:c.severity,wafPillar:c.wafPillar,codeSnippet:c.codeSnippet,locationHint:c.locationHint,foundBy:c.foundBy,sourceLocation:c.sourceLocation,stackName:c.stackName,ruleId:c.ruleId,seenInSynth:c.seenInSynth,validationPluginName:c.validationPluginName}))}});return{stackName:t,generatedAt:new Date().toISOString(),version:ite,summary:e,recommendations:n}},b4=(t,e,s)=>{let n=ote(t,e,s),r=`${t}_analysis_report.json`;try{x4.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Me.info(`\u{1F4C4} JSON report written to ${r}`)}catch(i){let o=i instanceof Error?i.message:String(i);throw Me.error(`\u274C Failed to write JSON report to ${r}: ${o}`),new Error(`Failed to write analysis report: ${o}`)}return n}});var ate,cte,v4,Pm,ute,zS=D(()=>{"use strict";({version:ate}=Rl()),cte=t=>{switch(t){case"CRITICAL":case"HIGH":return"error";case"MEDIUM":return"warning";default:return"note"}},v4=t=>{switch(t){case"CRITICAL":return 9;case"HIGH":return 7;case"MEDIUM":return 4;case"LOW":return 2;default:return 1}},Pm=(t,e)=>{let s=[],n=[],r=new Set;for(let[i,o]of Object.entries(e)){let a=[...o.sources?.cdkInsights?.issues||[],...o.sources?.cdkNag?.issues||[]];for(let c of a){let u=ute(c);r.has(u)||(r.add(u),s.push({id:u,name:c.issue.slice(0,100),shortDescription:{text:c.issue},fullDescription:c.recommendation?{text:c.recommendation}:void 0,helpUri:c.docUrl||c.githubUrl,properties:{"security-severity":v4(c.severity).toString(),tags:[c.wafPillar,c.severity,c.foundBy].filter(Boolean)}}));let d=(c.sourceLocation?.frames?.slice(1)??[]).map(p=>({physicalLocation:{artifactLocation:{uri:p.filePath,uriBaseId:"%SRCROOT%"},region:{startLine:p.line,startColumn:p.column}},message:{text:p.kind==="property"&&p.propertyName?`Property set: ${p.propertyName}`:p.kind==="creation"?"Construct created here":"Related call site"}}));n.push({ruleId:u,level:cte(c.severity),message:{text:c.recommendation||c.issue},locations:[{physicalLocation:{artifactLocation:{uri:c.sourceLocation?.filePath||`cdk.out/${t}.template.json`,uriBaseId:"%SRCROOT%"},region:c.sourceLocation?{startLine:c.sourceLocation.line,startColumn:c.sourceLocation.column}:void 0}}],...d.length>0?{relatedLocations:d}:{},properties:{"security-severity":v4(c.severity).toString(),wafPillar:c.wafPillar,recommendation:c.recommendation}})}}return{$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"cdk-insights",version:ate,informationUri:"https://cdkinsights.dev",rules:s}},results:n}]}},ute=t=>{let e=t.issue.toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,50);return`CDK-${t.severity}-${e}`}});var qS,C4,D4=D(()=>{"use strict";qS=oe(require("node:fs"));dt();Im();h4();GS();S4();zS();HS();C4=(t,e,s,n,r)=>{switch(Me.info(`Generating output in format: ${t}`),t){case"markdown":{let i=Nc(e,s,r,n),o=`${e}_analysis_report.md`;try{qS.writeFileSync(o,i),Me.info(`\u{1F4C4} Saved Markdown report to ${o}`)}catch(a){let c=a instanceof Error?a.message:String(a);throw Me.error(`\u274C Failed to write Markdown report to ${o}: ${c}`),new Error(`Failed to write Markdown report: ${c}`)}break}case"table":{El(s);break}case"json":{let i=b4(e,r,s);process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
300
300
|
`);break}case"sarif":{let i=Pm(e,s),o=`${e}_analysis_report.sarif`;try{qS.writeFileSync(o,JSON.stringify(i,null,2)),Me.info(`\u{1F4C4} SARIF report written to: ${o}`),console.log(JSON.stringify(i,null,2))}catch(a){let c=a instanceof Error?a.message:String(a);throw Me.error(`\u274C Failed to write SARIF report to ${o}: ${c}`),new Error(`Failed to write SARIF report: ${c}`)}break}case"github-actions":{Fm(e,s,r.severityCounts,r.totalResources);break}default:m4(e,r);break}}});var Lm,A4=D(()=>{"use strict";Lm=(t,e,s,n)=>{let r=0,i=0,o={CRITICAL:0,HIGH:0,MEDIUM:0,LOW:0},a={"Operational Excellence":0,Security:0,"Cost Optimization":0,Reliability:0,"Performance Efficiency":0,Sustainability:0};for(let l in t){let d=[...t[l].sources.cdkInsights?.issues??[],...t[l].sources.cdkNag?.issues??[]],p=!s||s.has(l);d.length>0&&p&&i++,r+=d.length;for(let f of d)o[f.severity]+=1,a[f.wafPillar]+=1}let c=e,u=c>0?Number.parseFloat((i/c*100).toFixed(1)):0;return{totalResources:c,resourcesWithIssues:i,percentWithIssues:u,totalIssues:r,severityCounts:o,wafIssues:a,generatedBy:"cdk-insights",generatedAt:new Date().toISOString(),...n?{aiSkippedReason:n}:{}}}});var w4,E4,R4=D(()=>{"use strict";w4=oe(require("node:crypto")),E4=t=>w4.createHash("sha256").update(JSON.stringify(t)).digest("hex")});var Om,lte,dte,KS,VS=D(()=>{"use strict";Om=(t,e)=>e.endsWith("*")?t.startsWith(e.slice(0,-1)):t===e,lte=(t,e)=>{if(!t)return!1;let s=t.startsWith("/")?t.slice(1):t,n=e.startsWith("/")?e.slice(1):e;return n?s===n||s.startsWith(`${n}/`):!0},dte=(t,e,s)=>!t.ruleId||s.length===0||e.length===0?!1:s.some(n=>n.ruleId===t.ruleId&&e.some(r=>lte(r,n.constructPath))),KS=(t,e,s)=>{let{ignoreRules:n=[],ignorePaths:r=[],acknowledgements:i=[]}=s;return n.length===0&&r.length===0&&i.length===0?!1:r.some(a=>e.some(c=>Om(c,a)))||t.ruleId&&n.some(c=>Om(t.ruleId,c))?!0:dte(t,e,i)}});var pte,fte,mte,hte,I4,k4=D(()=>{"use strict";pte=[/depends\s*on.*(?:not\s*(?:be\s*)?available|may\s*not\s*exist|circular)/i,/dependson.*relationship/i,/resource.*depends.*another.*resource/i,/dependency.*(?:not\s*)?(?:be\s*)?ready/i,/lacks?\s*(?:meaningful\s*)?tags?(?:\s*for)?/i,/missing.*tags?.*(?:metadata|identification)/i,/no\s*tags?\s*(?:defined|configured|specified)/i,/does\s*not\s*have\s*any\s*tags/i,/tags?.*(?:auditing|cost\s*allocation|management)/i,/\[redacted\].*(?:incomplete|invalid|malformed|missing)/i,/incomplete.*\[redacted\]/i,/placeholder.*value/i,/missing.*closing.*brace/i,/replac(?:e|ing).*\[redacted\]/i,/\[redacted\].*(?:should|could|must)\s*be/i,/trust.*policy.*any.*service.*\[redacted\]/i,/any.*service.*within.*account.*\[redacted\]/i,/cdk.*metadata.*exposed/i,/metadata.*cdk.*path/i,/nat\s*gateway.*(?:move|associated).*(?:private\s*subnet|public\s*subnet.*risk)/i,/move.*nat\s*gateway.*private/i,/eip.*not\s*associated.*(?:instance|resource)/i,/elastic\s*ip.*not.*(?:associated|utilized|being\s*used)/i,/userdata\s*(?:script\s*)?is\s*empty/i,/empty.*userdata/i,/routetable.*(?:tags?|metadata)/i,/iam.*(?:policy|role).*(?:grants?|has).*(?:sts:assumerole|administratoraccess).*(?:overly\s*)?permissive/i,/inline\s*policy\s*grants?\s*unrestricted\s*access\s*to\s*all/i,/subnet.*mappubliciponlaunch.*(?:true|set)/i,/mappubliciponlaunch.*(?:expose|public\s*ip|internet)/i,/instances.*launched.*subnet.*public\s*ip/i],fte=[/tags?/i,/naming\s*convention/i,/resource\s*name.*not.*descriptive/i,/lacks?\s*description/i,/missing\s*description/i,/default\s*iam\s*role.*(?:broad|permissive)/i,/security\s*group.*(?:all\s*outbound|all\s*egress|unrestricted\s*egress)/i,/allows?\s*all\s*outbound\s*traffic/i],mte=t=>pte.some(e=>e.test(t)),hte=t=>fte.some(e=>e.test(t)),I4=(t,e=!1)=>t.filter(s=>{let n=s.issue||"";return!(mte(n)||e&&hte(n))})});var _4,F4=D(()=>{"use strict";dt();xl();k4();_4=({staticRecommendations:t,aiRecommendations:e,recommendationMap:s,ruleFilter:n,filterIssuesByRule:r,_displayNameMap:i={}})=>{let o={...s};for(let[d,{issues:p}]of Object.entries(t))o[d]&&(o[d].sources||(o[d].sources={cdkInsights:{issues:[]},cdkNag:{issues:[]}}),o[d].sources.cdkInsights||(o[d].sources.cdkInsights={issues:[]}),o[d].sources.cdkInsights.issues.push(...p));let a=0,c=0,u=0,l=0;for(let[d,p]of Object.entries(e)){if(!p||!Array.isArray(p.issues)){Me.warn(`\u26A0\uFE0F No AI issues for resource '${d}', skipping.`);continue}let f=d;if(!o[f]){Me.warn(`\u26A0\uFE0F AI recommendations for unknown resource '${f}', skipping enrichment.`);continue}let m=o[f],g=n.length>0?r(p.issues,n):p.issues,y=I4(g,m.isGenerated).map(C=>{switch(C.severity||(Me.debug(`AI recommendation missing severity for resource '${f}', defaulting to MEDIUM`),C.severity="MEDIUM"),C.severity.toUpperCase()==="CRITICAL"&&(Me.debug(`Capping AI finding from CRITICAL \u2192 HIGH for resource '${f}' (AI findings are advisory)`),C.severity="HIGH"),C.severity.toUpperCase()){case"CRITICAL":a++;break;case"HIGH":c++;break;case"MEDIUM":u++;break;case"LOW":l++;break;default:Me.warn(`\u26A0\uFE0F Unknown severity '${C.severity}' for resource '${f}', defaulting to MEDIUM`),C.severity="MEDIUM",u++;break}return{resourceName:C.resourceName||m.resourceName,resourceId:f,friendlyName:m.friendlyName,displayName:m.displayName,locationHint:C.locationHint||m.locationHint,constructPath:m.cdkPath,githubUrl:m.githubUrl,docUrl:m.docUrl,issue:C.issue||"AI analysis issue",recommendation:C.recommendation||"No specific recommendation provided",severity:C.severity,wafPillar:(()=>{if(C.wafPillar)switch(C.wafPillar.toLowerCase().trim()){case"security":return"Security";case"operational excellence":return"Operational Excellence";case"cost optimization":return"Cost Optimization";case"reliability":return"Reliability";case"performance efficiency":return"Performance Efficiency";case"sustainability":return"Sustainability";default:return"Security"}return"Security"})(),codeSnippet:C.codeSnippet||"",foundBy:C.foundBy??"cdkInsights"}}),b=vm(y,m.cdkPath);m.sources||(m.sources={cdkInsights:{issues:[]},cdkNag:{issues:[]}}),m.sources.cdkInsights||(m.sources.cdkInsights={issues:[]}),m.sources.cdkInsights.issues.push(...b)}return{updatedMap:o,criticalCount:a,highCount:c,mediumCount:u,lowCount:l}}});var Mm,ZS,gte,yte,YS=D(()=>{"use strict";Mm=t=>{if(!t||t.length===0)return 0;let e=t.length,s=new Map;for(let r of t)s.set(r,(s.get(r)||0)+1);let n=0;for(let r of s.values()){let i=r/e;n-=i*Math.log2(i)}return n},ZS=(t,e=!1)=>{if(t.length<16||gte(t)||Mm(t)<(e?4:4.5))return!1;let r=/[A-Z]/.test(t),i=/[a-z]/.test(t),o=/[0-9]/.test(t),a=/[^A-Za-z0-9]/.test(t),c=[r,i,o,a].filter(Boolean).length;return e?c>=1:c>=2},gte=t=>{if(/^https?:\/\//i.test(t)||/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^arn:aws[a-z-]*:[a-z0-9-]+:[a-z0-9-]*:\d*:/.test(t)||/^(\/|\.\/|\.\.\/|[A-Za-z]:\\)/.test(t)||/^s3:\/\/[a-z0-9.-]+\//.test(t)||/^[A-Za-z][A-Za-z0-9]*(DefaultPolicy|DefaultRole|ServiceRole|EventsRole|ExecutionRole|LogRetention|LambdaFunction|Handler|Function|Role|Policy)[A-F0-9]{8,}$/.test(t)||/^sha256:[a-f0-9]{64}$/.test(t)||/^[a-f0-9]{40}$/.test(t)||/^Z[A-Z0-9]{14,22}$/.test(t)||/^[a-z]{2}-[a-z]+-\d_[A-Za-z0-9]{9,}$/.test(t)||/^(vpc|subnet|sg|igw|nat|rtb|acl|eni|i|ami|vol|snap|eipalloc)-[a-f0-9]{8,17}$/.test(t)||/^E[A-Z0-9]{13}$/.test(t))return!0;if(/^[A-Za-z0-9+/]{4,}={0,2}$/.test(t)){let e=new Set(t).size;if(t.length>50&&e<10)return!0}return!!yte(t)},yte=t=>{let e=t.length;for(let s=1;s<=e/2;s++)if(t.slice(0,s).repeat(Math.ceil(e/s)).slice(0,e)===t)return!0;return!1}});var JS,QS,xte,bte,Ste,vte,T4,P4,XS,ev,tv,sv,Bm,nv,rv=D(()=>{"use strict";JS=[/api[_-]?key/i,/secret[_-]?key/i,/^password$/i,/^passwd$/i,/credential/i,/private[_-]?key/i,/access[_-]?key/i,/auth[_-]?token/i,/bearer[_-]?token/i,/refresh[_-]?token/i,/client[_-]?secret/i,/app[_-]?secret/i,/secret[_-]?value/i,/aws[_-]?secret/i,/aws[_-]?access[_-]?key/i,/aws[_-]?session[_-]?token/i,/db[_-]?password/i,/database[_-]?password/i,/master[_-]?password/i,/master[_-]?user[_-]?password/i,/admin[_-]?password/i,/root[_-]?password/i,/connection[_-]?string/i,/stripe[_-]?key/i,/stripe[_-]?secret/i,/github[_-]?token/i,/gitlab[_-]?token/i,/slack[_-]?token/i,/slack[_-]?webhook/i,/discord[_-]?token/i,/twilio[_-]?token/i,/sendgrid[_-]?key/i,/mailgun[_-]?key/i,/datadog[_-]?key/i,/new[_-]?relic[_-]?key/i,/sentry[_-]?dsn/i,/webhook[_-]?secret/i,/signing[_-]?key/i,/signing[_-]?secret/i,/encryption[_-]?key/i,/jwt[_-]?secret/i,/hmac[_-]?key/i,/ssh[_-]?key/i,/ssh[_-]?private/i,/pem[_-]?key/i,/rsa[_-]?key/i],QS=[/^A[BGIK-Z][A-Z]{2}[0-9A-Z]{16}$/,/^[A-Za-z0-9/+=]{40}$/,/-----BEGIN (RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/,/-----BEGIN PGP PRIVATE KEY BLOCK-----/,/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,/^gh[pousr]_[A-Za-z0-9]{36,}$/,/^[srp]k_(live|test)_[A-Za-z0-9]{24,}$/,/^xox[bpas]-[A-Za-z0-9-]+$/,/^SK[a-f0-9]{32}$/i,/^SG\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/],xte=[/\{\{resolve:secretsmanager:/,/{{resolve:secretsmanager:/,/\{\{resolve:ssm:/,/{{resolve:ssm:/,/\{\{resolve:ssm-secure:/,/{{resolve:ssm-secure:/,/^\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+(\/[a-zA-Z0-9_.-]+)+$/,/!Ref\s+\w+/,/!GetAtt\s+[\w.]+/,/!Sub\s+/,/\$\{[\w:.]+\}/,/\$\{Token\[/,/\[\[token:/i,/\${Token\[TOKEN\.\d+\]\}/,/^arn:aws[a-z-]*:[a-z0-9-]+:[a-z0-9-]*:\d*:/],bte=[/^<[^>]+>$/,/^CHANGE[_-]?ME$/i,/^REPLACE[_-]?ME$/i,/^TODO$/i,/^TODO:/i,/^FIXME$/i,/^XXX$/i,/^YOUR[_-]/i,/^INSERT[_-]/i,/^ENTER[_-]/i,/^\*+$/,/^x+$/i,/^\s*$/,/^default$/i,/^example$/i,/^sample$/i,/^test$/i,/^demo$/i,/^dummy$/i,/^fake$/i,/^mock$/i,/^placeholder$/i],Ste=[/^Description$/i,/^AlarmDescription$/i,/^Comment$/i,/^Label$/i,/^Summary$/i,/^DisplayName$/i,/^Name$/i,/^PolicyName$/i,/^RoleName$/i,/^FunctionName$/i,/^QueueName$/i,/^TopicName$/i,/^BucketName$/i,/^TableName$/i,/^StreamName$/i,/^LogGroupName$/i,/^ParameterName$/i,/^SecretName$/i,/^StateMachineName$/i,/^RuleName$/i,/^AliasName$/i,/^StackName$/i,/^GroupName$/i,/^UserName$/i,/^PolicyDocument$/i,/^ClientId$/i,/^UserPoolClientId$/i,/^UserPoolId$/i,/^IdentityPoolId$/i,/^DistributionId$/i,/^HostedZoneId$/i,/^CertificateArn$/i,/^TopicArn$/i,/^QueueArn$/i,/^FunctionArn$/i,/^Arn$/i,/^EventPattern$/i,/^Definition$/i,/^DefinitionString$/i,/^Template$/i,/^TemplateURL$/i,/^TemplateBody$/i,/^EventSourceName$/i,/^PartnerEventSource$/i],vte=[/(?:^|\.)Targets\[\d+\]\.Input$/,/(?:^|\.)Create$/,/(?:^|\.)Update$/,/(?:^|\.)Delete$/,/(?:^|\.)DefinitionString$/,/(?:^|\.)Code\.ZipFile$/,/(?:^|\.)Statement\[\d+\]\.Resource$/,/(?:^|\.)Statement\[\d+\]\.Resource\[\d+\]$/,/(?:^|\.)Statement\[\d+\]\.Sid$/],T4=t=>Ste.some(e=>e.test(t)),P4=t=>vte.some(e=>e.test(t)),XS=t=>JS.some(e=>e.test(t)),ev=t=>QS.some(e=>e.test(t)),tv=t=>xte.some(e=>e.test(t)),sv=t=>bte.some(e=>e.test(t)),Bm=t=>{if(typeof t!="object"||t===null)return!1;let e=["Ref","Fn::GetAtt","Fn::Sub","Fn::Join","Fn::ImportValue","Fn::If","Fn::Select","Fn::Split","Fn::Base64","Fn::Cidr","Fn::FindInMap","Fn::GetAZs","Fn::Transform"],s=Object.keys(t);return s.length===1&&e.includes(s[0])},nv=t=>{let e=[{patterns:[/api[_-]?key/i,/access[_-]?key/i],category:"api_key"},{patterns:[/password/i,/passwd/i],category:"password"},{patterns:[/private[_-]?key/i,/ssh[_-]?key/i,/pem[_-]?key/i,/rsa[_-]?key/i],category:"private_key"},{patterns:[/aws[_-]?secret/i,/aws[_-]?access/i],category:"aws_credentials"},{patterns:[/token/i,/bearer/i],category:"token"},{patterns:[/secret/i,/credential/i],category:"secret"},{patterns:[/connection[_-]?string/i,/database/i,/db[_-]/i],category:"database"},{patterns:[/webhook/i,/signing/i,/encryption/i,/hmac/i,/jwt/i],category:"encryption_key"}];for(let{patterns:s,category:n}of e)if(s.some(r=>r.test(t)))return n;return"secret"}});var Il,kl,iv=D(()=>{"use strict";Il=t=>{let e={api_key:`Use AWS Secrets Manager to store API keys securely:
|
|
301
301
|
|
|
302
302
|
// CDK TypeScript example:
|
|
@@ -458,7 +458,7 @@ See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html`},kl
|
|
|
458
458
|
`,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 d5=M((OTe,l5)=>{"use strict";var Rre=ch(),{MAX_LENGTH:a5,CHAR_BACKSLASH:Zv,CHAR_BACKTICK:Ire,CHAR_COMMA:kre,CHAR_DOT:_re,CHAR_LEFT_PARENTHESES:Fre,CHAR_RIGHT_PARENTHESES:Tre,CHAR_LEFT_CURLY_BRACE:Pre,CHAR_RIGHT_CURLY_BRACE:Lre,CHAR_LEFT_SQUARE_BRACKET:c5,CHAR_RIGHT_SQUARE_BRACKET:u5,CHAR_DOUBLE_QUOTE:Ore,CHAR_SINGLE_QUOTE:Mre,CHAR_NO_BREAK_SPACE:Bre,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Nre}=o5(),$re=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let s=e||{},n=typeof s.maxLength=="number"?Math.min(a5,s.maxLength):a5;if(t.length>n)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${n})`);let r={type:"root",input:t,nodes:[]},i=[r],o=r,a=r,c=0,u=t.length,l=0,d=0,p,f=()=>t[l++],m=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(m({type:"bos"});l<u;)if(o=i[i.length-1],p=f(),!(p===Nre||p===Bre)){if(p===Zv){m({type:"text",value:(e.keepEscaping?p:"")+f()});continue}if(p===u5){m({type:"text",value:"\\"+p});continue}if(p===c5){c++;let g;for(;l<u&&(g=f());){if(p+=g,g===c5){c++;continue}if(g===Zv){p+=f();continue}if(g===u5&&(c--,c===0))break}m({type:"text",value:p});continue}if(p===Fre){o=m({type:"paren",nodes:[]}),i.push(o),m({type:"text",value:p});continue}if(p===Tre){if(o.type!=="paren"){m({type:"text",value:p});continue}o=i.pop(),m({type:"text",value:p}),o=i[i.length-1];continue}if(p===Ore||p===Mre||p===Ire){let g=p,h;for(e.keepQuotes!==!0&&(p="");l<u&&(h=f());){if(h===Zv){p+=h+f();continue}if(h===g){e.keepQuotes===!0&&(p+=h);break}p+=h}m({type:"text",value:p});continue}if(p===Pre){d++;let h={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:d,commas:0,ranges:0,nodes:[]};o=m(h),i.push(o),m({type:"open",value:p});continue}if(p===Lre){if(o.type!=="brace"){m({type:"text",value:p});continue}let g="close";o=i.pop(),o.close=!0,m({type:g,value:p}),d--,o=i[i.length-1];continue}if(p===kre&&d>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Rre(o)}]}m({type:"comma",value:p}),o.commas++;continue}if(p===_re&&d>0&&o.commas===0){let g=o.nodes;if(d===0||g.length===0){m({type:"text",value:p});continue}if(a.type==="dot"){if(o.range=[],a.value+=p,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let h=g[g.length-1];h.value+=a.value+p,a=h,o.ranges--;continue}m({type:"dot",value:p});continue}m({type:"text",value:p})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(y=>{y.nodes||(y.type==="open"&&(y.isOpen=!0),y.type==="close"&&(y.isClose=!0),y.nodes||(y.type="text"),y.invalid=!0)});let g=i[i.length-1],h=g.nodes.indexOf(o);g.nodes.splice(h,1,...o.nodes)}while(i.length>0);return m({type:"eos"}),r};l5.exports=$re});var m5=M((MTe,f5)=>{"use strict";var p5=ch(),Wre=t5(),jre=r5(),Ure=d5(),sn=(t,e={})=>{let s=[];if(Array.isArray(t))for(let n of t){let r=sn.create(n,e);Array.isArray(r)?s.push(...r):s.push(r)}else s=[].concat(sn.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(s=[...new Set(s)]),s};sn.parse=(t,e={})=>Ure(t,e);sn.stringify=(t,e={})=>p5(typeof t=="string"?sn.parse(t,e):t,e);sn.compile=(t,e={})=>(typeof t=="string"&&(t=sn.parse(t,e)),Wre(t,e));sn.expand=(t,e={})=>{typeof t=="string"&&(t=sn.parse(t,e));let s=jre(t,e);return e.noempty===!0&&(s=s.filter(Boolean)),e.nodupes===!0&&(s=[...new Set(s)]),s};sn.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?sn.compile(t,e):sn.expand(t,e);f5.exports=sn});var h5=M((BTe,Hre)=>{Hre.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 y5=M((NTe,g5)=>{g5.exports=h5()});var b5=M(($Te,x5)=>{"use strict";var Gre=require("path"),zre=y5(),qre=new Set(zre);x5.exports=t=>qre.has(Gre.extname(t).slice(1).toLowerCase())});var dh=M(Be=>{"use strict";var{sep:Kre}=require("path"),{platform:Yv}=process,Vre=require("os");Be.EV_ALL="all";Be.EV_READY="ready";Be.EV_ADD="add";Be.EV_CHANGE="change";Be.EV_ADD_DIR="addDir";Be.EV_UNLINK="unlink";Be.EV_UNLINK_DIR="unlinkDir";Be.EV_RAW="raw";Be.EV_ERROR="error";Be.STR_DATA="data";Be.STR_END="end";Be.STR_CLOSE="close";Be.FSEVENT_CREATED="created";Be.FSEVENT_MODIFIED="modified";Be.FSEVENT_DELETED="deleted";Be.FSEVENT_MOVED="moved";Be.FSEVENT_CLONED="cloned";Be.FSEVENT_UNKNOWN="unknown";Be.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;Be.FSEVENT_TYPE_FILE="file";Be.FSEVENT_TYPE_DIRECTORY="directory";Be.FSEVENT_TYPE_SYMLINK="symlink";Be.KEY_LISTENERS="listeners";Be.KEY_ERR="errHandlers";Be.KEY_RAW="rawEmitters";Be.HANDLER_KEYS=[Be.KEY_LISTENERS,Be.KEY_ERR,Be.KEY_RAW];Be.DOT_SLASH=`.${Kre}`;Be.BACK_SLASH_RE=/\\/g;Be.DOUBLE_SLASH_RE=/\/\//;Be.SLASH_OR_BACK_SLASH_RE=/[/\\]/;Be.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;Be.REPLACER_RE=/^\.[/\\]/;Be.SLASH="/";Be.SLASH_SLASH="//";Be.BRACE_START="{";Be.BANG="!";Be.ONE_DOT=".";Be.TWO_DOTS="..";Be.STAR="*";Be.GLOBSTAR="**";Be.ROOT_GLOBSTAR="/**/*";Be.SLASH_GLOBSTAR="/**";Be.DIR_SUFFIX="Dir";Be.ANYMATCH_OPTS={dot:!0};Be.STRING_TYPE="string";Be.FUNCTION_TYPE="function";Be.EMPTY_STR="";Be.EMPTY_FN=()=>{};Be.IDENTITY_FN=t=>t;Be.isWindows=Yv==="win32";Be.isMacos=Yv==="darwin";Be.isLinux=Yv==="linux";Be.isIBMi=Vre.type()==="OS400"});var w5=M((jTe,A5)=>{"use strict";var Jr=require("fs"),ls=require("path"),{promisify:Ql}=require("util"),Zre=b5(),{isWindows:Yre,isLinux:Jre,EMPTY_FN:Qre,EMPTY_STR:Xre,KEY_LISTENERS:Hc,KEY_ERR:Jv,KEY_RAW:Zl,HANDLER_KEYS:eie,EV_CHANGE:fh,EV_ADD:ph,EV_ADD_DIR:tie,EV_ERROR:v5,STR_DATA:sie,STR_END:nie,BRACE_START:rie,STAR:iie}=dh(),oie="watch",aie=Ql(Jr.open),C5=Ql(Jr.stat),cie=Ql(Jr.lstat),uie=Ql(Jr.close),Qv=Ql(Jr.realpath),lie={lstat:cie,stat:C5},eC=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Yl=(t,e,s)=>{let n=t[e];n instanceof Set||(t[e]=n=new Set([n])),n.add(s)},die=t=>e=>{let s=t[e];s instanceof Set?s.clear():delete t[e]},Jl=(t,e,s)=>{let n=t[e];n instanceof Set?n.delete(s):n===s&&delete t[e]},D5=t=>t instanceof Set?t.size===0:!t,mh=new Map;function S5(t,e,s,n,r){let i=(o,a)=>{s(t),r(o,a,{watchedPath:t}),a&&t!==a&&hh(ls.resolve(t,a),Hc,ls.join(t,a))};try{return Jr.watch(t,e,i)}catch(o){n(o)}}var hh=(t,e,s,n,r)=>{let i=mh.get(t);i&&eC(i[e],o=>{o(s,n,r)})},pie=(t,e,s,n)=>{let{listener:r,errHandler:i,rawEmitter:o}=n,a=mh.get(e),c;if(!s.persistent)return c=S5(t,s,r,i,o),c.close.bind(c);if(a)Yl(a,Hc,r),Yl(a,Jv,i),Yl(a,Zl,o);else{if(c=S5(t,s,hh.bind(null,e,Hc),i,hh.bind(null,e,Zl)),!c)return;c.on(v5,async u=>{let l=hh.bind(null,e,Jv);if(a.watcherUnusable=!0,Yre&&u.code==="EPERM")try{let d=await aie(t,"r");await uie(d),l(u)}catch{}else l(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:c},mh.set(e,a)}return()=>{Jl(a,Hc,r),Jl(a,Jv,i),Jl(a,Zl,o),D5(a.listeners)&&(a.watcher.close(),mh.delete(e),eie.forEach(die(a)),a.watcher=void 0,Object.freeze(a))}},Xv=new Map,fie=(t,e,s,n)=>{let{listener:r,rawEmitter:i}=n,o=Xv.get(e),a=new Set,c=new Set,u=o&&o.options;return u&&(u.persistent<s.persistent||u.interval>s.interval)&&(a=o.listeners,c=o.rawEmitters,Jr.unwatchFile(e),o=void 0),o?(Yl(o,Hc,r),Yl(o,Zl,i)):(o={listeners:r,rawEmitters:i,options:s,watcher:Jr.watchFile(e,s,(l,d)=>{eC(o.rawEmitters,f=>{f(fh,e,{curr:l,prev:d})});let p=l.mtimeMs;(l.size!==d.size||p>d.mtimeMs||p===0)&&eC(o.listeners,f=>f(t,l))})},Xv.set(e,o)),()=>{Jl(o,Hc,r),Jl(o,Zl,i),D5(o.listeners)&&(Xv.delete(e),Jr.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},tC=class{constructor(e){this.fsw=e,this._boundHandleError=s=>e._handleError(s)}_watchWithNodeFs(e,s){let n=this.fsw.options,r=ls.dirname(e),i=ls.basename(e);this.fsw._getWatchedDir(r).add(i);let a=ls.resolve(e),c={persistent:n.persistent};s||(s=Qre);let u;return n.usePolling?(c.interval=n.enableBinaryInterval&&Zre(i)?n.binaryInterval:n.interval,u=fie(e,a,c,{listener:s,rawEmitter:this.fsw._emitRaw})):u=pie(e,a,c,{listener:s,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,s,n){if(this.fsw.closed)return;let r=ls.dirname(e),i=ls.basename(e),o=this.fsw._getWatchedDir(r),a=s;if(o.has(i))return;let c=async(l,d)=>{if(this.fsw._throttle(oie,e,5)){if(!d||d.mtimeMs===0)try{let p=await C5(e);if(this.fsw.closed)return;let f=p.atimeMs,m=p.mtimeMs;(!f||f<=m||m!==a.mtimeMs)&&this.fsw._emit(fh,e,p),Jre&&a.ino!==p.ino?(this.fsw._closeFile(l),a=p,this.fsw._addPathCloser(l,this._watchWithNodeFs(e,c))):a=p}catch{this.fsw._remove(r,i)}else if(o.has(i)){let p=d.atimeMs,f=d.mtimeMs;(!p||p<=f||f!==a.mtimeMs)&&this.fsw._emit(fh,e,d),a=d}}},u=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ph,e,0))return;this.fsw._emit(ph,e,s)}return u}async _handleSymlink(e,s,n,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(s);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Qv(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(fh,n,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(ph,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,s,n,r,i,o,a){if(e=ls.join(e,Xre),!n.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let c=this.fsw._getWatchedDir(n.path),u=new Set,l=this.fsw._readdirp(e,{fileFilter:d=>n.filterPath(d),directoryFilter:d=>n.filterDir(d),depth:0}).on(sie,async d=>{if(this.fsw.closed){l=void 0;return}let p=d.path,f=ls.join(e,p);if(u.add(p),!(d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,f,p))){if(this.fsw.closed){l=void 0;return}(p===r||!r&&!c.has(p))&&(this.fsw._incrReadyCount(),f=ls.join(i,ls.relative(i,f)),this._addToNodeFs(f,s,n,o+1))}}).on(v5,this._boundHandleError);return new Promise(d=>l.once(nie,()=>{if(this.fsw.closed){l=void 0;return}let p=a?a.clear():!1;d(),c.getChildren().filter(f=>f!==e&&!u.has(f)&&(!n.hasGlob||n.filterPath({fullPath:ls.resolve(e,f)}))).forEach(f=>{this.fsw._remove(e,f)}),l=void 0,p&&this._handleRead(e,!1,n,r,i,o,a)}))}async _handleDir(e,s,n,r,i,o,a){let c=this.fsw._getWatchedDir(ls.dirname(e)),u=c.has(ls.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(tie,e,s),c.add(ls.basename(e)),this.fsw._getWatchedDir(e);let l,d,p=this.fsw.options.depth;if((p==null||r<=p)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,n,o,i,e,r,l),this.fsw.closed))return;d=this._watchWithNodeFs(e,(f,m)=>{m&&m.mtimeMs===0||this._handleRead(f,!1,o,i,e,r,l)})}return d}async _addToNodeFs(e,s,n,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&n&&(a.hasGlob=n.hasGlob,a.globFilter=n.globFilter,a.filterPath=c=>n.filterPath(c),a.filterDir=c=>n.filterDir(c));try{let c=await lie[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let u=this.fsw.options.followSymlinks&&!e.includes(iie)&&!e.includes(rie),l;if(c.isDirectory()){let d=ls.resolve(e),p=u?await Qv(e):e;if(this.fsw.closed||(l=await this._handleDir(a.watchPath,c,s,r,i,a,p),this.fsw.closed))return;d!==p&&p!==void 0&&this.fsw._symlinkPaths.set(d,p)}else if(c.isSymbolicLink()){let d=u?await Qv(e):e;if(this.fsw.closed)return;let p=ls.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(ph,a.watchPath,c),l=await this._handleDir(p,c,s,r,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(ls.resolve(e),d)}else l=this._handleFile(a.watchPath,c,s);return o(),this.fsw._addPathCloser(e,l),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};A5.exports=tC});var T5=M((UTe,uC)=>{"use strict";var aC=require("fs"),ds=require("path"),{promisify:cC}=require("util"),Gc;try{Gc=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(Gc){let t=process.version.match(/v(\d+)\.(\d+)/);if(t&&t[1]&&t[2]){let e=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10);e===8&&s<16&&(Gc=void 0)}}var{EV_ADD:sC,EV_CHANGE:mie,EV_ADD_DIR:E5,EV_UNLINK:gh,EV_ERROR:hie,STR_DATA:gie,STR_END:yie,FSEVENT_CREATED:xie,FSEVENT_MODIFIED:bie,FSEVENT_DELETED:Sie,FSEVENT_MOVED:vie,FSEVENT_UNKNOWN:Cie,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Die,FSEVENT_TYPE_FILE:Aie,FSEVENT_TYPE_DIRECTORY:Xl,FSEVENT_TYPE_SYMLINK:F5,ROOT_GLOBSTAR:R5,DIR_SUFFIX:wie,DOT_SLASH:I5,FUNCTION_TYPE:nC,EMPTY_FN:Eie,IDENTITY_FN:Rie}=dh(),Iie=t=>isNaN(t)?{}:{depth:t},iC=cC(aC.stat),kie=cC(aC.lstat),k5=cC(aC.realpath),_ie={stat:iC,lstat:kie},ua=new Map,Fie=10,Tie=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Pie=(t,e)=>({stop:Gc.watch(t,e)});function Lie(t,e,s,n){let r=ds.extname(e)?ds.dirname(e):e,i=ds.dirname(r),o=ua.get(r);Oie(i)&&(r=i);let a=ds.resolve(t),c=a!==e,u=(d,p,f)=>{c&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+ds.sep))&&s(d,p,f)},l=!1;for(let d of ua.keys())if(e.indexOf(ds.resolve(d)+ds.sep)===0){r=d,o=ua.get(r),l=!0;break}return o||l?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:n,watcher:Pie(r,(d,p)=>{if(!o.listeners.size||p&Die)return;let f=Gc.getInfo(d,p);o.listeners.forEach(m=>{m(d,p,f)}),o.rawEmitter(f.event,d,f)})},ua.set(r,o)),()=>{let d=o.listeners;if(d.delete(u),!d.size&&(ua.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var Oie=t=>{let e=0;for(let s of ua.keys())if(s.indexOf(t)===0&&(e++,e>=Fie))return!0;return!1},Mie=()=>Gc&&ua.size<128,rC=(t,e)=>{let s=0;for(;!t.indexOf(e)&&(t=ds.dirname(t))!==e;)s++;return s},_5=(t,e)=>t.type===Xl&&e.isDirectory()||t.type===F5&&e.isSymbolicLink()||t.type===Aie&&e.isFile(),oC=class{constructor(e){this.fsw=e}checkIgnored(e,s){let n=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,s))return n.add(e),s&&s.isDirectory()&&n.add(e+R5),!0;n.delete(e),n.delete(e+R5)}addOrChange(e,s,n,r,i,o,a,c){let u=i.has(o)?mie:sC;this.handleEvent(u,e,s,n,r,i,o,a,c)}async checkExists(e,s,n,r,i,o,a,c){try{let u=await iC(e);if(this.fsw.closed)return;_5(a,u)?this.addOrChange(e,s,n,r,i,o,a,c):this.handleEvent(gh,e,s,n,r,i,o,a,c)}catch(u){u.code==="EACCES"?this.addOrChange(e,s,n,r,i,o,a,c):this.handleEvent(gh,e,s,n,r,i,o,a,c)}}handleEvent(e,s,n,r,i,o,a,c,u){if(!(this.fsw.closed||this.checkIgnored(s)))if(e===gh){let l=c.type===Xl;(l||o.has(a))&&this.fsw._remove(i,a,l)}else{if(e===sC){if(c.type===Xl&&this.fsw._getWatchedDir(s),c.type===F5&&u.followSymlinks){let d=u.depth===void 0?void 0:rC(n,r)+1;return this._addToFsEvents(s,!1,!0,d)}this.fsw._getWatchedDir(i).add(a)}let l=c.type===Xl?e+wie:e;this.fsw._emit(l,s),l===E5&&this._addToFsEvents(s,!1,!0)}}_watchWithFsEvents(e,s,n,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=Lie(e,s,async(c,u,l)=>{if(this.fsw.closed||i.depth!==void 0&&rC(c,s)>i.depth)return;let d=n(ds.join(e,ds.relative(e,c)));if(r&&!r(d))return;let p=ds.dirname(d),f=ds.basename(d),m=this.fsw._getWatchedDir(l.type===Xl?d:p);if(Tie.has(u)||l.event===Cie)if(typeof i.ignored===nC){let g;try{g=await iC(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,g))return;_5(l,g)?this.addOrChange(d,c,s,p,m,f,l,i):this.handleEvent(gh,d,c,s,p,m,f,l,i)}else this.checkExists(d,c,s,p,m,f,l,i);else switch(l.event){case xie:case bie:return this.addOrChange(d,c,s,p,m,f,l,i);case Sie:case vie:return this.checkExists(d,c,s,p,m,f,l,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,s,n,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(s))){this.fsw._symlinkPaths.set(s,!0),this.fsw._incrReadyCount();try{let i=await k5(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==I5?a=o.replace(i,e):o!==I5&&(a=ds.join(e,o)),n(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,s,n,r,i){let o=n(e),a=s.isDirectory(),c=this.fsw._getWatchedDir(ds.dirname(o)),u=ds.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(u)&&(c.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?E5:sC,o,s))}initWatch(e,s,n,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(n.watchPath,ds.resolve(e||n.watchPath),r,n.globFilter);this.fsw._addPathCloser(s,i)}async _addToFsEvents(e,s,n,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof s===nC?s:Rie,a=this.fsw._getWatchHelpers(e);try{let c=await _ie[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))throw null;if(c.isDirectory()){if(a.globFilter||this.emitAdd(o(e),c,o,i,n),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:u=>a.filterPath(u),directoryFilter:u=>a.filterDir(u),...Iie(i.depth-(r||0))}).on(gie,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let l=ds.join(a.watchPath,u.path),{fullPath:d}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let p=i.depth===void 0?void 0:rC(l,ds.resolve(a.watchPath))+1;this._handleFsEventsSymlink(l,d,o,p)}else this.emitAdd(l,u.stats,o,i,n)}).on(hie,Eie).on(yie,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,c,o,i,n),this.fsw._emitReady()}catch(c){(!c||this.fsw._handleError(c))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&n!==!0)if(typeof s===nC)this.initWatch(void 0,e,a,o);else{let c;try{c=await k5(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};uC.exports=oC;uC.exports.canUse=Mie});var H5=M(AC=>{"use strict";var{EventEmitter:Bie}=require("events"),CC=require("fs"),bt=require("path"),{promisify:$5}=require("util"),Nie=JB(),hC=EN().default,$ie=TN(),lC=Hv(),Wie=m5(),jie=jv(),Uie=w5(),P5=T5(),{EV_ALL:dC,EV_READY:Hie,EV_ADD:yh,EV_CHANGE:ed,EV_UNLINK:L5,EV_ADD_DIR:Gie,EV_UNLINK_DIR:zie,EV_RAW:qie,EV_ERROR:pC,STR_CLOSE:Kie,STR_END:Vie,BACK_SLASH_RE:Zie,DOUBLE_SLASH_RE:O5,SLASH_OR_BACK_SLASH_RE:Yie,DOT_RE:Jie,REPLACER_RE:Qie,SLASH:fC,SLASH_SLASH:Xie,BRACE_START:eoe,BANG:gC,ONE_DOT:W5,TWO_DOTS:toe,GLOBSTAR:soe,SLASH_GLOBSTAR:mC,ANYMATCH_OPTS:yC,STRING_TYPE:DC,FUNCTION_TYPE:noe,EMPTY_STR:xC,EMPTY_FN:roe,isWindows:ioe,isMacos:ooe,isIBMi:aoe}=dh(),coe=$5(CC.stat),uoe=$5(CC.readdir),bC=(t=[])=>Array.isArray(t)?t:[t],j5=(t,e=[])=>(t.forEach(s=>{Array.isArray(s)?j5(s,e):e.push(s)}),e),M5=t=>{let e=j5(bC(t));if(!e.every(s=>typeof s===DC))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(U5)},B5=t=>{let e=t.replace(Zie,fC),s=!1;for(e.startsWith(Xie)&&(s=!0);e.match(O5);)e=e.replace(O5,fC);return s&&(e=fC+e),e},U5=t=>B5(bt.normalize(B5(t))),N5=(t=xC)=>e=>typeof e!==DC?e:U5(bt.isAbsolute(e)?e:bt.join(t,e)),loe=(t,e)=>bt.isAbsolute(t)?t:t.startsWith(gC)?gC+bt.join(e,t.slice(1)):bt.join(e,t),sr=(t,e)=>t[e]===void 0,SC=class{constructor(e,s){this.path=e,this._removeWatcher=s,this.items=new Set}add(e){let{items:s}=this;s&&e!==W5&&e!==toe&&s.add(e)}async remove(e){let{items:s}=this;if(!s||(s.delete(e),s.size>0))return;let n=this.path;try{await uoe(n)}catch{this._removeWatcher&&this._removeWatcher(bt.dirname(n),bt.basename(n))}}has(e){let{items:s}=this;if(s)return s.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},doe="stat",poe="lstat",vC=class{constructor(e,s,n,r){this.fsw=r,this.path=e=e.replace(Qie,xC),this.watchPath=s,this.fullWatchPath=bt.resolve(s),this.hasGlob=s!==e,e===xC&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&n?void 0:!1,this.globFilter=this.hasGlob?hC(e,void 0,yC):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=n,this.statMethod=n?doe:poe}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return bt.join(this.watchPath,bt.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:s}=e;if(s&&s.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===noe?this.globFilter(n):!0)&&this.fsw._isntIgnored(n,s)&&this.fsw._hasReadPermissions(s)}getDirParts(e){if(!this.hasGlob)return[];let s=[];return(e.includes(eoe)?Wie.expand(e):[e]).forEach(r=>{s.push(bt.relative(this.watchPath,r).split(Yie))}),s}filterDir(e){if(this.hasGlob){let s=this.getDirParts(this.checkGlobSymlink(e)),n=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===soe&&(n=!0),n||!s[0][o]||hC(i,s[0][o],yC))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},xh=class extends Bie{constructor(e){super();let s={};e&&Object.assign(s,e),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=!1,sr(s,"persistent")&&(s.persistent=!0),sr(s,"ignoreInitial")&&(s.ignoreInitial=!1),sr(s,"ignorePermissionErrors")&&(s.ignorePermissionErrors=!1),sr(s,"interval")&&(s.interval=100),sr(s,"binaryInterval")&&(s.binaryInterval=300),sr(s,"disableGlobbing")&&(s.disableGlobbing=!1),s.enableBinaryInterval=s.binaryInterval!==s.interval,sr(s,"useFsEvents")&&(s.useFsEvents=!s.usePolling),P5.canUse()||(s.useFsEvents=!1),sr(s,"usePolling")&&!s.useFsEvents&&(s.usePolling=ooe),aoe&&(s.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let c=r.toLowerCase();c==="false"||c==="0"?s.usePolling=!1:c==="true"||c==="1"?s.usePolling=!0:s.usePolling=!!c}let i=process.env.CHOKIDAR_INTERVAL;i&&(s.interval=Number.parseInt(i,10)),sr(s,"atomic")&&(s.atomic=!s.usePolling&&!s.useFsEvents),s.atomic&&(this._pendingUnlinks=new Map),sr(s,"followSymlinks")&&(s.followSymlinks=!0),sr(s,"awaitWriteFinish")&&(s.awaitWriteFinish=!1),s.awaitWriteFinish===!0&&(s.awaitWriteFinish={});let o=s.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),s.ignored&&(s.ignored=bC(s.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=roe,this._readyEmitted=!0,process.nextTick(()=>this.emit(Hie)))},this._emitRaw=(...c)=>this.emit(qie,...c),this._readyEmitted=!1,this.options=s,s.useFsEvents?this._fsEventsHandler=new P5(this):this._nodeFsHandler=new Uie(this),Object.freeze(s)}add(e,s,n){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=M5(e);return r&&(o=o.map(a=>{let c=loe(a,r);return i||!lC(a)?c:jie(c)})),o=o.filter(a=>a.startsWith(gC)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+mC),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,0,0,s);return c&&this._emitReady(),c})).then(a=>{this.closed||a.filter(c=>c).forEach(c=>{this.add(bt.dirname(c),bt.basename(s||c))})})),this}unwatch(e){if(this.closed)return this;let s=M5(e),{cwd:n}=this.options;return s.forEach(r=>{!bt.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=bt.join(n,r)),r=bt.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+mC),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(s=>s.forEach(n=>{let r=n();r instanceof Promise&&e.push(r)})),this._streams.forEach(s=>s.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(s=>s.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(s=>{this[`_${s}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((s,n)=>{let r=this.options.cwd?bt.relative(this.options.cwd,n):n;e[r||W5]=s.getChildren().sort()}),e}emitWithAll(e,s){this.emit(...s),e!==pC&&this.emit(dC,...s)}async _emit(e,s,n,r,i){if(this.closed)return;let o=this.options;ioe&&(s=bt.normalize(s)),o.cwd&&(s=bt.relative(o.cwd,s));let a=[e,s];i!==void 0?a.push(n,r,i):r!==void 0?a.push(n,r):n!==void 0&&a.push(n);let c=o.awaitWriteFinish,u;if(c&&(u=this._pendingWrites.get(s)))return u.lastChange=new Date,this;if(o.atomic){if(e===L5)return this._pendingUnlinks.set(s,a),setTimeout(()=>{this._pendingUnlinks.forEach((l,d)=>{this.emit(...l),this.emit(dC,...l),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===yh&&this._pendingUnlinks.has(s)&&(e=a[0]=ed,this._pendingUnlinks.delete(s))}if(c&&(e===yh||e===ed)&&this._readyEmitted){let l=(d,p)=>{d?(e=a[0]=pC,a[1]=d,this.emitWithAll(e,a)):p&&(a.length>2?a[2]=p:a.push(p),this.emitWithAll(e,a))};return this._awaitWriteFinish(s,c.stabilityThreshold,e,l),this}if(e===ed&&!this._throttle(ed,s,50))return this;if(o.alwaysStat&&n===void 0&&(e===yh||e===Gie||e===ed)){let l=o.cwd?bt.join(o.cwd,s):s,d;try{d=await coe(l)}catch{}if(!d||this.closed)return;a.push(d)}return this.emitWithAll(e,a),this}_handleError(e){let s=e&&e.code;return e&&s!=="ENOENT"&&s!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||s!=="EPERM"&&s!=="EACCES")&&this.emit(pC,e),e||this.closed}_throttle(e,s,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(s);if(i)return i.count++,!1;let o,a=()=>{let u=r.get(s),l=u?u.count:0;return r.delete(s),clearTimeout(o),u&&clearTimeout(u.timeoutObject),l};o=setTimeout(a,n);let c={timeoutObject:o,clear:a,count:0};return r.set(s,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,s,n,r){let i,o=e;this.options.cwd&&!bt.isAbsolute(e)&&(o=bt.join(this.options.cwd,e));let a=new Date,c=u=>{CC.stat(o,(l,d)=>{if(l||!this._pendingWrites.has(e)){l&&l.code!=="ENOENT"&&r(l);return}let p=Number(new Date);u&&d.size!==u.size&&(this._pendingWrites.get(e).lastChange=p);let f=this._pendingWrites.get(e);p-f.lastChange>=s?(this._pendingWrites.delete(e),r(void 0,d)):i=setTimeout(c,this.options.awaitWriteFinish.pollInterval,d)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),n)}),i=setTimeout(c,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,s){if(this.options.atomic&&Jie.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,r=this.options.ignored,i=r&&r.map(N5(n)),o=bC(i).filter(c=>typeof c===DC&&!lC(c)).map(c=>c+mC),a=this._getGlobIgnored().map(N5(n)).concat(i,o);this._userIgnored=hC(a,void 0,yC)}return this._userIgnored([e,s])}_isntIgnored(e,s){return!this._isIgnored(e,s)}_getWatchHelpers(e,s){let n=s||this.options.disableGlobbing||!lC(e)?e:$ie(e),r=this.options.followSymlinks;return new vC(e,n,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let s=bt.resolve(e);return this._watched.has(s)||this._watched.set(s,new SC(s,this._boundRemove)),this._watched.get(s)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let n=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(n.toString(8)[0],10))}_remove(e,s,n){let r=bt.join(e,s),i=bt.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,s,!0),this._getWatchedDir(r).getChildren().forEach(p=>this._remove(r,p));let c=this._getWatchedDir(e),u=c.has(s);c.remove(s),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let l=r;if(this.options.cwd&&(l=bt.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===yh)return;this._watched.delete(r),this._watched.delete(i);let d=n?zie:L5;u&&!this._isIgnored(r)&&this._emit(d,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let s=bt.dirname(e);this._getWatchedDir(s).remove(bt.basename(e))}_closeFile(e){let s=this._closers.get(e);s&&(s.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,s){if(!s)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(s)}_readdirp(e,s){if(this.closed)return;let n={type:dC,alwaysStat:!0,lstat:!0,...s},r=Nie(e,n);return this._streams.add(r),r.once(Kie,()=>{r=void 0}),r.once(Vie,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};AC.FSWatcher=xh;var foe=(t,e)=>{let s=new xh(e);return s.add(t),s};AC.watch=foe});var z5,Sr,moe,hoe,G5,goe,q5,K5=D(()=>{"use strict";z5=oe(require("node:fs")),Sr=oe(require("node:path")),moe=["**/.*","**/.*/**","**/node_modules/**"],hoe="cdk.out",G5=t=>t===void 0?[]:Array.isArray(t)?t:[t],goe=t=>{try{let e=z5.readFileSync(t,"utf-8");return JSON.parse(e)??{}}catch{return{}}},q5=(t=process.cwd())=>{let e=t,s=goe(Sr.join(e,"cdk.json")),n=G5(s.watch?.include),r=G5(s.watch?.exclude),i=s.output??hoe,o=n.length>0?n:[e],a=[...r,...moe],c=Sr.relative(e,Sr.resolve(e,i));return c.length>0&&!c.startsWith(`..${Sr.sep}`)&&!Sr.isAbsolute(c)&&a.push(`${c}/**`),{include:o,exclude:a,rootDir:e}}});var Y5,J5,yoe,Q5,X5,xoe,boe,Soe,V5,Z5,voe,Coe,e$,t$=D(()=>{"use strict";_m();Qn();Y5={critical:0,high:0,medium:0,low:0,total:0},J5={counts:{...Y5},byFingerprint:new Map},yoe={CRITICAL:"critical",HIGH:"high",MEDIUM:"medium",LOW:"low"},Q5=t=>{let e={counts:{...Y5},byFingerprint:new Map};if(!t)return e;for(let s of Object.values(t)){let n=[...s.sources?.cdkInsights?.issues??[],...s.sources?.cdkNag?.issues??[]];for(let r of n){let i=r.stackName??"_",o=ia(i,s,r);if(e.byFingerprint.has(o))continue;e.byFingerprint.set(o,{issue:r,group:s,stackName:i}),e.counts.total+=1;let a=yoe[r.severity];a&&(e.counts[a]+=1)}}return e},X5=(t,e)=>{let s=[],n=[];for(let[o,a]of e.byFingerprint)t.byFingerprint.has(o)||s.push({fingerprint:o,...a});for(let[o,a]of t.byFingerprint)e.byFingerprint.has(o)||n.push({fingerprint:o,...a});let r={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3},i=(o,a)=>{let c=r[o.issue.severity]-r[a.issue.severity];return c!==0?c:o.fingerprint.localeCompare(a.fingerprint)};return s.sort(i),n.sort(i),{added:s,removed:n}},xoe=t=>t==="CRITICAL"?de.severity.critical:t==="HIGH"?de.severity.high:t==="MEDIUM"?de.severity.medium:de.severity.low,boe=(t,e=70)=>{let s=t.replace(/\s+/g," ").trim();return s.length>e?`${s.slice(0,e-1)}\u2026`:s},Soe=t=>{let e=t.stackName!=="_"?t.stackName:"",s=t.group.cdkPath||t.group.friendlyName||t.group.resourceId||"?";return e&&!s.startsWith(`${e}/`)&&!s.includes("/")?`${e}/${s}`:s},V5=(t,e)=>{let n=xoe(e.issue.severity)(e.issue.severity.padEnd(8)),r=de.text(Soe(e)),i=de.comment(boe(e.issue.issue));return` ${t==="+"?de.error("+"):de.success("-")} ${n} ${r} ${i}`},Z5=8,voe=t=>t.toTimeString().slice(0,8),Coe=t=>t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,e$=({state:t,diff:e,trigger:s,elapsedMs:n,timestamp:r,isFirstRun:i,watchPathCount:o})=>{let a=[],c=de.comment("\u2500".repeat(72));a.push(c);let u=[de.primary("\u{1F440} CDK Insights \xB7 watch"),de.comment(voe(r)),de.comment(Coe(n)),de.text(`triggered: ${de.accent(s)}`)].join(de.comment(" \xB7 "));a.push(` ${u}`),a.push("");let{counts:l}=t,d=[`${de.severity.critical(`${_t.critical} CRITICAL`)} ${de.text(String(l.critical).padStart(3))}`,`${de.severity.high(`${_t.high} HIGH`)} ${de.text(String(l.high).padStart(3))}`,`${de.severity.medium(`${_t.medium} MEDIUM`)} ${de.text(String(l.medium).padStart(3))}`,`${de.severity.low(`${_t.low} LOW`)} ${de.text(String(l.low).padStart(3))}`].join(de.comment(" "));if(a.push(` ${d} ${de.comment("\xB7")} ${de.text(`total ${l.total}`)}`),a.push(""),i)a.push(de.comment(" Initial scan complete."));else if(e&&(e.added.length>0||e.removed.length>0)){a.push(de.text(` ${de.error(`+${e.added.length}`)} new \xB7 ${de.success(`-${e.removed.length}`)} resolved since last save:`));let f=e.added.slice(0,Z5);for(let g of f)a.push(V5("+",g));e.added.length>f.length&&a.push(de.comment(` \u2026and ${e.added.length-f.length} more added`));let m=e.removed.slice(0,Z5);for(let g of m)a.push(V5("-",g));e.removed.length>m.length&&a.push(de.comment(` \u2026and ${e.removed.length-m.length} more resolved`))}else a.push(de.comment(" No changes since last save."));a.push("");let p=[de.comment(`Watching ${o} pattern(s) \xB7 Ctrl+C to exit \xB7 --output table for full report`)].join("");return a.push(` ${p}`),a.push(c),a.join(`
|
|
459
459
|
`)}});var i$={};wh(i$,{runWatchLoop:()=>woe});var s$,n$,Doe,r$,Aoe,woe,o$=D(()=>{"use strict";s$=oe(require("node:path")),n$=oe(H5());K5();Qn();t$();EC();Doe=300,r$=t=>t.output!=="table"&&t.format!=="table",Aoe=t=>{let e=r$(t);return{...t,local:!0,github:!1,withIssue:!1,prComment:!1,writeBaseline:!1,diff:!1,failOnCritical:!1,output:e?"summary":"table",format:e?"summary":"table"}},woe=async t=>{let e=Aoe(t.config),s=r$(t.config),{include:n,exclude:r,rootDir:i}=q5(),o=null,a=!1,c=!1,u=J5,l=!0,d=async f=>{if(a){c=!0;return}a=!0;let m=Date.now();P.info(`\u{1F504} ${f}`);try{let g=await wC(e,t.fingerprint,t.authToken,t.licenseInfo,t.usageData,t.project,t.licenseKey,!0,void 0,void 0,void 0,s);if(s){let h=Q5(g?.recommendationMaps),y=l?void 0:X5(u,h),b=e$({state:h,diff:y,trigger:f,elapsedMs:Date.now()-m,timestamp:new Date,isFirstRun:l,watchPathCount:n.length});console.clear(),console.log(b),u=h,l=!1}else P.success(`\u2713 Done at ${new Date().toLocaleTimeString()}`)}catch(g){let h=g instanceof Error?g.message:String(g);P.error(`Run failed \u2014 keeping last good results. ${h.split(`
|
|
460
460
|
`)[0]}`)}finally{a=!1,c&&(c=!1,d("queued change(s)"))}};P.info(`\u{1F440} Watch mode \u2014 watching ${n.length} include pattern(s) under ${i}`),P.comment(" AI analysis disabled in watch mode. Press Ctrl+C to exit.");let p=n$.default.watch(n,{cwd:i,ignored:r,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await d("initial scan"),p.on("all",(f,m)=>{o&&clearTimeout(o),o=setTimeout(()=>{let g=s$.relative(i,m)||m;d(`${f} ${g}`)},Doe)}),p.on("error",f=>{P.error(`Watcher error: ${f instanceof Error?f.message:String(f)}`)}),await new Promise(f=>{let m=()=>{P.info(`
|
|
461
|
-
\u{1F44B} Stopping watcher.`),p.close().then(()=>f())};process.once("SIGINT",m),process.once("SIGTERM",m)})}});async function Roe(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await Ii({message:"Which stack would you like to analyze?",default:s,choices:e.map(c=>({name:c,value:c}))}),r=t.output||t.format||"table",i=await Ii({message:"Choose output format:",choices:[{name:"\u{1F4CA} Table (default) - Human-readable table with colors",value:"table"},{name:"\u{1F4C4} Markdown - GitHub-compatible markdown report",value:"markdown"},{name:"\u{1F527} JSON - Structured data for CI/CD integration",value:"json"},{name:"\u{1F4CB} Summary - Brief overview with counts",value:"summary"}],default:r}),o=t.services&&t.services.length>0?t.services:["All services"],a=await Vy({message:"Which AWS services would you like to analyze? (Use <space> to toggle, <enter> to confirm)",choices:[{name:"\u{1F50D} All services (recommended)",value:"All services",checked:o.includes("All services")},{name:"\u{1F510} IAM - Identity and Access Management",value:"IAM",checked:o.includes("IAM")},{name:"\u{1F4E6} S3 - Simple Storage Service",value:"S3",checked:o.includes("S3")},{name:"\u26A1 Lambda - Serverless Functions",value:"Lambda",checked:o.includes("Lambda")},{name:"\u{1F5C4}\uFE0F DynamoDB - NoSQL Database",value:"DynamoDB",checked:o.includes("DynamoDB")},{name:"\u{1F5C4}\uFE0F RDS - Relational Database",value:"RDS",checked:o.includes("RDS")},{name:"\u{1F5A5}\uFE0F EC2 - Virtual Machines",value:"EC2",checked:o.includes("EC2")},{name:"\u{1F4E2} SNS - Simple Notification Service",value:"SNS",checked:o.includes("SNS")},{name:"\u{1F4E8} SQS - Simple Queue Service",value:"SQS",checked:o.includes("SQS")},{name:"\u{1F504} Step Functions - Workflow Orchestration",value:"StepFunctions",checked:o.includes("StepFunctions")},{name:"\u{1F4DD} CloudTrail - API Logging",value:"CloudTrail",checked:o.includes("CloudTrail")},{name:"\u{1F310} API Gateway - REST APIs",value:"ApiGateway",checked:o.includes("ApiGateway")},{name:"\u{1F511} Secrets Manager - Secret Management",value:"SecretsManager",checked:o.includes("SecretsManager")},{name:"\u{1F510} KMS - Key Management",value:"KMS",checked:o.includes("KMS")},{name:"\u{1F4E1} EventBridge - Event Routing",value:"EventBridge",checked:o.includes("EventBridge")},{name:"\u{1F310} CloudFront - Content Delivery Network",value:"CloudFront",checked:o.includes("CloudFront")},{name:"\u2696\uFE0F ELB - Elastic Load Balancing",value:"ELB",checked:o.includes("ELB")},{name:"\u{1F433} ECS - Elastic Container Service",value:"ECS",checked:o.includes("ECS")},{name:"\u{1F464} Cognito - User Authentication",value:"Cognito",checked:o.includes("Cognito")},{name:"\u{1F6E1}\uFE0F WAF - Web Application Firewall",value:"WAF",checked:o.includes("WAF")},{name:"\u{1F4CA} CloudWatch - Monitoring & Logging",value:"CloudWatch",checked:o.includes("CloudWatch")},{name:"\u{1F30D} Route53 - DNS Management",value:"Route53",checked:o.includes("Route53")},{name:"\u26A1 ElastiCache - In-Memory Caching",value:"ElastiCache",checked:o.includes("ElastiCache")},{name:"\u{1F4E6} ECR - Container Registry",value:"ECR",checked:o.includes("ECR")},{name:"\u{1F50E} OpenSearch - Search & Analytics",value:"OpenSearch",checked:o.includes("OpenSearch")},{name:"\u{1F50F} ACM - Certificate Manager",value:"ACM",checked:o.includes("ACM")},{name:"\u{1F4BE} Backup - Backup Management",value:"Backup",checked:o.includes("Backup")},{name:"\u{1F517} VPC - Virtual Private Cloud",value:"VPC",checked:o.includes("VPC")},{name:"\u{1F30A} Kinesis - Real-time Streaming",value:"Kinesis",checked:o.includes("Kinesis")},{name:"\u{1F4F1} AppSync - GraphQL APIs",value:"AppSync",checked:o.includes("AppSync")},{name:"\u2638\uFE0F EKS - Kubernetes Service",value:"EKS",checked:o.includes("EKS")},{name:"\u{1F4C8} Redshift - Data Warehouse",value:"Redshift",checked:o.includes("Redshift")},{name:"\u{1F4EC} MSK - Managed Kafka",value:"MSK",checked:o.includes("MSK")},{name:"\u{1F9EA} Glue - ETL & Data Catalog",value:"Glue",checked:o.includes("Glue")}]});return{stackName:n,output:i,services:a}}async function wC(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:y}=t,b=p==="All stacks"?void 0:p,{stacks:C,inlineFindings:A,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,cdkVersion:H,supportsBoxTraces:B,cdkContext:S,resourceIdMetadata:U,validationReportFindings:k}=om(b),K=Object.keys(C).length;P.success(`Synthesis complete. Found ${K} stack${K===1?"":"s"} to analyze.`),H&&!B&&P.info(`Detected aws-cdk-lib ${H}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let x=Object.values(C).reduce((q,_)=>{let le=Object.entries(_.Resources||{}).filter(([,F])=>!F.Type.startsWith("AWS::CDK::"));return q+le.length},0);x>0?P.info(`\u{1F50D} Preparing to analyze ${x} total resources across ${K} stacks...`):P.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let v=null,X=!!s;if(a&&(X=!1,P.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){P.info("\u{1F50D} Checking license quota...");let q=n.licenseType==="FREE"||n.status==="TRIAL",_=n.totalResourcesAnalyzed||0,le=n.trialUsageLimit||n.maxUsage||200,F=Number.isNaN(_)?0:_,te=Number.isNaN(le)?200:le;if(q&&F>=te)X=!1,v={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:F,maxResources:te,remainingResources:Math.max(0,te-F),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${F}/${te} used)`,upgradePath:"https://cdkinsights.dev/pricing"},P.warning("\u26A0\uFE0F Trial AI credit allowance exceeded \u2014 falling back to static scans only"),P.comment(" Upgrade to Pro for 5,000 AI credits per month");else if(v=await nB({licenseKey:o,requestedResources:x,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),X=!!s&&(v?.canRunAIAnalysis??!0),v?.quota?.isTrial){let ye=v.quota.currentResourcesAnalyzed,Se=v.quota.maxResources;ye>=Se&&(v={...v,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${ye}/${Se} used) \u2014 falling back to static scans only`},X=!1)}v?.quota?.isTrial&&P.displayTrialStatus({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial,trialExpired:v.quota.trialExpired,trialStart:n.trialStart,trialEnd:n.trialEnd,tier:n.tier}),!X&&v?.quota?P.displayQuotaWarning({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,requestedResources:x,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial}):X&&o&&P.success("AI analysis enabled - you'll receive comprehensive recommendations")}let Z=Hp(t.services),J=Z.services;Z.removedAllServices?ie.debug(`Services normalization: removed "All services", using: ${J.join(", ")}`):Z.defaultedToAll&&ie.debug('Services normalization: defaulting to "All services"');let re=c||{},pe=t.warnSensitive||re.warnOnly||!1,Ae=(()=>{let q=S?.["cdkInsights:aiModel"];return typeof q=="string"?q:void 0})(),we=mB({flag:t.model,cdkContext:Ae,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});we.downgradedFromTierGate?P.warning(`\u26A0\uFE0F Requested AI model "${we.requestedAlias}" is not available on your tier \u2014 using "${we.alias}" instead.`):we.source!=="tierDefault"&&P.comment(`\u{1F916} AI model: ${we.alias} (from ${we.source})`);let ue=t.ai?.batchSize,Re=typeof ue=="number"&&Number.isFinite(ue)?Math.max(1,Math.floor(ue)):void 0;Re&&Re>1&&P.comment(`\u{1F9FA} AI batching: ${Re} resources per call`);let z={stacks:C,inlineFindings:A,validationReportFindings:k,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,output:u$(t),services:J,withIssue:t.withIssue,ruleFilter:t.ruleFilter||[],ignoreRules:t.ignoreRules||[],ignorePaths:t.ignorePaths||[],failOnCritical:t.failOnCritical,authToken:s,fingerprint:e,tier:n?.tier,quotaValidation:v||null,noCache:t.noCache||!1,cache:{enabled:t.cache?.enabled??!0,ttl:t.cache?.ttl??3e5,maxSize:t.cache?.maxSize??5e3},allowOveruse:t.allowOveruse||!1,warnSensitive:pe,sensitiveDataDetection:{disabled:re.enabled===!1,ignoreProperties:re.ignoreProperties||[],allowPatterns:re.allowPatterns||[],strictMode:re.strictMode||!1},cdkContext:S,resourceIdMetadata:U,aiModelId:we.bedrockModelId,aiBatchSize:Re,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await zm(z),totalResources:x,acknowledgementsPerStack:R}}var a$,c$,Eoe,u$,l$,EC=D(()=>{"use strict";a$=oe(require("node:fs")),c$=oe(require("node:path"));gb();rr();pp();dF();Sb();mF();DF();jb();ec();DT();tS();dv();sB();tc();xy();mp();rB();Db();dt();aB();lB();gv();Qn();hB();xB();$l();Eoe=()=>{let t=c$.resolve(process.cwd(),"cdk.out");return a$.existsSync(t)},u$=t=>t.summaryOnly?"summary":t.format==="json"||t.output==="json"?"json":t.format==="markdown"||t.output==="markdown"?"markdown":t.format==="summary"||t.output==="summary"?"summary":t.format==="sarif"||t.output==="sarif"?"sarif":t.format==="github-actions"||t.output==="github-actions"?"github-actions":"table";l$={command:"scan [stackName]",describe:"Scan CDK stacks for best practices and security issues",builder:t=>t.positional("stackName",{type:"string",describe:"Name of the stack to analyze"}).option("ci",{type:"boolean",default:!1}).option("withIssue",{type:"boolean",description:"Create GitHub issues from findings?"}).option("output",{alias:"o",type:"string",choices:["json","table","markdown","summary","sarif","github-actions"]}).option("all",{type:"boolean",description:"Analyze all CDK stacks,",default:!1}).option("services",{type:"array",string:!0,description:"Only run checks for these services (e.g. IAM, S3, Lambda)"}).option("format",{type:"string",choices:["json","table","markdown","summary","sarif","github-actions"],describe:"Alias for --output (preferred)"}).option("yes",{type:"boolean",description:"Skip prompts and use saved/default values,",default:!1,alias:"y"}).option("reset",{type:"boolean",description:"Clear saved config and start fresh"}).option("redact",{type:"boolean",description:"Redact sensitive resource names in output",default:!1}).option("summaryOnly",{type:"boolean",description:"Only show summary in console output",default:!1}).option("synth",{type:"boolean",description:"Run cdk synth before analysis",default:!1}).option("watch",{type:"boolean",description:"Watch CDK files and re-run static analysis on save. AI, baseline writes, GitHub issues, PR comments and scan history are disabled in watch mode. Reuses cdk.json `watch.include` / `watch.exclude` (same as `cdk watch`).",default:!1}).option("failOnCritical",{type:"boolean",description:"Exit with code 1 if critical issues are found (defaults to true)",default:!0}).option("ruleFilter",{type:"array",string:!0,describe:"Filter findings to only include matching rule IDs or categories (e.g. AwsSolutions-IAM4, Security)"}).option("github",{describe:"Create GitHub issues for findings,",type:"boolean",default:!1}).option("noCache",{describe:"Disable cache and force fresh analysis",type:"boolean",default:!1}).option("allowOveruse",{describe:"Allow AI analysis even when exceeding paid allowance (extra usage will be charged)",type:"boolean",default:!1}).option("local",{describe:"Run static analysis only (skip AI analysis even with a valid license)",type:"boolean",default:!1}).option("warnSensitive",{describe:"Treat sensitive data as warning instead of critical (will not fail CI)",type:"boolean",default:!1}).option("prComment",{describe:"Post analysis summary as a PR comment (GitHub Actions only)",type:"boolean",default:!1}).option("model",{describe:"AI model alias for analysis (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). Overrides cdk.json and user config. Tier-gated.",type:"string"}).option("diff",{describe:"Only show findings new since the saved baseline (.cdk-insights-baseline.json). Existing findings still appear in summaries but never fail CI.",type:"boolean",default:!1}).option("writeBaseline",{describe:"Write the current findings to .cdk-insights-baseline.json (or --baseline path) and exit 0 regardless of severity. Skips findings rendering.",type:"boolean",default:!1}).option("baseline",{describe:"Path to the baseline file. Defaults to .cdk-insights-baseline.json in cwd. Used by both --diff and --writeBaseline.",type:"string"}),handler:async t=>{try{let e=t.output||t.format;if((e==="json"||e==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),t.reset){Ym(),ie.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=el(),n=s.fingerprint,r=s.project;(!n||n.length===0)&&(P.error("Failed to generate system fingerprint for authentication."),P.comment(" This may indicate a permissions issue with reading system information."),process.exit(1));let i=process.env.CDK_INSIGHTS_LICENSE_KEY,o,a,c;if(i){let k=await Ck(i,n,r);k?(o=k.token,a=k.usageData,c=k.licenseInfo||await Km(i,o),k.fingerprint?n=k.fingerprint:n=el(o).fingerprint):(P.warning("\u26A0\uFE0F License validation failed. Running in free tier mode."),P.comment(" Check your license key and internet connection."),c=await Km(i,void 0))}else c=await Km(void 0,void 0);let u=`${c?.tier??"free"} tier`;P.info(`\u{1F50D} CDK Insights (${u})`),c.tier==="free"&&!i&&(P.comment("\u{1F4A1} Upgrade to Pro for AI-powered recommendations and GitHub integration"),P.comment(" Visit: https://cdkinsights.dev"));let l=tr(),d=yB(l,t),p=d.ci||fp();if(p&&!d.ci){let k=QR();P.info(`Detected CI environment${k?`: ${k}`:""}`)}let f=!p&&XR();if(p&&!d.stackName&&!d.all&&(d.all=!0),p&&!d.output&&(d.output="json"),d.watch){(d.writeBaseline||d.diff)&&(P.error("--watch cannot be combined with --writeBaseline or --diff."),P.comment(" Run those modes one-shot, then start `cdk-insights scan --watch` for the live loop."),process.exit(2));let k=["json","sarif","github-actions","markdown"],K=typeof t.output=="string"?t.output:void 0,x=typeof t.format=="string"?t.format:void 0,v=K??x;v&&k.includes(v)?(P.warning(`--watch ignores --output ${v}; using compact summary output.`),d.output="summary",d.format="summary"):v==="table"?(d.output="table",d.format="table"):(d.output="summary",d.format="summary"),d.local=!0,d.failOnCritical=!1,!d.stackName&&!d.all&&(d.stackName="All stacks");let{runWatchLoop:X}=await Promise.resolve().then(()=>(o$(),i$));await X({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Eoe()||(P.info("\u26A1 No cdk.out directory found. Running cdk synth..."),ST()||(P.error("Failed to synthesize CDK stacks."),P.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=fF();m.length===0&&(P.error("No CDK stacks found in cdk.out directory."),P.comment(' Make sure you have run "cdk synth" and that your CDK app defines at least one stack.'),P.comment(" If cdk.out exists, check that it contains valid CloudFormation templates."),process.exit(1));let g=["All stacks",...m],h=d;if((t.github||h.withIssue)&&(Ir.isFeatureEnabled("githubIntegration",c.tier)?P.success("\u{1F517} GitHub integration enabled"):(P.error("GitHub integration is not available for your current tier"),P.comment(dp("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let k=await Roe(d,g);h={...d,...k}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=u$(h)),h.format=h.output,(h.output==="json"||h.output==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),f&&h.output==="markdown"&&h.withIssue===void 0?h.withIssue=await vc({message:"Create GitHub issues from findings? (only available with markdown output)",default:!1}):h.withIssue===void 0&&(h.withIssue=!1),h.output==="table"&&(h.withIssue=!1);let y,b=0;if(h.diff)try{let k=xb(h.baseline);k?(y=new Set(k.fingerprints),b=k.fingerprints.length,P.info(`\u{1F4D0} Diff against baseline (${k.fingerprints.length} known findings; ${k.generatedAt}).`)):P.warning("No baseline file found. Run `cdk-insights scan --writeBaseline` to create one. Showing all findings.")}catch(k){P.error(k instanceof Error?k.message:"Failed to load baseline file."),process.exit(2)}let C=h.writeBaseline?new Set:void 0,A=h.writeBaseline===!0,w=uB(),N=new Date,L=await wC(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,y,C,A),R=l.telemetry?.enabled===!0&&!!i;if(h.diff&&y){let k=0,K=[];for(let x of Object.values(L.recommendationMaps||{})){if(!x?.sources)continue;let v=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[]];k+=v.length,K.push(...v)}if(P.info(`\u{1F4D0} Diff result: ${k} new finding${k===1?"":"s"} (${b} existing, suppressed).`),R){let x=(()=>{try{return xb(h.baseline)}catch{return null}})();Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:k,existingSuppressed:b,newSeverities:hv(K),baselineGeneratedAt:x?.generatedAt,failedOnCritical:!!L.hasCriticalIssues}})}}if(h.writeBaseline&&C){let k="1.42.2",{path:K,count:x}=lF([...C],{cliVersion:k,overridePath:h.baseline});if(P.success(`\u{1F4CC} Wrote baseline of ${x} finding${x===1?"":"s"} to ${K}.`),P.comment(" On the next run, pass --diff to see only new findings since this point."),R){let v=[],X={},Z=new Set;for(let J of Object.values(L.recommendationMaps||{})){if(!J?.sources)continue;let re=[...J.sources.cdkInsights?.issues??[],...J.sources.cdkNag?.issues??[]];v.push(...re);for(let Ae of re){let we=Ae.ruleId,ue=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(Ae.issue??""),Re=we||ue?.[1]||"unknown";X[Re]=(X[Re]??0)+1}let pe=J.type;pe?.startsWith("AWS::")&&Z.add(pe.split("::")[1])}Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:x,severityCounts:hv(v),ruleHistogram:X,uniqueServices:Z.size}})}return}let H=[],B=L.recommendationMaps||{},S=new Set;for(let[k,K]of Object.entries(B)){let x=K,v=k.includes(":")?k.substring(k.indexOf(":")+1):k,X=k.includes(":")?k.substring(0,k.indexOf(":")):"";X&&S.add(X);let Z=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[],...x.sources.validationReport?.issues??[]];for(let J of Z)H.push({resourceId:v,issue:J.issue,recommendation:J.recommendation,severity:J.severity,wafPillar:J.wafPillar||"Security",foundBy:J.foundBy||"cdkInsights",validationPluginName:J.validationPluginName,seenInSynth:J.seenInSynth,constructPath:J.constructPath,codeSnippet:J.codeSnippet,sourceLocation:J.sourceLocation,ruleId:J.ruleId,context:J.context,constructType:J.constructType||x.constructType})}if(h.prComment)if(qf()){P.info("Posting analysis summary to PR...");let k=[...S],K={stackNames:k.length>0?k:[h.stackName||"Unknown"],resourceCount:L.totalResources,issues:H,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},x=await Ab({data:K,updateExisting:!0});x.success?P.success("PR comment posted successfully"):P.warning(`Failed to post PR comment: ${x.error}`)}else P.warning("PR comment requested but not in GitHub Actions PR context. Skipping."),P.comment(" PR comments require: GitHub Actions + pull_request event + GITHUB_TOKEN permissions");if(P.success(`Analysis complete! ${h.withIssue?"GitHub issues have been created for the findings.":"Review the findings above."}`),l.scanHistory?.enabled===!0&&i&&o&&!h.writeBaseline){let k="1.42.2",K=new Date,x=!h.local&&!!i,v=Object.values(L.acknowledgementsPerStack??{}).flat().map(J=>({ruleId:J.ruleId,...J.constructPath?{constructPath:J.constructPath}:{}})),X=oB({scanId:w,cliVersion:k,recommendationMaps:L.recommendationMaps||{},scannedResourceIds:L.scannedResourceIds??new Set,scanStartedAt:N,scanCompletedAt:K,aiAnalysis:{ran:x},suppressions:{ignoreRules:h.ignoreRules||[],ignorePaths:h.ignorePaths||[],baselineFingerprints:y?[...y]:[],acknowledgedRules:v}});P.info("\u{1F4E4} Uploading scan to CDK Insights...");let Z=await cB({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:X});if(!Z.skipped)if(Z.success)P.success(`Uploaded as scan ${Z.scanId}`),Z.viewUrl&&P.comment(` View: ${Z.viewUrl}`),Z.retentionDays&&P.comment(` Retained for ${Z.retentionDays} day${Z.retentionDays===1?"":"s"} \u2014 adjust in scanHistory settings.`),P.comment(" You opted in via .cdk-insights.json. To opt out, set scanHistory.enabled = false.");else{let J=Z.serverMessage??Z.reason??"unknown";P.warning(`Could not upload scan to CDK Insights (${J}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&H.length>0)try{let k=await Ii({message:"Was this analysis helpful?",choices:[{name:"Yes, helpful!",value:"helpful"},{name:"Actionable - I'll fix these",value:"actionable"},{name:"Not helpful",value:"not_helpful"},{name:"Inaccurate findings",value:"inaccurate"},{name:"Skip",value:"skip"}],default:"skip"});if(k!=="skip"){let K=xi(),v=CT({apiClient:{post:async(Z,J)=>{let{data:re}=await Rt.post(`${K}${Z}`,J,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return re}}}),X={};for(let[Z,J]of Object.entries(L.recommendationMaps||{})){let re=J,pe=Z.includes(":")?Z.substring(Z.indexOf(":")+1):Z;re.type&&(X[pe]=re.type)}if(k==="helpful")v.markReportAsHelpful(H,X).catch(()=>{}),P.comment(" Thanks for your feedback!");else{let Z=H.map(J=>({issue:J,rating:k,resourceType:X[J.resourceId]}));v.submitBatchFeedback(Z).catch(()=>{}),P.comment(" Thanks for your feedback!")}}}catch{}else f||P.comment(" Have feedback? Let us know: https://cdkinsights.dev/feedback?source=cli");L.hasCriticalIssues&&(L.hasSensitiveData&&!h.warnSensitive?(P.error("Sensitive data detected. Exiting with code 1."),P.comment(" Use --warn-sensitive to continue without failing, or fix the issues.")):P.error("Critical issues found. Exiting with code 1."),await new Promise(k=>{process.stdout.write("")?k():process.stdout.once("drain",k)}),process.exit(1))}catch(e){let{message:s}=e;P.error(`An error occurred during analysis: ${s||e}`),process.exit(1)}}}});var zc,C$,v$,zoe,D$,A$=D(()=>{"use strict";zc=oe(require("node:fs")),C$=oe(require("node:path")),v$="@aws-cdk/core:stackTrace",zoe=t=>{let e;try{e=JSON.parse(t)}catch{return{status:"invalid-json"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"invalid-json"};let s=e,n=s.context,r=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};if(r[v$]===!0)return{status:"already-set",updated:t};r[v$]=!0;let i={...s,context:r},o=t.endsWith(`
|
|
461
|
+
\u{1F44B} Stopping watcher.`),p.close().then(()=>f())};process.once("SIGINT",m),process.once("SIGTERM",m)})}});async function Roe(t,e){let s=t.all?"All stacks":t.stackName||"All stacks",n=await Ii({message:"Which stack would you like to analyze?",default:s,choices:e.map(c=>({name:c,value:c}))}),r=t.output||t.format||"table",i=await Ii({message:"Choose output format:",choices:[{name:"\u{1F4CA} Table (default) - Human-readable table with colors",value:"table"},{name:"\u{1F4C4} Markdown - GitHub-compatible markdown report",value:"markdown"},{name:"\u{1F527} JSON - Structured data for CI/CD integration",value:"json"},{name:"\u{1F4CB} Summary - Brief overview with counts",value:"summary"}],default:r}),o=t.services&&t.services.length>0?t.services:["All services"],a=await Vy({message:"Which AWS services would you like to analyze? (Use <space> to toggle, <enter> to confirm)",choices:[{name:"\u{1F50D} All services (recommended)",value:"All services",checked:o.includes("All services")},{name:"\u{1F510} IAM - Identity and Access Management",value:"IAM",checked:o.includes("IAM")},{name:"\u{1F4E6} S3 - Simple Storage Service",value:"S3",checked:o.includes("S3")},{name:"\u26A1 Lambda - Serverless Functions",value:"Lambda",checked:o.includes("Lambda")},{name:"\u{1F5C4}\uFE0F DynamoDB - NoSQL Database",value:"DynamoDB",checked:o.includes("DynamoDB")},{name:"\u{1F5C4}\uFE0F RDS - Relational Database",value:"RDS",checked:o.includes("RDS")},{name:"\u{1F5A5}\uFE0F EC2 - Virtual Machines",value:"EC2",checked:o.includes("EC2")},{name:"\u{1F4E2} SNS - Simple Notification Service",value:"SNS",checked:o.includes("SNS")},{name:"\u{1F4E8} SQS - Simple Queue Service",value:"SQS",checked:o.includes("SQS")},{name:"\u{1F504} Step Functions - Workflow Orchestration",value:"StepFunctions",checked:o.includes("StepFunctions")},{name:"\u{1F4DD} CloudTrail - API Logging",value:"CloudTrail",checked:o.includes("CloudTrail")},{name:"\u{1F310} API Gateway - REST APIs",value:"ApiGateway",checked:o.includes("ApiGateway")},{name:"\u{1F511} Secrets Manager - Secret Management",value:"SecretsManager",checked:o.includes("SecretsManager")},{name:"\u{1F510} KMS - Key Management",value:"KMS",checked:o.includes("KMS")},{name:"\u{1F4E1} EventBridge - Event Routing",value:"EventBridge",checked:o.includes("EventBridge")},{name:"\u{1F310} CloudFront - Content Delivery Network",value:"CloudFront",checked:o.includes("CloudFront")},{name:"\u2696\uFE0F ELB - Elastic Load Balancing",value:"ELB",checked:o.includes("ELB")},{name:"\u{1F433} ECS - Elastic Container Service",value:"ECS",checked:o.includes("ECS")},{name:"\u{1F464} Cognito - User Authentication",value:"Cognito",checked:o.includes("Cognito")},{name:"\u{1F6E1}\uFE0F WAF - Web Application Firewall",value:"WAF",checked:o.includes("WAF")},{name:"\u{1F4CA} CloudWatch - Monitoring & Logging",value:"CloudWatch",checked:o.includes("CloudWatch")},{name:"\u{1F30D} Route53 - DNS Management",value:"Route53",checked:o.includes("Route53")},{name:"\u26A1 ElastiCache - In-Memory Caching",value:"ElastiCache",checked:o.includes("ElastiCache")},{name:"\u{1F4E6} ECR - Container Registry",value:"ECR",checked:o.includes("ECR")},{name:"\u{1F50E} OpenSearch - Search & Analytics",value:"OpenSearch",checked:o.includes("OpenSearch")},{name:"\u{1F50F} ACM - Certificate Manager",value:"ACM",checked:o.includes("ACM")},{name:"\u{1F4BE} Backup - Backup Management",value:"Backup",checked:o.includes("Backup")},{name:"\u{1F517} VPC - Virtual Private Cloud",value:"VPC",checked:o.includes("VPC")},{name:"\u{1F30A} Kinesis - Real-time Streaming",value:"Kinesis",checked:o.includes("Kinesis")},{name:"\u{1F4F1} AppSync - GraphQL APIs",value:"AppSync",checked:o.includes("AppSync")},{name:"\u2638\uFE0F EKS - Kubernetes Service",value:"EKS",checked:o.includes("EKS")},{name:"\u{1F4C8} Redshift - Data Warehouse",value:"Redshift",checked:o.includes("Redshift")},{name:"\u{1F4EC} MSK - Managed Kafka",value:"MSK",checked:o.includes("MSK")},{name:"\u{1F9EA} Glue - ETL & Data Catalog",value:"Glue",checked:o.includes("Glue")}]});return{stackName:n,output:i,services:a}}async function wC(t,e,s,n,r,i,o,a,c,u,l,d){let{stackName:p,output:f,services:m,withIssue:g,ruleFilter:h,failOnCritical:y}=t,b=p==="All stacks"?void 0:p,{stacks:C,inlineFindings:A,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,cdkVersion:H,supportsBoxTraces:B,cdkContext:S,resourceIdMetadata:U,validationReportFindings:k}=om(b),K=Object.keys(C).length;P.success(`Synthesis complete. Found ${K} stack${K===1?"":"s"} to analyze.`),H&&!B&&P.info(`Detected aws-cdk-lib ${H}. Upgrade to >= 2.252.0 for per-property source locations on deferred values.`);let x=Object.values(C).reduce((q,_)=>{let le=Object.entries(_.Resources||{}).filter(([,F])=>!F.Type.startsWith("AWS::CDK::"));return q+le.length},0);x>0?P.info(`\u{1F50D} Preparing to analyze ${x} total resources across ${K} stacks...`):P.warning("No user resources found in stacks. Make sure your CDK app is properly configured.");let v=null,X=!!s;if(a&&(X=!1,P.info("\u{1F3E0} Running in local mode - static analysis only")),o&&!a){P.info("\u{1F50D} Checking license quota...");let q=n.licenseType==="FREE"||n.status==="TRIAL",_=n.totalResourcesAnalyzed||0,le=n.trialUsageLimit||n.maxUsage||200,F=Number.isNaN(_)?0:_,te=Number.isNaN(le)?200:le;if(q&&F>=te)X=!1,v={canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,quota:{currentResourcesAnalyzed:F,maxResources:te,remainingResources:Math.max(0,te-F),isTrial:!0,trialExpired:!1},reason:`Trial AI credit allowance exceeded (${F}/${te} used)`,upgradePath:"https://cdkinsights.dev/pricing"},P.warning("\u26A0\uFE0F Trial AI credit allowance exceeded \u2014 falling back to static scans only"),P.comment(" Upgrade to Pro for 5,000 AI credits per month");else if(v=await nB({licenseKey:o,requestedResources:x,allowOveruse:t.allowOveruse,usageData:r,licenseInfo:n}),X=!!s&&(v?.canRunAIAnalysis??!0),v?.quota?.isTrial){let ye=v.quota.currentResourcesAnalyzed,Se=v.quota.maxResources;ye>=Se&&(v={...v,canProceed:!0,canRunStaticAnalysis:!0,canRunAIAnalysis:!1,reason:`Trial AI credit allowance exceeded (${ye}/${Se} used) \u2014 falling back to static scans only`},X=!1)}v?.quota?.isTrial&&P.displayTrialStatus({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial,trialExpired:v.quota.trialExpired,trialStart:n.trialStart,trialEnd:n.trialEnd,tier:n.tier}),!X&&v?.quota?P.displayQuotaWarning({currentResourcesAnalyzed:v.quota.currentResourcesAnalyzed,maxResources:v.quota.maxResources,requestedResources:x,remainingResources:v.quota.remainingResources,isTrial:v.quota.isTrial}):X&&o&&P.success("AI analysis enabled - you'll receive comprehensive recommendations")}let Z=Hp(t.services),J=Z.services;Z.removedAllServices?ie.debug(`Services normalization: removed "All services", using: ${J.join(", ")}`):Z.defaultedToAll&&ie.debug('Services normalization: defaulting to "All services"');let re=c||{},pe=t.warnSensitive||re.warnOnly||!1,Ae=(()=>{let q=S?.["cdkInsights:aiModel"];return typeof q=="string"?q:void 0})(),we=mB({flag:t.model,cdkContext:Ae,userConfig:typeof t.ai?.model=="string"?t.ai?.model:void 0,tier:n?.tier});we.downgradedFromTierGate?P.warning(`\u26A0\uFE0F Requested AI model "${we.requestedAlias}" is not available on your tier \u2014 using "${we.alias}" instead.`):we.source!=="tierDefault"&&P.comment(`\u{1F916} AI model: ${we.alias} (from ${we.source})`);let ue=t.ai?.batchSize,Re=typeof ue=="number"&&Number.isFinite(ue)?Math.max(1,Math.floor(ue)):void 0;Re&&Re>1&&P.comment(`\u{1F9FA} AI batching: ${Re} resources per call`);let z={stacks:C,inlineFindings:A,validationReportFindings:k,pathToLogicalId:w,recommendationMapPerStack:N,assetSourcePaths:L,acknowledgementsPerStack:R,output:u$(t),services:J,withIssue:t.withIssue,ruleFilter:t.ruleFilter||[],ignoreRules:t.ignoreRules||[],ignorePaths:t.ignorePaths||[],failOnCritical:t.failOnCritical,authToken:s,fingerprint:e,tier:n?.tier,quotaValidation:v||null,noCache:t.noCache||!1,cache:{enabled:t.cache?.enabled??!0,ttl:t.cache?.ttl??3e5,maxSize:t.cache?.maxSize??5e3},allowOveruse:t.allowOveruse||!1,warnSensitive:pe,sensitiveDataDetection:{disabled:re.enabled===!1,ignoreProperties:re.ignoreProperties||[],allowPatterns:re.allowPatterns||[],strictMode:re.strictMode||!1},cdkContext:S,resourceIdMetadata:U,aiModelId:we.bedrockModelId,aiBatchSize:Re,forceLocal:a,baselineExclude:u,collectFingerprints:l,skipRendering:d};return{...await zm(z),totalResources:x,acknowledgementsPerStack:R}}var a$,c$,Eoe,u$,l$,EC=D(()=>{"use strict";a$=oe(require("node:fs")),c$=oe(require("node:path"));gb();rr();pp();dF();Sb();mF();DF();jb();ec();DT();tS();dv();sB();tc();xy();mp();rB();Db();dt();aB();lB();gv();Qn();hB();xB();$l();Eoe=()=>{let t=c$.resolve(process.cwd(),"cdk.out");return a$.existsSync(t)},u$=t=>t.summaryOnly?"summary":t.format==="json"||t.output==="json"?"json":t.format==="markdown"||t.output==="markdown"?"markdown":t.format==="summary"||t.output==="summary"?"summary":t.format==="sarif"||t.output==="sarif"?"sarif":t.format==="github-actions"||t.output==="github-actions"?"github-actions":"table";l$={command:"scan [stackName]",describe:"Scan CDK stacks for best practices and security issues",builder:t=>t.positional("stackName",{type:"string",describe:"Name of the stack to analyze"}).option("ci",{type:"boolean",default:!1}).option("withIssue",{type:"boolean",description:"Create GitHub issues from findings?"}).option("output",{alias:"o",type:"string",choices:["json","table","markdown","summary","sarif","github-actions"]}).option("all",{type:"boolean",description:"Analyze all CDK stacks,",default:!1}).option("services",{type:"array",string:!0,description:"Only run checks for these services (e.g. IAM, S3, Lambda)"}).option("format",{type:"string",choices:["json","table","markdown","summary","sarif","github-actions"],describe:"Alias for --output (preferred)"}).option("yes",{type:"boolean",description:"Skip prompts and use saved/default values,",default:!1,alias:"y"}).option("reset",{type:"boolean",description:"Clear saved config and start fresh"}).option("redact",{type:"boolean",description:"Redact sensitive resource names in output",default:!1}).option("summaryOnly",{type:"boolean",description:"Only show summary in console output",default:!1}).option("synth",{type:"boolean",description:"Run cdk synth before analysis",default:!1}).option("watch",{type:"boolean",description:"Watch CDK files and re-run static analysis on save. AI, baseline writes, GitHub issues, PR comments and scan history are disabled in watch mode. Reuses cdk.json `watch.include` / `watch.exclude` (same as `cdk watch`).",default:!1}).option("failOnCritical",{type:"boolean",description:"Exit with code 1 if critical issues are found (defaults to true)",default:!0}).option("ruleFilter",{type:"array",string:!0,describe:"Filter findings to only include matching rule IDs or categories (e.g. AwsSolutions-IAM4, Security)"}).option("github",{describe:"Create GitHub issues for findings,",type:"boolean",default:!1}).option("noCache",{describe:"Disable cache and force fresh analysis",type:"boolean",default:!1}).option("allowOveruse",{describe:"Allow AI analysis even when exceeding paid allowance (extra usage will be charged)",type:"boolean",default:!1}).option("local",{describe:"Run static analysis only (skip AI analysis even with a valid license)",type:"boolean",default:!1}).option("warnSensitive",{describe:"Treat sensitive data as warning instead of critical (will not fail CI)",type:"boolean",default:!1}).option("prComment",{describe:"Post analysis summary as a PR comment (GitHub Actions only)",type:"boolean",default:!1}).option("model",{describe:"AI model alias for analysis (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). Overrides cdk.json and user config. Tier-gated.",type:"string"}).option("diff",{describe:"Only show findings new since the saved baseline (.cdk-insights-baseline.json). Existing findings still appear in summaries but never fail CI.",type:"boolean",default:!1}).option("writeBaseline",{describe:"Write the current findings to .cdk-insights-baseline.json (or --baseline path) and exit 0 regardless of severity. Skips findings rendering.",type:"boolean",default:!1}).option("baseline",{describe:"Path to the baseline file. Defaults to .cdk-insights-baseline.json in cwd. Used by both --diff and --writeBaseline.",type:"string"}),handler:async t=>{try{let e=t.output||t.format;if((e==="json"||e==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),t.reset){Ym(),ie.info("\u{1F5D1}\uFE0F Cleared saved CLI preferences.");return}let s=el(),n=s.fingerprint,r=s.project;(!n||n.length===0)&&(P.error("Failed to generate system fingerprint for authentication."),P.comment(" This may indicate a permissions issue with reading system information."),process.exit(1));let i=process.env.CDK_INSIGHTS_LICENSE_KEY,o,a,c;if(i){let k=await Ck(i,n,r);k?(o=k.token,a=k.usageData,c=k.licenseInfo||await Km(i,o),k.fingerprint?n=k.fingerprint:n=el(o).fingerprint):(P.warning("\u26A0\uFE0F License validation failed. Running in free tier mode."),P.comment(" Check your license key and internet connection."),c=await Km(i,void 0))}else c=await Km(void 0,void 0);let u=`${c?.tier??"free"} tier`;P.info(`\u{1F50D} CDK Insights (${u})`),c.tier==="free"&&!i&&(P.comment("\u{1F4A1} Upgrade to Pro for AI-powered recommendations and GitHub integration"),P.comment(" Visit: https://cdkinsights.dev"));let l=tr(),d=yB(l,t),p=d.ci||fp();if(p&&!d.ci){let k=QR();P.info(`Detected CI environment${k?`: ${k}`:""}`)}let f=!p&&XR();if(p&&!d.stackName&&!d.all&&(d.all=!0),p&&!d.output&&(d.output="json"),d.watch){(d.writeBaseline||d.diff)&&(P.error("--watch cannot be combined with --writeBaseline or --diff."),P.comment(" Run those modes one-shot, then start `cdk-insights scan --watch` for the live loop."),process.exit(2));let k=["json","sarif","github-actions","markdown"],K=typeof t.output=="string"?t.output:void 0,x=typeof t.format=="string"?t.format:void 0,v=K??x;v&&k.includes(v)?(P.warning(`--watch ignores --output ${v}; using compact summary output.`),d.output="summary",d.format="summary"):v==="table"?(d.output="table",d.format="table"):(d.output="summary",d.format="summary"),d.local=!0,d.failOnCritical=!1,!d.stackName&&!d.all&&(d.stackName="All stacks");let{runWatchLoop:X}=await Promise.resolve().then(()=>(o$(),i$));await X({config:d,fingerprint:n,authToken:o,licenseInfo:c,usageData:a,project:r,licenseKey:i});return}Eoe()||(P.info("\u26A1 No cdk.out directory found. Running cdk synth..."),ST()||(P.error("Failed to synthesize CDK stacks."),P.comment(" Make sure your CDK app compiles correctly."),process.exit(1)));let m=fF();m.length===0&&(P.error("No CDK stacks found in cdk.out directory."),P.comment(' Make sure you have run "cdk synth" and that your CDK app defines at least one stack.'),P.comment(" If cdk.out exists, check that it contains valid CloudFormation templates."),process.exit(1));let g=["All stacks",...m],h=d;if((t.github||h.withIssue)&&(Ir.isFeatureEnabled("githubIntegration",c.tier)?P.success("\u{1F517} GitHub integration enabled"):(P.error("GitHub integration is not available for your current tier"),P.comment(dp("githubIntegration",c.tier,"GitHub integration")),process.exit(1))),f&&!d.yes){let k=await Roe(d,g);h={...d,...k}}h.all&&(h.stackName="All stacks"),h.stackName||(h.stackName="All stacks"),f&&h.output||(h.output=u$(h)),h.format=h.output,(h.output==="json"||h.output==="sarif")&&(process.env.CDK_INSIGHTS_QUIET_STDOUT="1"),f&&h.output==="markdown"&&h.withIssue===void 0?h.withIssue=await vc({message:"Create GitHub issues from findings? (only available with markdown output)",default:!1}):h.withIssue===void 0&&(h.withIssue=!1),h.output==="table"&&(h.withIssue=!1);let y,b=0;if(h.diff)try{let k=xb(h.baseline);k?(y=new Set(k.fingerprints),b=k.fingerprints.length,P.info(`\u{1F4D0} Diff against baseline (${k.fingerprints.length} known findings; ${k.generatedAt}).`)):P.warning("No baseline file found. Run `cdk-insights scan --writeBaseline` to create one. Showing all findings.")}catch(k){P.error(k instanceof Error?k.message:"Failed to load baseline file."),process.exit(2)}let C=h.writeBaseline?new Set:void 0,A=h.writeBaseline===!0,w=uB(),N=new Date,L=await wC(h,n,o,c,a,r,i,h.local,l.sensitiveDataDetection,y,C,A),R=l.telemetry?.enabled===!0&&!!i;if(h.diff&&y){let k=0,K=[];for(let x of Object.values(L.recommendationMaps||{})){if(!x?.sources)continue;let v=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[]];k+=v.length,K.push(...v)}if(P.info(`\u{1F4D0} Diff result: ${k} new finding${k===1?"":"s"} (${b} existing, suppressed).`),R){let x=(()=>{try{return xb(h.baseline)}catch{return null}})();Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"diff_run",newFindings:k,existingSuppressed:b,newSeverities:hv(K),baselineGeneratedAt:x?.generatedAt,failedOnCritical:!!L.hasCriticalIssues}})}}if(h.writeBaseline&&C){let k="1.42.3",{path:K,count:x}=lF([...C],{cliVersion:k,overridePath:h.baseline});if(P.success(`\u{1F4CC} Wrote baseline of ${x} finding${x===1?"":"s"} to ${K}.`),P.comment(" On the next run, pass --diff to see only new findings since this point."),R){let v=[],X={},Z=new Set;for(let J of Object.values(L.recommendationMaps||{})){if(!J?.sources)continue;let re=[...J.sources.cdkInsights?.issues??[],...J.sources.cdkNag?.issues??[]];v.push(...re);for(let Ae of re){let we=Ae.ruleId,ue=/^([A-Za-z][A-Za-z0-9-]+):\s/.exec(Ae.issue??""),Re=we||ue?.[1]||"unknown";X[Re]=(X[Re]??0)+1}let pe=J.type;pe?.startsWith("AWS::")&&Z.add(pe.split("::")[1])}Pl({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,event:{type:"baseline_written",totalFindings:x,severityCounts:hv(v),ruleHistogram:X,uniqueServices:Z.size}})}return}let H=[],B=L.recommendationMaps||{},S=new Set;for(let[k,K]of Object.entries(B)){let x=K,v=k.includes(":")?k.substring(k.indexOf(":")+1):k,X=k.includes(":")?k.substring(0,k.indexOf(":")):"";X&&S.add(X);let Z=[...x.sources.cdkInsights?.issues??[],...x.sources.cdkNag?.issues??[],...x.sources.validationReport?.issues??[]];for(let J of Z)H.push({resourceId:v,issue:J.issue,recommendation:J.recommendation,severity:J.severity,wafPillar:J.wafPillar||"Security",foundBy:J.foundBy||"cdkInsights",validationPluginName:J.validationPluginName,seenInSynth:J.seenInSynth,constructPath:J.constructPath,codeSnippet:J.codeSnippet,sourceLocation:J.sourceLocation,ruleId:J.ruleId,context:J.context,constructType:J.constructType||x.constructType})}if(h.prComment)if(qf()){P.info("Posting analysis summary to PR...");let k=[...S],K={stackNames:k.length>0?k:[h.stackName||"Unknown"],resourceCount:L.totalResources,issues:H,reportUrl:void 0,aiEnabled:!h.local&&!!i,tier:c?.tier||"free"},x=await Ab({data:K,updateExisting:!0});x.success?P.success("PR comment posted successfully"):P.warning(`Failed to post PR comment: ${x.error}`)}else P.warning("PR comment requested but not in GitHub Actions PR context. Skipping."),P.comment(" PR comments require: GitHub Actions + pull_request event + GITHUB_TOKEN permissions");if(P.success(`Analysis complete! ${h.withIssue?"GitHub issues have been created for the findings.":"Review the findings above."}`),l.scanHistory?.enabled===!0&&i&&o&&!h.writeBaseline){let k="1.42.3",K=new Date,x=!h.local&&!!i,v=Object.values(L.acknowledgementsPerStack??{}).flat().map(J=>({ruleId:J.ruleId,...J.constructPath?{constructPath:J.constructPath}:{}})),X=oB({scanId:w,cliVersion:k,recommendationMaps:L.recommendationMaps||{},scannedResourceIds:L.scannedResourceIds??new Set,scanStartedAt:N,scanCompletedAt:K,aiAnalysis:{ran:x},suppressions:{ignoreRules:h.ignoreRules||[],ignorePaths:h.ignorePaths||[],baselineFingerprints:y?[...y]:[],acknowledgedRules:v}});P.info("\u{1F4E4} Uploading scan to CDK Insights...");let Z=await cB({enabled:!0,licenseKey:i,authToken:o,tier:c?.tier,report:X});if(!Z.skipped)if(Z.success)P.success(`Uploaded as scan ${Z.scanId}`),Z.viewUrl&&P.comment(` View: ${Z.viewUrl}`),Z.retentionDays&&P.comment(` Retained for ${Z.retentionDays} day${Z.retentionDays===1?"":"s"} \u2014 adjust in scanHistory settings.`),P.comment(" You opted in via .cdk-insights.json. To opt out, set scanHistory.enabled = false.");else{let J=Z.serverMessage??Z.reason??"unknown";P.warning(`Could not upload scan to CDK Insights (${J}). Run continues normally.`)}}if(l.feedback!==!1&&f&&o&&H.length>0)try{let k=await Ii({message:"Was this analysis helpful?",choices:[{name:"Yes, helpful!",value:"helpful"},{name:"Actionable - I'll fix these",value:"actionable"},{name:"Not helpful",value:"not_helpful"},{name:"Inaccurate findings",value:"inaccurate"},{name:"Skip",value:"skip"}],default:"skip"});if(k!=="skip"){let K=xi(),v=CT({apiClient:{post:async(Z,J)=>{let{data:re}=await Rt.post(`${K}${Z}`,J,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","x-cdk-insights-fingerprint":n,"x-cdk-insights-client":"cli"},timeout:1e4});return re}}}),X={};for(let[Z,J]of Object.entries(L.recommendationMaps||{})){let re=J,pe=Z.includes(":")?Z.substring(Z.indexOf(":")+1):Z;re.type&&(X[pe]=re.type)}if(k==="helpful")v.markReportAsHelpful(H,X).catch(()=>{}),P.comment(" Thanks for your feedback!");else{let Z=H.map(J=>({issue:J,rating:k,resourceType:X[J.resourceId]}));v.submitBatchFeedback(Z).catch(()=>{}),P.comment(" Thanks for your feedback!")}}}catch{}else f||P.comment(" Have feedback? Let us know: https://cdkinsights.dev/feedback?source=cli");L.hasCriticalIssues&&(L.hasSensitiveData&&!h.warnSensitive?(P.error("Sensitive data detected. Exiting with code 1."),P.comment(" Use --warn-sensitive to continue without failing, or fix the issues.")):P.error("Critical issues found. Exiting with code 1."),await new Promise(k=>{process.stdout.write("")?k():process.stdout.once("drain",k)}),process.exit(1))}catch(e){let{message:s}=e;P.error(`An error occurred during analysis: ${s||e}`),process.exit(1)}}}});var zc,C$,v$,zoe,D$,A$=D(()=>{"use strict";zc=oe(require("node:fs")),C$=oe(require("node:path")),v$="@aws-cdk/core:stackTrace",zoe=t=>{let e;try{e=JSON.parse(t)}catch{return{status:"invalid-json"}}if(e===null||typeof e!="object"||Array.isArray(e))return{status:"invalid-json"};let s=e,n=s.context,r=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};if(r[v$]===!0)return{status:"already-set",updated:t};r[v$]=!0;let i={...s,context:r},o=t.endsWith(`
|
|
462
462
|
`)?`
|
|
463
463
|
`:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},D$=t=>{let e=C$.join(t,"cdk.json");if(!zc.existsSync(e))return{status:"missing",cdkJsonPath:e};let s=zc.readFileSync(e,"utf-8"),n=zoe(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:e}:n.status==="already-set"?{status:"already-set",cdkJsonPath:e}:(zc.writeFileSync(e,n.updated,"utf-8"),{status:"added",cdkJsonPath:e})}});var T$=oe(Ih()),Dh=require("node:child_process"),P$=oe(require("node:path")),L$=require("node:util");rr();var O$=oe(p0());var Qd=require("assert");var cH={right:fH,center:mH},uH=0,zd=1,lH=2,qd=3,f0=class{constructor(e){var s;this.width=e.width,this.wrap=(s=e.wrap)!==null&&s!==void 0?s:!0,this.rows=[]}span(...e){let s=this.div(...e);s.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0&&this.div(""),this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]=="string")return this.applyLayoutDSL(e[0]);let s=e.map(n=>typeof n=="string"?this.colFromString(n):n);return this.rows.push(s),s}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]=="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let s=e.split(`
|
|
464
464
|
`).map(r=>r.split(" ")),n=0;return s.forEach(r=>{r.length>1&&Ks.stringWidth(r[0])>n&&(n=Math.min(Math.floor(this.width*.5),Ks.stringWidth(r[0])))}),s.forEach(r=>{this.div(...r.map((i,o)=>({text:i.trim(),padding:this.measurePadding(i),width:o===0&&r.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let s=Ks.stripAnsi(e);return[0,s.match(/\s*$/)[0].length,0,s.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(s=>{this.rowToString(s,e)}),e.filter(s=>!s.hidden).map(s=>s.text).join(`
|
|
@@ -582,7 +582,7 @@ ${t.body.join(`
|
|
|
582
582
|
\u2705 Configuration saved successfully!`),console.log(`
|
|
583
583
|
\u{1F4CB} Your current configuration:`),console.log(JSON.stringify(t,null,2))}finally{s.close()}},Joe=()=>{let t=tr();console.log("\u{1F4CB} Current Configuration:"),console.log(JSON.stringify(t,null,2))},Qoe=t=>{let{key:e,value:s}=t;if(t.help){nd(e);return}s||(console.log(`
|
|
584
584
|
\u274C No value provided for ${e}`),nd(e),process.exit(1));let n=tr(),r;try{e==="services"||e==="ruleFilter"?r=s.split(",").map(o=>o.trim()):e==="cache"?r=JSON.parse(s):s.toLowerCase()==="true"||s.toLowerCase()==="false"?r=s.toLowerCase()==="true":Number.isNaN(Number(s))?r=s:r=Number(s)}catch{ie.error(`\u274C Invalid value for ${e}: ${s}`),nd(e),process.exit(1)}let i=_C[e];i&&(i.type==="boolean"&&typeof r!="boolean"&&(ie.error(`\u274C ${e} must be a boolean (true/false)`),nd(e),process.exit(1)),i.type==="array"&&!Array.isArray(r)&&(ie.error(`\u274C ${e} must be a comma-separated list`),nd(e),process.exit(1))),n[e]=r,Nl(n),ie.info(`\u2714\uFE0F ${e} = ${JSON.stringify(r)}`)},Xoe=t=>{let{key:e}=t,s=tr();if(s[e]===void 0){ie.warn(`\u26A0\uFE0F ${e} not set`);return}delete s[e],Nl(s),ie.info(`\u2714\uFE0F Removed ${e}`)},M$=new Set(["vi","vim","nvim","nano","emacs","code","subl","atom","gedit","kate","notepad","notepad++","micro","helix","pico"]),eae=t=>{let e=t.split("/").pop()||t;return M$.has(e.toLowerCase())},tae=()=>{let t=Jp.get("EDITOR")||"vi";eae(t)||(ie.error(`\u274C Unsupported editor: ${t}. Allowed editors: ${Array.from(M$).join(", ")}`),process.exit(1));let e=(0,Dh.spawnSync)(t,[Zoe],{stdio:"inherit"});e.error&&(ie.error("\u274C Editor error",{error:e.error.message}),process.exit(1)),ie.info("\u2714\uFE0F Config saved")},FC=t=>t.teamId||process.env.CDK_INSIGHTS_TEAM_ID||void 0,TC=()=>{let t=Jp.get("CDK_INSIGHTS_LICENSE_KEY");if(!t)throw new Error("CDK_INSIGHTS_LICENSE_KEY environment variable is required for team config operations");return{"Content-Type":"application/json","x-api-key":t}},PC=()=>Jp.get("CDK_INSIGHTS_API_URL")||"https://api.cdkinsights.dev",sae=async t=>{let e=FC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{console.log("\u{1F4E5} Fetching team configurations...");let n=(await Rt.get(`${PC()}/v1/teams/${e}/configs`,{headers:TC()})).data;n.success||(console.error(`\u274C ${n.error||n.message}`),process.exit(1));let i=n.configurations?.find(u=>u.isDefault);if(!i){console.log('\u2139\uFE0F No default team configuration found. Use "config team-configs" to list available configs.');return}let o=Bl(i.configData),c={...tr(),...o};Nl(c),console.log(`\u2705 Pulled team config "${i.configName}" (v${i.version}) to .cdk-insights.json`)}catch(s){console.error(`\u274C Failed to pull config: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},nae=async t=>{let e=FC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{let s=tr(),n=t.name||"CLI Config",r=t.description||"";console.log(`\u{1F4E4} Pushing local config as "${n}"...`);let o=(await Rt.post(`${PC()}/v1/teams/${e}/configs`,{configName:n,configDescription:r,configData:s},{headers:TC()})).data;o.success||(console.error(`\u274C ${o.error||o.message}`),process.exit(1));let a=o.configuration;console.log(`\u2705 Config pushed as "${a?.configName}" (v${a?.version})`)}catch(s){console.error(`\u274C Failed to push config: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},rae=async t=>{let e=FC(t);e||(console.error("\u274C Team ID required. Use --team-id or set CDK_INSIGHTS_TEAM_ID env var."),process.exit(1));try{console.log(`\u{1F4CB} Listing team configurations...
|
|
585
|
-
`);let n=(await Rt.get(`${PC()}/v1/teams/${e}/configs`,{headers:TC()})).data;n.success||(console.error(`\u274C ${n.error||n.message}`),process.exit(1));let r=n.configurations;if(!r||r.length===0){console.log(' No configurations found. Use "config push" to share your config with the team.');return}for(let i of r){let o=i.updatedAt?new Date(i.updatedAt*1e3).toISOString().replace("T"," ").split(".")[0]:"-",a=i.isDefault?" [DEFAULT]":"";console.log(` ${i.configName||"Unnamed"}${a} (v${i.version||1})`),i.configDescription&&console.log(` ${i.configDescription}`),console.log(` Updated: ${o}`),console.log("")}}catch(s){console.error(`\u274C Failed to list configs: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},iae=async t=>{let{path:e}=t,s=(0,L$.promisify)(Dh.exec),n=e||process.cwd();ie.info(`\u{1F6E0}\uFE0F Running 'cdk synth' in ${n}...`);try{let{stderr:r}=await s("cdk synth",{cwd:n,env:{...process.env,CDK_DEBUG:"true"}});r&&ie.error(r)}catch(r){ie.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},oae=()=>{ie.info("\u{1F5D1}\uFE0F Clearing caches..."),pk(),Dk();let t=fy();ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},aae=()=>{ie.info("\u{1F4CA} Cache Status:");let t=fy();if(ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),ie.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);ie.info(`\u{1F4CF} Cache file size: ${e} KB`)}ie.info(`\u2699\uFE0F Cache enabled: ${fk()?"Yes":"No"}`),ie.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},cae=()=>{let t=new O$.default({head:["Command/Option","Description"],colWidths:[30,80]});return t.push(["COMMANDS",""],["scan [stackName]","Scan CDK stacks for best practices and security issues"],["fix","Apply mechanical fixes for findings whose remediation is unambiguous (defaults to dry-run; pass --apply)"],["init","Add cdk-insights npm scripts to your package.json"],["config <action>","Manage project-level configuration"],["synth","Run `cdk synth` automatically before analysis"],["hook","Install Git pre-commit hook for CDK Insights"],["reset","Clear saved prompt answers and CLI preferences"],["clear-cache","Clear the analysis cache"],["cache-status","Show cache status and statistics"],["setup","Interactive setup: install the CDK Insights aspect, Validations plugin, or AwsSolutionsChecks"],["",""]),t.push(["SCAN OPTIONS",""],["--output, -o","Output format: json, table, markdown, summary, sarif, github-actions"],["--format","Alias for --output"],["--all, -a","Analyze all available stacks"],["--services","Comma-separated list of AWS services to analyze"],["--with-issue","Create GitHub issues for findings (markdown output only)"],["--github","Alias for --with-issue"],["--redact","Redact sensitive resource names in output"],["--summaryOnly","Only show summary in console"],["--synth","Run `cdk synth` before analysis"],["--ci","Run in CI mode (no prompts)"],["--yes, -y","Skip prompts and use saved/default values"],["--reset","Clear saved config and start fresh"],["--failOnCritical","Exit with code 1 if critical issues found"],["--ruleFilter","Filter findings by rule IDs or categories"],["--noCache","Disable cache and force fresh analysis"],["--allow-overuse","Allow AI analysis even when exceeding paid allowance (extra usage charged)"],["--local","Run static analysis only (skip AI even with valid license)"],["--warn-sensitive","Treat sensitive data as warning (does not fail CI)"],["--prComment","Post analysis summary as a PR comment (GitHub Actions only)"],["--model","AI model alias (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). Tier-gated."],["--diff","Filter findings to only those new since the saved baseline (.cdk-insights-baseline.json)"],["--writeBaseline","Save current findings as the baseline; suppresses fail-on-critical and skips rendering"],["--baseline","Override path to the baseline file"],["",""]),t.push(["FIX OPTIONS",""],["--rule","Only fix findings for this rule ID (e.g. AwsSolutions-S10). Without this flag, fixes every supported rule."],["--dry-run","Preview changes without writing files. Default behaviour; pass --apply to disable."],["--apply","Write fixes to disk. Implies --dry-run=false."],["",""]),t.push(["CONFIG SUBCOMMANDS",""],["config list","Show current configuration"],["config set <key> <value>","Set a configuration key"],["config unset <key>","Remove a configuration key"],["config edit","Open config file in your editor"],["config setup","Interactive setup to configure CDK Insights"],["",""]),t.push(["GLOBAL OPTIONS",""],["--help, -h","Show help information"],["--version, -v","Show version information"]),t.toString()},uae={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:Joe}).command({command:"set <key> <value>",describe:"Set a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to set"}).positional("value",{type:"string",describe:"Value to set (use --help for field-specific help)"}).option("help",{type:"boolean",describe:"Show detailed help for the specified field"}),handler:Qoe}).command({command:"unset <key>",describe:"Remove a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to remove"}),handler:Xoe}).command({command:"edit",describe:"Open config file in your editor",handler:tae}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:Yoe}).command({command:"pull",describe:"Pull the team default configuration to local .cdk-insights.json",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:sae}).command({command:"push",describe:"Push local .cdk-insights.json as a team configuration",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}).option("name",{type:"string",describe:"Configuration name",default:"CLI Config"}).option("description",{type:"string",describe:"Configuration description",default:""}),handler:nae}).command({command:"team-configs",describe:"List available team configurations",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:rae}).demandCommand(1).help(),handler:()=>{}},lae=()=>{JR(v0(process.argv)).scriptName("cdk-insights").version("1.42.
|
|
585
|
+
`);let n=(await Rt.get(`${PC()}/v1/teams/${e}/configs`,{headers:TC()})).data;n.success||(console.error(`\u274C ${n.error||n.message}`),process.exit(1));let r=n.configurations;if(!r||r.length===0){console.log(' No configurations found. Use "config push" to share your config with the team.');return}for(let i of r){let o=i.updatedAt?new Date(i.updatedAt*1e3).toISOString().replace("T"," ").split(".")[0]:"-",a=i.isDefault?" [DEFAULT]":"";console.log(` ${i.configName||"Unnamed"}${a} (v${i.version||1})`),i.configDescription&&console.log(` ${i.configDescription}`),console.log(` Updated: ${o}`),console.log("")}}catch(s){console.error(`\u274C Failed to list configs: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}},iae=async t=>{let{path:e}=t,s=(0,L$.promisify)(Dh.exec),n=e||process.cwd();ie.info(`\u{1F6E0}\uFE0F Running 'cdk synth' in ${n}...`);try{let{stderr:r}=await s("cdk synth",{cwd:n,env:{...process.env,CDK_DEBUG:"true"}});r&&ie.error(r)}catch(r){ie.error("\u274C Failed to synthesize stacks",{error:r instanceof Error?r.message:String(r)}),process.exit(1)}},oae=()=>{ie.info("\u{1F5D1}\uFE0F Clearing caches..."),pk(),Dk();let t=fy();ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4CA} Cache status: ${t.cacheFileExists?"Files found":"No persistent cache files"}`)},aae=()=>{ie.info("\u{1F4CA} Cache Status:");let t=fy();if(ie.info(`\u{1F4C1} Cache directory: ${t.cacheDir}`),ie.info(`\u{1F4C2} Directory exists: ${t.cacheDirExists?"Yes":"No"}`),ie.info(`\u{1F4C4} Cache file exists: ${t.cacheFileExists?"Yes":"No"}`),t.cacheSize!==void 0){let e=(t.cacheSize/1024).toFixed(2);ie.info(`\u{1F4CF} Cache file size: ${e} KB`)}ie.info(`\u2699\uFE0F Cache enabled: ${fk()?"Yes":"No"}`),ie.info("\u2139\uFE0F Note: Current cache is in-memory and clears on process restart")},cae=()=>{let t=new O$.default({head:["Command/Option","Description"],colWidths:[30,80]});return t.push(["COMMANDS",""],["scan [stackName]","Scan CDK stacks for best practices and security issues"],["fix","Apply mechanical fixes for findings whose remediation is unambiguous (defaults to dry-run; pass --apply)"],["init","Add cdk-insights npm scripts to your package.json"],["config <action>","Manage project-level configuration"],["synth","Run `cdk synth` automatically before analysis"],["hook","Install Git pre-commit hook for CDK Insights"],["reset","Clear saved prompt answers and CLI preferences"],["clear-cache","Clear the analysis cache"],["cache-status","Show cache status and statistics"],["setup","Interactive setup: install the CDK Insights aspect, Validations plugin, or AwsSolutionsChecks"],["",""]),t.push(["SCAN OPTIONS",""],["--output, -o","Output format: json, table, markdown, summary, sarif, github-actions"],["--format","Alias for --output"],["--all, -a","Analyze all available stacks"],["--services","Comma-separated list of AWS services to analyze"],["--with-issue","Create GitHub issues for findings (markdown output only)"],["--github","Alias for --with-issue"],["--redact","Redact sensitive resource names in output"],["--summaryOnly","Only show summary in console"],["--synth","Run `cdk synth` before analysis"],["--ci","Run in CI mode (no prompts)"],["--yes, -y","Skip prompts and use saved/default values"],["--reset","Clear saved config and start fresh"],["--failOnCritical","Exit with code 1 if critical issues found"],["--ruleFilter","Filter findings by rule IDs or categories"],["--noCache","Disable cache and force fresh analysis"],["--allow-overuse","Allow AI analysis even when exceeding paid allowance (extra usage charged)"],["--local","Run static analysis only (skip AI even with valid license)"],["--warn-sensitive","Treat sensitive data as warning (does not fail CI)"],["--prComment","Post analysis summary as a PR comment (GitHub Actions only)"],["--model","AI model alias (nova-lite, mistral-14b, haiku-4-5, sonnet-4-6). Tier-gated."],["--diff","Filter findings to only those new since the saved baseline (.cdk-insights-baseline.json)"],["--writeBaseline","Save current findings as the baseline; suppresses fail-on-critical and skips rendering"],["--baseline","Override path to the baseline file"],["",""]),t.push(["FIX OPTIONS",""],["--rule","Only fix findings for this rule ID (e.g. AwsSolutions-S10). Without this flag, fixes every supported rule."],["--dry-run","Preview changes without writing files. Default behaviour; pass --apply to disable."],["--apply","Write fixes to disk. Implies --dry-run=false."],["",""]),t.push(["CONFIG SUBCOMMANDS",""],["config list","Show current configuration"],["config set <key> <value>","Set a configuration key"],["config unset <key>","Remove a configuration key"],["config edit","Open config file in your editor"],["config setup","Interactive setup to configure CDK Insights"],["",""]),t.push(["GLOBAL OPTIONS",""],["--help, -h","Show help information"],["--version, -v","Show version information"]),t.toString()},uae={command:"config <action> [key] [value]",describe:"Manage project-level configuration",builder:t=>t.command({command:"list",describe:"Show current configuration",handler:Joe}).command({command:"set <key> <value>",describe:"Set a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to set"}).positional("value",{type:"string",describe:"Value to set (use --help for field-specific help)"}).option("help",{type:"boolean",describe:"Show detailed help for the specified field"}),handler:Qoe}).command({command:"unset <key>",describe:"Remove a configuration key",builder:e=>e.positional("key",{type:"string",choices:["stackName","output","services","redact","withIssue","summaryOnly","synth","ruleFilter","failOnCritical","noCache","allowOveruse","local","cache","sensitiveDataDetection"],describe:"Configuration field to remove"}),handler:Xoe}).command({command:"edit",describe:"Open config file in your editor",handler:tae}).command({command:"setup",describe:"Interactive setup to configure CDK Insights",handler:Yoe}).command({command:"pull",describe:"Pull the team default configuration to local .cdk-insights.json",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:sae}).command({command:"push",describe:"Push local .cdk-insights.json as a team configuration",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}).option("name",{type:"string",describe:"Configuration name",default:"CLI Config"}).option("description",{type:"string",describe:"Configuration description",default:""}),handler:nae}).command({command:"team-configs",describe:"List available team configurations",builder:e=>e.option("team-id",{type:"string",describe:"Team/subscription ID (uses CDK_INSIGHTS_TEAM_ID env var if not set)"}),handler:rae}).demandCommand(1).help(),handler:()=>{}},lae=()=>{JR(v0(process.argv)).scriptName("cdk-insights").version("1.42.3").usage("Usage: $0 <command> [options]").command(l$).command(p$).command(b$).command(S$).command(_$).command(F$).command(uae).command("hook","Install Git pre-commit hook for CDK Insights",()=>{},()=>f$()).command("synth","Run `cdk synth` automatically before analysis",t=>t.option("path",{type:"string",describe:"Path to the CDK project (defaults to current directory)"}),iae).command("clear-cache","Clear the analysis cache",()=>{},oae).command("cache-status","Show the current cache status",()=>{},aae).demandCommand(1,"Please specify a command.").strict().help().wrap(null).epilog(cae()).parse()};lae();
|
|
586
586
|
/*! Bundled license information:
|
|
587
587
|
|
|
588
588
|
mime-db/index.js:
|
package/dist/index.js
CHANGED
|
@@ -77,7 +77,7 @@ ${JSON.stringify(z)}`}).join(`
|
|
|
77
77
|
`)!=-1,n=this._styles,r=n.length;r--;){var i=Cn[n[r]];t=i.open+t.replace(i.closeRe,i.open)+i.close,s&&(t=t.replace(b_,function(o){return i.close+o+i.open}))}return t}Ae.setTheme=function(e){if(typeof e=="string"){console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");return}for(var t in e)(function(s){Ae[s]=function(n){if(typeof e[s]=="object"){var r=n;for(var i in e[s])r=Ae[e[s][i]](r);return r}return Ae[e[s]](n)}})(t)};function x_(){var e={};return Object.keys(Tv).forEach(function(t){e[t]={get:function(){return kv([t])}}}),e}var w_=function(t,s){var n=s.split("");return n=n.map(t),n.join("")};Ae.trap=yv();Ae.zalgo=bv();Ae.maps={};Ae.maps.america=vv()(Ae);Ae.maps.zebra=Av()(Ae);Ae.maps.rainbow=wv()(Ae);Ae.maps.random=Rv()(Ae);for(Fv in Ae.maps)(function(e){Ae[e]=function(t){return w_(Ae.maps[e],t)}})(Fv);var Fv;Iv(Ae,x_())});var Ov=T((xV,_v)=>{var E_=Lv();_v.exports=E_});var Wv=T((wV,ra)=>{var{info:R_,debug:Nv}=sa(),Rt=El(),Il=class e{constructor(t){this.setOptions(t),this.x=null,this.y=null}setOptions(t){["boolean","number","bigint","string"].indexOf(typeof t)!==-1&&(t={content:""+t}),t=t||{},this.options=t;let s=t.content;if(["boolean","number","bigint","string"].indexOf(typeof s)!==-1)this.content=String(s);else if(!s)this.content=this.options.href||"";else throw new Error("Content needs to be a primitive, got: "+typeof s);this.colSpan=t.colSpan||1,this.rowSpan=t.rowSpan||1,this.options.href&&Object.defineProperty(this,"href",{get(){return this.options.href}})}mergeTableOptions(t,s){this.cells=s;let n=this.options.chars||{},r=t.chars,i=this.chars={};I_.forEach(function(u){Fl(n,r,u,i)}),this.truncate=this.options.truncate||t.truncate;let o=this.options.style=this.options.style||{},a=t.style;Fl(o,a,"padding-left",this),Fl(o,a,"padding-right",this),this.head=o.head||a.head,this.border=o.border||a.border,this.fixedWidth=t.colWidths[this.x],this.lines=this.computeLines(t),this.desiredWidth=Rt.strlen(this.content)+this.paddingLeft+this.paddingRight,this.desiredHeight=this.lines.length}computeLines(t){let s=t.wordWrap||t.textWrap,{wordWrap:n=s}=this.options;if(this.fixedWidth&&n){if(this.fixedWidth-=this.paddingLeft+this.paddingRight,this.colSpan){let o=1;for(;o<this.colSpan;)this.fixedWidth+=t.colWidths[this.x+o],o++}let{wrapOnWordBoundary:r=!0}=t,{wrapOnWordBoundary:i=r}=this.options;return this.wrapLines(Rt.wordWrap(this.fixedWidth,this.content,i))}return this.wrapLines(this.content.split(`
|
|
78
78
|
`))}wrapLines(t){let s=Rt.colorizeLines(t);return this.href?s.map(n=>Rt.hyperlink(this.href,n)):s}init(t){let s=this.x,n=this.y;this.widths=t.colWidths.slice(s,s+this.colSpan),this.heights=t.rowHeights.slice(n,n+this.rowSpan),this.width=this.widths.reduce(Mv,-1),this.height=this.heights.reduce(Mv,-1),this.hAlign=this.options.hAlign||t.colAligns[s],this.vAlign=this.options.vAlign||t.rowAligns[n],this.drawRight=s+this.colSpan==t.colWidths.length}draw(t,s){if(t=="top")return this.drawTop(this.drawRight);if(t=="bottom")return this.drawBottom(this.drawRight);let n=Rt.truncate(this.content,10,this.truncate);t||R_(`${this.y}-${this.x}: ${this.rowSpan-t}x${this.colSpan} Cell ${n}`);let r=Math.max(this.height-this.lines.length,0),i;switch(this.vAlign){case"center":i=Math.ceil(r/2);break;case"bottom":i=r;break;default:i=0}if(t<i||t>=i+this.lines.length)return this.drawEmpty(this.drawRight,s);let o=this.lines.length>this.height&&t+1>=this.height;return this.drawLine(t-i,this.drawRight,o,s)}drawTop(t){let s=[];return this.cells?this.widths.forEach(function(n,r){s.push(this._topLeftChar(r)),s.push(Rt.repeat(this.chars[this.y==0?"top":"mid"],n))},this):(s.push(this._topLeftChar(0)),s.push(Rt.repeat(this.chars[this.y==0?"top":"mid"],this.width))),t&&s.push(this.chars[this.y==0?"topRight":"rightMid"]),this.wrapWithStyleColors("border",s.join(""))}_topLeftChar(t){let s=this.x+t,n;if(this.y==0)n=s==0?"topLeft":t==0?"topMid":"top";else if(s==0)n="leftMid";else if(n=t==0?"midMid":"bottomMid",this.cells&&(this.cells[this.y-1][s]instanceof e.ColSpanCell&&(n=t==0?"topMid":"mid"),t==0)){let i=1;for(;this.cells[this.y][s-i]instanceof e.ColSpanCell;)i++;this.cells[this.y][s-i]instanceof e.RowSpanCell&&(n="leftMid")}return this.chars[n]}wrapWithStyleColors(t,s){if(this[t]&&this[t].length)try{let n=Ov();for(let r=this[t].length-1;r>=0;r--)n=n[this[t][r]];return n(s)}catch{return s}else return s}drawLine(t,s,n,r){let i=this.chars[this.x==0?"left":"middle"];if(this.x&&r&&this.cells){let d=this.cells[this.y+r][this.x-1];for(;d instanceof fi;)d=this.cells[d.y][d.x-1];d instanceof gi||(i=this.chars.rightMid)}let o=Rt.repeat(" ",this.paddingLeft),a=s?this.chars.right:"",u=Rt.repeat(" ",this.paddingRight),c=this.lines[t],l=this.width-(this.paddingLeft+this.paddingRight);n&&(c+=this.truncate||"\u2026");let p=Rt.truncate(c,l,this.truncate);return p=Rt.pad(p,l," ",this.hAlign),p=o+p+u,this.stylizeLine(i,p,a)}stylizeLine(t,s,n){return t=this.wrapWithStyleColors("border",t),n=this.wrapWithStyleColors("border",n),this.y===0&&(s=this.wrapWithStyleColors("head",s)),t+s+n}drawBottom(t){let s=this.chars[this.x==0?"bottomLeft":"bottomMid"],n=Rt.repeat(this.chars.bottom,this.width),r=t?this.chars.bottomRight:"";return this.wrapWithStyleColors("border",s+n+r)}drawEmpty(t,s){let n=this.chars[this.x==0?"left":"middle"];if(this.x&&s&&this.cells){let o=this.cells[this.y+s][this.x-1];for(;o instanceof fi;)o=this.cells[o.y][o.x-1];o instanceof gi||(n=this.chars.rightMid)}let r=t?this.chars.right:"",i=Rt.repeat(" ",this.width);return this.stylizeLine(n,i,r)}},fi=class{constructor(){}draw(t){return typeof t=="number"&&Nv(`${this.y}-${this.x}: 1x1 ColSpanCell`),""}init(){}mergeTableOptions(){}},gi=class{constructor(t){this.originalCell=t}init(t){let s=this.y,n=this.originalCell.y;this.cellOffset=s-n,this.offset=F_(t.rowHeights,n,this.cellOffset)}draw(t){return t=="top"?this.originalCell.draw(this.offset,this.cellOffset):t=="bottom"?this.originalCell.draw("bottom"):(Nv(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`),this.originalCell.draw(this.offset+1+t))}mergeTableOptions(){}};function Bv(...e){return e.filter(t=>t!=null).shift()}function Fl(e,t,s,n){let r=s.split("-");r.length>1?(r[1]=r[1].charAt(0).toUpperCase()+r[1].substr(1),r=r.join(""),n[r]=Bv(e[r],e[s],t[r],t[s])):n[s]=Bv(e[s],t[s])}function F_(e,t,s){let n=e[t];for(let r=1;r<s;r++)n+=1+e[t+r];return n}function Mv(e,t){return e+t+1}var I_=["top","top-mid","top-left","top-right","bottom","bottom-mid","bottom-left","bottom-right","left","left-mid","mid","mid-mid","right","right-mid","middle"];ra.exports=Il;ra.exports.ColSpanCell=fi;ra.exports.RowSpanCell=gi});var $v=T((EV,jv)=>{var{warn:k_,debug:T_}=sa(),kl=Wv(),{ColSpanCell:P_,RowSpanCell:L_}=kl;(function(){function e(m,f){return m[f]>0?e(m,f+1):f}function t(m){let f={};m.forEach(function(g,h){let y=0;g.forEach(function(b){b.y=h,b.x=h?e(f,y):y;let x=b.rowSpan||1,v=b.colSpan||1;if(x>1)for(let E=0;E<v;E++)f[b.x+E]=x;y=b.x+v}),Object.keys(f).forEach(b=>{f[b]--,f[b]<1&&delete f[b]})})}function s(m){let f=0;return m.forEach(function(g){g.forEach(function(h){f=Math.max(f,h.x+(h.colSpan||1))})}),f}function n(m){return m.length}function r(m,f){let g=m.y,h=m.y-1+(m.rowSpan||1),y=f.y,b=f.y-1+(f.rowSpan||1),x=!(g>b||y>h),v=m.x,E=m.x-1+(m.colSpan||1),O=f.x,M=f.x-1+(f.colSpan||1),P=!(v>M||O>E);return x&&P}function i(m,f,g){let h=Math.min(m.length-1,g),y={x:f,y:g};for(let b=0;b<=h;b++){let x=m[b];for(let v=0;v<x.length;v++)if(r(y,x[v]))return!0}return!1}function o(m,f,g,h){for(let y=g;y<h;y++)if(i(m,y,f))return!1;return!0}function a(m){m.forEach(function(f,g){f.forEach(function(h){for(let y=1;y<h.rowSpan;y++){let b=new L_(h);b.x=h.x,b.y=h.y+y,b.colSpan=h.colSpan,c(b,m[g+y])}})})}function u(m){for(let f=m.length-1;f>=0;f--){let g=m[f];for(let h=0;h<g.length;h++){let y=g[h];for(let b=1;b<y.colSpan;b++){let x=new P_;x.x=y.x+b,x.y=y.y,g.splice(h+1,0,x)}}}}function c(m,f){let g=0;for(;g<f.length&&f[g].x<m.x;)g++;f.splice(g,0,m)}function l(m){let f=n(m),g=s(m);T_(`Max rows: ${f}; Max cols: ${g}`);for(let h=0;h<f;h++)for(let y=0;y<g;y++)if(!i(m,y,h)){let b={x:y,y:h,colSpan:1,rowSpan:1};for(y++;y<g&&!i(m,y,h);)b.colSpan++,y++;let x=h+1;for(;x<f&&o(m,x,b.x,b.x+b.colSpan);)b.rowSpan++,x++;let v=new kl(b);v.x=b.x,v.y=b.y,k_(`Missing cell at ${v.y}-${v.x}.`),c(v,m[h])}}function p(m){return m.map(function(f){if(!Array.isArray(f)){let g=Object.keys(f)[0];f=f[g],Array.isArray(f)?(f=f.slice(),f.unshift(g)):f=[g,f]}return f.map(function(g){return new kl(g)})})}function d(m){let f=p(m);return t(f),l(f),a(f),u(f),f}jv.exports={makeTableLayout:d,layoutTable:t,addRowSpanCells:a,maxWidth:s,fillInTable:l,computeWidths:Uv("colSpan","desiredWidth","x",1),computeHeights:Uv("rowSpan","desiredHeight","y",1)}})();function Uv(e,t,s,n){return function(r,i){let o=[],a=[],u={};i.forEach(function(c){c.forEach(function(l){(l[e]||1)>1?a.push(l):o[l[s]]=Math.max(o[l[s]]||0,l[t]||0,n)})}),r.forEach(function(c,l){typeof c=="number"&&(o[l]=c)});for(let c=a.length-1;c>=0;c--){let l=a[c],p=l[e],d=l[s],m=o[d],f=typeof r[d]=="number"?0:1;if(typeof m=="number")for(let g=1;g<p;g++)m+=1+o[d+g],typeof r[d+g]!="number"&&f++;else m=t==="desiredWidth"?l.desiredWidth-1:1,(!u[d]||u[d]<m)&&(u[d]=m);if(l[t]>m){let g=0;for(;f>0&&l[t]>m;){if(typeof r[d+g]!="number"){let h=Math.round((l[t]-m)/f);m+=h,o[d+g]+=h,f--}g++}}}Object.assign(r,o,u);for(let c=0;c<r.length;c++)r[c]=Math.max(n,r[c]||0)}}});var Hv=T((RV,Gv)=>{var Ss=sa(),__=El(),Tl=$v(),ia=class extends Array{constructor(t){super();let s=__.mergeOptions(t);if(Object.defineProperty(this,"options",{value:s,enumerable:s.debug}),s.debug){switch(typeof s.debug){case"boolean":Ss.setDebugLevel(Ss.WARN);break;case"number":Ss.setDebugLevel(s.debug);break;case"string":Ss.setDebugLevel(parseInt(s.debug,10));break;default:Ss.setDebugLevel(Ss.WARN),Ss.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof s.debug}`)}Object.defineProperty(this,"messages",{get(){return Ss.debugMessages()}})}}toString(){let t=this,s=this.options.head&&this.options.head.length;s?(t=[this.options.head],this.length&&t.push.apply(t,this)):this.options.style.head=[];let n=Tl.makeTableLayout(t);n.forEach(function(i){i.forEach(function(o){o.mergeTableOptions(this.options,n)},this)},this),Tl.computeWidths(this.options.colWidths,n),Tl.computeHeights(this.options.rowHeights,n),n.forEach(function(i){i.forEach(function(o){o.init(this.options)},this)},this);let r=[];for(let i=0;i<n.length;i++){let o=n[i],a=this.options.rowHeights[i];(i===0||!this.options.style.compact||i==1&&s)&&Pl(o,"top",r);for(let u=0;u<a;u++)Pl(o,u,r);i+1==n.length&&Pl(o,"bottom",r)}return r.join(`
|
|
79
79
|
`)}get width(){return this.toString().split(`
|
|
80
|
-
`)[0].length}};ia.reset=()=>Ss.reset();function Pl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}Gv.exports=ia});var qv=T((FV,zv)=>{zv.exports=Hv()});var Ll=T((kV,N_)=>{N_.exports={name:"cdk-insights",version:"1.42.
|
|
80
|
+
`)[0].length}};ia.reset=()=>Ss.reset();function Pl(e,t,s){let n=[];e.forEach(function(i){n.push(i.draw(t))});let r=n.join("");r.length&&s.push(r)}Gv.exports=ia});var qv=T((FV,zv)=>{zv.exports=Hv()});var Ll=T((kV,N_)=>{N_.exports={name:"cdk-insights",version:"1.42.3",description:"AWS CDK security and cost analysis CLI. Free static scans via npm \u2014 no account needed. Sign up free to add AI-powered insights.",main:"dist/index.js",types:"dist/index.d.ts",bin:{"cdk-insights":"dist/entry.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.js"}},files:["dist/**/*","README.md","LICENSE"],scripts:{test:"vitest --run",lint:"biome lint src/",typecheck:"tsc --noEmit",format:"biome format --write src/",check:"biome check src/","check:schema-sync":"ts-node scripts/check-schema-sync.ts",build:"ts-node scripts/build.ts","build:dev":"CDK_INSIGHTS_ENVIRONMENT=dev CDK_INSIGHTS_API_URL=https://s2zhmjbwlj.execute-api.eu-west-2.amazonaws.com/v1 ts-node scripts/build.ts",start:"node dist/index.js",dev:"ts-node src/index.ts",prepare:"husky install && npm run build","start:dev":"CDK_ENV=local ts-node src/index.ts","ai-run":"ts-node src/index.ts",unlink:"npm unlink -g cdk-insights",link:"npm link","prepare:test":"npm run unlink && npm run build && npm run link","prepare:dev":"npm run unlink && npm run build:dev && npm run link","deploy:dev":"STAGE=dev cdk deploy","destroy:dev":"STAGE=dev cdk destroy","release:patch":"bumper release patch","release:minor":"bumper release minor","release:major":"bumper release major","release:dry-run":"bumper release patch --dry-run","changelog:preview":"bumper preview","changelog:generate":"bumper generate","validate:commits":"bumper validate","release:check":"npm run validate:commits && npm run test && npm run build","release:full":"npm run release:check && npm run changelog:generate","setup:bumper":"bumper setup","publish:beta":"npm run build && npm publish --tag beta && npm dist-tag add cdk-insights@$npm_package_version latest","publish:alpha":"npm run build && npm publish --tag alpha","publish:canary":"npm run build && npm publish --tag canary","publish:latest":"npm run build && npm publish --tag latest","version:beta":"npm version prerelease --preid=beta","version:alpha":"npm version prerelease --preid=alpha","version:rc":"npm version prerelease --preid=rc","cdk-insights":"node scripts/cdk-insights-wrapper.js",scan:"node scripts/cdk-insights-wrapper.js scan","scan:all":"node scripts/cdk-insights-wrapper.js scan --all","scan:json":"node scripts/cdk-insights-wrapper.js scan --format json","scan:markdown":"node scripts/cdk-insights-wrapper.js scan --format markdown","scan:summary":"node scripts/cdk-insights-wrapper.js scan --format summary","scan:with-issues":"node scripts/cdk-insights-wrapper.js scan --withIssue","cache:clear":"node scripts/cdk-insights-wrapper.js cache clear","cache:status":"node scripts/cdk-insights-wrapper.js cache status","demo:progress":"ts-node src/examples/progress-demo.ts","demo:single-line":"ts-node src/examples/single-line-progress-demo.ts","test:line-clearing":"ts-node src/examples/line-clearing-test.ts"},publishConfig:{access:"public"},keywords:["aws","cdk","cloudformation","analysis","security","cost-optimization","static-analysis","devops","infrastructure","aws-cdk","cloud-security","compliance"],author:"Lee Priest <lee@cdkinsights.dev>",license:"BUSL-1.1",homepage:"https://github.com/instancelabs/cdk-insights",bugs:"https://github.com/instancelabs/cdk-insights/issues",repository:{type:"git",url:"git+https://github.com/instancelabs/cdk-insights.git"},dependencies:{"@inquirer/prompts":"^7.4.1","@middy/core":"^6.1.6","@types/glob":"^8.1.0",axios:"^1.8.4",chalk:"^5.4.1",chokidar:"^3.6.0","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.5.0",envolution:"^1.4.1",glob:"^11.0.3",ora:"^8.2.0",strogger:"^2.0.3",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies:{"@aws-sdk/client-dynamodb":"^3.788.0","@biomejs/biome":"^2.0.6","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@types/cli-progress":"^3.11.6","@types/jsonwebtoken":"^9.0.9","@types/node":"^22.14.1","@types/yargs":"^17.0.33","aws-cdk":"^2.1010.0","bumper-cli":"^1.6.0",esbuild:"^0.25.2",husky:"^8.0.3","ts-node":"^10.9.2",typescript:"^5.8.3",vitest:"^3.1.1"},peerDependencies:{"@aws-solutions-constructs/aws-apigateway-lambda":"^2.0.0","@aws-solutions-constructs/aws-lambda-stepfunctions":"^2.0.0","@aws-solutions-constructs/aws-s3-lambda":"^2.0.0","aws-cdk-lib":"^2.190.0","cdk-nag":"^2.35.73",constructs:"^10.4.2"},peerDependenciesMeta:{"@aws-solutions-constructs/aws-apigateway-lambda":{optional:!0},"@aws-solutions-constructs/aws-lambda-stepfunctions":{optional:!0},"@aws-solutions-constructs/aws-s3-lambda":{optional:!0}}}});var hC={};xi(hC,{STACK_TRACE_CONTEXT_KEY:()=>ga,ensureStackTraceInCdkJson:()=>yO,isStackTraceContextEnabledInCdkJson:()=>SO,patchCdkJsonForStackTrace:()=>gC});var Bs,Kl,ga,gC,yO,SO,yC=ep(()=>{"use strict";Bs=Z(require("node:fs")),Kl=Z(require("node:path")),ga="@aws-cdk/core:stackTrace",gC=e=>{let t;try{t=JSON.parse(e)}catch{return{status:"invalid-json"}}if(t===null||typeof t!="object"||Array.isArray(t))return{status:"invalid-json"};let s=t,n=s.context,r=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};if(r[ga]===!0)return{status:"already-set",updated:e};r[ga]=!0;let i={...s,context:r},o=e.endsWith(`
|
|
81
81
|
`)?`
|
|
82
82
|
`:"";return{status:"added",updated:`${JSON.stringify(i,null,2)}${o}`}},yO=e=>{let t=Kl.join(e,"cdk.json");if(!Bs.existsSync(t))return{status:"missing",cdkJsonPath:t};let s=Bs.readFileSync(t,"utf-8"),n=gC(s);return n.status==="invalid-json"?{status:"invalid-json",cdkJsonPath:t}:n.status==="already-set"?{status:"already-set",cdkJsonPath:t}:(Bs.writeFileSync(t,n.updated,"utf-8"),{status:"added",cdkJsonPath:t})},SO=e=>{try{let t=Kl.join(e,"cdk.json");if(!Bs.existsSync(t))return!1;let s=JSON.parse(Bs.readFileSync(t,"utf-8"));if(!s||typeof s!="object"||Array.isArray(s))return!1;let n=s.context;return!n||typeof n!="object"||Array.isArray(n)?!1:n[ga]===!0}catch{return!1}}});var a2={};xi(a2,{CDK_INSIGHTS_ANNOTATION_PREFIX:()=>va,CDK_INSIGHTS_METADATA_VERSION:()=>Jl,CDK_INSIGHTS_NAG_FINDING_PREFIX:()=>ya,CdkInsightsAspect:()=>Da,CdkInsightsPolicyValidationPlugin:()=>vi,ExtremelyHelpfulConsoleLogger:()=>Di,SCAN_REPORT_SCHEMA_VERSION:()=>FC,clearCaches:()=>EC,createCdkInsightsAspect:()=>wC,createCdkInsightsLogger:()=>AC,createCdkInsightsPolicyValidationPlugin:()=>WC,createExtremelyHelpfulConsoleLogger:()=>xC,getCacheStats:()=>RC,isCdkDebugEnabled:()=>Ql,runAnalysis:()=>o2});module.exports=Fa(a2);var GC=Z(require("node:fs"));function Dr(e,t){return function(){return e.apply(t,arguments)}}var{toString:QC}=Object.prototype,{getPrototypeOf:Ei}=Object,{iterator:Ri,toStringTag:rp}=Symbol,Fi=(e=>t=>{let s=QC.call(t);return e[s]||(e[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),$t=e=>(e=e.toLowerCase(),t=>Fi(t)===e),Ii=e=>t=>typeof t===e,{isArray:wn}=Array,xn=Ii("undefined");function vr(e){return e!==null&&!xn(e)&&e.constructor!==null&&!xn(e.constructor)&&ft(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var ip=$t("ArrayBuffer");function XC(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ip(e.buffer),t}var eA=Ii("string"),ft=Ii("function"),op=Ii("number"),Cr=e=>e!==null&&typeof e=="object",tA=e=>e===!0||e===!1,wi=e=>{if(Fi(e)!=="object")return!1;let t=Ei(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(rp in e)&&!(Ri in e)},sA=e=>{if(!Cr(e)||vr(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},nA=$t("Date"),rA=$t("File"),iA=e=>!!(e&&typeof e.uri<"u"),oA=e=>e&&typeof e.getParts<"u",aA=$t("Blob"),cA=$t("FileList"),uA=e=>Cr(e)&&ft(e.pipe);function lA(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var sp=lA(),np=typeof sp.FormData<"u"?sp.FormData:void 0,pA=e=>{if(!e)return!1;if(np&&e instanceof np)return!0;let t=Ei(e);if(!t||t===Object.prototype||!ft(e.append))return!1;let s=Fi(e);return s==="formdata"||s==="object"&&ft(e.toString)&&e.toString()==="[object FormData]"},dA=$t("URLSearchParams"),[mA,fA,gA,hA]=["ReadableStream","Request","Response","Headers"].map($t),yA=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ar(e,t,{allOwnKeys:s=!1}={}){if(e===null||typeof e>"u")return;let n,r;if(typeof e!="object"&&(e=[e]),wn(e))for(n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else{if(vr(e))return;let i=s?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length,a;for(n=0;n<o;n++)a=i[n],t.call(null,e[a],a,e)}}function ap(e,t){if(vr(e))return null;t=t.toLowerCase();let s=Object.keys(e),n=s.length,r;for(;n-- >0;)if(r=s[n],t===r.toLowerCase())return r;return null}var Ws=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,cp=e=>!xn(e)&&e!==Ws;function Ia(...e){let{caseless:t,skipUndefined:s}=cp(this)&&this||{},n={},r=(i,o)=>{if(o==="__proto__"||o==="constructor"||o==="prototype")return;let a=t&&ap(n,o)||o,u=ka(n,a)?n[a]:void 0;wi(u)&&wi(i)?n[a]=Ia(u,i):wi(i)?n[a]=Ia({},i):wn(i)?n[a]=i.slice():(!s||!xn(i))&&(n[a]=i)};for(let i=0,o=e.length;i<o;i++)e[i]&&Ar(e[i],r);return n}var SA=(e,t,s,{allOwnKeys:n}={})=>(Ar(t,(r,i)=>{s&&ft(r)?Object.defineProperty(e,i,{__proto__:null,value:Dr(r,s),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{__proto__:null,value:r,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),bA=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),DA=(e,t,s,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),s&&Object.assign(e.prototype,s)},vA=(e,t,s,n)=>{let r,i,o,a={};if(t=t||{},e==null)return t;do{for(r=Object.getOwnPropertyNames(e),i=r.length;i-- >0;)o=r[i],(!n||n(o,e,t))&&!a[o]&&(t[o]=e[o],a[o]=!0);e=s!==!1&&Ei(e)}while(e&&(!s||s(e,t))&&e!==Object.prototype);return t},CA=(e,t,s)=>{e=String(e),(s===void 0||s>e.length)&&(s=e.length),s-=t.length;let n=e.indexOf(t,s);return n!==-1&&n===s},AA=e=>{if(!e)return null;if(wn(e))return e;let t=e.length;if(!op(t))return null;let s=new Array(t);for(;t-- >0;)s[t]=e[t];return s},xA=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ei(Uint8Array)),wA=(e,t)=>{let n=(e&&e[Ri]).call(e),r;for(;(r=n.next())&&!r.done;){let i=r.value;t.call(e,i[0],i[1])}},EA=(e,t)=>{let s,n=[];for(;(s=e.exec(t))!==null;)n.push(s);return n},RA=$t("HTMLFormElement"),FA=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,n,r){return n.toUpperCase()+r}),ka=(({hasOwnProperty:e})=>(t,s)=>e.call(t,s))(Object.prototype),IA=$t("RegExp"),up=(e,t)=>{let s=Object.getOwnPropertyDescriptors(e),n={};Ar(s,(r,i)=>{let o;(o=t(r,i,e))!==!1&&(n[i]=o||r)}),Object.defineProperties(e,n)},kA=e=>{up(e,(t,s)=>{if(ft(e)&&["arguments","caller","callee"].includes(s))return!1;let n=e[s];if(ft(n)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+s+"'")})}})},TA=(e,t)=>{let s={},n=r=>{r.forEach(i=>{s[i]=!0})};return wn(e)?n(e):n(String(e).split(t)),s},PA=()=>{},LA=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _A(e){return!!(e&&ft(e.append)&&e[rp]==="FormData"&&e[Ri])}var OA=e=>{let t=new Array(10),s=(n,r)=>{if(Cr(n)){if(t.indexOf(n)>=0)return;if(vr(n))return n;if(!("toJSON"in n)){t[r]=n;let i=wn(n)?[]:{};return Ar(n,(o,a)=>{let u=s(o,r+1);!xn(u)&&(i[a]=u)}),t[r]=void 0,i}}return n};return s(e,0)},BA=$t("AsyncFunction"),MA=e=>e&&(Cr(e)||ft(e))&&ft(e.then)&&ft(e.catch),lp=((e,t)=>e?setImmediate:t?((s,n)=>(Ws.addEventListener("message",({source:r,data:i})=>{r===Ws&&i===s&&n.length&&n.shift()()},!1),r=>{n.push(r),Ws.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",ft(Ws.postMessage)),NA=typeof queueMicrotask<"u"?queueMicrotask.bind(Ws):typeof process<"u"&&process.nextTick||lp,WA=e=>e!=null&&ft(e[Ri]),D={isArray:wn,isArrayBuffer:ip,isBuffer:vr,isFormData:pA,isArrayBufferView:XC,isString:eA,isNumber:op,isBoolean:tA,isObject:Cr,isPlainObject:wi,isEmptyObject:sA,isReadableStream:mA,isRequest:fA,isResponse:gA,isHeaders:hA,isUndefined:xn,isDate:nA,isFile:rA,isReactNativeBlob:iA,isReactNative:oA,isBlob:aA,isRegExp:IA,isFunction:ft,isStream:uA,isURLSearchParams:dA,isTypedArray:xA,isFileList:cA,forEach:Ar,merge:Ia,extend:SA,trim:yA,stripBOM:bA,inherits:DA,toFlatObject:vA,kindOf:Fi,kindOfTest:$t,endsWith:CA,toArray:AA,forEachEntry:wA,matchAll:EA,isHTMLForm:RA,hasOwnProperty:ka,hasOwnProp:ka,reduceDescriptors:up,freezeMethods:kA,toObjectSet:TA,toCamelCase:FA,noop:PA,toFiniteNumber:LA,findKey:ap,global:Ws,isContextDefined:cp,isSpecCompliantForm:_A,toJSONObject:OA,isAsyncFn:BA,isThenable:MA,setImmediate:lp,asap:NA,isIterable:WA};var UA=D.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),pp=e=>{let t={},s,n,r;return e&&e.split(`
|
|
83
83
|
`).forEach(function(o){r=o.indexOf(":"),s=o.substring(0,r).trim().toLowerCase(),n=o.substring(r+1).trim(),!(!s||t[s]&&UA[s])&&(s==="set-cookie"?t[s]?t[s].push(n):t[s]=[n]:t[s]=t[s]?t[s]+", "+n:n)}),t};var dp=Symbol("internals"),jA=/[^\x09\x20-\x7E\x80-\xFF]/g;function $A(e){let t=0,s=e.length;for(;t<s;){let n=e.charCodeAt(t);if(n!==9&&n!==32)break;t+=1}for(;s>t;){let n=e.charCodeAt(s-1);if(n!==9&&n!==32)break;s-=1}return t===0&&s===e.length?e:e.slice(t,s)}function xr(e){return e&&String(e).trim().toLowerCase()}function GA(e){return $A(e.replace(jA,""))}function ki(e){return e===!1||e==null?e:D.isArray(e)?e.map(ki):GA(String(e))}function HA(e){let t=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=s.exec(e);)t[n[1]]=n[2];return t}var zA=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ta(e,t,s,n,r){if(D.isFunction(n))return n.call(this,t,s);if(r&&(t=s),!!D.isString(t)){if(D.isString(n))return t.indexOf(n)!==-1;if(D.isRegExp(n))return n.test(t)}}function qA(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,s,n)=>s.toUpperCase()+n)}function KA(e,t){let s=D.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+s,{__proto__:null,value:function(r,i,o){return this[n].call(this,t,r,i,o)},configurable:!0})})}var En=class{constructor(t){t&&this.set(t)}set(t,s,n){let r=this;function i(a,u,c){let l=xr(u);if(!l)throw new Error("header name must be a non-empty string");let p=D.findKey(r,l);(!p||r[p]===void 0||c===!0||c===void 0&&r[p]!==!1)&&(r[p||u]=ki(a))}let o=(a,u)=>D.forEach(a,(c,l)=>i(c,l,u));if(D.isPlainObject(t)||t instanceof this.constructor)o(t,s);else if(D.isString(t)&&(t=t.trim())&&!zA(t))o(pp(t),s);else if(D.isObject(t)&&D.isIterable(t)){let a={},u,c;for(let l of t){if(!D.isArray(l))throw TypeError("Object iterator must return a key-value pair");a[c=l[0]]=(u=a[c])?D.isArray(u)?[...u,l[1]]:[u,l[1]]:l[1]}o(a,s)}else t!=null&&i(s,t,n);return this}get(t,s){if(t=xr(t),t){let n=D.findKey(this,t);if(n){let r=this[n];if(!s)return r;if(s===!0)return HA(r);if(D.isFunction(s))return s.call(this,r,n);if(D.isRegExp(s))return s.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,s){if(t=xr(t),t){let n=D.findKey(this,t);return!!(n&&this[n]!==void 0&&(!s||Ta(this,this[n],n,s)))}return!1}delete(t,s){let n=this,r=!1;function i(o){if(o=xr(o),o){let a=D.findKey(n,o);a&&(!s||Ta(n,n[a],a,s))&&(delete n[a],r=!0)}}return D.isArray(t)?t.forEach(i):i(t),r}clear(t){let s=Object.keys(this),n=s.length,r=!1;for(;n--;){let i=s[n];(!t||Ta(this,this[i],i,t,!0))&&(delete this[i],r=!0)}return r}normalize(t){let s=this,n={};return D.forEach(this,(r,i)=>{let o=D.findKey(n,i);if(o){s[o]=ki(r),delete s[i];return}let a=t?qA(i):String(i).trim();a!==i&&delete s[i],s[a]=ki(r),n[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let s=Object.create(null);return D.forEach(this,(n,r)=>{n!=null&&n!==!1&&(s[r]=t&&D.isArray(n)?n.join(", "):n)}),s}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,s])=>t+": "+s).join(`
|
|
@@ -124,7 +124,7 @@ ${q.comment("\u{1F4A1} Next Steps:")}`),W?(e.log(q.error(" \u274C Trial expire
|
|
|
124
124
|
`)},displayQuotaWarning:_=>{let{currentResourcesAnalyzed:U,maxResources:Y,requestedResources:ae,isTrial:W}=_;if(!W)return;U+ae>Y&&(e.log(`
|
|
125
125
|
${q.warning.bold("\u26A0\uFE0F AI credit allowance exceeded")}`),e.log(q.comment("\u2500".repeat(40))),e.log(q.warning(` You've used ${U}/${Y} AI credits`)),e.log(q.warning(` This analysis would add ${ae} more`)),e.log(q.warning(` Total would be ${U+ae}/${Y}`)),e.log(`
|
|
126
126
|
${q.info("\u{1F4CB} Falling back to static analysis only")}`),e.log(q.comment("\u{1F4A1} Upgrade to Pro for unlimited AI analysis: https://cdkinsights.dev/pricing")),e.log(`${q.comment("\u2500".repeat(40))}
|
|
127
|
-
`))}}},V=SL();var CD=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var pl=null,AD=e=>{pl=e};var dl=()=>{if(pl&&!process.env.CI)try{pl.saveToDisk(),st.info("\u{1F4BE} Cache saved to disk on exit")}catch(e){st.warn("\u26A0\uFE0F Could not save cache on exit",{error:e instanceof Error?e.message:String(e)})}};process.on("exit",dl);process.on("SIGINT",()=>{dl(),process.exit(0)});process.on("SIGTERM",()=>{dl(),process.exit(0)});var bL={maxConcurrent:ei.DEFAULT_MAX_CONCURRENT,retryAttempts:ei.DEFAULT_RETRY_ATTEMPTS,retryDelay:ei.DEFAULT_RETRY_DELAY_MS,timeoutMs:ei.DEFAULT_TIMEOUT_MS},DL=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},Qo=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${ur(t,n)}${r}`},vL=e=>{let t=$r({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=t.get(i)||0;return DL(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},CL=({analyzeResource:e,redactionMapping:t,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:u,originalResources:c,relationships:l,aiModelId:p})=>async({redactedId:d,redactedResources:m,findingsByResource:f,progressTracker:g})=>{let h=f.get(d)||[],y=m[d];if(!y)return{status:"skipped",redactedId:d};let x=wu(d,y,i,o,[]),v=Eu(x),E=t[d];if(!E)return{status:"skipped",redactedId:d};let O=E,M=()=>(s[O]||(s[O]={issues:[]}),s[O]),P=u.get(v);if(P){let ie=(P.issues||[]).map(_=>({..._,resource:O,resourceId:O})),se=M();return se.issues.push(...bn({existing:se.issues,incoming:ie})),se.resourceName=P.resourceName,{status:"success",redactedId:d,resourceKey:O,remappedIssues:ie,resourceName:P.resourceName}}let X=ur(a,E),B=ur("cdk-insights-stack",a),z=eo(E,l,c),ne={dependencies:z.dependencies.map(ie=>Qo(ie,a)),dependents:z.dependents.map(ie=>Qo(ie,a)),usageDescription:z.usageDescription};for(let ie=1;ie<=r.retryAttempts;ie++)try{let se=await Promise.race([e(B,X,y,y.Type,i,o,h,g,ne,p),new Promise((Y,ae)=>setTimeout(()=>ae(new Error("Analysis timeout")),r.timeoutMs))]);se.resourceId=O;let _=(se.issues||[]).map(Y=>({...Y,resource:O,resourceId:O})),U=M();return U.issues.push(...bn({existing:U.issues,incoming:_})),U.resourceName=se.resourceName,u.set(v,se,x),{status:"success",redactedId:d,resourceKey:O,remappedIssues:_,resourceName:se.resourceName}}catch(se){if(ie===r.retryAttempts)return n({analysisError:se,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ie-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},AL=async(e,t,s)=>{let n=Math.max(1,Math.floor(t)),r=0,i=Array.from({length:Math.min(n,e.length)}).map(async()=>{for(;r<e.length;){let o=r;r+=1;let a=e[o];await s(a)}});await Promise.allSettled(i)},xL=10,xD=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=bL})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:u,fingerprint:c,noCache:l=!1,cacheConfig:p,aiModelId:d,aiBatchSize:m})=>{let f={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:y,mapping:b}=s(i),x=pb(a,b,u),v=new Map;for(let W of x){let ee=v.get(W.resourceId);ee?ee.push(W):v.set(W.resourceId,[W])}let E=Object.keys(y),O=E.length,M=Ks(i),P=new No({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});AD(P);let X=vL(n),B=CL({analyzeResource:e,redactionMapping:b,aggregatedResult:f,errorHandler:X,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:P,originalResources:i,relationships:M,aiModelId:d}),z=Yo.createSingleLineProgressTracker(O,"Analyzing resources with AI"),ne=Math.min(Math.max(1,Math.floor(m??1)),xL);if(ne>1&&!!t&&t){st.debug("Batched analysis enabled",{batchSize:ne,totalResources:O});let W=ur("cdk-insights-stack",r),ee=te=>{let pe=eo(te,M,i);return{dependencies:pe.dependencies.map(ce=>Qo(ce,r)),dependents:pe.dependents.map(ce=>Qo(ce,r)),usageDescription:pe.usageDescription}};for(let te=0;te<E.length;te+=ne){let pe=E.slice(te,te+ne),ce=async()=>{for(let re of pe){let G=await B({redactedId:re,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,G.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:re,resourceData:y[re],resourceType:y[re].Type,existingFindings:v.get(re)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},Le=new Map,De=[];for(let re of pe){let G=y[re],k=b[re];if(!G||!k){h.processedCount++,h.failureCount++;continue}let J=wu(re,G,o,c,[]),Se=Eu(J),K=P.get(Se);if(K){let He=(K.issues||[]).map(mt=>({...mt,resource:k,resourceId:k}));f[k]||(f[k]={issues:[]});let xe=f[k];xe.issues.push(...bn({existing:xe.issues,incoming:He})),xe.resourceName=K.resourceName,h.processedCount++,h.successCount++;continue}let he=ur(r,k);Le.set(he,{redactedId:re,originalResourceId:k,cacheKey:Se,cacheComponents:J}),De.push({stableResourceId:he,resourceData:G,resourceType:G.Type,context:ee(k),existingFindings:v.get(re)||[]})}if(De.length!==0)try{let re=await Promise.race([t(W,De,o,c,d),new Promise((G,k)=>setTimeout(()=>k(new Error("Analysis timeout")),n.timeoutMs))]);for(let[G,k]of Le){let J=re.get(G);if(h.processedCount++,!J){st.warn(`Batched response missing entry for resource ${k.originalResourceId}`,{stableResourceId:G,redactedId:k.redactedId}),h.failureCount++;continue}let Se=(J.issues||[]).map(he=>({...he,resource:k.originalResourceId,resourceId:k.originalResourceId}));f[k.originalResourceId]||(f[k.originalResourceId]={issues:[]});let K=f[k.originalResourceId];K.issues.push(...bn({existing:K.issues,incoming:Se})),K.resourceName=J.resourceName,P.set(k.cacheKey,{resourceId:k.originalResourceId,issues:J.issues||[],resourceName:J.resourceName},k.cacheComponents),h.successCount++}}catch(re){st.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:re instanceof Error?re.message:String(re),chunkSize:pe.length}),await ce()}}}else await AL(E,n.maxConcurrent,async W=>{st.debug(`Starting analysis for resource ${W}`,{redactedId:W,maxConcurrent:n.maxConcurrent});let ee=await B({redactedId:W,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,st.debug(`Resource ${W} analysis result: ${ee.status}`,{redactedId:W,status:ee.status,hasProgressTracker:!!z}),ee.status){case"success":h.successCount++,st.debug(`Resource ${W} completed successfully`,{redactedId:W,resourceKey:ee.resourceKey});break;case"timeout":h.timeoutCount++,st.warn(`Resource ${W} timed out`,{redactedId:W}),g.push({redactedId:W,resourceData:y[W],resourceType:y[W].Type,existingFindings:v.get(W)||[]});break;case"fail":case"skipped":h.failureCount++,st.warn(`Resource ${W} failed or was skipped`,{redactedId:W,status:ee.status});break}});let se=Date.now()-h.startTime,_=z.getStats();if(st.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:h,totalTime:se,totalResources:O,maxConcurrent:n.maxConcurrent}),V.analysisComplete(se,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let W=h.successCount>0?Math.round(se/1e3/h.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${W}s`),V.comment(` \u{1F4CA} Success rate: ${(h.successCount/O*100).toFixed(1)}%`)}if(g.length>0){V.newline(),V.warning("\u23F0 Timed Out Resources:"),V.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let W of g){if(V.comment(` \u274C ${W.resourceType}: ${W.redactedId}`),W.resourceData?.Properties){let te=W.resourceData.Properties,pe=CD(te);V.comment(` \u{1F4DD} Name: ${pe}`)}W.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${W.existingFindings.length}`),W.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(W.resourceType)&&V.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}V.newline(),V.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),V.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),V.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let U=new Set(Object.keys(f)),Y=new Set(Object.values(b)),ae=Array.from(Y).filter(W=>!U.has(W)||!f[W]?.issues?.length);if(ae.length>0){let W=P.getCachedResultsForResources(ae),ee=0;for(let[te,pe]of Array.from(W.entries())){if(f[te]?.issues?.length>0)continue;let ce=(pe.issues||[]).map(Le=>({...Le,resource:te,resourceId:te}));ce.length>0&&(f[te]||(f[te]={issues:[]}),f[te].issues.push(...ce),f[te].resourceName=pe.resourceName,ee+=ce.length)}ee>0}return f};var fl=require("node:child_process"),nt=Z(require("node:fs")),gl=Z(require("node:os")),li=Z(require("node:path"));var ED="1.42.2",wL={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},wD=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),EL=(e,t)=>{let s=0;if(s+=2e3,t){let n=Object.values(e).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(e)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},RL=e=>e?e.split(`
|
|
127
|
+
`))}}},V=SL();var CD=e=>e&&(e.Name||e.ResourceName||e.FunctionName)||"Unnamed";var pl=null,AD=e=>{pl=e};var dl=()=>{if(pl&&!process.env.CI)try{pl.saveToDisk(),st.info("\u{1F4BE} Cache saved to disk on exit")}catch(e){st.warn("\u26A0\uFE0F Could not save cache on exit",{error:e instanceof Error?e.message:String(e)})}};process.on("exit",dl);process.on("SIGINT",()=>{dl(),process.exit(0)});process.on("SIGTERM",()=>{dl(),process.exit(0)});var bL={maxConcurrent:ei.DEFAULT_MAX_CONCURRENT,retryAttempts:ei.DEFAULT_RETRY_ATTEMPTS,retryDelay:ei.DEFAULT_RETRY_DELAY_MS,timeoutMs:ei.DEFAULT_TIMEOUT_MS},DL=e=>{if(!(e instanceof Error))return!1;let t=e.message??"";return t.startsWith("Polling timed out")||t==="Analysis timeout"||t.toLowerCase().includes("timeout")},Qo=(e,t)=>{let s=e.match(/^(.+?)(\s\([^)]+\))?$/);if(!s)return e;let[,n,r=""]=s;return`${ur(t,n)}${r}`},vL=e=>{let t=$r({ttl:6e4,maxSize:1e3});return({analysisError:s,redactedId:n})=>{let r=s instanceof Error?s.message:"unknown",i=`${n}:${r}`,o=t.get(i)||0;return DL(s)?{status:"timeout",redactedId:n}:(t.set(i,o+1),o>e.retryAttempts?{status:"skipped",redactedId:n}:{status:"fail",redactedId:n,error:s})}},CL=({analyzeResource:e,redactionMapping:t,aggregatedResult:s,errorHandler:n,config:r,authToken:i,fingerprint:o,stackName:a,analysisCache:u,originalResources:c,relationships:l,aiModelId:p})=>async({redactedId:d,redactedResources:m,findingsByResource:f,progressTracker:g})=>{let h=f.get(d)||[],y=m[d];if(!y)return{status:"skipped",redactedId:d};let x=wu(d,y,i,o,[]),v=Eu(x),E=t[d];if(!E)return{status:"skipped",redactedId:d};let O=E,M=()=>(s[O]||(s[O]={issues:[]}),s[O]),P=u.get(v);if(P){let ie=(P.issues||[]).map(_=>({..._,resource:O,resourceId:O})),se=M();return se.issues.push(...bn({existing:se.issues,incoming:ie})),se.resourceName=P.resourceName,{status:"success",redactedId:d,resourceKey:O,remappedIssues:ie,resourceName:P.resourceName}}let X=ur(a,E),B=ur("cdk-insights-stack",a),z=eo(E,l,c),ne={dependencies:z.dependencies.map(ie=>Qo(ie,a)),dependents:z.dependents.map(ie=>Qo(ie,a)),usageDescription:z.usageDescription};for(let ie=1;ie<=r.retryAttempts;ie++)try{let se=await Promise.race([e(B,X,y,y.Type,i,o,h,g,ne,p),new Promise((Y,ae)=>setTimeout(()=>ae(new Error("Analysis timeout")),r.timeoutMs))]);se.resourceId=O;let _=(se.issues||[]).map(Y=>({...Y,resource:O,resourceId:O})),U=M();return U.issues.push(...bn({existing:U.issues,incoming:_})),U.resourceName=se.resourceName,u.set(v,se,x),{status:"success",redactedId:d,resourceKey:O,remappedIssues:_,resourceName:se.resourceName}}catch(se){if(ie===r.retryAttempts)return n({analysisError:se,redactedId:d});await new Promise(_=>setTimeout(_,r.retryDelay*2**(ie-1)))}return{status:"fail",redactedId:d,error:new Error("Max retries exceeded")}},AL=async(e,t,s)=>{let n=Math.max(1,Math.floor(t)),r=0,i=Array.from({length:Math.min(n,e.length)}).map(async()=>{for(;r<e.length;){let o=r;r+=1;let a=e[o];await s(a)}});await Promise.allSettled(i)},xL=10,xD=({analyzeResource:e,analyzeResourcesBatch:t,redactResources:s,config:n=bL})=>async({stackName:r,resources:i,authToken:o,existingFindingsMap:a,pathToLogicalId:u,fingerprint:c,noCache:l=!1,cacheConfig:p,aiModelId:d,aiBatchSize:m})=>{let f={},g=[],h={startTime:Date.now(),processedCount:0,successCount:0,failureCount:0,timeoutCount:0},{redactedResources:y,mapping:b}=s(i),x=pb(a,b,u),v=new Map;for(let W of x){let ee=v.get(W.resourceId);ee?ee.push(W):v.set(W.resourceId,[W])}let E=Object.keys(y),O=E.length,M=Ks(i),P=new No({ttl:p?.ttl||6*60*60*1e3,maxSize:p?.maxSize||5e3,disabled:l||!p?.enabled});AD(P);let X=vL(n),B=CL({analyzeResource:e,redactionMapping:b,aggregatedResult:f,errorHandler:X,config:n,authToken:o,fingerprint:c,stackName:r,analysisCache:P,originalResources:i,relationships:M,aiModelId:d}),z=Yo.createSingleLineProgressTracker(O,"Analyzing resources with AI"),ne=Math.min(Math.max(1,Math.floor(m??1)),xL);if(ne>1&&!!t&&t){st.debug("Batched analysis enabled",{batchSize:ne,totalResources:O});let W=ur("cdk-insights-stack",r),ee=te=>{let pe=eo(te,M,i);return{dependencies:pe.dependencies.map(ce=>Qo(ce,r)),dependents:pe.dependents.map(ce=>Qo(ce,r)),usageDescription:pe.usageDescription}};for(let te=0;te<E.length;te+=ne){let pe=E.slice(te,te+ne),ce=async()=>{for(let re of pe){let G=await B({redactedId:re,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,G.status){case"success":h.successCount++;break;case"timeout":h.timeoutCount++,g.push({redactedId:re,resourceData:y[re],resourceType:y[re].Type,existingFindings:v.get(re)||[]});break;case"fail":case"skipped":h.failureCount++;break}}},Le=new Map,De=[];for(let re of pe){let G=y[re],k=b[re];if(!G||!k){h.processedCount++,h.failureCount++;continue}let J=wu(re,G,o,c,[]),Se=Eu(J),K=P.get(Se);if(K){let He=(K.issues||[]).map(mt=>({...mt,resource:k,resourceId:k}));f[k]||(f[k]={issues:[]});let xe=f[k];xe.issues.push(...bn({existing:xe.issues,incoming:He})),xe.resourceName=K.resourceName,h.processedCount++,h.successCount++;continue}let he=ur(r,k);Le.set(he,{redactedId:re,originalResourceId:k,cacheKey:Se,cacheComponents:J}),De.push({stableResourceId:he,resourceData:G,resourceType:G.Type,context:ee(k),existingFindings:v.get(re)||[]})}if(De.length!==0)try{let re=await Promise.race([t(W,De,o,c,d),new Promise((G,k)=>setTimeout(()=>k(new Error("Analysis timeout")),n.timeoutMs))]);for(let[G,k]of Le){let J=re.get(G);if(h.processedCount++,!J){st.warn(`Batched response missing entry for resource ${k.originalResourceId}`,{stableResourceId:G,redactedId:k.redactedId}),h.failureCount++;continue}let Se=(J.issues||[]).map(he=>({...he,resource:k.originalResourceId,resourceId:k.originalResourceId}));f[k.originalResourceId]||(f[k.originalResourceId]={issues:[]});let K=f[k.originalResourceId];K.issues.push(...bn({existing:K.issues,incoming:Se})),K.resourceName=J.resourceName,P.set(k.cacheKey,{resourceId:k.originalResourceId,issues:J.issues||[],resourceName:J.resourceName},k.cacheComponents),h.successCount++}}catch(re){st.warn("Batched analysis call failed \u2014 falling back to per-resource for this chunk",{error:re instanceof Error?re.message:String(re),chunkSize:pe.length}),await ce()}}}else await AL(E,n.maxConcurrent,async W=>{st.debug(`Starting analysis for resource ${W}`,{redactedId:W,maxConcurrent:n.maxConcurrent});let ee=await B({redactedId:W,redactedResources:y,findingsByResource:v,progressTracker:z});switch(h.processedCount++,st.debug(`Resource ${W} analysis result: ${ee.status}`,{redactedId:W,status:ee.status,hasProgressTracker:!!z}),ee.status){case"success":h.successCount++,st.debug(`Resource ${W} completed successfully`,{redactedId:W,resourceKey:ee.resourceKey});break;case"timeout":h.timeoutCount++,st.warn(`Resource ${W} timed out`,{redactedId:W}),g.push({redactedId:W,resourceData:y[W],resourceType:y[W].Type,existingFindings:v.get(W)||[]});break;case"fail":case"skipped":h.failureCount++,st.warn(`Resource ${W} failed or was skipped`,{redactedId:W,status:ee.status});break}});let se=Date.now()-h.startTime,_=z.getStats();if(st.debug("Analysis completed with progress tracker stats",{progressTrackerStats:_,performanceMetrics:h,totalTime:se,totalResources:O,maxConcurrent:n.maxConcurrent}),V.analysisComplete(se,h.successCount,h.failureCount,h.timeoutCount),h.failureCount>0||h.timeoutCount>0){V.newline(),V.info("\u{1F4CA} Performance Analysis:");let W=h.successCount>0?Math.round(se/1e3/h.successCount):0;V.comment(` \u23F1\uFE0F Average completion time: ${W}s`),V.comment(` \u{1F4CA} Success rate: ${(h.successCount/O*100).toFixed(1)}%`)}if(g.length>0){V.newline(),V.warning("\u23F0 Timed Out Resources:"),V.comment(` \u{1F4CB} Total timed out: ${g.length}`);for(let W of g){if(V.comment(` \u274C ${W.resourceType}: ${W.redactedId}`),W.resourceData?.Properties){let te=W.resourceData.Properties,pe=CD(te);V.comment(` \u{1F4DD} Name: ${pe}`)}W.existingFindings.length>0&&V.comment(` \u{1F50D} Existing findings: ${W.existingFindings.length}`),W.resourceData?.Metadata&&V.comment(" \u{1F4CD} Has metadata: Yes"),["AWS::CloudFormation::Stack","AWS::Serverless::Application","AWS::ECS::Service"].includes(W.resourceType)&&V.comment(" \u26A0\uFE0F Complex resource type - may require extended analysis time")}V.newline(),V.info("\u{1F4A1} Tip: Some resources are taking longer to analyze than expected."),V.comment(" This is normal for complex resources. The analysis will continue with the remaining resources."),V.warning(`Retrying ${g.length} resource${g.length===1?"":"s"} that need a little more time...`)}let U=new Set(Object.keys(f)),Y=new Set(Object.values(b)),ae=Array.from(Y).filter(W=>!U.has(W)||!f[W]?.issues?.length);if(ae.length>0){let W=P.getCachedResultsForResources(ae),ee=0;for(let[te,pe]of Array.from(W.entries())){if(f[te]?.issues?.length>0)continue;let ce=(pe.issues||[]).map(Le=>({...Le,resource:te,resourceId:te}));ce.length>0&&(f[te]||(f[te]={issues:[]}),f[te].issues.push(...ce),f[te].resourceName=pe.resourceName,ee+=ce.length)}ee>0}return f};var fl=require("node:child_process"),nt=Z(require("node:fs")),gl=Z(require("node:os")),li=Z(require("node:path"));var ED="1.42.3",wL={Security:"https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/",Reliability:"https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/","Performance Efficiency":"https://docs.aws.amazon.com/wellarchitected/latest/performance-efficiency-pillar/","Cost Optimization":"https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/","Operational Excellence":"https://docs.aws.amazon.com/wellarchitected/latest/operational-excellence-pillar/",Sustainability:"https://docs.aws.amazon.com/wellarchitected/latest/sustainability-pillar/"},wD=e=>e.toLowerCase().replace(/[^\w\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),EL=(e,t)=>{let s=0;if(s+=2e3,t){let n=Object.values(e).filter(r=>{let i=r.sources.cdkInsights?.issues??[],o=r.sources.cdkNag?.issues??[];return i.length>0||o.length>0});s+=n.length*100}for(let[,n]of Object.entries(e)){let r=n.sources.cdkInsights?.issues??[],i=n.sources.cdkNag?.issues??[];for(let o of[...r,...i])s+=o.issue.length,s+=o.recommendation?.length||0,s+=o.codeSnippet?.length||0,s+=500}return s},RL=e=>e?e.split(`
|
|
128
128
|
`).map(t=>t.trim()).filter(Boolean).join(`
|
|
129
129
|
`):"",ml=e=>{let t=`- **Issue:** ${e.issue}`;return e.recommendation&&(t+=`
|
|
130
130
|
- **Recommendation:** ${RL(e.recommendation)}`),e.context&&(e.context.property&&(t+=`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cdk-insights",
|
|
3
|
-
"version": "1.42.
|
|
3
|
+
"version": "1.42.3",
|
|
4
4
|
"description": "AWS CDK security and cost analysis CLI. Free static scans via npm — no account needed. Sign up free to add AI-powered insights.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|