@constellationdev/cli 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/main.js +41 -41
  3. package/package.json +7 -6
package/README.md CHANGED
@@ -54,6 +54,8 @@ _Additional languages (C, C++, C#, Go, Java, JSON, PHP, Ruby, Shell) coming soon
54
54
  npm install -g @constellationdev/cli@latest
55
55
  ```
56
56
 
57
+ Both `constellation` and the shorter alias `const` are installed and interchangeable. Every example below uses `constellation`, but `const` accepts the same subcommands, flags, and arguments.
58
+
57
59
  ### Requirements
58
60
 
59
61
  - Node.js 24.0.0 or higher
package/dist/main.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import {z}from'zod';import {base32}from'@scure/base';import {Readable}from'stream';import p from'ansi-colors';import*as Ie from'os';import Ie__default from'os';import*as Et from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as fr from'zlib';import fr__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import {execFile,execFileSync,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import*as N from'path';import N__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as B from'fs/promises';import B__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import Ca from'tree-sitter-javascript';import wa from'tree-sitter-python';import _a from'tree-sitter-typescript';import fl from'tree-sitter';import ai from'ignore';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var yo=Object.defineProperty;var y=(i,e)=>()=>(i&&(e=i(i=0)),e);var qr=(i,e)=>{for(var t in e)yo(i,t,{get:e[t],enumerable:true});};var nt,qt=y(()=>{nt=["help","--help","-h","--version","-V","-v"];});var vo,J,Te,So,fe,$e,Co,wo,_o,je,xo,Eo,Po,Io,No,Ro,To,$o,jo,Lo,Fo,ko,Ao,Do,Oo,Mo,Bo,Xr,Uo,Go,zo,Ho,Wo,Ko,Jo,Vo,qo,Yo,Xo,Qo,Zo,es,ts,rs,Zr,ns,is,Yt,os,ss,as,ls,Le,cs,ps,us,ds,ms,en,tn,Qr,gs,fs,hs,ys,bs,vs,Ss,Cs,rn,nn,on,sn,ws,_s,xs,an,ln,Fe=y(()=>{vo=z.object({total:z.number().int().nonnegative(),returned:z.number().int().nonnegative(),hasMore:z.boolean(),nextOffset:z.number().int().nonnegative().optional(),currentOffset:z.number().int().nonnegative().optional()}),z.object({overall:z.number().min(0).max(1),factors:z.object({dataFreshness:z.number().min(0).max(1).optional(),coverageComplete:z.number().min(0).max(1).optional(),heuristicAccuracy:z.number().min(0).max(1).optional(),semanticAnalysisDepth:z.number().min(0).max(1).optional(),patternMatchQuality:z.number().min(0).max(1).optional()}).optional(),warnings:z.array(z.string()).optional(),recommendations:z.array(z.string()).optional()}),z.object({qualityScore:z.number().min(0).max(100).optional(),lastUpdated:z.string().optional(),cached:z.boolean().optional(),executionTime:z.number().nonnegative().optional(),coveragePercentage:z.number().min(0).max(100).optional(),issues:z.array(z.string()).optional()}),J=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),Te=z.enum(["low","medium","high","critical"]),So=z.enum(["low","moderate","high","very_high"]),fe=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:So}),$e=z.object({filePath:z.string(),line:z.number().int().positive().optional(),lineStart:z.number().int().positive().optional(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional()}),$e.extend({symbolId:z.string().optional(),symbolName:z.string().optional(),symbolKind:z.string().optional()}),z.object({outgoing:z.array(z.string()),incoming:z.array(z.string())}),Co=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),wo=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),_o=z.object({nodes:z.array(Co),edges:z.array(wo),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),je=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),xo=$e.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),isExported:z.boolean(),usageCount:z.number().int().nonnegative().optional(),complexity:fe.optional(),languageMetadata:J.optional()}),z.object({symbols:z.array(xo),pagination:vo.optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeReferences:z.boolean().optional(),includeRelationships:z.boolean().optional(),includeImpactScore:z.boolean().optional()}),Eo=$e.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),modifiers:z.array(z.string()).optional(),typeInfo:z.any().optional(),decorators:z.array(z.string()).optional(),isExported:z.boolean(),isDeprecated:z.boolean(),complexity:fe.optional(),languageMetadata:J.optional()}),Po=$e.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),Io=z.object({calls:z.array(z.string()),calledBy:z.array(z.string()),inheritsFrom:z.array(z.string()),inheritedBy:z.array(z.string()),children:z.array(z.string())}),No=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:Te}),z.object({symbol:Eo,references:z.array(Po).optional(),relationships:Io.optional(),impactScore:No.optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includePackages:z.boolean().optional(),includeSymbols:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),Ro=z.object({type:z.enum(["file","module"]),filePath:z.string().nullable(),moduleName:z.string().nullable().optional(),importedSymbols:z.array(z.string()).optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),To=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),$o=z.object({name:z.string(),version:z.string().optional(),type:z.string()}),z.object({totalFiles:z.number().int().nonnegative(),totalPackages:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()}),z.object({file:z.string(),directDependencies:z.array(Ro),transitiveDependencies:z.array(To).optional(),packages:z.array($o).optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includeSymbols:z.boolean().optional(),includeImpactMetrics:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),jo=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),Lo=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),z.object({totalFiles:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative(),riskLevel:Te}),z.object({file:z.string(),directDependents:z.array(jo),transitiveDependents:z.array(Lo).optional(),detailedMetrics:z.object({byDepth:z.record(z.string(),z.number()),criticalPaths:z.array(z.array(z.string())),mostImpactedFiles:z.array(z.string())}).optional()}),z.object({filePath:z.string().min(1).optional(),minCycleLength:z.number().int().min(2).max(10).optional(),maxCycleLength:z.number().int().min(2).max(10).optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeImpactScore:z.boolean().optional(),includeConfidence:z.boolean().optional()}),Fo=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:Te}),z.object({cycles:z.array(Fo)}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),filterByUsageType:z.array(z.string()).optional(),filterByRelationshipType:z.array(z.string()).optional(),includeTransitive:z.boolean().optional(),includeContext:z.boolean().optional(),excludeTests:z.boolean().optional(),excludeGenerated:z.boolean().optional(),includeImportanceWeight:z.boolean().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0)}),ko=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:fe.optional(),languageMetadata:J.optional()}),Ao=z.object({filePath:z.string(),usageType:z.string(),relationshipType:z.string(),line:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional(),enclosingSymbol:z.object({name:z.string(),kind:z.string()}).optional(),context:z.string().optional(),aliasName:z.string().optional(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),importanceWeight:z.number().min(0).max(1).optional()}),Do=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:ko,directUsages:z.array(Ao),transitiveUsages:z.array(Do).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),Oo=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),complexity:fe.optional(),languageMetadata:J.optional()}),Mo=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:fe.optional(),languageMetadata:J.optional()}),Bo=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isAsync:z.boolean(),depth:z.number().int().nonnegative(),complexity:fe.optional(),languageMetadata:J.optional()}),z.object({root:Oo,callers:z.array(Mo).optional(),callees:z.array(Bo).optional(),graph:_o.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),Xr=$e.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),relationshipType:z.string(),depth:z.number().int().positive(),isExported:z.boolean().optional(),transitiveImpactCount:z.number().int().nonnegative().optional(),languageMetadata:J.optional()}),Uo=z.object({filePath:z.string(),symbolCount:z.number().int().positive(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),symbols:z.array(z.object({id:z.string(),name:z.string(),kind:z.string(),line:z.number().int().positive()}))}),Go=z.object({riskLevel:Te,factors:z.array(z.object({factor:z.string(),severity:z.enum(["low","medium","high"]),description:z.string()})),recommendations:z.array(z.string())}),z.object({symbol:z.object({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isExported:z.boolean().optional(),languageMetadata:J.optional()}),directDependents:z.array(Xr).optional(),transitiveDependents:z.array(Xr).optional(),impactedFiles:z.array(Uo),breakingChangeRisk:Go.optional(),summary:z.object({directDependentCount:z.number().int().nonnegative(),transitiveDependentCount:z.number().int().nonnegative(),impactedFileCount:z.number().int().nonnegative(),testFileCount:z.number().int().nonnegative(),productionFileCount:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()})}),z.object({filePattern:z.string().optional(),filterByKind:z.array(z.string()).optional(),exportedOnly:z.boolean().optional(),excludeTests:z.boolean().default(true),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeConfidence:z.boolean().optional()}),zo=z.object({symbolId:z.string(),name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),isExported:z.boolean(),reason:z.string(),confidence:z.number().min(0).max(1),languageMetadata:J.optional()}),Ho=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(zo),orphanedFiles:z.array(Ho)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),Wo=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),Ko=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),Jo=z.object({languages:z.array(Wo),frameworks:z.array(Ko),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),Vo=z.object({files:z.object({total:z.number().int().nonnegative(),byType:z.record(z.string(),z.number()),byParadigm:z.record(z.string(),z.number())}),symbols:z.object({total:z.number().int().nonnegative(),byKind:z.record(z.string(),z.number()),exported:z.number().int().nonnegative(),public:z.number().int().nonnegative()}),modules:z.object({total:z.number().int().nonnegative(),averageSize:z.number().nonnegative(),largest:z.string()})}),qo=z.object({internal:z.object({totalConnections:z.number().int().nonnegative(),averagePerFile:z.number().nonnegative(),mostConnectedFiles:z.array(z.object({path:z.string(),incomingCount:z.number().int().nonnegative(),outgoingCount:z.number().int().nonnegative()}))}),external:z.object({totalPackages:z.number().int().nonnegative(),directDependencies:z.number().int().nonnegative(),topPackages:z.array(z.object({name:z.string(),usageCount:z.number().int().nonnegative()}))})}),Yo=z.object({complexity:z.object({average:z.number().nonnegative(),high:z.number().int().nonnegative()}),maintainability:z.object({score:z.number().min(0).max(100),issues:z.array(z.string())}),testCoverage:z.object({percentage:z.number().min(0).max(100),testedFiles:z.number().int().nonnegative(),totalFiles:z.number().int().nonnegative()}).optional()}),Xo=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),Qo=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),Zo=z.object({nodes:z.array(Xo),edges:z.array(Qo)}),z.object({metadata:Jo,structure:Vo,dependencies:qo,metrics:Yo.optional(),moduleGraph:Zo.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),es=z.enum(["relative","workspace","alias","external","builtin"]),ts=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:es}),rs=z.record(z.string(),ts),Zr=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),ns=Zr.exclude(["import-use","declaration"]),is=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:Zr}).strict(),Yt=z.object({filePath:z.string().min(1),entries:z.array(is)}).strict(),z.object({file:z.string().min(1),language:z.string().min(1),commit:z.string().min(1),timestamp:z.string().datetime(),ast:z.string().min(1),importResolutions:rs.optional(),classificationMap:Yt.optional()}).strict(),os=z.object({file:z.string(),error:z.string()}),ss=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),as=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(ss)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(os).optional(),relationships:as}),z.object({projectId:z.string(),projectName:z.string(),branch:z.string(),latestCommit:z.string().nullable(),fileCount:z.number().int().nonnegative(),lastIndexedAt:z.string().nullable(),languages:z.array(z.string())}),ls=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(ls),isType:z.boolean(),isDynamic:z.boolean(),isConditional:z.boolean().optional(),isLazy:z.boolean().optional(),isWildcard:z.boolean().optional(),line:z.number(),column:z.number()}),z.object({referencerId:z.string(),referencedName:z.string(),referenceType:ns,line:z.number(),column:z.number(),scope:z.string().optional(),objectContext:z.string().optional(),language:z.string().optional()}),z.enum(["processing","completed","failed","cancelled","queued","superseded","cleaned_up"]),z.enum(["acquired","current","duplicate","superseded","queued"]),Le={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},cs=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...Le}),ps=z.object({status:z.literal("current"),...Le}),us=z.object({status:z.literal("duplicate"),...Le}),ds=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...Le}),ms=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...Le}),en=z.discriminatedUnion("status",[cs,ps,us,ds,ms]),z.object({"x-attempt-id":z.string().uuid(),"x-project-id":z.string(),"x-branch-name":z.string(),"x-commit-hash":z.string().length(40),"x-constellation-dirty":z.union([z.literal("true"),z.literal("false")]).optional()}),tn=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),Qr=tn.extend({name:z.string().min(1)}).strict(),gs=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().optional()}).strict(),fs=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:gs.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(tn).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(Qr).max(200),outgoingCalls:z.array(Qr).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(fs)}).strict(),z.object({projectId:z.string().min(1),branch:z.string().min(1),commit:z.string().regex(/^[0-9a-f]{40}$/),timestamp:z.string().datetime()}).strict(),z.enum(["pending","processing","completed","failed","skipped"]),hs=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),ys=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),bs=z.object({id:z.string(),label:z.string(),type:hs,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),vs=z.object({id:z.string(),source:z.string(),target:z.string(),type:ys,label:z.string().optional()}),Ss=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:Te.optional()}),Cs=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array(bs),edges:z.array(vs),summary:Ss,metadata:Cs,features:z.record(z.string(),z.boolean()).optional()}),rn=z.object({projectId:z.string(),projectName:z.string(),defaultBranch:z.string(),lastIndexedAt:z.string().datetime().optional(),fileCount:z.number().int().nonnegative().optional(),languages:z.array(z.string()).optional()}),z.object({projects:z.array(rn)}),rn.pick({projectId:true,projectName:true,defaultBranch:true}),nn=z.enum(["unresolved","resolved","archived"]),on=z.enum(["succeeded","failed"]),sn=z.enum(["full","incremental"]),ws=z.enum(["info","warn","error"]),_s=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),xs=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),an=z.object({errors:z.array(_s),warnings:z.array(xs)}),ln=z.object({level:ws,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:an,logEntries:z.array(ln),cliVersion:z.string(),outcome:on,indexType:sn}),z.object({status:nn.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:sn,status:nn,outcome:on,errorSummary:z.string(),errorData:an,logEntries:z.array(ln),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});function cn(i){return base32.encode(Buffer.from(i))}var pn=y(()=>{});function un(i,e,t){let n=`${i}:${e}${t?`:${t}`:""}`;return cn(n)}var dn=y(()=>{pn();});var it,mn=y(()=>{it=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
3
- `,o=Buffer.from(n,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});function Is(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Ie.platform()==="win32"?!!(process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"||process.env.TERM_PROGRAM==="Hyper"||process.env.TERM&&process.env.TERM!=="cygwin"&&process.env.TERM!=="dumb"):true}var Ns,Rs,Ts,$s,js,Ls,Fs,ks,As,Ds,Ae,S,I,b,v,te,D=y(()=>{Ns="\u2714",Rs="\u2717",Ts="\u26A0",$s="\u2139",js="\u26A1",Ls="[OK]",Fs="[ERR]",ks="[WARN]",As="[INFO]",Ds="[>>]",Ae=Is(),S=p.green(Ae?Ns:Ls),I=p.red(Ae?Rs:Fs),b=p.yellow(Ae?Ts:ks),v=p.blue(Ae?$s:As),te=p.yellow(Ae?js:Ds);});var ot,st,T,re,M,he,ne,at=y(()=>{Fe();dn();mn();D();ot=class{constructor(e,t,n=false){this.config=e;this.accessKey=t;this.dirty=n;}apiVersion="intel/v1";features={};isFeatureEnabled(e){return this.features[e]===true}parseFeatureHeader(e){if(Object.keys(this.features).length>0)return;let t=e.headers.get("X-Features");if(t)for(let n of t.split(",")){let[o,s]=n.split("=");o&&s!==void 0&&(this.features[o]=s==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new M(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new M(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new M(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new re("Project not found - no previous index exists");default:throw e.status===404?new re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof M||t instanceof re?t:e.status===404?new re("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let s=await this.sendRequest(o,null,"GET");return !s||!s.ok?null:await s.json()}catch(s){if(s instanceof T)throw s;return null}}async claimAstLock(e,t,n,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":n?"incremental":"full","x-commit-hash":o,"x-commit-timestamp":s,"x-constellation-dirty":this.dirty?"true":"false"});if(!a)throw new Error("Failed to claim indexing lock: no response");if(a.status===409)throw await this.parseIndexingConflict(a);if(a.status===401)throw new T("Authentication failed");if(!a.ok){let d=await this.formatErrorBody(a);throw new Error(`Failed to claim indexing lock: ${a.status}${d?` \u2014 ${d}`:""}`)}let l=await a.json(),c=en.safeParse(l);if(!c.success)throw new Error(`Invalid lock response from server: ${c.error.issues.map(d=>d.message).join("; ")}`);return c.data}async pollIndexStatus(e,t,n,o=300*1e3){let s=Date.now(),a=2e3,l=3e4;for(;Date.now()-s<o;){try{let c=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(n)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new T("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let d=await c.json();if(d.status==="current")return !0;if(d.status==="stale"||d.status==="failed")return !1}}catch(c){if(c instanceof T)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,n,o,s){return this.streamToApi(e,"ast/queue",t,n,true,o,s)}async startEnrichment(e,t,n){let o=new Agent({headersTimeout:1e4,bodyTimeout:1e4});try{let s=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment/start`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/json; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-attempt-id":e,"x-constellation-dirty":this.dirty?"true":"false"},dispatcher:o});if(s.ok)return !0;let a=`status ${s.status}`;try{let l=await s.json();l?.message?a=Array.isArray(l.message)?l.message.join("; "):String(l.message):l?.code&&(a=`status ${s.status} (${String(l.code)})`);}catch{}return console.warn(`Enrichment start heartbeat rejected: ${a}`),!1}catch(s){return console.warn(`Enrichment start heartbeat failed: ${s instanceof Error?s.message:String(s)}`),false}finally{o.destroy().catch(()=>{});}}async uploadEnrichment(e,t,n,o){let s=[5e3,1e4,2e4];for(let a=0;a<=s.length;a++)try{let l=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(l.status===401)throw new T("Authentication failed during enrichment upload");if(l.status===409){if((await l.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return console.warn("Enrichment skipped: index state changed since AST upload"),!1;if(a<s.length){await new Promise(d=>setTimeout(d,s[a]));continue}return console.warn("Enrichment skipped: indexing still in progress after retries"),!1}return l.ok||l.status===202?!0:(console.warn(`Enrichment upload failed with status ${l.status}`),!1)}catch(l){if(l instanceof T)throw l;if(a<s.length){console.warn(`Enrichment upload network error (attempt ${a+1}/${s.length+1}): ${l instanceof Error?l.message:String(l)}`),await new Promise(c=>setTimeout(c,s[a]));continue}return console.warn(`Enrichment upload error: ${l instanceof Error?l.message:String(l)}`),false}return false}async deleteFiles(e){for(let t of e){let n=un(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",n;try{let o=await e.json();t=o?.message||t,n=o?.details?.branchName;}catch{}return new he(t,n)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let n=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${n}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,n,o,s,a,l){try{let{Readable:c}=await import('stream'),d=new it(e),m=process.env.CAPTURE_PAYLOAD_PATH,u=null,g=c.toWeb(d);if(m){let[h,x]=g.tee(),w=Et.createWriteStream(m);u=pipeline(c.fromWeb(x),fr.createGzip(),w).catch(_=>{console.warn(`[constellation] capture tap failed: ${_ instanceof Error?_.message:String(_)}`);}),g=h;}let f=new Agent({headersTimeout:0,bodyTimeout:0});try{let h=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":o,"x-constellation-index":s?"incremental":"full","x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`,...a&&{"x-commit-hash":a},...l&&{"x-attempt-id":l}},body:g,duplex:"half",dispatcher:f});if(!h.ok&&typeof d.destroy=="function"&&d.destroy(),h.status===401)throw new T("Authentication failed");if(h.status===409)throw await this.parseIndexingConflict(h);if(h.status===200)try{let w=await h.json();if(w?.status==="current")return console.log(`${S} Index already up to date for ${o} at commit ${w.commitHash||"unknown"}`),!0}catch{}if(h.ok||h.status===202)return !0;let x=`Server returned ${h.status}`;try{let w=await h.json();w?.message&&(x=Array.isArray(w.message)?w.message.join("; "):w.message);}catch{}throw new Error(x)}finally{u&&await u;}}catch(c){if(c instanceof T||c instanceof he)throw c;let d=c instanceof Error?c:new Error(String(c)),m="";if(d.message==="fetch failed"||c.code){let g=[],f=c.code||c.cause?.code;if(c.code&&g.push(`Error Code: ${c.code}`),c.cause){let h=c.cause;h.code&&g.push(`Cause Code: ${h.code}`),h.errno&&g.push(`Errno: ${h.errno}`),h.syscall&&g.push(`System Call: ${h.syscall}`),h.address&&g.push(`Address: ${h.address}`),h.port&&g.push(`Port: ${h.port}`);}f==="ERR_INVALID_ARG_VALUE"?m="Invalid argument value - check stream/body format and duplex option":f==="ECONNREFUSED"?m="Connection refused - service may be down or unreachable":f==="ENOTFOUND"?m="DNS lookup failed - check service URL":f==="ETIMEDOUT"?m="Connection timeout - service not responding":f==="ECONNRESET"?m="Connection reset by server":f==="EHOSTUNREACH"?m="Host unreachable - check network connectivity":m="Network failure",g.length>0&&(m+=` (${g.join(", ")})`);}else m=d.message;let u=new Error(`Failed to upload data to Constellation Service: ${m}`);throw u.cause=d,u.stack=`${u.stack}
4
- Caused by: ${d.stack}`,u}}async sendRequest(e,t,n,o={},s=0,a=3,l=1e3,c=250){for(let d=1;d<=a;d++){let m;try{let u=new AbortController;s>0&&(m=setTimeout(()=>u.abort(),s));let g={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},f=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:g,body:t?JSON.stringify(t):void 0,signal:u.signal});if(m&&clearTimeout(m),f.status===401)throw new T("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new st(`${f.statusText} (${f.status})`);return f}catch(u){if(m&&clearTimeout(m),!(u instanceof T)){let g=u instanceof Error?`${u.message}${u.cause?` (Cause: ${u.cause})`:""}`:String(u);console.log(`HTTP request attempt ${d}/${a} failed: ${g}`);}if(d<a&&u instanceof st){let g=l+Math.floor(Math.random()*c);await new Promise(f=>setTimeout(f,g));}else throw u}}}async reportErrors(e){try{let t=await this.sendRequest("error-reports",e,"POST",{"x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false"},1e4,1,0,0);if(!t){console.warn("Failed to upload error report: no response received");return}if(t.status===403){console.warn("Error reporting is not available on your current plan");return}t.ok||console.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){console.warn(`Failed to upload error report: ${t?.message||"Unknown error"}`);}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false"},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},st=class extends Error{constructor(e){super(e),this.name="RetryableError";}},T=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},re=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},M=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}},he=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},ne=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});var F,lt=y(()=>{F={prefix:{idle:p.blue("\u25C6"),done:p.green("\u2714")},style:{highlight:i=>p.blue(i),answer:i=>p.green(i),error:i=>p.red(`\u2716 ${i}`),help:i=>p.gray(i)},icon:{checked:p.green("\u25FC"),unchecked:p.gray("\u25FB"),cursor:p.blue("\u276F")}};});async function yn(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await Zt("open",[i]),!0;case "linux":return await Zt("xdg-open",[i]),!0;case "win32":return await Zt("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var Zt,bn=y(()=>{Zt=promisify(execFile);});function Hs(i,e){if(!e)return false;let t,n;try{t=new URL(e),n=new URL(i);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"?false:n.origin===t.origin}function vn(i={}){let e=i.allowedOrigin;return new Promise((t,n)=>{let o=createServer(),s,a=false;o.listen(0,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l=="string"){o.close(),n(new Error("Failed to bind callback server"));return}t({port:l.port,close(){s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections();},waitForCallback(c,d=3e5){return new Promise((m,u)=>{s=setTimeout(()=>{s=void 0,a=true,o.close(),o.closeAllConnections(),u(new Error("Authentication timed out"));},d),o.on("request",(g,f)=>{let h=new URL(g.url??"/",`http://127.0.0.1:${l.port}`);if(h.pathname!=="/callback"){f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not found");return}let x=h.searchParams.get("key");if(h.searchParams.get("state")!==c){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid state parameter");return}if(!x||!Gs.test(x)){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid key format");return}if(a)return;a=true;let _=h.searchParams.get("return_url");_&&Hs(_,e)?(f.writeHead(302,{Location:_}),f.end()):(f.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),f.end(zs)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),m(x);});})}});}),o.on("error",l=>{n(l);});})}var Gs,zs,Sn=y(()=>{Gs=/^ak:[0-9a-f]{32}$/i,zs=`<!DOCTYPE html>
2
+ import {z}from'zod';import {base32}from'@scure/base';import {Readable}from'stream';import p from'ansi-colors';import*as Ne from'os';import Ne__default from'os';import*as It from'fs';import {readFileSync,existsSync}from'fs';import {pipeline}from'stream/promises';import*as Sr from'zlib';import Sr__default from'zlib';import {Agent,fetch as fetch$1}from'undici';import {execFile,execFileSync,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import {confirm,password,input,select,checkbox}from'@inquirer/prompts';import*as N from'path';import N__default,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import*as B from'fs/promises';import B__default from'fs/promises';import {findAll,find,parse}from'tsconfck';import Fa from'tree-sitter-javascript';import Aa from'tree-sitter-python';import ka from'tree-sitter-typescript';import Nl from'tree-sitter';import pi from'ignore';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq,stringify}from'yaml';import {simpleGit}from'simple-git';import {Command}from'commander';var wo=Object.defineProperty;var y=(i,e)=>()=>(i&&(e=i(i=0)),e);var Xr=(i,e)=>{for(var t in e)wo(i,t,{get:e[t],enumerable:true});};var it,Qt=y(()=>{it=["help","--help","-h","--version","-V","-v"];});var Eo,V,$e,Po,he,je,Io,No,Ro,Le,To,$o,jo,Lo,Fo,Ao,ko,Do,Oo,Mo,Bo,Uo,Go,zo,Wo,Ho,Ko,Zr,Jo,Vo,qo,Yo,Xo,Qo,Zo,es,ts,rs,ns,is,os,ss,as,ls,tn,cs,ps,Zt,us,ds,ms,gs,Fe,fs,hs,ys,bs,vs,rn,Ss,Cs,ot,nn,en,_s,ws,xs,er,on,Es,Ps,Is,Ns,tr,Rs,Ts,$s,js,Ls,Fs,sn,an,ln,cn,As,ks,Ds,pn,un,Ae=y(()=>{Eo=z.object({total:z.number().int().nonnegative(),returned:z.number().int().nonnegative(),hasMore:z.boolean(),nextOffset:z.number().int().nonnegative().optional(),currentOffset:z.number().int().nonnegative().optional()}),z.object({overall:z.number().min(0).max(1),factors:z.object({dataFreshness:z.number().min(0).max(1).optional(),coverageComplete:z.number().min(0).max(1).optional(),heuristicAccuracy:z.number().min(0).max(1).optional(),semanticAnalysisDepth:z.number().min(0).max(1).optional(),patternMatchQuality:z.number().min(0).max(1).optional()}).optional(),warnings:z.array(z.string()).optional(),recommendations:z.array(z.string()).optional()}),z.object({qualityScore:z.number().min(0).max(100).optional(),lastUpdated:z.string().optional(),cached:z.boolean().optional(),executionTime:z.number().nonnegative().optional(),coveragePercentage:z.number().min(0).max(100).optional(),issues:z.array(z.string()).optional()}),V=z.object({language:z.string(),features:z.array(z.string()).optional(),visibility:z.string().optional(),decorators:z.array(z.string()).optional(),typeInfo:z.any().optional(),custom:z.record(z.string(),z.any()).optional()}),z.enum(["function","class","interface","type","variable","constant","enum","module","namespace","method","property","parameter","constructor","decorator","trait","struct","macro","unknown"]),$e=z.enum(["low","medium","high","critical"]),Po=z.enum(["low","moderate","high","very_high"]),he=z.object({cyclomaticComplexity:z.number().int().nonnegative(),complexityRisk:Po}),je=z.object({filePath:z.string(),line:z.number().int().positive().optional(),lineStart:z.number().int().positive().optional(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional()}),je.extend({symbolId:z.string().optional(),symbolName:z.string().optional(),symbolKind:z.string().optional()}),z.object({outgoing:z.array(z.string()),incoming:z.array(z.string())}),Io=z.object({id:z.string(),name:z.string(),type:z.string(),properties:z.record(z.string(),z.any()).optional()}),No=z.object({from:z.string(),to:z.string(),type:z.string().optional(),weight:z.number().optional(),properties:z.record(z.string(),z.any()).optional()}),Ro=z.object({nodes:z.array(Io),edges:z.array(No),metadata:z.object({nodeCount:z.number().int().nonnegative(),edgeCount:z.number().int().nonnegative(),directed:z.boolean(),hasCycles:z.boolean().optional()}).optional()}),Le=new Set(["abc","aifc","argparse","array","ast","asynchat","asyncio","asyncore","atexit","audioop","base64","bdb","binascii","bisect","builtins","bz2","cProfile","calendar","cgi","cgitb","chunk","cmath","cmd","code","codecs","codeop","collections","colorsys","compileall","concurrent","configparser","contextlib","contextvars","copy","copyreg","crypt","csv","ctypes","curses","dataclasses","datetime","dbm","decimal","difflib","dis","distutils","doctest","email","encodings","ensurepip","enum","errno","faulthandler","fcntl","filecmp","fileinput","fnmatch","fractions","ftplib","functools","gc","getopt","getpass","gettext","glob","graphlib","grp","gzip","hashlib","heapq","hmac","html","http","idlelib","imaplib","imghdr","imp","importlib","inspect","io","ipaddress","itertools","json","keyword","lib2to3","linecache","locale","logging","lzma","mailbox","mailcap","marshal","math","mimetypes","mmap","modulefinder","msilib","msvcrt","multiprocessing","netrc","nis","nntplib","numbers","operator","optparse","os","ossaudiodev","pathlib","pdb","pickle","pickletools","pipes","pkgutil","platform","plistlib","poplib","posix","posixpath","pprint","profile","pstats","pty","pwd","py_compile","pyclbr","pydoc","queue","quopri","random","re","readline","reprlib","resource","rlcompleter","runpy","sched","secrets","select","selectors","shelve","shlex","shutil","signal","site","sitecustomize","smtpd","smtplib","sndhdr","socket","socketserver","spwd","sqlite3","ssl","stat","statistics","string","stringprep","struct","subprocess","sunau","symtable","sys","sysconfig","syslog","tabnanny","tarfile","telnetlib","tempfile","termios","test","textwrap","threading","time","timeit","tkinter","token","tokenize","tomllib","trace","traceback","tracemalloc","tty","turtle","turtledemo","types","typing","unicodedata","unittest","urllib","usercustomize","uu","uuid","venv","warnings","wave","weakref","webbrowser","winreg","winsound","wsgiref","xdrlib","xml","xmlrpc","zipapp","zipfile","zipimport","zlib","zoneinfo","_thread","_tkinter","__future__","__main__"]),z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.any().optional()})}),z.object({query:z.string().max(200),filterByKind:z.array(z.string()).optional(),filterByVisibility:z.array(z.string()).optional(),isExported:z.boolean().optional(),filterByFile:z.string().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeUsageCount:z.boolean().optional(),includeDocumentation:z.boolean().optional()}).refine(i=>i.query.length>0||i.filterByKind&&i.filterByKind.length>0||i.filterByVisibility&&i.filterByVisibility.length>0||i.isExported!==void 0||i.filterByFile!==void 0,{message:"Either query must be non-empty or at least one filter (filterByKind, filterByVisibility, isExported, filterByFile) must be provided",path:["query"]}),To=je.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),isExported:z.boolean(),usageCount:z.number().int().nonnegative().optional(),complexity:he.optional(),languageMetadata:V.optional()}),z.object({symbols:z.array(To),pagination:Eo.optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeReferences:z.boolean().optional(),includeRelationships:z.boolean().optional(),includeImpactScore:z.boolean().optional()}),$o=je.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),signature:z.string().optional(),documentation:z.string().optional(),visibility:z.string().optional(),modifiers:z.array(z.string()).optional(),typeInfo:z.any().optional(),decorators:z.array(z.string()).optional(),isExported:z.boolean(),isDeprecated:z.boolean(),complexity:he.optional(),languageMetadata:V.optional()}),jo=je.extend({usageType:z.string(),context:z.string().optional(),aliasName:z.string().optional()}),Lo=z.object({calls:z.array(z.string()),calledBy:z.array(z.string()),inheritsFrom:z.array(z.string()),inheritedBy:z.array(z.string()),children:z.array(z.string())}),Fo=z.object({directUsage:z.number().int().nonnegative(),transitiveImpact:z.number().int().nonnegative(),riskScore:z.number().min(0).max(100),riskLevel:$e}),z.object({symbol:$o,references:z.array(jo).optional(),relationships:Lo.optional(),impactScore:Fo.optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includePackages:z.boolean().optional(),includeSymbols:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),Ao=z.object({type:z.enum(["file","module"]),filePath:z.string().nullable(),moduleName:z.string().nullable().optional(),importedSymbols:z.array(z.string()).optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),ko=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),Do=z.object({name:z.string(),version:z.string().optional(),type:z.string()}),z.object({totalFiles:z.number().int().nonnegative(),totalPackages:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()}),z.object({file:z.string(),directDependencies:z.array(Ao),transitiveDependencies:z.array(ko).optional(),packages:z.array(Do).optional()}),z.object({filePath:z.string().min(1),depth:z.number().int().nonnegative().max(10).optional(),includeSymbols:z.boolean().optional(),includeImpactMetrics:z.boolean().optional(),limit:z.number().int().positive().max(100).default(20),offset:z.number().int().nonnegative().default(0)}),Oo=z.object({filePath:z.string(),usedSymbols:z.array(z.string()).optional()}),Mo=z.object({filePath:z.string(),distance:z.number().int().positive(),path:z.array(z.string())}),z.object({totalFiles:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative(),riskLevel:$e}),z.object({file:z.string(),directDependents:z.array(Oo),transitiveDependents:z.array(Mo).optional(),detailedMetrics:z.object({byDepth:z.record(z.string(),z.number()),criticalPaths:z.array(z.array(z.string())),mostImpactedFiles:z.array(z.string())}).optional()}),z.object({filePath:z.string().min(1).optional(),minCycleLength:z.number().int().min(2).max(10).optional(),maxCycleLength:z.number().int().min(2).max(10).optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeImpactScore:z.boolean().optional(),includeConfidence:z.boolean().optional()}),Bo=z.object({files:z.array(z.string()),length:z.number().int().positive(),impactScore:z.number().min(0).max(100).optional(),severity:$e}),z.object({cycles:z.array(Bo)}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),filterByUsageType:z.array(z.string()).optional(),filterByRelationshipType:z.array(z.string()).optional(),includeTransitive:z.boolean().optional(),includeContext:z.boolean().optional(),excludeTests:z.boolean().optional(),excludeGenerated:z.boolean().optional(),includeImportanceWeight:z.boolean().optional(),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0)}),Uo=z.object({name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),complexity:he.optional(),languageMetadata:V.optional()}),Go=z.object({filePath:z.string(),usageType:z.string(),relationshipType:z.string(),line:z.number().int().positive().optional(),column:z.number().int().nonnegative().optional(),enclosingSymbol:z.object({name:z.string(),kind:z.string()}).optional(),context:z.string().optional(),aliasName:z.string().optional(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),importanceWeight:z.number().min(0).max(1).optional()}),zo=z.object({filePath:z.string(),distance:z.number().int().positive(),chain:z.array(z.string())}),z.object({symbol:Uo,directUsages:z.array(Go),transitiveUsages:z.array(zo).optional()}),z.object({symbolId:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),direction:z.enum(["callers","callees","both"]).default("both"),depth:z.number().int().positive().max(10).default(3),excludeExternal:z.boolean().optional(),includeGraph:z.boolean().optional(),limit:z.number().int().positive().max(100).default(25),offset:z.number().int().nonnegative().default(0)}),Wo=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),complexity:he.optional(),languageMetadata:V.optional()}),Ho=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),depth:z.number().int().nonnegative(),complexity:he.optional(),languageMetadata:V.optional()}),Ko=z.object({symbolId:z.string(),name:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isAsync:z.boolean(),depth:z.number().int().nonnegative(),complexity:he.optional(),languageMetadata:V.optional()}),z.object({root:Wo,callers:z.array(Ho).optional(),callees:z.array(Ko).optional(),graph:Ro.optional()}),z.object({symbolId:z.string().optional(),qualifiedName:z.string().optional(),symbolName:z.string().optional(),filePath:z.string().optional(),includeDirectDependents:z.boolean().default(true),includeTransitiveDependents:z.boolean().default(true),depth:z.number().int().min(1).max(5).default(3),excludeTests:z.boolean().default(true),excludeGenerated:z.boolean().default(true),analyzeBreakingChanges:z.boolean().default(true)}),Zr=je.extend({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),relationshipType:z.string(),depth:z.number().int().positive(),isExported:z.boolean().optional(),transitiveImpactCount:z.number().int().nonnegative().optional(),languageMetadata:V.optional()}),Jo=z.object({filePath:z.string(),symbolCount:z.number().int().positive(),isTest:z.boolean().optional(),isGenerated:z.boolean().optional(),symbols:z.array(z.object({id:z.string(),name:z.string(),kind:z.string(),line:z.number().int().positive()}))}),Vo=z.object({riskLevel:$e,factors:z.array(z.object({factor:z.string(),severity:z.enum(["low","medium","high"]),description:z.string()})),recommendations:z.array(z.string())}),z.object({symbol:z.object({id:z.string(),name:z.string(),qualifiedName:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),line:z.number().int().positive(),lineEnd:z.number().int().positive().optional(),column:z.number().int().nonnegative(),isExported:z.boolean().optional(),languageMetadata:V.optional()}),directDependents:z.array(Zr).optional(),transitiveDependents:z.array(Zr).optional(),impactedFiles:z.array(Jo),breakingChangeRisk:Vo.optional(),summary:z.object({directDependentCount:z.number().int().nonnegative(),transitiveDependentCount:z.number().int().nonnegative(),impactedFileCount:z.number().int().nonnegative(),testFileCount:z.number().int().nonnegative(),productionFileCount:z.number().int().nonnegative(),maxDepth:z.number().int().nonnegative()})}),z.object({filePattern:z.string().optional(),filterByKind:z.array(z.string()).optional(),exportedOnly:z.boolean().optional(),excludeTests:z.boolean().default(true),limit:z.number().int().positive().max(100).default(50),offset:z.number().int().nonnegative().default(0),includeConfidence:z.boolean().optional()}),qo=z.object({symbolId:z.string(),name:z.string(),kind:z.string(),visibility:z.string().optional(),filePath:z.string(),lineEnd:z.number().int().positive().optional(),isExported:z.boolean(),reason:z.string(),confidence:z.number().min(0).max(1),languageMetadata:V.optional()}),Yo=z.object({filePath:z.string(),reason:z.string(),lastUpdated:z.string(),confidence:z.number().min(0).max(1)}),z.object({orphanedSymbols:z.array(qo),orphanedFiles:z.array(Yo)}),z.object({includeMetrics:z.boolean().default(false),includeModuleGraph:z.boolean().default(false),includePackages:z.boolean().default(true)}),Xo=z.object({language:z.string(),fileCount:z.number().int().nonnegative(),percentage:z.number().min(0).max(100)}),Qo=z.object({name:z.string(),version:z.string().optional(),confidence:z.enum(["high","medium","low"]),evidence:z.array(z.string())}),Zo=z.object({languages:z.array(Xo),frameworks:z.array(Qo),primaryLanguage:z.string(),totalFiles:z.number().int().nonnegative(),totalLines:z.number().int().nonnegative().optional()}),es=z.object({files:z.object({total:z.number().int().nonnegative(),byType:z.record(z.string(),z.number()),byParadigm:z.record(z.string(),z.number())}),symbols:z.object({total:z.number().int().nonnegative(),byKind:z.record(z.string(),z.number()),exported:z.number().int().nonnegative(),public:z.number().int().nonnegative()}),modules:z.object({total:z.number().int().nonnegative(),averageSize:z.number().nonnegative(),largest:z.string()})}),ts=z.object({internal:z.object({totalConnections:z.number().int().nonnegative(),averagePerFile:z.number().nonnegative(),mostConnectedFiles:z.array(z.object({path:z.string(),incomingCount:z.number().int().nonnegative(),outgoingCount:z.number().int().nonnegative()}))}),external:z.object({totalPackages:z.number().int().nonnegative(),directDependencies:z.number().int().nonnegative(),topPackages:z.array(z.object({name:z.string(),usageCount:z.number().int().nonnegative()}))})}),rs=z.object({complexity:z.object({average:z.number().nonnegative(),high:z.number().int().nonnegative()}),maintainability:z.object({score:z.number().min(0).max(100),issues:z.array(z.string())}),testCoverage:z.object({percentage:z.number().min(0).max(100),testedFiles:z.number().int().nonnegative(),totalFiles:z.number().int().nonnegative()}).optional()}),ns=z.object({id:z.string(),name:z.string(),fileCount:z.number().int().nonnegative(),type:z.string()}),is=z.object({from:z.string(),to:z.string(),weight:z.number().int().nonnegative()}),os=z.object({nodes:z.array(ns),edges:z.array(is)}),z.object({metadata:Zo,structure:es,dependencies:ts,metrics:rs.optional(),moduleGraph:os.optional()}),z.object({}).strict(),z.object({pong:z.literal(true)}),ss=z.enum(["relative","workspace","alias","external","builtin"]),as=z.object({source:z.string(),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:ss}),ls=z.record(z.string(),as),tn=z.enum(["call","read","write","type","instantiate","import-use","declaration"]),cs=tn.exclude(["import-use","declaration"]),ps=z.object({line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),referenceType:tn}).strict(),Zt=z.object({filePath:z.string().min(1),entries:z.array(ps)}).strict(),z.object({file:z.string().min(1),language:z.string().min(1),commit:z.string().min(1),timestamp:z.string().datetime(),ast:z.string().min(1),importResolutions:ls.optional(),classificationMap:Zt.optional()}).strict(),us=z.object({file:z.string(),error:z.string()}),ds=z.object({file:z.string(),failedCount:z.number().int().nonnegative(),createdCount:z.number().int().nonnegative(),isTransient:z.boolean()}),ms=z.object({totalCreated:z.number().int().nonnegative(),totalFailed:z.number().int().nonnegative(),filesWithFailures:z.array(ds)}),z.object({processed:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),projectId:z.string(),branchName:z.string(),failedFiles:z.array(us).optional(),relationships:ms}),z.object({projectId:z.string(),projectName:z.string(),branch:z.string(),latestCommit:z.string().nullable(),fileCount:z.number().int().nonnegative(),lastIndexedAt:z.string().nullable(),languages:z.array(z.string())}),gs=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),z.object({source:z.string(),specifiers:z.array(gs),isType:z.boolean(),isDynamic:z.boolean(),isConditional:z.boolean().optional(),isLazy:z.boolean().optional(),isWildcard:z.boolean().optional(),line:z.number(),column:z.number()}),z.object({referencerId:z.string(),referencedName:z.string(),referenceType:cs,line:z.number(),column:z.number(),scope:z.string().optional(),objectContext:z.string().optional(),language:z.string().optional()}),z.enum(["processing","completed","failed","cancelled","queued","superseded","cleaned_up"]),z.enum(["acquired","current","duplicate","superseded","queued"]),Fe={branchName:z.string().optional(),effectiveBranchName:z.string().optional(),remapped:z.boolean().optional()},fs=z.object({status:z.literal("acquired"),attemptId:z.string().uuid(),...Fe}),hs=z.object({status:z.literal("current"),...Fe}),ys=z.object({status:z.literal("duplicate"),...Fe}),bs=z.object({status:z.literal("superseded"),activeCommit:z.string().optional(),...Fe}),vs=z.object({status:z.literal("queued"),queuedAttemptId:z.string().uuid(),...Fe}),rn=z.discriminatedUnion("status",[fs,hs,ys,bs,vs]),z.object({"x-attempt-id":z.string().uuid(),"x-project-id":z.string(),"x-branch-name":z.string(),"x-commit-hash":z.string().length(40),"x-constellation-dirty":z.union([z.literal("true"),z.literal("false")]).optional()}),Ss=z.enum(["pass1","pass2","pass2b","pass3"]),Cs=z.object({phase:Ss,durationMs:z.number().int().nonnegative(),fileCount:z.number().int().nonnegative(),symbolCount:z.number().int().nonnegative().optional(),relationshipCount:z.number().int().nonnegative().optional(),throughputPerSec:z.number().nonnegative(),deadlockRetryCount:z.number().int().nonnegative().optional()}),ot=z.array(Cs),nn=z.object({filePath:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative()}).strict(),en=nn.extend({name:z.string().min(1)}).strict(),_s=z.object({resolvedType:z.string().min(1),returnType:z.string().optional(),documentation:z.string().optional()}).strict(),ws=z.object({name:z.string().min(1),line:z.number().int().positive(),column:z.number().int().nonnegative(),kind:z.string().min(1),typeInfo:_s.optional(),references:z.object({count:z.number().int().nonnegative(),locations:z.array(nn).max(100)}).optional(),callHierarchy:z.object({incomingCalls:z.array(en).max(200),outgoingCalls:z.array(en).max(200)}).optional()}).strict(),z.object({filePath:z.string().min(1),language:z.string().min(1),symbols:z.array(ws)}).strict(),z.object({projectId:z.string().min(1),branch:z.string().min(1),commit:z.string().regex(/^[0-9a-f]{40}$/),timestamp:z.string().datetime()}).strict(),xs=z.enum(["pending","processing","completed","failed","skipped"]),er=z.object({status:xs,filesProcessed:z.number().int().nonnegative().nullable(),completedAt:z.union([z.string().datetime({offset:true}),z.date()]).nullable()}),z.enum(["current","processing","stale","failed"]),on=z.union([z.string().datetime({offset:true}),z.date()]),Es=z.object({status:z.literal("processing"),commitHash:z.string().nullable().optional(),startedAt:on.optional(),phaseMetrics:ot.optional()}).passthrough(),Ps=z.object({status:z.literal("current"),commitHash:z.string().nullable().optional(),completedAt:on.nullable().optional(),enrichment:er.optional(),phaseMetrics:ot.optional()}).passthrough(),Is=z.object({status:z.literal("stale"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:er.optional(),phaseMetrics:ot.optional()}).passthrough(),Ns=z.object({status:z.literal("failed"),currentCommit:z.string().nullable().optional(),requestedCommit:z.string().optional(),enrichment:er.optional(),phaseMetrics:ot.optional()}).passthrough(),tr=z.discriminatedUnion("status",[Es,Ps,Is,Ns]),Rs=z.enum(["function","class","variable","import","module","interface","type","constant","export"]),Ts=z.enum(["calls","imports","extends","inherits","implements","uses","references","exports","contains"]),$s=z.object({id:z.string(),label:z.string(),type:Rs,data:z.object({filePath:z.string(),lineNumber:z.number().int().nonnegative(),module:z.string(),visibility:z.string(),isExported:z.boolean()})}),js=z.object({id:z.string(),source:z.string(),target:z.string(),type:Ts,label:z.string().optional()}),Ls=z.object({totalNodes:z.number().int().nonnegative(),totalEdges:z.number().int().nonnegative(),toolName:z.string(),query:z.string(),riskLevel:$e.optional()}),Fs=z.object({projectName:z.string(),branch:z.string(),asOfCommit:z.string(),lastIndexedAt:z.string().datetime()}),z.object({nodes:z.array($s),edges:z.array(js),summary:Ls,metadata:Fs,features:z.record(z.string(),z.boolean()).optional()}),sn=z.object({projectId:z.string(),projectName:z.string(),defaultBranch:z.string(),lastIndexedAt:z.string().datetime().optional(),fileCount:z.number().int().nonnegative().optional(),languages:z.array(z.string()).optional()}),z.object({projects:z.array(sn)}),sn.pick({projectId:true,projectName:true,defaultBranch:true}),an=z.enum(["unresolved","resolved","archived"]),ln=z.enum(["succeeded","failed"]),cn=z.enum(["full","incremental"]),As=z.enum(["info","warn","error"]),ks=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional(),stack:z.string().optional()}),Ds=z.object({type:z.string(),message:z.string(),phase:z.string(),filePath:z.string().optional()}),pn=z.object({errors:z.array(ks),warnings:z.array(Ds)}),un=z.object({level:As,message:z.string(),timestamp:z.string().datetime()}),z.object({errorSummary:z.string().max(500),errorData:pn,logEntries:z.array(un),cliVersion:z.string(),outcome:ln,indexType:cn}),z.object({status:an.exclude(["archived"])}),z.object({id:z.string(),organizationId:z.string(),userId:z.string(),projectId:z.string(),branchName:z.string(),commitHash:z.string().nullable(),indexType:cn,status:an,outcome:ln,errorSummary:z.string(),errorData:pn,logEntries:z.array(un),cliVersion:z.string(),resolvedAt:z.string().nullable(),resolvedBy:z.string().nullable(),createdAt:z.string(),updatedAt:z.string(),organizationName:z.string().optional(),projectName:z.string().optional(),userEmail:z.string().optional(),resolvedByEmail:z.string().optional()}),z.object({unresolvedCount:z.number(),failedRunCount:z.number(),resolvedLast30d:z.number(),avgResolutionDays:z.number().nullable(),affectedOrgCount:z.number()});});function dn(i){return base32.encode(Buffer.from(i))}var mn=y(()=>{});function gn(i,e,t){let n=`${i}:${e}${t?`:${t}`:""}`;return dn(n)}var fn=y(()=>{mn();});var st,hn=y(()=>{st=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
3
+ `,o=Buffer.from(n,"utf8");if(!this.push(o))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};});function Bs(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Ne.platform()==="win32"?!!(process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"||process.env.TERM_PROGRAM==="Hyper"||process.env.TERM&&process.env.TERM!=="cygwin"&&process.env.TERM!=="dumb"):true}var Us,Gs,zs,Ws,Hs,Ks,Js,Vs,qs,Ys,De,S,I,b,v,ee,D=y(()=>{Us="\u2714",Gs="\u2717",zs="\u26A0",Ws="\u2139",Hs="\u26A1",Ks="[OK]",Js="[ERR]",Vs="[WARN]",qs="[INFO]",Ys="[>>]",De=Bs(),S=p.green(De?Us:Ks),I=p.red(De?Gs:Js),b=p.yellow(De?zs:Vs),v=p.blue(De?Ws:qs),ee=p.yellow(De?Hs:Ys);});var at,lt,$,te,M,ye,re,ct=y(()=>{Ae();fn();hn();D();at=class{constructor(e,t,n=false){this.config=e;this.accessKey=t;this.dirty=n;}apiVersion="intel/v1";features={};isFeatureEnabled(e){return this.features[e]===true}parseFeatureHeader(e){if(Object.keys(this.features).length>0)return;let t=e.headers.get("X-Features");if(t)for(let n of t.split(",")){let[o,s]=n.split("=");o&&s!==void 0&&(this.features[o]=s==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new M(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new M(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new M(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new te("Project not found - no previous index exists");default:throw e.status===404?new te("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof M||t instanceof te?t:e.status===404?new te("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let o=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let s=await this.sendRequest(o,null,"GET");if(!s||!s.ok)return null;let a=await s.json(),l=tr.safeParse(a);return l.success?l.data:(console.warn(`[constellation] getIndexStatus: unrecognized response shape \u2014 ${l.error.issues.map(c=>c.message).join("; ")}`),null)}catch(s){if(s instanceof $)throw s;return null}}async claimAstLock(e,t,n,o,s){let a=await this.sendRequest("ast/lock",null,"POST",{"x-project-id":e,"x-branch-name":t,"x-constellation-index":n?"incremental":"full","x-commit-hash":o,"x-commit-timestamp":s,"x-constellation-dirty":this.dirty?"true":"false"});if(!a)throw new Error("Failed to claim indexing lock: no response");if(a.status===409)throw await this.parseIndexingConflict(a);if(a.status===401)throw new $("Authentication failed");if(!a.ok){let m=await this.formatErrorBody(a);throw new Error(`Failed to claim indexing lock: ${a.status}${m?` \u2014 ${m}`:""}`)}let l=await a.json(),c=rn.safeParse(l);if(!c.success)throw new Error(`Invalid lock response from server: ${c.error.issues.map(m=>m.message).join("; ")}`);return c.data}async pollIndexStatus(e,t,n,o=300*1e3){let s=Date.now(),a=2e3,l=3e4;for(;Date.now()-s<o;){try{let c=await this.sendRequest(`projects/${encodeURIComponent(e)}/index-status?branch=${encodeURIComponent(t)}&commit=${encodeURIComponent(n)}`,null,"GET",{"x-constellation-dirty":this.dirty?"true":"false"});if(!c)continue;if(c.status===401)throw new $("Authentication failed during index status polling");if(c.status===403||c.status===404)return !1;if(c.ok){let m=await c.json(),u=tr.safeParse(m);if(u.success){if(u.data.status==="current")return !0;if(u.data.status==="stale"||u.data.status==="failed")return !1}}}catch(c){if(c instanceof $)throw c}await new Promise(c=>setTimeout(c,a)),a=Math.min(a*2,l);}return false}async uploadToQueue(e,t,n,o,s){return this.streamToApi(e,"ast/queue",t,n,true,o,s)}async startEnrichment(e,t,n){let o=new Agent({headersTimeout:1e4,bodyTimeout:1e4});try{let s=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment/start`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/json; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-attempt-id":e,"x-constellation-dirty":this.dirty?"true":"false"},dispatcher:o});if(s.ok)return !0;let a=`status ${s.status}`;try{let l=await s.json();l?.message?a=Array.isArray(l.message)?l.message.join("; "):String(l.message):l?.code&&(a=`status ${s.status} (${String(l.code)})`);}catch{}return console.warn(`Enrichment start heartbeat rejected: ${a}`),!1}catch(s){return console.warn(`Enrichment start heartbeat failed: ${s instanceof Error?s.message:String(s)}`),false}finally{o.destroy().catch(()=>{});}}async uploadEnrichment(e,t,n,o){let s=[5e3,1e4,2e4];for(let a=0;a<=s.length;a++)try{let l=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/enrichment`,{method:"POST",headers:{Authorization:`Bearer ${this.accessKey}`,"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":t,"x-branch-name":n,"x-commit-hash":o,"x-constellation-dirty":this.dirty?"true":"false"},body:e,dispatcher:new Agent({headersTimeout:0,bodyTimeout:0})});if(l.status===401)throw new $("Authentication failed during enrichment upload");if(l.status===409){if((await l.json().catch(()=>({})))?.code==="COMMIT_MISMATCH")return console.warn("Enrichment skipped: index state changed since AST upload"),!1;if(a<s.length){await new Promise(m=>setTimeout(m,s[a]));continue}return console.warn("Enrichment skipped: indexing still in progress after retries"),!1}return l.ok||l.status===202?!0:(console.warn(`Enrichment upload failed with status ${l.status}`),!1)}catch(l){if(l instanceof $)throw l;if(a<s.length){console.warn(`Enrichment upload network error (attempt ${a+1}/${s.length+1}): ${l instanceof Error?l.message:String(l)}`),await new Promise(c=>setTimeout(c,s[a]));continue}return console.warn(`Enrichment upload error: ${l instanceof Error?l.message:String(l)}`),false}return false}async deleteFiles(e){for(let t of e){let n=gn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async parseIndexingConflict(e){let t="Indexing already in progress",n;try{let o=await e.json();t=o?.message||t,n=o?.details?.branchName;}catch{}return new ye(t,n)}async formatErrorBody(e){try{let t=await e.json();if(typeof t?.message=="string"){let n=typeof t.code=="string"&&t.code.length>0?` [${t.code}]`:"";return `${t.message}${n}`}if(Array.isArray(t?.message))return t.message.join("; ");if(typeof t?.code=="string")return t.code}catch{}return ""}async streamToApi(e,t,n,o,s,a,l){try{let{Readable:c}=await import('stream'),m=new st(e),u=process.env.CAPTURE_PAYLOAD_PATH,d=null,g=c.toWeb(m);if(u){let[h,x]=g.tee(),_=It.createWriteStream(u);d=pipeline(c.fromWeb(x),Sr.createGzip(),_).catch(w=>{console.warn(`[constellation] capture tap failed: ${w instanceof Error?w.message:String(w)}`);}),g=h;}let f=new Agent({headersTimeout:0,bodyTimeout:0});try{let h=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":o,"x-constellation-index":s?"incremental":"full","x-constellation-dirty":this.dirty?"true":"false",Authorization:`Bearer ${this.accessKey}`,...a&&{"x-commit-hash":a},...l&&{"x-attempt-id":l}},body:g,duplex:"half",dispatcher:f});if(!h.ok&&typeof m.destroy=="function"&&m.destroy(),h.status===401)throw new $("Authentication failed");if(h.status===409)throw await this.parseIndexingConflict(h);if(h.status===200)try{let _=await h.json();if(_?.status==="current")return console.log(`${S} Index already up to date for ${o} at commit ${_.commitHash||"unknown"}`),!0}catch{}if(h.ok||h.status===202)return !0;let x=`Server returned ${h.status}`;try{let _=await h.json();_?.message&&(x=Array.isArray(_.message)?_.message.join("; "):_.message);}catch{}throw new Error(x)}finally{d&&await d;}}catch(c){if(c instanceof $||c instanceof ye)throw c;let m=c instanceof Error?c:new Error(String(c)),u="";if(m.message==="fetch failed"||c.code){let g=[],f=c.code||c.cause?.code;if(c.code&&g.push(`Error Code: ${c.code}`),c.cause){let h=c.cause;h.code&&g.push(`Cause Code: ${h.code}`),h.errno&&g.push(`Errno: ${h.errno}`),h.syscall&&g.push(`System Call: ${h.syscall}`),h.address&&g.push(`Address: ${h.address}`),h.port&&g.push(`Port: ${h.port}`);}f==="ERR_INVALID_ARG_VALUE"?u="Invalid argument value - check stream/body format and duplex option":f==="ECONNREFUSED"?u="Connection refused - service may be down or unreachable":f==="ENOTFOUND"?u="DNS lookup failed - check service URL":f==="ETIMEDOUT"?u="Connection timeout - service not responding":f==="ECONNRESET"?u="Connection reset by server":f==="EHOSTUNREACH"?u="Host unreachable - check network connectivity":u="Network failure",g.length>0&&(u+=` (${g.join(", ")})`);}else u=m.message;let d=new Error(`Failed to upload data to Constellation Service: ${u}`);throw d.cause=m,d.stack=`${d.stack}
4
+ Caused by: ${m.stack}`,d}}async sendRequest(e,t,n,o={},s=0,a=3,l=1e3,c=250){for(let m=1;m<=a;m++){let u;try{let d=new AbortController;s>0&&(u=setTimeout(()=>d.abort(),s));let g={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},f=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:g,body:t?JSON.stringify(t):void 0,signal:d.signal});if(u&&clearTimeout(u),f.status===401)throw new $("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new lt(`${f.statusText} (${f.status})`);return f}catch(d){if(u&&clearTimeout(u),!(d instanceof $)){let g=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);console.log(`HTTP request attempt ${m}/${a} failed: ${g}`);}if(m<a&&d instanceof lt){let g=l+Math.floor(Math.random()*c);await new Promise(f=>setTimeout(f,g));}else throw d}}}async reportErrors(e){try{let t=await this.sendRequest("error-reports",e,"POST",{"x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false"},1e4,1,0,0);if(!t){console.warn("Failed to upload error report: no response received");return}if(t.status===403){console.warn("Error reporting is not available on your current plan");return}t.ok||console.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){console.warn(`Failed to upload error report: ${t?.message||"Unknown error"}`);}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch,"x-constellation-dirty":this.dirty?"true":"false"},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},lt=class extends Error{constructor(e){super(e),this.name="RetryableError";}},$=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},te=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},M=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}},ye=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},re=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});var F,pt=y(()=>{F={prefix:{idle:p.blue("\u25C6"),done:p.green("\u2714")},style:{highlight:i=>p.blue(i),answer:i=>p.green(i),error:i=>p.red(`\u2716 ${i}`),help:i=>p.gray(i)},icon:{checked:p.green("\u25FC"),unchecked:p.gray("\u25FB"),cursor:p.blue("\u276F")}};});async function Sn(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await ir("open",[i]),!0;case "linux":return await ir("xdg-open",[i]),!0;case "win32":return await ir("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var ir,Cn=y(()=>{ir=promisify(execFile);});function na(i,e){if(!e)return false;let t,n;try{t=new URL(e),n=new URL(i);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"?false:n.origin===t.origin}function _n(i={}){let e=i.allowedOrigin;return new Promise((t,n)=>{let o=createServer(),s,a=false;o.listen(0,"127.0.0.1",()=>{let l=o.address();if(!l||typeof l=="string"){o.close(),n(new Error("Failed to bind callback server"));return}t({port:l.port,close(){s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections();},waitForCallback(c,m=3e5){return new Promise((u,d)=>{s=setTimeout(()=>{s=void 0,a=true,o.close(),o.closeAllConnections(),d(new Error("Authentication timed out"));},m),o.on("request",(g,f)=>{let h=new URL(g.url??"/",`http://127.0.0.1:${l.port}`);if(h.pathname!=="/callback"){f.writeHead(404,{"Content-Type":"text/plain"}),f.end("Not found");return}let x=h.searchParams.get("key");if(h.searchParams.get("state")!==c){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid state parameter");return}if(!x||!ta.test(x)){f.writeHead(400,{"Content-Type":"text/plain"}),f.end("Invalid key format");return}if(a)return;a=true;let w=h.searchParams.get("return_url");w&&na(w,e)?(f.writeHead(302,{Location:w}),f.end()):(f.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),f.end(ra)),s&&(clearTimeout(s),s=void 0),o.close(),o.closeAllConnections(),u(x);});})}});}),o.on("error",l=>{n(l);});})}var ta,ra,wn=y(()=>{ta=/^ak:[0-9a-f]{32}$/i,ra=`<!DOCTYPE html>
5
5
  <html><head><title>Authentication Successful</title></head>
6
- <body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function er(i){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
6
+ <body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function or(i){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
7
7
  \u2502 ${p.gray("'")} ${p.blueBright(".")} ${p.dim("`")} ${p.yellowBright("'")} ${p.blueBright("+")} ${p.whiteBright(".")} ${p.gray(".")} ${p.yellowBright("'")} ${p.yellowBright("*")} ${p.whiteBright("'")} ${p.blueBright("+")} ${p.gray(".")} ${p.yellowBright("*")} ${p.whiteBright(",")} ${p.gray.dim(".")}\u2502
8
8
  \u2502 _____ ${p.yellowBright("*")} ${p.dim("`")} __${p.whiteBright(".")} ${p.whiteBright("'")} ____ ${p.dim(".")} __ _ ${p.gray("`")} . . ${p.yellowBright("o")} ${p.blueBright("+")} \u2502
9
9
  \u2502 ${p.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${p.gray(".")} ${p.yellowBright("'")} ${p.gray("+")} ${p.gray("\\")} ${p.gray("`")} \u2502
@@ -13,7 +13,7 @@ Caused by: ${d.stack}`,u}}async sendRequest(e,t,n,o={},s=0,a=3,l=1e3,c=250){for(
13
13
  \u2502${p.yellowBright("'")} ${p.whiteBright("*")} ${p.blueBright("+")} ${p.yellowBright("*")} ${p.gray(",")} ${p.whiteBright("'")} + ${p.whiteBright("constellationdev.io")} ${p.whiteBright("' .")} ${p.gray(",")} ${p.blueBright("*")} ${p.yellowBright(".")} ${p.whiteBright("+")} \u2502`),i&&i.length>0?console.log(`\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u252C${"\u2500".repeat(59-i.length)}\u256F
14
14
  \u2502 ${p.bold(`constellation \u203A ${i}`)} \u2502
15
15
  \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u256F
16
- `):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var ie,Cn,ct=y(()=>{`
16
+ `):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var ne,xn,ut=y(()=>{`
17
17
  \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
18
18
  \u2502 ${p.gray("'")} ${p.blueBright(".")} ${p.dim("`")} ${p.yellowBright("'")} ${p.blueBright("+")} ${p.whiteBright(".")} ${p.gray(".")} ${p.yellowBright("'")} ${p.yellowBright("*")} ${p.whiteBright("'")} ${p.blueBright("+")} ${p.gray(".")} ${p.yellowBright("*")} ${p.whiteBright(",")} ${p.gray.dim(".")}\u2502
19
19
  \u2502 _____ ${p.yellowBright("*")} ${p.dim("`")} __${p.whiteBright(".")} ${p.whiteBright("'")} ____ ${p.dim(".")} __ _ ${p.gray("`")} . . ${p.yellowBright("o")} ${p.blueBright("+")} \u2502
@@ -29,10 +29,10 @@ ${p.gray(" \\")}
29
29
  ${p.blueBright(" o")}${p.blueBright("----")}${p.yellowBright("o")} ${p.gray("o")}
30
30
  ${p.gray(" \\ \\ ")}${p.blueBright("/")}
31
31
  ${p.whiteBright(" o o")}${p.blueBright("-")}${p.blueBright("o")}
32
- `,ie="CONSTELLATION_ACCESS_KEY",Cn="CONSTELLATION_WEB_URL";});var oe,pt=y(()=>{oe=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function qs(i){return Vs.test(i)}function Ys(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Vs,De,wn=y(()=>{lt();bn();Sn();ct();D();pt();Vs=/^ak:[0-9a-f]{32}$/i;De=class extends oe{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${te}Configuring access key authentication...
32
+ `,ne="CONSTELLATION_ACCESS_KEY",xn="CONSTELLATION_WEB_URL";});var ie,dt=y(()=>{ie=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function la(i){return aa.test(i)}function ca(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var aa,Oe,En=y(()=>{pt();Cn();wn();ut();D();dt();aa=/^ak:[0-9a-f]{32}$/i;Oe=class extends ie{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${ee}Configuring access key authentication...
33
33
  `),this.env.isCI()){console.error(`${I} Cannot configure authentication in CI/CD environments
34
34
 
35
- The ${ie} environment variable must be configured
35
+ The ${ne} environment variable must be configured
36
36
  directly in your pipeline settings:
37
37
 
38
38
  - GitHub Actions: Repository Settings -> Secrets and variables -> Actions
@@ -40,41 +40,41 @@ ${p.whiteBright(" o o")}${p.blueBright("-")}${p.blueBright("o")}
40
40
  - Azure DevOps: Pipelines -> Library -> Variable groups
41
41
  - Jenkins: Manage Jenkins -> Credentials
42
42
  - CircleCI: Project Settings -> Environment Variables
43
- `);return}if(await this.env.getKey(ie)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:F})){console.log(`${S} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred",o=Ys(n);console.error(`${I} Failed to store Constellation access key
43
+ `);return}if(await this.env.getKey(ne)&&!await confirm({message:"Replace existing Constellation access key?",default:!1,theme:F})){console.log(`${S} Keeping existing Constellation access key`);return}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred",o=ca(n);console.error(`${I} Failed to store Constellation access key
44
44
  ${o}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await password({message:"Constellation Access Key:",theme:F})).trim(),!e){console.log(`${b} Access key cannot be empty.
45
- `),t++;continue}if(!qs(e)){if(t++,t<n)console.log(`${b} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
45
+ `),t++;continue}if(!la(e)){if(t++,t<n)console.log(`${b} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
46
46
  Attempts remaining: ${n-t}
47
47
  `);else {console.error(`${I} Invalid access key format after ${n} attempts.
48
- Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),t=process.env[Cn]||"https://app.constellationdev.io",{port:n,waitForCallback:o}=await vn({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${n}&state=${e}`;console.log(`${v} Opening browser for authentication...`),await yn(s)||console.log(`${b} Could not open browser automatically.
48
+ Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),t=process.env[xn]||"https://app.constellationdev.io",{port:n,waitForCallback:o}=await _n({allowedOrigin:t}),s=`${t}/auth/cli?callback_port=${n}&state=${e}`;console.log(`${v} Opening browser for authentication...`),await Sn(s)||console.log(`${b} Could not open browser automatically.
49
49
  Please open this URL manually:
50
50
 
51
51
  ${s}
52
52
  `),console.log(`${v} Waiting for authentication... (press Ctrl+C to cancel)
53
53
  `);try{let l=await o(e);await this.storeKey(l);}catch{console.error(`${I} Authentication timed out.
54
- Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(ie,e),console.log(`${S} Stored access key in ${ie} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${v} To activate in this session, run:
54
+ Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(ne,e),console.log(`${S} Stored access key in ${ne} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${v} To activate in this session, run:
55
55
 
56
56
  source ${t}
57
57
 
58
- New terminal sessions will load it automatically.`);}};});function _n(i){return i.replace(/\\/g,"/")}function ut(i){return _n(i).replace(/^\.?\//,"")}function O(i,e){return _n(N.relative(i,e))}var pe=y(()=>{});var ye,rr=y(()=>{ye=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,o=0,s=0;for(;s<e.length&&n.size<this.concurrency;){let a=o++,l=this.processItem(e[s],s,t).then(c=>({result:c!==null?c.result:null,promiseId:a}));n.set(a,l),s++;}for(;n.size>0;){let a=await Promise.race(n.values());if(n.delete(a.promiseId),a.result!==null&&(yield a.result),s<e.length){let l=o++,c=this.processItem(e[s],s,t).then(d=>({result:d!==null?d.result:null,promiseId:l}));n.set(l,c),s++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});var Zs,ea,nr,ta,ra,na,dt,En=y(()=>{pe();rr();D();Zs={function:{hover:true,references:true,callHierarchy:true},method:{hover:true,references:true,callHierarchy:true},class:{hover:false,references:true,callHierarchy:false},interface:{hover:false,references:true,callHierarchy:false},variable:{hover:true,references:true,callHierarchy:false},property:{hover:true,references:true,callHierarchy:false},import:{hover:true,references:false,callHierarchy:false}},ea={hover:true,references:true,callHierarchy:false},nr=1e4,ta=1200*1e3,ra=50,na={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},dt=class{constructor(e){this.projectRoot=e;}async enrich(e,t,n,o){let s=[],a=Date.now(),l={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null},c=false;return await Promise.all([...e.entries()].map(async([d,m])=>{let u=n.get(d);if(!u)return;let g=m.length,f=g>1e4?4:g>5e3?6:8,h=new ye(f),x=0,w=h.run(m,async _=>{try{if(c||Date.now()-a>ta)return c=!0,null;let P=await this.openFile(u,_,l,o?.get(_));if(!P)return null;let{uri:W}=P;try{let E=t.get(_)??[];if(E.length===0&&(E=await this.discoverSymbols(u,_,W,l),E.length===0))return l.filesNoSymbols++,null;let k=await this.enrichOpenFile(u,_,W,E,l);return k.length>0?{filePath:_,language:d,symbols:k}:null}finally{this.closeFile(u,W);}}finally{if(x++,x%ra===0){let P=Math.round(x/g*100);console.log(`${v} ${na[d]??d} index enrichment: ${P}% (${x}/${g} files)`);}}});for await(let _ of w)_&&s.push(_);})),c&&console.log(`${v} Enrichment timeout reached. Uploading partial results.`),this.logDiagnostics(l),s}async openFile(e,t,n,o){let s=N.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=Et.readFileSync(s,"utf-8");}catch(c){return n.filesUnreadable++,n.firstFileError||(n.firstFileError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(t),version:1,text:l}});}catch(c){return n.filesOpenFailed++,n.firstOpenError||(n.firstOpenError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}return {uri:a,content:l}}closeFile(e,t){try{e.sendNotification("textDocument/didClose",{textDocument:{uri:t}});}catch{}}async enrichOpenFile(e,t,n,o,s){let a=await Promise.allSettled(o.map(c=>this.querySymbol(e,n,c,s))),l=[];for(let c=0;c<a.length;c++){let d=a[c];if(d.status==="fulfilled")d.value&&l.push(d.value);else if(s.symbolQueryErrors++,!s.firstSymbolError){let m=o[c];s.firstSymbolError=`${m.name} in ${t}: ${d.reason instanceof Error?d.reason.message:String(d.reason)}`;}}return l}logDiagnostics(e){let t=[];e.filesUnreadable>0&&t.push(`${e.filesUnreadable} files unreadable`),e.filesOpenFailed>0&&t.push(`${e.filesOpenFailed} files failed to open in language server`),e.filesNoSymbols>0&&t.push(`${e.filesNoSymbols} files had no discoverable symbols`),e.discoveryErrors>0&&t.push(`${e.discoveryErrors} symbol discovery failures`),e.symbolQueryErrors>0&&t.push(`${e.symbolQueryErrors} symbol query failures`),e.queryRejections>0&&t.push(`${e.queryRejections} individual LSP query rejections`);let n=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(n.length>0){let o=n.reduce((a,[,l])=>a+l,0),s=n.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(console.log(`${b} Enrichment issues: ${t.join(", ")}`),e.firstFileError&&console.log(`${b} First file read error: ${e.firstFileError}`),e.firstOpenError&&console.log(`${b} First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&console.log(`${b} First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&console.log(`${b} First symbol query error: ${e.firstSymbolError}`));}async querySymbol(e,t,n,o){let s=Zs[n.kind.toLowerCase()]||ea,a={line:n.line-1,character:n.column},l={textDocument:{uri:t},position:a},c={name:n.name,line:n.line,column:n.column,kind:n.kind},d=false,[m,u]=await Promise.allSettled([s.hover?e.sendRequest("textDocument/hover",l,nr):null,s.references?e.sendRequest("textDocument/references",{...l,context:{includeDeclaration:false}},nr):null]);for(let g of [m,u])g.status==="rejected"&&o.queryRejections++;if(m.status==="fulfilled"&&m.value?.contents){let g=m.value,f=typeof g.contents=="string"?g.contents:g.contents.value||"";f&&(c.typeInfo={resolvedType:f},d=true);}if(u.status==="fulfilled"&&u.value){let g=u.value;if(g.length>0){let f=g.slice(0,100).map(h=>({filePath:O(this.projectRoot,this.uriToPath(h.uri||"")),line:(h.range?.start?.line??0)+1,column:h.range?.start?.character??0}));c.references={count:g.length,locations:f},d=true;}}if(s.callHierarchy)try{let g=await e.sendRequest("textDocument/prepareCallHierarchy",l,nr);if(g&&g.length>0){let f=g[0],[h,x]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:f}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:f}).catch(()=>[])]),w=(h||[]).slice(0,200).map(P=>({name:P.from?.name||"",filePath:O(this.projectRoot,this.uriToPath(P.from?.uri||"")),line:(P.from?.range?.start?.line??0)+1,column:P.from?.selectionRange?.start?.character??P.from?.range?.start?.character??0})),_=(x||[]).slice(0,200).map(P=>({name:P.to?.name||"",filePath:O(this.projectRoot,this.uriToPath(P.to?.uri||"")),line:(P.to?.range?.start?.line??0)+1,column:P.to?.selectionRange?.start?.character??P.to?.range?.start?.character??0}));(w.length>0||_.length>0)&&(c.callHierarchy={incomingCalls:w,outgoingCalls:_},d=!0);}}catch{o.queryRejections++;}if(!d){let g=n.kind.toLowerCase();o.symbolsWithNoEnrichment[g]=(o.symbolsWithNoEnrichment[g]??0)+1;}return d?c:null}async discoverSymbols(e,t,n,o){try{let s=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:n}});return !s||!Array.isArray(s)?[]:this.flattenDocumentSymbols(s)}catch(s){return o.discoveryErrors++,o.firstDiscoveryError||(o.firstDiscoveryError=`${t}: ${s instanceof Error?s.message:String(s)}`),[]}}flattenDocumentSymbols(e){let t=[],n={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let o of e){let s=n[o.kind]||"variable",a=o.selectionRange||o.range||o.location?.range;a&&t.push({name:o.name,line:(a.start?.line??0)+1,column:a.start?.character??0,kind:s}),o.children&&Array.isArray(o.children)&&t.push(...this.flattenDocumentSymbols(o.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=N.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function Pn(i){return i.map(e=>JSON.stringify(e)).join(`
58
+ New terminal sessions will load it automatically.`);}};});function Pn(i){return i.replace(/\\/g,"/")}function mt(i){return Pn(i).replace(/^\.?\//,"")}function O(i,e){return Pn(N.relative(i,e))}var ue=y(()=>{});var be,ar=y(()=>{be=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,o=0,s=0;for(;s<e.length&&n.size<this.concurrency;){let a=o++,l=this.processItem(e[s],s,t).then(c=>({result:c!==null?c.result:null,promiseId:a}));n.set(a,l),s++;}for(;n.size>0;){let a=await Promise.race(n.values());if(n.delete(a.promiseId),a.result!==null&&(yield a.result),s<e.length){let l=o++,c=this.processItem(e[s],s,t).then(m=>({result:m!==null?m.result:null,promiseId:l}));n.set(l,c),s++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});var da,ma,lr,ga,fa,ha,gt,Nn=y(()=>{ue();ar();D();da={function:{hover:true,references:true,callHierarchy:true},method:{hover:true,references:true,callHierarchy:true},class:{hover:false,references:true,callHierarchy:false},interface:{hover:false,references:true,callHierarchy:false},variable:{hover:true,references:true,callHierarchy:false},property:{hover:true,references:true,callHierarchy:false},import:{hover:true,references:false,callHierarchy:false}},ma={hover:true,references:true,callHierarchy:false},lr=1e4,ga=1200*1e3,fa=50,ha={typescript:"TypeScript",javascript:"JavaScript",python:"Python"},gt=class{constructor(e){this.projectRoot=e;}async enrich(e,t,n,o){let s=[],a=Date.now(),l={filesUnreadable:0,filesOpenFailed:0,filesNoSymbols:0,symbolQueryErrors:0,discoveryErrors:0,queryRejections:0,symbolsWithNoEnrichment:{},firstFileError:null,firstOpenError:null,firstSymbolError:null,firstDiscoveryError:null},c=false;return await Promise.all([...e.entries()].map(async([m,u])=>{let d=n.get(m);if(!d)return;let g=u.length,f=g>1e4?4:g>5e3?6:8,h=new be(f),x=0,_=h.run(u,async w=>{try{if(c||Date.now()-a>ga)return c=!0,null;let P=await this.openFile(d,w,l,o?.get(w));if(!P)return null;let{uri:K}=P;try{let E=t.get(w)??[];if(E.length===0&&(E=await this.discoverSymbols(d,w,K,l),E.length===0))return l.filesNoSymbols++,null;let A=await this.enrichOpenFile(d,w,K,E,l);return A.length>0?{filePath:w,language:m,symbols:A}:null}finally{this.closeFile(d,K);}}finally{if(x++,x%fa===0){let P=Math.round(x/g*100);console.log(`${v} ${ha[m]??m} index enrichment: ${P}% (${x}/${g} files)`);}}});for await(let w of _)w&&s.push(w);})),c&&console.log(`${v} Enrichment timeout reached. Uploading partial results.`),this.logDiagnostics(l),s}async openFile(e,t,n,o){let s=N.resolve(this.projectRoot,t),a=pathToFileURL(s).href,l=o;if(l===void 0)try{l=It.readFileSync(s,"utf-8");}catch(c){return n.filesUnreadable++,n.firstFileError||(n.firstFileError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}try{e.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(t),version:1,text:l}});}catch(c){return n.filesOpenFailed++,n.firstOpenError||(n.firstOpenError=`${t}: ${c instanceof Error?c.message:String(c)}`),null}return {uri:a,content:l}}closeFile(e,t){try{e.sendNotification("textDocument/didClose",{textDocument:{uri:t}});}catch{}}async enrichOpenFile(e,t,n,o,s){let a=await Promise.allSettled(o.map(c=>this.querySymbol(e,n,c,s))),l=[];for(let c=0;c<a.length;c++){let m=a[c];if(m.status==="fulfilled")m.value&&l.push(m.value);else if(s.symbolQueryErrors++,!s.firstSymbolError){let u=o[c];s.firstSymbolError=`${u.name} in ${t}: ${m.reason instanceof Error?m.reason.message:String(m.reason)}`;}}return l}logDiagnostics(e){let t=[];e.filesUnreadable>0&&t.push(`${e.filesUnreadable} files unreadable`),e.filesOpenFailed>0&&t.push(`${e.filesOpenFailed} files failed to open in language server`),e.filesNoSymbols>0&&t.push(`${e.filesNoSymbols} files had no discoverable symbols`),e.discoveryErrors>0&&t.push(`${e.discoveryErrors} symbol discovery failures`),e.symbolQueryErrors>0&&t.push(`${e.symbolQueryErrors} symbol query failures`),e.queryRejections>0&&t.push(`${e.queryRejections} individual LSP query rejections`);let n=Object.entries(e.symbolsWithNoEnrichment).filter(([,o])=>o>0).sort(([,o],[,s])=>s-o);if(n.length>0){let o=n.reduce((a,[,l])=>a+l,0),s=n.map(([a,l])=>`${l} ${a}`).join(", ");t.push(`${o} symbols yielded no enrichment (${s})`);}t.length!==0&&(console.log(`${b} Enrichment issues: ${t.join(", ")}`),e.firstFileError&&console.log(`${b} First file read error: ${e.firstFileError}`),e.firstOpenError&&console.log(`${b} First didOpen error: ${e.firstOpenError}`),e.firstDiscoveryError&&console.log(`${b} First discovery error: ${e.firstDiscoveryError}`),e.firstSymbolError&&console.log(`${b} First symbol query error: ${e.firstSymbolError}`));}async querySymbol(e,t,n,o){let s=da[n.kind.toLowerCase()]||ma,a={line:n.line-1,character:n.column},l={textDocument:{uri:t},position:a},c={name:n.name,line:n.line,column:n.column,kind:n.kind},m=false,[u,d]=await Promise.allSettled([s.hover?e.sendRequest("textDocument/hover",l,lr):null,s.references?e.sendRequest("textDocument/references",{...l,context:{includeDeclaration:false}},lr):null]);for(let g of [u,d])g.status==="rejected"&&o.queryRejections++;if(u.status==="fulfilled"&&u.value?.contents){let g=u.value,f=typeof g.contents=="string"?g.contents:g.contents.value||"";f&&(c.typeInfo={resolvedType:f},m=true);}if(d.status==="fulfilled"&&d.value){let g=d.value;if(g.length>0){let f=g.slice(0,100).map(h=>({filePath:O(this.projectRoot,this.uriToPath(h.uri||"")),line:(h.range?.start?.line??0)+1,column:h.range?.start?.character??0}));c.references={count:g.length,locations:f},m=true;}}if(s.callHierarchy)try{let g=await e.sendRequest("textDocument/prepareCallHierarchy",l,lr);if(g&&g.length>0){let f=g[0],[h,x]=await Promise.all([e.sendRequest("callHierarchy/incomingCalls",{item:f}).catch(()=>[]),e.sendRequest("callHierarchy/outgoingCalls",{item:f}).catch(()=>[])]),_=(h||[]).slice(0,200).map(P=>({name:P.from?.name||"",filePath:O(this.projectRoot,this.uriToPath(P.from?.uri||"")),line:(P.from?.range?.start?.line??0)+1,column:P.from?.selectionRange?.start?.character??P.from?.range?.start?.character??0})),w=(x||[]).slice(0,200).map(P=>({name:P.to?.name||"",filePath:O(this.projectRoot,this.uriToPath(P.to?.uri||"")),line:(P.to?.range?.start?.line??0)+1,column:P.to?.selectionRange?.start?.character??P.to?.range?.start?.character??0}));(_.length>0||w.length>0)&&(c.callHierarchy={incomingCalls:_,outgoingCalls:w},m=!0);}}catch{o.queryRejections++;}if(!m){let g=n.kind.toLowerCase();o.symbolsWithNoEnrichment[g]=(o.symbolsWithNoEnrichment[g]??0)+1;}return m?c:null}async discoverSymbols(e,t,n,o){try{let s=await e.sendRequest("textDocument/documentSymbol",{textDocument:{uri:n}});return !s||!Array.isArray(s)?[]:this.flattenDocumentSymbols(s)}catch(s){return o.discoveryErrors++,o.firstDiscoveryError||(o.firstDiscoveryError=`${t}: ${s instanceof Error?s.message:String(s)}`),[]}}flattenDocumentSymbols(e){let t=[],n={1:"file",2:"module",3:"namespace",4:"package",5:"class",6:"method",7:"property",8:"field",9:"constructor",10:"enum",11:"interface",12:"function",13:"variable",14:"constant",15:"string",16:"number",17:"boolean",18:"array",19:"object",20:"key",21:"null",22:"enumMember",23:"struct",24:"event",25:"operator",26:"typeParameter"};for(let o of e){let s=n[o.kind]||"variable",a=o.selectionRange||o.range||o.location?.range;a&&t.push({name:o.name,line:(a.start?.line??0)+1,column:a.start?.character??0,kind:s}),o.children&&Array.isArray(o.children)&&t.push(...this.flattenDocumentSymbols(o.children));}return t}uriToPath(e){try{return fileURLToPath(new URL(e))}catch{return e.replace(/^file:\/\//,"")}}getLanguageId(e){let t=N.extname(e).toLowerCase();return {".ts":"typescript",".tsx":"typescriptreact",".js":"javascript",".jsx":"javascriptreact",".py":"python",".pyi":"python"}[t]||"plaintext"}};});function Rn(i){return i.map(e=>JSON.stringify(e)).join(`
59
59
  `)+`
60
- `}var In=y(()=>{});function gt(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var C,q=y(()=>{C={async directoryExists(i){try{return (await B__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await B__default.access(i,B__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await B__default.readFile(i,{encoding:e,flag:B__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await B__default.writeFile(i,n,{encoding:t,flag:B__default.constants.O_WRONLY|B__default.constants.O_CREAT|B__default.constants.O_TRUNC});},async getFileStats(i){return await B__default.stat(i)},async getFileHandle(i,e,t){return await B__default.open(i,e,t)}};});var ft,Nn=y(()=>{ft=class i{constructor(e,t,n=1e4){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=n;this.stdout.on("data",o=>this.handleData(o)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
60
+ `}var Tn=y(()=>{});function ht(i){try{return execFileSync(process.platform==="win32"?"where":"which",[i],{stdio:"ignore"}),!0}catch{return false}}var C,Y=y(()=>{C={async directoryExists(i){try{return (await B__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await B__default.access(i,B__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await B__default.readFile(i,{encoding:e,flag:B__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await B__default.writeFile(i,n,{encoding:t,flag:B__default.constants.O_WRONLY|B__default.constants.O_CREAT|B__default.constants.O_TRUNC});},async getFileStats(i){return await B__default.stat(i)},async getFileHandle(i,e,t){return await B__default.open(i,e,t)}};});var yt,$n=y(()=>{yt=class i{constructor(e,t,n=1e4){this.stdin=e;this.stdout=t;this.defaultTimeoutMs=n;this.stdout.on("data",o=>this.handleData(o)),this.stdin.on("error",()=>{});}static HEADER_SEPARATOR=Buffer.from(`\r
61
61
  \r
62
62
  `);nextId=1;pendingRequests=new Map;buffer=Buffer.alloc(0);disposed=false;loggedMalformedJson=false;sendRequest(e,t,n){if(this.disposed)return Promise.reject(new Error("LspClient disposed"));let o=this.nextId++,s={jsonrpc:"2.0",id:o,method:e,...t!==void 0&&{params:t}};return new Promise((a,l)=>{let c=setTimeout(()=>{this.pendingRequests.delete(o),l(new Error(`LSP request '${e}' timed out after ${n??this.defaultTimeoutMs}ms`));},n??this.defaultTimeoutMs);this.pendingRequests.set(o,{resolve:a,reject:l,timer:c}),this.writeMessage(s);})}sendNotification(e,t){if(this.disposed)return;let n={jsonrpc:"2.0",method:e,...t!==void 0&&{params:t}};this.writeMessage(n);}dispose(){this.disposed=true;for(let[,e]of this.pendingRequests)clearTimeout(e.timer),e.reject(new Error("LspClient disposed"));this.pendingRequests.clear(),this.stdout.removeAllListeners("data");}writeMessage(e){let t=JSON.stringify(e),o=`Content-Length: ${Buffer.byteLength(t,"utf-8")}\r
63
63
  \r
64
- `;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,console.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var or,ht,se,Oe=y(()=>{or=N.join(Ie.homedir(),".constellation","lsp-servers"),ht=N.join(or,"node_modules",".bin"),se=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});function $n(i){return i.replace(/\\/g,"/")}function aa(i){let e=$n(i);return N.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function jn(i,e){if(!i||i.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=$n(i);if(sa.test(t))return {classification:"denied",reason:"LSP command contains shell metacharacters"};for(let o of e){if(typeof o!="string")return {classification:"denied",reason:"LSP argument is not a string"};if(o.includes("\0"))return {classification:"denied",reason:"LSP argument contains a null byte"};if(o.includes(`
65
- `)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let n=aa(i);if(oa.has(n))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${n}')`};for(let[,o]of se)if(n===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var oa,sa,Ln=y(()=>{Oe();oa=new Set(["sh","bash","zsh","zsh5","fish","dash","ash","ksh","csh","tcsh","rc","yash","cmd","command","powershell","pwsh","node","nodejs","deno","bun","python","python2","python3","pypy","pypy3","perl","ruby","php","lua","luajit","tclsh","wish","osascript","wscript","cscript","mshta","rundll32","sudo","su","doas","pkexec","runas","gsudo","env","xargs","exec","nohup","timeout","setsid"].map(i=>i.toLowerCase())),sa=/[;&|`$<>\n\r\0"']/;});function Fn(i,e,t,n){return i.projectRoot===e&&i.command===t&&i.args.length===n.length&&i.args.every((o,s)=>o===n[s])}function la(i){if(!i||typeof i!="object")return false;let e=i;return typeof e.projectRoot=="string"&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var be,sr=y(()=>{be=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,n){return (await this.load()).entries.some(s=>Fn(s,e,t,n))}async recordTrust(e,t,n){let o=await this.load();if(o.entries.some(l=>Fn(l,e,t,n)))return;o.entries.push({projectRoot:e,command:t,args:[...n],trustedAt:new Date().toISOString()}),await B.mkdir(N.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await B.writeFile(a,JSON.stringify(o,null,2)+`
66
- `,"utf-8"),await B.rename(a,this.trustFilePath);}catch(l){throw await B.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await B.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(la)}:{entries:[]}}catch{return {entries:[]}}}static isCIEnvironment(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}};});var yt,An=y(()=>{Ln();sr();yt=class{projectRoot;logger;trustStore;prompt;isCI;constructor(e){this.projectRoot=e.projectRoot,this.logger=e.logger,this.trustStore=e.trustStore,this.prompt=e.prompt,this.isCI=e.isCI??be.isCIEnvironment;}async authorize(e,t,n){let{classification:o,reason:s}=jn(t,n);if(o==="denied")return this.logger.error(`[LSP:${e}] Refusing unsafe LSP command '${t}': ${s??"denied"}.`),false;if(o==="known-safe"||await this.trustStore.isTrusted(this.projectRoot,t,n))return true;if(this.isCI())return this.logger.warn(`[LSP:${e}] Skipping untrusted custom LSP command '${t}' in CI. Run 'constellation index' interactively once to approve it, or set the 'lsp' field to a known binary.`),false;let a=n.length>0?` ${n.join(" ")}`:"",l=`Trust custom LSP command for this project?
64
+ `;this.stdin.write(o+t);}handleData(e){for(this.buffer=Buffer.concat([this.buffer,e]);;){let t=this.buffer.indexOf(i.HEADER_SEPARATOR);if(t===-1)break;let o=this.buffer.subarray(0,t).toString("utf-8").match(/Content-Length:\s*(\d+)/i);if(!o){this.buffer=this.buffer.subarray(t+4);continue}let s=parseInt(o[1],10),a=t+4;if(this.buffer.length-a<s)break;let l=this.buffer.subarray(a,a+s).toString("utf-8");this.buffer=this.buffer.subarray(a+s);try{let c=JSON.parse(l);this.handleResponse(c);}catch{this.loggedMalformedJson||(this.loggedMalformedJson=true,console.error("[LSP] Received malformed JSON from language server"));}}}handleResponse(e){if(e.id===void 0||e.id===null)return;let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(`LSP error ${e.error.code}: ${e.error.message}`)):t.resolve(e.result));}};});var pr,bt,oe,Me=y(()=>{pr=N.join(Ne.homedir(),".constellation","lsp-servers"),bt=N.join(pr,"node_modules",".bin"),oe=new Map([["typescript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["javascript",{command:"typescript-language-server",args:["--stdio"],npmPackages:["typescript-language-server","typescript"],testCommand:["--version"]}],["python",{command:"pyright-langserver",args:["--stdio"],npmPackages:["pyright"],testCommand:["--version"]}]]);});function Fn(i){return i.replace(/\\/g,"/")}function Sa(i){let e=Fn(i);return N.posix.basename(e).toLowerCase().replace(/\.(exe|com|bat|cmd|ps1)$/i,"")}function An(i,e){if(!i||i.trim().length===0)return {classification:"denied",reason:"LSP command is empty"};let t=Fn(i);if(va.test(t))return {classification:"denied",reason:"LSP command contains shell metacharacters"};for(let o of e){if(typeof o!="string")return {classification:"denied",reason:"LSP argument is not a string"};if(o.includes("\0"))return {classification:"denied",reason:"LSP argument contains a null byte"};if(o.includes(`
65
+ `)||o.includes("\r"))return {classification:"denied",reason:"LSP argument contains newline/carriage-return"}}let n=Sa(i);if(ba.has(n))return {classification:"denied",reason:`LSP command resolves to a shell or interpreter ('${n}')`};for(let[,o]of oe)if(n===o.command.toLowerCase())return {classification:"known-safe"};return {classification:"custom-untrusted"}}var ba,va,kn=y(()=>{Me();ba=new Set(["sh","bash","zsh","zsh5","fish","dash","ash","ksh","csh","tcsh","rc","yash","cmd","command","powershell","pwsh","node","nodejs","deno","bun","python","python2","python3","pypy","pypy3","perl","ruby","php","lua","luajit","tclsh","wish","osascript","wscript","cscript","mshta","rundll32","sudo","su","doas","pkexec","runas","gsudo","env","xargs","exec","nohup","timeout","setsid"].map(i=>i.toLowerCase())),va=/[;&|`$<>\n\r\0"']/;});function Dn(i,e,t,n){return i.projectRoot===e&&i.command===t&&i.args.length===n.length&&i.args.every((o,s)=>o===n[s])}function Ca(i){if(!i||typeof i!="object")return false;let e=i;return typeof e.projectRoot=="string"&&typeof e.command=="string"&&Array.isArray(e.args)&&e.args.every(t=>typeof t=="string")}var ve,ur=y(()=>{ve=class{constructor(e){this.trustFilePath=e;}async isTrusted(e,t,n){return (await this.load()).entries.some(s=>Dn(s,e,t,n))}async recordTrust(e,t,n){let o=await this.load();if(o.entries.some(l=>Dn(l,e,t,n)))return;o.entries.push({projectRoot:e,command:t,args:[...n],trustedAt:new Date().toISOString()}),await B.mkdir(N.dirname(this.trustFilePath),{recursive:true});let a=`${this.trustFilePath}.${process.pid}.tmp`;try{await B.writeFile(a,JSON.stringify(o,null,2)+`
66
+ `,"utf-8"),await B.rename(a,this.trustFilePath);}catch(l){throw await B.rm(a,{force:true}).catch(()=>{}),l}}async load(){try{let e=await B.readFile(this.trustFilePath,"utf-8"),t=JSON.parse(e);return t&&typeof t=="object"&&Array.isArray(t.entries)?{entries:t.entries.filter(Ca)}:{entries:[]}}catch{return {entries:[]}}}static isCIEnvironment(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}};});var vt,Mn=y(()=>{kn();ur();vt=class{projectRoot;logger;trustStore;prompt;isCI;constructor(e){this.projectRoot=e.projectRoot,this.logger=e.logger,this.trustStore=e.trustStore,this.prompt=e.prompt,this.isCI=e.isCI??ve.isCIEnvironment;}async authorize(e,t,n){let{classification:o,reason:s}=An(t,n);if(o==="denied")return this.logger.error(`[LSP:${e}] Refusing unsafe LSP command '${t}': ${s??"denied"}.`),false;if(o==="known-safe"||await this.trustStore.isTrusted(this.projectRoot,t,n))return true;if(this.isCI())return this.logger.warn(`[LSP:${e}] Skipping untrusted custom LSP command '${t}' in CI. Run 'constellation index' interactively once to approve it, or set the 'lsp' field to a known binary.`),false;let a=n.length>0?` ${n.join(" ")}`:"",l=`Trust custom LSP command for this project?
67
67
  ${t}${a}
68
68
 
69
69
  Only approve commands you recognize. Untrusted commands can execute arbitrary code.
70
- Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,n),this.logger.log(`[LSP:${e}] Trusted custom LSP command '${t}' for this project.`),true):(this.logger.warn(`[LSP:${e}] User declined to trust LSP command '${t}'. Skipping enrichment for this language.`),false)}};});var da,ma,bt,On=y(()=>{q();Nn();Oe();An();sr();da={log:i=>console.log(i),warn:i=>console.warn(i),error:i=>console.error(i)},ma=N.join(Ie.homedir(),".constellation","lsp-trust.json"),bt=class{constructor(e,t,n){this.projectRoot=e;this.logger=t??da,this.policy=n??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new yt({projectRoot:this.projectRoot,logger:this.logger,trustStore:new be(ma),prompt:async e=>{let{confirm:t}=await import('@inquirer/prompts');try{return await t({message:e,default:!1})}catch{return false}}})}async startServer(e,t){if(t===false||this.unavailableLanguages.has(e))return null;let n=this.languageToServerKey.get(e),o=n?this.serversByKey.get(n):void 0;if(o)return this.toConnection(o,e);let s=this.resolveCommand(e,t);if(!s)return this.unavailableLanguages.add(e),null;let{command:a,args:l}=s,c=this.getServerKey(a,l);if(this.unavailableServerKeys.has(c))return this.unavailableLanguages.add(e),null;let d=this.serversByKey.get(c);if(d)return d.languages.add(e),this.languageToServerKey.set(e,c),this.toConnection(d,e);if(!await this.policy.authorize(e,a,l))return this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c),null;try{let u=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((x,w)=>{u.once("spawn",x),u.once("error",w);}),u.stderr?.on("data",x=>{let w=x.toString().trim();w.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${w}`);});let g=new ft(u.stdin,u.stdout,12e4),f=await g.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);g.sendNotification("initialized",{});let h={key:c,language:e,languages:new Set([e]),process:u,client:g};return this.serversByKey.set(c,h),this.languageToServerKey.set(e,c),u.on("exit",x=>{let w=this.serversByKey.get(c);if(w){w.client.dispose(),this.serversByKey.delete(c);for(let[_,P]of this.languageToServerKey.entries())P===c&&this.languageToServerKey.delete(_);}x!==0&&x!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${x}`);}),this.toConnection(h,e)}catch(u){this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let g=`[LSP:${e}] Failed to start: ${u instanceof Error?u.message:String(u)}`,f=u?.code;return f==="ENOENT"||f==="EACCES"?this.logger.warn(g):this.logger.error(g),null}}async shutdown(e){let t=this.languageToServerKey.get(e);if(!t)return;this.languageToServerKey.delete(e);let n=this.serversByKey.get(t);n&&(n.languages.delete(e),!(n.languages.size>0)&&await this.shutdownByKey(t));}async shutdownByKey(e){let t=this.serversByKey.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(n=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),n();},3e3);t.process.on("exit",()=>{clearTimeout(o),n();});});}catch(n){this.logger.warn(`[LSP:${t.language}] Graceful shutdown failed, force killing: ${n instanceof Error?n.message:String(n)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.serversByKey.delete(e);for(let[n,o]of this.languageToServerKey.entries())o===e&&this.languageToServerKey.delete(n);}}async shutdownAll(){let e=[...this.serversByKey.keys()];await Promise.allSettled(e.map(t=>this.shutdownByKey(t)));}destroyAll(){for(let e of this.serversByKey.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.serversByKey.clear(),this.languageToServerKey.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let n=se.get(e);if(!n)return null;let o=N.join(ht,n.command);return existsSync(o)?{command:o,args:n.args}:gt(n.command)?{command:n.command,args:n.args}:null}getServerKey(e,t){return `${e}\0${t.join("\0")}`}toConnection(e,t){let n=`lsp-${t}-${this.nextId++}`;return {language:t,process:e.process,id:n,sendRequest:(o,s,a)=>e.client.sendRequest(o,s,a),sendNotification:(o,s)=>e.client.sendNotification(o,s)}}};});var ae,vt=y(()=>{ae=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var ve,lr=y(()=>{D();ve=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${b} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let o=t instanceof Error?t.message:String(t);console.warn(`${b} Failed to parse ${n}: ${o}`),console.warn(`${b} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${b} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var St,Bn=y(()=>{pe();St=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(n,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?N.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=N.resolve(n,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=N.join(this.projectRoot,"package.json"),n=await B.readFile(t,"utf-8"),s=JSON.parse(n).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let d of c){let m=await this.loadWorkspacePackage(d);m&&Object.assign(e,m);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),o=N.join(this.projectRoot,n);try{let s=await B.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(N.join(o,a.name));}catch{}}else {let n=N.join(this.projectRoot,e);try{(await B.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=N.join(e,"package.json"),n=await B.readFile(t,"utf-8"),o=JSON.parse(n),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return N.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return N.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return N.join(e,a)}}}if(t.main)return N.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of n){let s=N.join(e,o);try{if((await B.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let o=N.join(e,n);try{if((await B.stat(o)).isFile())return o}catch{}}try{if((await B.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?N.dirname(e):N.dirname(e),o=[N.join(n,t+".ts"),N.join(n,t+".tsx"),N.join(n,t+".js"),N.join(n,t+".jsx"),N.join(n,t+".d.ts"),N.join(n,t,"index.ts"),N.join(n,t,"index.tsx"),N.join(n,t,"index.js"),N.join(n,t,"index.jsx")];for(let s of o)try{if((await B.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=O(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var Se,cr=y(()=>{pe();Bn();Se=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=N.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new St(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),s=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=N.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=N.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=N.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(n);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=O(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of n){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,o]=t.split("*");if(!e.startsWith(n)||o&&!e.endsWith(o))return null;let s=n.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,n,o){let s=n.replaceAll("*",o),a=N.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=N.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],o=n.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of n)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=N.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await B.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await B.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=N.join(t,"package.json");try{if((await B.stat(n)).isFile())return n}catch{}let o=N.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await B.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=N.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof n=="string"){let s=await this.tryPackageImportSubstitution(n,o);if(s)return s}if(Array.isArray(n)){for(let s of n)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),o=N.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};});var Ct,Un=y(()=>{vt();lr();cr();Ct=class extends ae{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new ve(e,t)}getImportResolver(e,t){return new Se(e,t)}};});var wt,Gn=y(()=>{vt();lr();cr();wt=class extends ae{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new ve(e,t)}getImportResolver(e,t){return new Se(e,t)}};});async function le(i,e,t,n,o,s=[]){let a=await t.resolve(i),l=zn(i,a),c=o(i,a,l),d=l?void 0:ut(a);n[e.toString()]={source:i,resolvedPath:d,isExternal:l,importType:c,specifiers:s};}function zn(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var pr,Me=y(()=>{pe();pr=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function ya(i,e,t,n){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await le(s,i.startPosition.row,e,t,n,[a]);}function ba(i,e){if(!e)return [];let t=[],n=i.childForFieldName("name");if(n){if(n.type==="aliased_import"){let s=n.childForFieldName("name"),a=n.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:n.text,original:n.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function va(i,e,t,n){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let d=i.child(c);if(d){if(d.type==="relative_import"){l=d.text;break}(d.type==="."||d.type==="import_prefix")&&(l+=d.text);}}o=l||".";}let a=ba(i,!!s);await le(o,i.startPosition.row,e,t,n,a);}async function Sa(i,e,t,n){await le("__future__",i.startPosition.row,e,t,n,[]);}function ur(){return {language:"python",handlers:new Map([["import_statement",ya],["import_from_statement",va],["future_import_statement",Sa]]),classifyImportType:ha}}var ha,_t=y(()=>{Fe();Me();Fe();ha=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return je.has(n)?"builtin":"alias"};});var xt,Hn=y(()=>{_t();xt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=N.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(je.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),o=await this.tryResolveFile(N.resolve(this.projectRoot,n));return o?N.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",a=N.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?N.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,N.join(e,"__init__.py"),N.join(e,"__init__.pyi")];for(let n of t)try{return await Et.promises.access(n,Et.constants.F_OK),n}catch{continue}return null}};});var Pt,Wn=y(()=>{vt();Hn();Pt=class extends ae{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new xt(e,process.cwd())}};});function Ue(i){return xa[i]??i.charAt(0).toUpperCase()+i.slice(1)}var xa,Be,It,Nt=y(()=>{Un();Gn();Wn();xa={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",typescript:"TypeScript"};Be={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},It=class{constructor(e){this.config=e;this.registerPlugin(new Ct),this.registerPlugin(new wt),this.registerPlugin(new Pt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Ca,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Be.javascript};typescript={language:()=>_a.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Be.typescript};python={language:()=>wa,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Be.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function Ce(i,e,t=32){let n=i.parent,o=0;for(;n!==null&&o<t;){if(e(n))return n;n=n.parent,o++;}return null}var Rt,dr=y(()=>{Rt=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function mr(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&Ea(t,e);}for(let t of i.namedChildren)t&&mr(t,e);}function Ea(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(de(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(de(t.startPosition.row,t.startPosition.column),"call");}}var Kn=y(()=>{Ge();});function we(i,e){i.rootNode&&(Vn(i.rootNode,e),mr(i.rootNode,e));}function Vn(i,e){if(Pa.has(i.type)){let t=Ia(i);t!==null&&e.set(de(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Vn(t,e);}function Ia(i){if(Ra(i))return "declaration";if(Ma(i))return "read";if(Da(i))return "type";let e=Ce(i,t=>t.type==="decorator");return e!==null&&ja(i,e)?"call":$a(i)?"instantiate":Ta(i)?"call":La(i)||Fa(i)||ka(i)||Ja(i)||Ka(i)?"write":Ba(i)?"import-use":"read"}function Ra(i){let e=i.parent;return e===null?false:!!(Na.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function Ta(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function $a(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function ja(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let n=t.childForFieldName("function");if(n===i||n?.type==="member_expression"&&n.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function La(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||Rt.has(t.type))return false;e=t;}return false}function Fa(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function ka(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||Rt.has(t.type))return false;e=t;}return false}function Da(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let n=e.namedChild(1);return n===null?false:n===t||Oa(n,i)}if(Aa.has(e.type))return true;if(Rt.has(e.type))return false;t=e,e=e.parent;}return false}function Oa(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function Ma(i){return Ce(i,t=>t.type==="type_query")!==null}function Ba(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,n=Ha(i);return Wa(n,t)?!Ga(i,t):false}function Ga(i,e){let t=i.parent;for(;t!==null;){if(Ua.has(t.type)&&za(t,e))return true;t=t.parent;}return false}function za(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let n of t.namedChildren){if(n.type!=="variable_declarator")continue;if(n.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let n of t.namedChildren){if(n.type!=="required_parameter"&&n.type!=="optional_parameter")continue;let o=n.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function Ha(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function Wa(i,e){for(let t of i.descendantsOfType("namespace_import")){let n=t.namedChild(0);if(n!==null&&n.text===e)return true}return false}function Ka(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function Ja(i){let e=i.parent;if(e===null||!Jn.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let n=t.parent;if(n===null)return false;if(n.type==="variable_declarator"&&n.childForFieldName("name")===t||(n.type==="assignment_expression"||n.type==="augmented_assignment_expression")&&n.childForFieldName("left")===t||(n.type==="required_parameter"||n.type==="optional_parameter")&&n.childForFieldName("pattern")===t||n.type==="formal_parameters"||n.type==="for_in_statement"&&n.childForFieldName("left")===t)return true;if(!Jn.has(n.type))return false;t=n;}return false}var Pa,Na,Aa,Ua,Jn,Tt=y(()=>{Ge();dr();Kn();Pa=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));Na=Object.freeze(new Set(["variable_declarator","function_declaration","function_signature","generator_function_declaration","class_declaration","abstract_class_declaration","interface_declaration","type_alias_declaration","enum_declaration","enum_assignment","method_signature","abstract_method_signature","method_definition","public_field_definition","field_definition","property_signature"]));Aa=Object.freeze(new Set(["type_annotation","type_arguments","type_parameter","type_parameters","type_alias_declaration","interface_declaration","generic_type","type_predicate","type_query","conditional_type","union_type","intersection_type","tuple_type","mapped_type_clause","implements_clause","extends_type_clause"]));Ua=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Jn=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function qn(i,e){we(i,e);}var Yn=y(()=>{Tt();});function Xn(i,e){we(i,e);}var Qn=y(()=>{Tt();});function Zn(i,e){if(!i.rootNode)return;let t=gl(i.rootNode);ei(i.rootNode,e,t);}function ei(i,e,t){if(Va.has(i.type)){let n=qa(i,t);n!==null&&e.set(de(i.startPosition.row,i.startPosition.column),n);}for(let n of i.namedChildren)n&&ei(n,e,t);}function qa(i,e){if(Ya(i))return "declaration";if(Za(i))return "read";if(Qa(i))return "declaration";if(el(i))return "type";let t=Ce(i,n=>n.type==="decorator");return t!==null&&tl(i,t)||rl(i)?"call":nl(i)||il(i)||ol(i)||al(i)||cl(i)?"write":pl(i,e)?"import-use":"read"}function Ya(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||Xa(i))}function Xa(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function Qa(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(gr.has(e.type))return false;e=e.parent;}return false}function Za(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function el(i){return Ce(i,t=>t.type==="type")!==null}function tl(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let n=t.childForFieldName("function");if(n===i||n?.type==="attribute"&&n.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function rl(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function nl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||gr.has(t.type))return false;e=t;}return false}function il(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function ol(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function al(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(sl.has(t.type)){e=t;continue}if(gr.has(t.type))return false;e=t;}return false}function cl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!ll.has(t.type))return false;e=t;}return false}function pl(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let n=i.text;return e.has(n)?!dl(i,n):false}function dl(i,e){let t=i.parent;for(;t!==null;){if(ul.has(t.type)&&ml(t,e))return true;t=t.parent;}return false}function ml(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let n=t.namedChild(0);if(n?.type==="assignment"){let o=n.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let n of t.namedChildren)if(n.type==="identifier"&&n.text===e||(n.type==="typed_parameter"||n.type==="typed_default_parameter"||n.type==="default_parameter")&&n.namedChild(0)?.type==="identifier"&&n.namedChild(0)?.text===e)return true}}return false}function gl(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let n of t.namedChildren)if(n.type==="dotted_name"&&e.add(n.text),n.type==="aliased_import"){let o=n.childForFieldName("alias");o&&e.add(o.text);}return e}var Va,gr,sl,ll,ul,ti=y(()=>{Ge();dr();Va=Object.freeze(new Set(["identifier"])),gr=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));sl=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));ll=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));ul=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function ni(i,e){let t=new Map;switch(e){case "typescript":we(i,t);break;case "tsx":qn(i,t);break;case "javascript":Xn(i,t);break;case "python":Zn(i,t);break}return t}function de(i,e){return `${i}:${e}`}var ri,Ge=y(()=>{Tt();Yn();Qn();ti();ri=Object.freeze(new Set(["typescript","javascript","python"]));});function yl(i,e){return ri.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function bl(i){let e=[];for(let[t,n]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:n});}return e.sort((t,n)=>t.line-n.line||t.column-n.column),e}var $t,si=y(()=>{Ge();q();$t=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let o=await n();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=_a.tsx);let s=new fl;s.setLanguage(o);let a=await C.getFileStats(e),l=10*1024*1024,c,d;if(a.size<=l){let f=await C.readFile(e);d=f;let h={bufferSize:1024*1024};c=s.parse(f,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let m=yl(t,e),u=m===null?[]:bl(ni(c,m));return {tree:c,classificationMap:{filePath:e,entries:u},content:d}}async parseWithStream(e,t,n){let o=null;try{o=await B.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(m=>{if(n>50*1024*1024){let g=Math.round(m/n*100);g>c+10&&(console.log(` Parsing large file: ${g}%...`),c=g);}let u=Et.readSync(s,l,0,a,m);return u===0?null:l.subarray(0,u).toString("utf-8")})}catch(s){if(o)try{await o.close();}catch(a){console.error(`Warning: Failed to close file handle for ${t}:`,a);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var jt,li=y(()=>{q();pe();D();jt=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=ai();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=ai().add(t.exclude));let s=await B__default.realpath(this.rootPath);for(let a of e)try{let l=N__default.isAbsolute(a)?a:N__default.join(this.rootPath,a),c=await B__default.lstat(l);if(c.isSymbolicLink()){let d=await B__default.realpath(l);if(!d.startsWith(s+N__default.sep)&&d!==s){console.warn(`${b} Skipping symlink pointing outside project: ${a} -> ${d}`);continue}let m=await B__default.stat(l);if(!m.isFile())continue;let u=O(this.rootPath,l);if(o&&o.ignores(u))continue;let g=this.detectLanguage(u,t.languages);if(!g)continue;n.push({path:l,relativePath:u,language:g,size:m.size});}else if(c.isFile()){let d=O(this.rootPath,l);if(o&&o.ignores(d))continue;let m=this.detectLanguage(d,t.languages);if(!m)continue;n.push({path:l,relativePath:d,language:m,size:c.size});}}catch{console.warn(`${b} Skipping inaccessible file: ${a}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let s=N__default.join(o,".gitignore");await C.fileIsReadable(s)&&n.unshift(s);let a=N__default.dirname(o);if(a===o)break;o=a;let l=N__default.join(o,".git");if(await C.directoryExists(l)){let c=N__default.join(o,".gitignore");await C.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let s of n)try{let a=await C.readFile(s);e.add(a);}catch{console.warn(`${b} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,n,o){let s=[],a=t||e,l=n||await B__default.realpath(this.rootPath),c=o||new Set([l]);try{let d=await B__default.readdir(e,{withFileTypes:!0});for(let m of d){let u=N__default.join(e,m.name),g=O(a,u);if(m.isDirectory()){if(m.name.startsWith("."))continue;let f=await this.walkDirectory(u,a,l,c);s.push(...f);}else if(m.isFile()){let f=await B__default.stat(u);s.push({path:u,relativePath:g,language:"",size:f.size});}else if(m.isSymbolicLink())try{let f=await B__default.realpath(u);if(!f.startsWith(l+N__default.sep)&&f!==l){console.warn(`${b} Skipping symlink pointing outside project: ${u} -> ${f}`);continue}let h=await B__default.stat(u);if(h.isDirectory()){if(m.name.startsWith(".")||c.has(f))continue;c.add(f);let x=await this.walkDirectory(u,a,l,c);s.push(...x);}else h.isFile()&&s.push({path:u,relativePath:g,language:"",size:h.size});}catch{console.warn(`${b} Skipping invalid symlink: ${u}`);}}}catch(d){console.error(`${I} Error walking directory ${e}:`,d);}return s}matchesLanguageExtension(e,t){let n=N__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=N__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return o;return null}};});var vl,Sl,Cl,ci,pi=y(()=>{Fe();vl=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Sl=z.object({source:z.string().min(1,"Import source cannot be empty"),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:z.enum(["relative","workspace","alias","external","builtin"]),specifiers:z.array(vl).optional()}),Cl=z.record(z.string(),Sl),ci=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Cl.optional(),classificationMap:Yt.optional()});});var _l,Lt,mi=y(()=>{_l=promisify(fr__default.gunzip),Lt=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=fr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(e);return await pipeline(s,n),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=fr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,n),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await _l(t);return JSON.parse(n.toString("utf-8"))}};});var hr,Ft=y(()=>{hr=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED","ENRICHMENT_FAILED"]);});function yr(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var ze,gi=y(()=>{Ft();ze=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:p.unstyle(e.map(yr).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:p.unstyle(e.map(yr).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:p.unstyle(e.map(yr).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!hr.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!hr.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:p.unstyle(t),timestamp:new Date().toISOString(),code:n});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});function _e(i,e){let t=e??i;return {line:t.startPosition.row+1,column:t.startPosition.column}}function xe(i){return i?i.text:null}function yi(){return {language:"javascript",handlers:new Map(hi)}}function bi(){return {language:"typescript",handlers:new Map([...hi,["interface_declaration",Pl],["public_field_definition",fi],["property_signature",fi]])}}var xl,El,Pl,Il,fi,Nl,hi,vi=y(()=>{xl=(i,e)=>{let t=i.childForFieldName("name"),n=xe(t);n&&e.symbols.push({name:n,kind:"function",..._e(i,t)});},El=(i,e)=>{let t=i.childForFieldName("name"),n=xe(t);if(n)return e.symbols.push({name:n,kind:"class",..._e(i,t)}),{...e,enclosingType:n}},Pl=(i,e)=>{let t=i.childForFieldName("name"),n=xe(t);if(n)return e.symbols.push({name:n,kind:"interface",..._e(i,t)}),{...e,enclosingType:n}},Il=(i,e)=>{let t=i.childForFieldName("name"),n=xe(t);n&&e.symbols.push({name:n,kind:"method",..._e(i,t)});},fi=(i,e)=>{let t=i.childForFieldName("name"),n=xe(t);n&&e.symbols.push({name:n,kind:"property",..._e(i,t)});},Nl=(i,e)=>{let t=i.childForFieldName("name"),n=xe(t);if(!n)return;let o=i.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:n,kind:s?"function":"variable",..._e(i,t)});},hi=[["function_declaration",xl],["class_declaration",El],["method_definition",Il],["variable_declarator",Nl]];});function br(i){return {line:i.startPosition.row+1,column:i.startPosition.column}}function Si(){return {language:"python",handlers:new Map([["function_definition",Rl],["class_definition",Tl],["assignment",$l]])}}var Rl,Tl,$l,Ci=y(()=>{Rl=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let n=e.enclosingType?"method":"function";e.symbols.push({name:t.text,kind:n,...br(t)});},Tl=(i,e)=>{let t=i.childForFieldName("name");if(t)return e.symbols.push({name:t.text,kind:"class",...br(t)}),{...e,enclosingType:t.text}},$l=(i,e)=>{let t=i.childForFieldName("left");if(!t||t.type!=="identifier")return;let n=e.enclosingType?"property":"variable";e.symbols.push({name:t.text,kind:n,...br(t)});};});var wi,_i=y(()=>{vi();Ci();wi=[yi(),bi(),Si()];});var At,xi=y(()=>{_i();At=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??wi)this.languageHandlers.set(t.language,t.handlers);}extract(e,t){let n=this.languageHandlers.get(t);if(!n)return [];let o={symbols:[]};return this.walk(e.rootNode,o,n),o.symbols}walk(e,t,n){let s=n.get(e.type)?.(e,t)??t;for(let a=0;a<e.childCount;a++){let l=e.child(a);l&&this.walk(l,s,n);}}};});function jl(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n){if(n.type==="identifier")e.push({local:n.text,original:"default",isDefault:true,isNamespace:false});else if(n.type==="namespace_import"){let o;for(let s=0;s<n.childCount;s++){let a=n.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(n.type==="named_imports")for(let o=0;o<n.childCount;o++){let s=n.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,d=l?l.text:c,m=c==="default";e.push({local:d,original:c,isDefault:m,isNamespace:false});}}}return e}async function Ll(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?jl(l):[];await le(a,s,e,t,n,c);}async function Fl(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await le(a,s,e,t,n,[]);}function Dt(){return {language:"javascript",handlers:new Map([["import_statement",Ll],["export_statement",Fl]])}}function vr(){return {...Dt(),language:"typescript"}}var Sr=y(()=>{Me();});var Ei,Pi=y(()=>{Sr();_t();Me();Sr();_t();Ei=[Dt(),vr(),ur()];});var Ii={};qr(Ii,{ImportExtractor:()=>Cr});var Cr,Ni=y(()=>{Pi();Me();Cr=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Ei)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,o){if(!o)return {};let s=this.languageHandlers.get(n);if(!s)return {};let a=this.classifiers.get(n)??pr,l={};return await this.walkAST(e.rootNode,async c=>{let d=s.get(c.type);d&&await d(c,o,l,a);}),l}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let o=e.child(n);o&&await this.walkAST(o,t);}}};});var He,Ri,wr,Ti,$i,Ot=y(()=>{He=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),Ri=new Set(["true","false","null","undefined","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type"]),wr={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Ti={language:"javascript",textIncludedTypes:Ri,fieldNames:wr},$i={language:"typescript",textIncludedTypes:Ri,fieldNames:wr};});var kl,ji,Li,_r=y(()=>{kl=new Set(["true","false","none","None","True","False","yield","pass","continue","break","ellipsis","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","type","subscript","attribute","list","tuple","binary_operator","union_type","generic_type"]),ji={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],list_splat_pattern:[],dictionary_splat_pattern:[],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]},Li={language:"python",textIncludedTypes:kl,fieldNames:ji,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function Fi(i){return We.get(i)}function ki(i){if(!i)return He;let e=We.get(i);if(!e)return He;let t=new Set(He);for(let n of e.textIncludedTypes)t.add(n);return t}function xr(i){if(!i){let t=Array.from(We.values()).map(n=>n.fieldNames);return Ke(...t)}let e=We.get(i);if(!e){let t=Array.from(We.values()).map(n=>n.fieldNames);return Ke(...t)}return e.fieldNames}var We,Ai=y(()=>{Er();Ot();_r();Ot();Ot();_r();We=new Map([["javascript",Ti],["typescript",$i],["python",Li]]);});var Ui={};qr(Ui,{COMMON_FIELD_NAMES:()=>Nr,JS_TS_FIELD_NAMES:()=>Mi,PYTHON_FIELD_NAMES:()=>Bi,TEXT_INCLUDED_TYPES:()=>Di,mergeFieldMaps:()=>Ke,serializeAST:()=>Dl,serializeASTStream:()=>Al});function*Al(i,e,t){yield*Ir(i,e,t);}function*Ir(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Oi(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?xr(t):Nr)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*Ir(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*Ir(c,void 0,t));}yield "]";}yield "}";}async function Dl(i,e,t){let n=Pr(i,e,t),o=t?xr(t):Nr,s=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let d=a.treeNode.childForFieldName(c);if(d){a.fieldChildren.add(d);let m=Pr(d,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(m),s.push({treeNode:d,serializedNode:m,fieldName:c,childIndex:0,fieldChildren:new Set});}}}if(a.childIndex<a.treeNode.childCount){let l=a.treeNode.child(a.childIndex);if(a.childIndex++,l&&!a.fieldChildren.has(l)){let c=Pr(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return n}function Pr(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return Oi(i,t)&&(n.text=i.text),n}function Oi(i,e){if(e){let n=Fi(e);if(n?.shouldIncludeText){let s=n.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return ki(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Di.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Ke(...i){let e={};for(let t of i)for(let[n,o]of Object.entries(t)){let a=[...e[n]||[]];for(let l of o)a.includes(l)||a.push(l);e[n]=a;}return e}var Di,Mi,Bi,Nr,Er=y(()=>{Ai();Di=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","string_fragment","number","true","false","null","undefined","import_specifier","export_specifier","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","yield","pass","continue","break","None","none","True","False","ellipsis","type","string_content"]);Mi={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Bi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]};Nr=Ke(Mi,Bi);});var Je,zi=y(()=>{at();En();In();On();Oe();Nt();si();li();pi();mi();ct();Ft();gi();pe();rr();xi();D();pt();Je=class extends oe{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;logCollector=new ze;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new At;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new jt(process.cwd()),this.parser=new $t(this.langRegistry),this.compressor=new Lt;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let o=n.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,n=false){this.logCollector=new ze,this.logCollector.start();let o="failed";try{let s=await this.getAccessKey();this.apiClient=new ot(this.config,s,t),await this.validateProject(),this.logCollector.log(`${te}Starting indexing procedure...
71
- `);let a=performance.now();if(t?this.logCollector.log(`${b} Skipping git branch validation`):await this.validateGitBranch(),t?this.logCollector.log(`${b} Skipping git status validation`):await this.validateGitStatus(),t?this.logCollector.log(`${b} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){this.logCollector.log(`${v} Discovering language build configurations...`);let R=0;for(let[,L]of this.buildConfigManagers.entries()){let Z=await L.initialize();R+=Z.length;}R>0&&this.logCollector.log(`${S} Found ${R} configuration file(s)`);}let l=await this.determineIndexScope(e),c=await this.git.getLatestCommitHash(),d=await this.git.getCommitTimestamp();if(l.upToDate){this.logCollector.log(`
72
- ${S} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${c.substring(0,8)}`),o="succeeded";return}let m=await this.apiClient.claimAstLock(this.config.projectId,this.config.branch,l.isIncremental,c,d);switch(m.remapped===!0&&(m.effectiveBranchName?this.logCollector.log(`${b} --dirty: server is indexing as default branch "${m.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.logCollector.log(`${b} --dirty: server reported a branch remap but did not include the effective branch name.`)),m.status){case "current":this.logCollector.log(`${S} Index already up to date for branch ${this.config.branch} at commit ${c?.substring(0,8)||"unknown"}`),o="succeeded";return;case "duplicate":this.logCollector.log("\u2713 Index for this commit is already in progress."),o="succeeded";return;case "superseded":this.logCollector.log("\u2713 A newer commit is already being indexed."),o="succeeded";return;case "queued":if(!m.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(m.queuedAttemptId,l.isIncremental,c),o="succeeded";return;default:break}let u=!1,g=()=>{u||this.logCollector.log(`${v} Uploading metadata, processing, and indexing...`);},f,h,x=new Promise((R,L)=>{f=R,h=L;}),w=new AbortController,_=this.createIndexPipeline(l.isIncremental,g,f),P=null;try{let[,R]=await Promise.all([this.uploadToAPI(_,l.isIncremental,c,m.attemptId).then(L=>(u=!0,L)).catch(L=>{throw w.abort(L),h(L),u=!0,L}),x.then(L=>{let Z=this.getEnrichmentEligibleLanguages(n,L);return Z?(m.attemptId&&this.apiClient.startEnrichment(m.attemptId,this.config.projectId,this.config.branch),this.runLspEnrichment(L,Z,this.parseSymbols,this.parseContent,w.signal).catch(ee=>(w.signal.aborted||this.logCollector.warn(`${b} Index enrichment failed: ${ee instanceof Error?ee.message:String(ee)}`,{code:"ENRICHMENT_FAILED"}),null))):null}).catch(()=>null)]);P=R;}catch(R){throw u=!0,R}if(P&&P.length>0)try{let ee=this.discoveredFiles.length,Re=Math.min(12e4+ee*1e3,9e5);if(this.logCollector.log(`${v} Waiting for server to finish syntax tree processing (${ee} files, timeout ${Math.round(Re/1e3)}s)...`),await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,c,Re)){this.logCollector.log(`${v} Uploading enrichment data (${P.length} files)...`);let Vr=Pn(P);await this.apiClient.uploadEnrichment(Vr,this.config.projectId,this.config.branch,c)?this.logCollector.log(`${S} Enrichment data uploaded to Constellation Service, index enhancement in progress`):this.logCollector.log(`${b} Enrichment upload skipped (index state changed)`);}else this.logCollector.log(`${b} AST processing did not complete in time, enrichment skipped`);}catch(R){this.logCollector.warn(`${b} Enrichment upload failed: ${R instanceof Error?R.message:String(R)}`,{code:"ENRICHMENT_FAILED"});}let k=(performance.now()-a)/1e3,j=Math.floor(k/60),K=(k%60).toFixed(3),Q=j>0?`${j}m ${K}s`:`${K}s`;this.logCollector.log(`
73
- ${S} Upload completed in ${Q}! Server indexing in progress.`),o="succeeded";}catch(s){if(s instanceof M)throw s;if(s instanceof he){this.logIndexingInProgress(s.branchName||this.config?.branch),o="succeeded";return}if(s instanceof T)throw this.logCollector.error(`
70
+ Approve?`,c=false;try{c=await this.prompt(l);}catch{c=false;}return c?(await this.trustStore.recordTrust(this.projectRoot,t,n),this.logger.log(`[LSP:${e}] Trusted custom LSP command '${t}' for this project.`),true):(this.logger.warn(`[LSP:${e}] User declined to trust LSP command '${t}'. Skipping enrichment for this language.`),false)}};});var Ea,Pa,St,Un=y(()=>{Y();$n();Me();Mn();ur();Ea={log:i=>console.log(i),warn:i=>console.warn(i),error:i=>console.error(i)},Pa=N.join(Ne.homedir(),".constellation","lsp-trust.json"),St=class{constructor(e,t,n){this.projectRoot=e;this.logger=t??Ea,this.policy=n??this.buildDefaultPolicy();}serversByKey=new Map;languageToServerKey=new Map;unavailableLanguages=new Set;unavailableServerKeys=new Set;nextId=1;logger;policy;buildDefaultPolicy(){return new vt({projectRoot:this.projectRoot,logger:this.logger,trustStore:new ve(Pa),prompt:async e=>{let{confirm:t}=await import('@inquirer/prompts');try{return await t({message:e,default:!1})}catch{return false}}})}async startServer(e,t){if(t===false||this.unavailableLanguages.has(e))return null;let n=this.languageToServerKey.get(e),o=n?this.serversByKey.get(n):void 0;if(o)return this.toConnection(o,e);let s=this.resolveCommand(e,t);if(!s)return this.unavailableLanguages.add(e),null;let{command:a,args:l}=s,c=this.getServerKey(a,l);if(this.unavailableServerKeys.has(c))return this.unavailableLanguages.add(e),null;let m=this.serversByKey.get(c);if(m)return m.languages.add(e),this.languageToServerKey.set(e,c),this.toConnection(m,e);if(!await this.policy.authorize(e,a,l))return this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c),null;try{let d=spawn(a,l,{stdio:["pipe","pipe","pipe"],cwd:this.projectRoot});await new Promise((x,_)=>{d.once("spawn",x),d.once("error",_);}),d.stderr?.on("data",x=>{let _=x.toString().trim();_.toLowerCase().includes("error")&&this.logger.warn(`[LSP:${e}] ${_}`);});let g=new yt(d.stdin,d.stdout,12e4),f=await g.sendRequest("initialize",{processId:process.pid,rootUri:pathToFileURL(this.projectRoot).href,capabilities:{textDocument:{hover:{contentFormat:["plaintext"]},references:{},callHierarchy:{},implementation:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0}}}},12e4);g.sendNotification("initialized",{});let h={key:c,language:e,languages:new Set([e]),process:d,client:g};return this.serversByKey.set(c,h),this.languageToServerKey.set(e,c),d.on("exit",x=>{let _=this.serversByKey.get(c);if(_){_.client.dispose(),this.serversByKey.delete(c);for(let[w,P]of this.languageToServerKey.entries())P===c&&this.languageToServerKey.delete(w);}x!==0&&x!==null&&this.logger.warn(`[LSP:${e}] Server exited unexpectedly with code ${x}`);}),this.toConnection(h,e)}catch(d){this.unavailableLanguages.add(e),this.unavailableServerKeys.add(c);let g=`[LSP:${e}] Failed to start: ${d instanceof Error?d.message:String(d)}`,f=d?.code;return f==="ENOENT"||f==="EACCES"?this.logger.warn(g):this.logger.error(g),null}}async shutdown(e){let t=this.languageToServerKey.get(e);if(!t)return;this.languageToServerKey.delete(e);let n=this.serversByKey.get(t);n&&(n.languages.delete(e),!(n.languages.size>0)&&await this.shutdownByKey(t));}async shutdownByKey(e){let t=this.serversByKey.get(e);if(t)try{await t.client.sendRequest("shutdown",null,5e3),t.client.sendNotification("exit",null),await new Promise(n=>{let o=setTimeout(()=>{t.process.kill("SIGKILL"),n();},3e3);t.process.on("exit",()=>{clearTimeout(o),n();});});}catch(n){this.logger.warn(`[LSP:${t.language}] Graceful shutdown failed, force killing: ${n instanceof Error?n.message:String(n)}`),t.process.kill("SIGKILL");}finally{t.client.dispose(),this.serversByKey.delete(e);for(let[n,o]of this.languageToServerKey.entries())o===e&&this.languageToServerKey.delete(n);}}async shutdownAll(){let e=[...this.serversByKey.keys()];await Promise.allSettled(e.map(t=>this.shutdownByKey(t)));}destroyAll(){for(let e of this.serversByKey.values()){try{e.process.kill("SIGKILL");}catch{}try{e.client.dispose();}catch{}}this.serversByKey.clear(),this.languageToServerKey.clear();}resolveCommand(e,t){if(t?.command)return {command:t.command,args:t.args||[]};let n=oe.get(e);if(!n)return null;let o=N.join(bt,n.command);return existsSync(o)?{command:o,args:n.args}:ht(n.command)?{command:n.command,args:n.args}:null}getServerKey(e,t){return `${e}\0${t.join("\0")}`}toConnection(e,t){let n=`lsp-${t}-${this.nextId++}`;return {language:t,process:e.process,id:n,sendRequest:(o,s,a)=>e.client.sendRequest(o,s,a),sendNotification:(o,s)=>e.client.sendNotification(o,s)}}};});var se,Ct=y(()=>{se=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var Se,mr=y(()=>{D();Se=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${b} Failed to discover config files:`,e),[]}}async getConfigForFile(e){if(this.parseCache.has(e))return this.parseCache.get(e);if(!this.isPathResolutionEnabled)return this.parseCache.set(e,null),null;try{let t=e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".d.ts"),n=e.endsWith(".js")||e.endsWith(".jsx")||e.endsWith(".mjs");if(t&&this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let s=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,s),s}throw o}if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let o=t instanceof Error?t.message:String(t);console.warn(`${b} Failed to parse ${n}: ${o}`),console.warn(`${b} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${b} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var _t,zn=y(()=>{ue();_t=class{constructor(e,t){this.projectRoot=e;this.tsconfigResult=t;}workspacePackages={};initialized=false;async initialize(){if(this.initialized)return;this.initialized=true;let e={},t=await this.loadFromPackageJsonWorkspaces();Object.assign(e,t);let n=await this.loadFromTsConfig();Object.assign(e,n),this.workspacePackages=e;}async resolve(e){if(await this.initialize(),this.workspacePackages[e])return this.toProjectRelative(this.workspacePackages[e]);for(let[t,n]of Object.entries(this.workspacePackages))if(e.startsWith(t+"/")){let o=e.substring(t.length+1),s=await this.resolveSubPath(n,o);if(s)return this.toProjectRelative(s)}return null}async isWorkspacePackage(e){return await this.resolve(e)!==null}async loadFromTsConfig(){let e={};if(!this.tsconfigResult?.tsconfig?.compilerOptions?.paths)return e;let t=this.tsconfigResult.tsconfig.compilerOptions.paths,n=this.tsconfigResult.tsconfigFile?N.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,s]of Object.entries(t)){if(o.includes("*")||!Array.isArray(s))continue;let a=s[0];if(!a)continue;let l=N.resolve(n,a),c=await this.findEntryPoint(l);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=N.join(this.projectRoot,"package.json"),n=await B.readFile(t,"utf-8"),s=JSON.parse(n).workspaces;if(!s)return e;let a=Array.isArray(s)?s:s.packages||[];for(let l of a){let c=await this.findWorkspaceDirs(l);for(let m of c){let u=await this.loadWorkspacePackage(m);u&&Object.assign(e,u);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),o=N.join(this.projectRoot,n);try{let s=await B.readdir(o,{withFileTypes:!0});for(let a of s)a.isDirectory()&&t.push(N.join(o,a.name));}catch{}}else {let n=N.join(this.projectRoot,e);try{(await B.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=N.join(e,"package.json"),n=await B.readFile(t,"utf-8"),o=JSON.parse(n),s=o.name;if(!s)return null;let a=await this.findPackageEntryPoint(e,o);return a?{[s]:a}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return N.join(e,o);if(typeof o=="object"){let s=o["."]||o["./index"];if(typeof s=="string")return N.join(e,s);if(typeof s=="object"){let a=s.import||s.default||s.require;if(a)return N.join(e,a)}}}if(t.main)return N.join(e,t.main);let n=["src/index.ts","src/index.tsx","src/index.js","src/index.jsx","index.ts","index.tsx","index.js","index.jsx"];for(let o of n){let s=N.join(e,o);try{if((await B.stat(s)).isFile())return s}catch{}}return null}async findEntryPoint(e){let t=["index.ts","index.tsx","index.js","index.jsx","index.d.ts"];for(let n of t){let o=N.join(e,n);try{if((await B.stat(o)).isFile())return o}catch{}}try{if((await B.stat(e)).isFile())return e}catch{}return null}async resolveSubPath(e,t){let n=e.endsWith("index.ts")||e.endsWith("index.tsx")||e.endsWith("index.js")||e.endsWith("index.jsx")?N.dirname(e):N.dirname(e),o=[N.join(n,t+".ts"),N.join(n,t+".tsx"),N.join(n,t+".js"),N.join(n,t+".jsx"),N.join(n,t+".d.ts"),N.join(n,t,"index.ts"),N.join(n,t,"index.tsx"),N.join(n,t,"index.js"),N.join(n,t,"index.jsx")];for(let s of o)try{if((await B.stat(s)).isFile())return s}catch{}return null}toProjectRelative(e){let t=O(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var Ce,gr=y(()=>{ue();zn();Ce=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=N.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new _t(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),s=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:s?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=N.dirname(t.tsconfigFile);let a=t.tsconfig?.compilerOptions;a&&(a.baseUrl&&(this.baseUrl=N.resolve(this.tsconfigDir,a.baseUrl)),a.paths&&typeof a.paths=="object"&&(this.paths=a.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=N.resolve(this.sourceDir,e),o=await this.findFileWithExtensions(n);return o?this.toProjectRelative(o):e}if(e.startsWith("#")){let n=await this.resolveWithPackageImports(e);return n?this.toProjectRelative(n):e}let t=await this.workspaceResolver.resolve(e);if(t)return t;if(!e.startsWith("@")&&!e.startsWith("~")&&(!e.includes("/")||!this.baseUrl))return e;if(Object.keys(this.paths).length>0){let n=await this.resolveWithPaths(e);if(n)return this.toProjectRelative(n)}if(this.baseUrl){let n=await this.resolveWithBaseUrl(e);if(n)return this.toProjectRelative(n)}return e}toProjectRelative(e){let t=O(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}async resolveWithPaths(e){for(let[t,n]of Object.entries(this.paths)){let o=this.matchPathPattern(e,t);if(o!==null)for(let s of n){let a=await this.trySubstitution(e,t,s,o);if(a)return a}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,o]=t.split("*");if(!e.startsWith(n)||o&&!e.endsWith(o))return null;let s=n.length,a=o?e.length-o.length:e.length;return e.substring(s,a)}async trySubstitution(e,t,n,o){let s=n.replaceAll("*",o),a=N.resolve(this.tsconfigDir,s);return await this.findFileWithExtensions(a)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=N.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(a=>e.endsWith(a));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],o=n.some(a=>e.endsWith(a)),s=e;if(o&&!t){for(let a of n)if(e.endsWith(a)){s=e.slice(0,-a.length);break}}if(!t)for(let a of this.extensions){let l=s+a;if(await this.fileExists(l))return await this.resolveSymlink(l)}for(let a of this.extensions){let l=N.join(s,`index${a}`);if(await this.fileExists(l))return await this.resolveSymlink(l)}return null}async fileExists(e){try{return (await B.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await B.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=N.join(t,"package.json");try{if((await B.stat(n)).isFile())return n}catch{}let o=N.dirname(t);if(o===t)break;t=o;}return null}async loadPackageImports(){if(this.packageJsonDir!==null)return;let e=await this.findPackageJson(this.sourceDir);if(!e){this.packageJsonDir="";return}try{let t=await B.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=N.dirname(e),n.imports&&typeof n.imports=="object"&&(this.packageImports=n.imports);}catch{this.packageJsonDir="";}}async resolveWithPackageImports(e){if(await this.loadPackageImports(),!this.packageJsonDir||Object.keys(this.packageImports).length===0)return null;for(let[t,n]of Object.entries(this.packageImports)){let o=this.matchPathPattern(e,t);if(o!==null){if(typeof n=="string"){let s=await this.tryPackageImportSubstitution(n,o);if(s)return s}if(Array.isArray(n)){for(let s of n)if(typeof s=="string"){let a=await this.tryPackageImportSubstitution(s,o);if(a)return a}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),o=N.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};});var wt,Wn=y(()=>{Ct();mr();gr();wt=class extends se{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new Se(e,t)}getImportResolver(e,t){return new Ce(e,t)}};});var xt,Hn=y(()=>{Ct();mr();gr();xt=class extends se{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new Se(e,t)}getImportResolver(e,t){return new Ce(e,t)}};});async function ae(i,e,t,n,o,s=[]){let a=await t.resolve(i),l=Kn(i,a),c=o(i,a,l),m=l?void 0:mt(a);n[e.toString()]={source:i,resolvedPath:m,isExternal:l,importType:c,specifiers:s};}function Kn(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var fr,Be=y(()=>{ue();fr=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function Ta(i,e,t,n){let o=i.childForFieldName("name");if(!o)return;let s,a;if(o.type==="aliased_import"){let l=o.childForFieldName("name"),c=o.childForFieldName("alias");s=l?l.text:o.text,a={local:c?c.text:s.split(".")[0],original:s,isDefault:false,isNamespace:false};}else s=o.text,a={local:s.split(".")[0],original:s,isDefault:false,isNamespace:false};await ae(s,i.startPosition.row,e,t,n,[a]);}function $a(i,e){if(!e)return [];let t=[],n=i.childForFieldName("name");if(n){if(n.type==="aliased_import"){let s=n.childForFieldName("name"),a=n.childForFieldName("alias");s&&t.push({local:a?a.text:s.text,original:s.text,isDefault:false,isNamespace:false});}else t.push({local:n.text,original:n.text,isDefault:false,isNamespace:false});return t}let o=false;for(let s=0;s<i.childCount;s++){let a=i.child(s);if(a){if(a.type==="import"){o=true;continue}if(o){if(a.type==="dotted_name"||a.type==="identifier")t.push({local:a.text,original:a.text,isDefault:false,isNamespace:false});else if(a.type==="aliased_import"){let l=a.childForFieldName("name"),c=a.childForFieldName("alias");l&&t.push({local:c?c.text:l.text,original:l.text,isDefault:false,isNamespace:false});}}}}return t}async function ja(i,e,t,n){let o,s=i.childForFieldName("module_name");if(s)o=s.text;else {let l="";for(let c=0;c<i.childCount;c++){let m=i.child(c);if(m){if(m.type==="relative_import"){l=m.text;break}(m.type==="."||m.type==="import_prefix")&&(l+=m.text);}}o=l||".";}let a=$a(i,!!s);await ae(o,i.startPosition.row,e,t,n,a);}async function La(i,e,t,n){await ae("__future__",i.startPosition.row,e,t,n,[]);}function hr(){return {language:"python",handlers:new Map([["import_statement",Ta],["import_from_statement",ja],["future_import_statement",La]]),classifyImportType:Ra}}var Ra,Et=y(()=>{Ae();Be();Ae();Ra=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return Le.has(n)?"builtin":"alias"};});var Pt,Jn=y(()=>{Et();Pt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=N.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(Le.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),o=await this.tryResolveFile(N.resolve(this.projectRoot,n));return o?N.relative(this.projectRoot,o).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),o=t<=1?"":"../".repeat(t-1),s=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",a=N.resolve(this.sourceDir,s),l=await this.tryResolveFile(a);return l?N.relative(this.projectRoot,l).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,N.join(e,"__init__.py"),N.join(e,"__init__.pyi")];for(let n of t)try{return await It.promises.access(n,It.constants.F_OK),n}catch{continue}return null}};});var Nt,Vn=y(()=>{Ct();Jn();Nt=class extends se{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Pt(e,process.cwd())}};});function Ge(i){return Da[i]??i.charAt(0).toUpperCase()+i.slice(1)}var Da,Ue,Rt,Tt=y(()=>{Wn();Hn();Vn();Da={bash:"Bash",c:"C","c-sharp":"C#",cpp:"C++",go:"Go",java:"Java",javascript:"JavaScript",json:"JSON",php:"PHP",python:"Python",ruby:"Ruby",typescript:"TypeScript"};Ue={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},Rt=class{constructor(e){this.config=e;this.registerPlugin(new wt),this.registerPlugin(new xt),this.registerPlugin(new Nt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Fa,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Ue.javascript};typescript={language:()=>ka.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Ue.typescript};python={language:()=>Aa,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Ue.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function _e(i,e,t=32){let n=i.parent,o=0;for(;n!==null&&o<t;){if(e(n))return n;n=n.parent,o++;}return null}var $t,yr=y(()=>{$t=Object.freeze(new Set(["program","statement_block","function_declaration","function_expression","generator_function_declaration","generator_function","arrow_function","method_definition","class_body"]));});function br(i,e){if(i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"||i.type==="jsx_closing_element"){let t=i.childForFieldName("name");t!==null&&Oa(t,e);}for(let t of i.namedChildren)t&&br(t,e);}function Oa(i,e){if(i.type==="identifier"||i.type==="type_identifier"){e.set(me(i.startPosition.row,i.startPosition.column),"call");return}if(i.type==="member_expression"||i.type==="nested_identifier"){let t=i.childForFieldName("property");t!==null&&e.set(me(t.startPosition.row,t.startPosition.column),"call");}}var qn=y(()=>{ze();});function we(i,e){i.rootNode&&(Xn(i.rootNode,e),br(i.rootNode,e));}function Xn(i,e){if(Ma.has(i.type)){let t=Ba(i);t!==null&&e.set(me(i.startPosition.row,i.startPosition.column),t);}for(let t of i.namedChildren)t&&Xn(t,e);}function Ba(i){if(Ga(i))return "declaration";if(Qa(i))return "read";if(Ya(i))return "type";let e=_e(i,t=>t.type==="decorator");return e!==null&&Ha(i,e)?"call":Wa(i)?"instantiate":za(i)?"call":Ka(i)||Ja(i)||Va(i)||sl(i)||ol(i)?"write":Za(i)?"import-use":"read"}function Ga(i){let e=i.parent;return e===null?false:!!(Ua.has(e.type)&&(e.childForFieldName("name")===i||e.childForFieldName("property")===i)||(e.type==="required_parameter"||e.type==="optional_parameter")&&e.childForFieldName("pattern")===i||e.type==="import_specifier"&&(e.childForFieldName("name")===i||e.childForFieldName("alias")===i)||e.type==="namespace_import"||e.type==="import_clause"&&e.namedChild(0)===i&&i.type==="identifier"||e.type==="catch_clause"&&e.childForFieldName("parameter")===i||e.type==="enum_body")}function za(i){let e=i.parent;if(e===null)return false;if(e.type==="call_expression"&&e.childForFieldName("function")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="call_expression"&&t.childForFieldName("function")===e)return true}return false}function Wa(i){let e=i.parent;if(e===null)return false;if(e.type==="new_expression"&&e.childForFieldName("constructor")===i)return true;if(e.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t!==null&&t.type==="new_expression"&&t.childForFieldName("constructor")===e)return true}return false}function Ha(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call_expression"){let n=t.childForFieldName("function");if(n===i||n?.type==="member_expression"&&n.childForFieldName("property")===i)return true}return t.type==="member_expression"&&t.childForFieldName("property")===i}function Ka(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="unary_expression")return t.child(0)?.type==="delete";if(t.type==="member_expression"&&t.childForFieldName("object")===e||$t.has(t.type))return false;e=t;}return false}function Ja(i){let e=i.parent;if(e?.type==="update_expression"&&e.childForFieldName("argument")===i)return true;if(e?.type==="member_expression"&&e.childForFieldName("property")===i){let t=e.parent;if(t?.type==="update_expression"&&t.childForFieldName("argument")===e)return true}return false}function Va(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="assignment_expression"||t.type==="augmented_assignment_expression")&&t.childForFieldName("left")===e)return true;if(t.type==="member_expression"&&t.childForFieldName("object")===e||t.type==="subscript_expression"&&t.childForFieldName("object")!==e||$t.has(t.type))return false;e=t;}return false}function Ya(i){let e=i.parent,t=i;for(;e!==null;){if(e.type==="as_expression"||e.type==="satisfies_expression"){let n=e.namedChild(1);return n===null?false:n===t||Xa(n,i)}if(qa.has(e.type))return true;if($t.has(e.type))return false;t=e,e=e.parent;}return false}function Xa(i,e){let t=e;for(;t!==null;){if(t===i)return true;t=t.parent;}return false}function Qa(i){return _e(i,t=>t.type==="type_query")!==null}function Za(i){let e=i.parent;if(e?.type!=="member_expression"||e.childForFieldName("object")!==i)return false;let t=i.text,n=nl(i);return il(n,t)?!tl(i,t):false}function tl(i,e){let t=i.parent;for(;t!==null;){if(el.has(t.type)&&rl(t,e))return true;t=t.parent;}return false}function rl(i,e){for(let t of i.namedChildren){if(t.type==="lexical_declaration"||t.type==="variable_declaration")for(let n of t.namedChildren){if(n.type!=="variable_declarator")continue;if(n.childForFieldName("name")?.text===e)return true}if(t.type==="formal_parameters")for(let n of t.namedChildren){if(n.type!=="required_parameter"&&n.type!=="optional_parameter")continue;let o=n.childForFieldName("pattern");if(o?.type==="identifier"&&o.text===e)return true}}return false}function nl(i){let e=i;for(;e.parent!==null;)e=e.parent;return e}function il(i,e){for(let t of i.descendantsOfType("namespace_import")){let n=t.namedChild(0);if(n!==null&&n.text===e)return true}return false}function ol(i){let e=i.parent;return e?.type==="for_in_statement"&&e.childForFieldName("left")===i}function sl(i){let e=i.parent;if(e===null||!Yn.has(e.type)||e.type==="pair_pattern"&&e.childForFieldName("key")===i||(e.type==="object_assignment_pattern"||e.type==="assignment_pattern")&&e.namedChild(0)!==i)return false;let t=e;for(;t!==null;){let n=t.parent;if(n===null)return false;if(n.type==="variable_declarator"&&n.childForFieldName("name")===t||(n.type==="assignment_expression"||n.type==="augmented_assignment_expression")&&n.childForFieldName("left")===t||(n.type==="required_parameter"||n.type==="optional_parameter")&&n.childForFieldName("pattern")===t||n.type==="formal_parameters"||n.type==="for_in_statement"&&n.childForFieldName("left")===t)return true;if(!Yn.has(n.type))return false;t=n;}return false}var Ma,Ua,qa,el,Yn,jt=y(()=>{ze();yr();qn();Ma=Object.freeze(new Set(["identifier","type_identifier","property_identifier","private_property_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]));Ua=Object.freeze(new Set(["variable_declarator","function_declaration","function_signature","generator_function_declaration","class_declaration","abstract_class_declaration","interface_declaration","type_alias_declaration","enum_declaration","enum_assignment","method_signature","abstract_method_signature","method_definition","public_field_definition","field_definition","property_signature"]));qa=Object.freeze(new Set(["type_annotation","type_arguments","type_parameter","type_parameters","type_alias_declaration","interface_declaration","generic_type","type_predicate","type_query","conditional_type","union_type","intersection_type","tuple_type","mapped_type_clause","implements_clause","extends_type_clause"]));el=Object.freeze(new Set(["statement_block","function_declaration","function_expression","arrow_function","method_definition","generator_function","generator_function_declaration","for_statement","for_in_statement"]));Yn=Object.freeze(new Set(["object_pattern","array_pattern","pair_pattern","rest_pattern","object_assignment_pattern","assignment_pattern"]));});function Qn(i,e){we(i,e);}var Zn=y(()=>{jt();});function ei(i,e){we(i,e);}var ti=y(()=>{jt();});function ri(i,e){if(!i.rootNode)return;let t=Il(i.rootNode);ni(i.rootNode,e,t);}function ni(i,e,t){if(al.has(i.type)){let n=ll(i,t);n!==null&&e.set(me(i.startPosition.row,i.startPosition.column),n);}for(let n of i.namedChildren)n&&ni(n,e,t);}function ll(i,e){if(cl(i))return "declaration";if(dl(i))return "read";if(ul(i))return "declaration";if(ml(i))return "type";let t=_e(i,n=>n.type==="decorator");return t!==null&&gl(i,t)||fl(i)?"call":hl(i)||yl(i)||bl(i)||Sl(i)||_l(i)?"write":wl(i,e)?"import-use":"read"}function cl(i){let e=i.parent;if(e===null)return false;if((e.type==="function_definition"||e.type==="class_definition")&&e.childForFieldName("name")===i||e.type==="parameters"||e.type==="lambda_parameters"||(e.type==="typed_parameter"||e.type==="typed_default_parameter"||e.type==="default_parameter")&&e.namedChild(0)===i)return true;if(e.type==="list_splat_pattern"||e.type==="dictionary_splat_pattern"){let t=e.parent;if(t?.type==="parameters"||t?.type==="lambda_parameters")return true}return !!(e.type==="as_pattern_target"||pl(i))}function pl(i){let e=i.parent;if(e?.type!=="type")return false;let t=e.parent;return t?.type!=="type_alias_statement"?false:t.namedChild(0)===e}function ul(i){let e=i.parent;for(;e!==null;){if(e.type==="import_statement"||e.type==="import_from_statement")return true;if(vr.has(e.type))return false;e=e.parent;}return false}function dl(i){let e=i.parent;return e?.type==="global_statement"||e?.type==="nonlocal_statement"}function ml(i){return _e(i,t=>t.type==="type")!==null}function gl(i,e){let t=e.namedChild(0);if(t===null)return false;if(t===i)return true;if(t.type==="call"){let n=t.childForFieldName("function");if(n===i||n?.type==="attribute"&&n.childForFieldName("attribute")===i)return true}return t.type==="attribute"&&t.childForFieldName("attribute")===i}function fl(i){let e=i.parent;if(e?.type==="call"&&e.childForFieldName("function")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="call"&&t.childForFieldName("function")===e)return true}return false}function hl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="delete_statement")return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||vr.has(t.type))return false;e=t;}return false}function yl(i){let e=i.parent;if(e?.type==="augmented_assignment"&&e.childForFieldName("left")===i)return true;if(e?.type==="attribute"&&e.childForFieldName("attribute")===i){let t=e.parent;if(t?.type==="augmented_assignment"&&t.childForFieldName("left")===e)return true}return false}function bl(i){let e=i.parent;return e?.type==="named_expression"&&e.childForFieldName("name")===i}function Sl(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if(t.type==="assignment"&&t.childForFieldName("left")===e)return true;if(t.type==="attribute"&&t.childForFieldName("object")===e||t.type==="subscript"&&t.childForFieldName("value")!==e)return false;if(vl.has(t.type)){e=t;continue}if(vr.has(t.type))return false;e=t;}return false}function _l(i){let e=i;for(;e!==null;){let t=e.parent;if(t===null)return false;if((t.type==="for_statement"||t.type==="for_in_clause")&&t.childForFieldName("left")===e)return true;if(!Cl.has(t.type))return false;e=t;}return false}function wl(i,e){let t=i.parent;if(t?.type!=="attribute"||t.childForFieldName("object")!==i)return false;let n=i.text;return e.has(n)?!El(i,n):false}function El(i,e){let t=i.parent;for(;t!==null;){if(xl.has(t.type)&&Pl(t,e))return true;t=t.parent;}return false}function Pl(i,e){for(let t of i.namedChildren){if(t.type==="expression_statement"){let n=t.namedChild(0);if(n?.type==="assignment"){let o=n.childForFieldName("left");if(o?.type==="identifier"&&o.text===e)return true}}if(t.type==="parameters"){for(let n of t.namedChildren)if(n.type==="identifier"&&n.text===e||(n.type==="typed_parameter"||n.type==="typed_default_parameter"||n.type==="default_parameter")&&n.namedChild(0)?.type==="identifier"&&n.namedChild(0)?.text===e)return true}}return false}function Il(i){let e=new Set;for(let t of i.descendantsOfType("import_statement"))for(let n of t.namedChildren)if(n.type==="dotted_name"&&e.add(n.text),n.type==="aliased_import"){let o=n.childForFieldName("alias");o&&e.add(o.text);}return e}var al,vr,vl,Cl,xl,ii=y(()=>{ze();yr();al=Object.freeze(new Set(["identifier"])),vr=Object.freeze(new Set(["module","block","function_definition","class_definition","lambda"]));vl=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern","list_splat_pattern"]));Cl=Object.freeze(new Set(["pattern_list","tuple_pattern","list_pattern"]));xl=Object.freeze(new Set(["block","function_definition","class_definition","lambda"]));});function si(i,e){let t=new Map;switch(e){case "typescript":we(i,t);break;case "tsx":Qn(i,t);break;case "javascript":ei(i,t);break;case "python":ri(i,t);break}return t}function me(i,e){return `${i}:${e}`}var oi,ze=y(()=>{jt();Zn();ti();ii();oi=Object.freeze(new Set(["typescript","javascript","python"]));});function Tl(i,e){return oi.has(i)?i==="typescript"?e.toLowerCase().endsWith(".tsx")?"tsx":"typescript":i:null}function $l(i){let e=[];for(let[t,n]of i.entries()){let o=t.indexOf(":");if(o<0)continue;let s=Number(t.slice(0,o)),a=Number(t.slice(o+1));!Number.isFinite(s)||!Number.isFinite(a)||e.push({line:s,column:a,referenceType:n});}return e.sort((t,n)=>t.line-n.line||t.column-n.column),e}var Lt,ci=y(()=>{ze();Y();Lt=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let o=await n();if(!o)throw new Error(`Failed to load language: ${t}`);t==="typescript"&&e.toLowerCase().endsWith(".tsx")&&(o=ka.tsx);let s=new Nl;s.setLanguage(o);let a=await C.getFileStats(e),l=10*1024*1024,c,m;if(a.size<=l){let f=await C.readFile(e);m=f;let h={bufferSize:1024*1024};c=s.parse(f,void 0,h);}else c=await this.parseWithStream(s,e,a.size);let u=Tl(t,e),d=u===null?[]:$l(si(c,u));return {tree:c,classificationMap:{filePath:e,entries:d},content:m}}async parseWithStream(e,t,n){let o=null;try{o=await B.open(t,"r");let s=o.fd,a=64*1024,l=Buffer.alloc(a),c=0;return e.parse(u=>{if(n>50*1024*1024){let g=Math.round(u/n*100);g>c+10&&(console.log(` Parsing large file: ${g}%...`),c=g);}let d=It.readSync(s,l,0,a,u);return d===0?null:l.subarray(0,d).toString("utf-8")})}catch(s){if(o)try{await o.close();}catch(a){console.error(`Warning: Failed to close file handle for ${t}:`,a);}throw s}finally{if(o)try{await o.close();}catch{}}}};});var Ft,ui=y(()=>{Y();ue();D();Ft=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=pi();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(s=>!t.ignores(s.relativePath)&&this.matchesLanguageExtension(s,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=pi().add(t.exclude));let s=await B__default.realpath(this.rootPath);for(let a of e)try{let l=N__default.isAbsolute(a)?a:N__default.join(this.rootPath,a),c=await B__default.lstat(l);if(c.isSymbolicLink()){let m=await B__default.realpath(l);if(!m.startsWith(s+N__default.sep)&&m!==s){console.warn(`${b} Skipping symlink pointing outside project: ${a} -> ${m}`);continue}let u=await B__default.stat(l);if(!u.isFile())continue;let d=O(this.rootPath,l);if(o&&o.ignores(d))continue;let g=this.detectLanguage(d,t.languages);if(!g)continue;n.push({path:l,relativePath:d,language:g,size:u.size});}else if(c.isFile()){let m=O(this.rootPath,l);if(o&&o.ignores(m))continue;let u=this.detectLanguage(m,t.languages);if(!u)continue;n.push({path:l,relativePath:m,language:u,size:c.size});}}catch{console.warn(`${b} Skipping inaccessible file: ${a}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let s=N__default.join(o,".gitignore");await C.fileIsReadable(s)&&n.unshift(s);let a=N__default.dirname(o);if(a===o)break;o=a;let l=N__default.join(o,".git");if(await C.directoryExists(l)){let c=N__default.join(o,".gitignore");await C.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let s of n)try{let a=await C.readFile(s);e.add(a);}catch{console.warn(`${b} Failed to load .gitignore: ${s}`);}e.add(".git");}async walkDirectory(e,t,n,o){let s=[],a=t||e,l=n||await B__default.realpath(this.rootPath),c=o||new Set([l]);try{let m=await B__default.readdir(e,{withFileTypes:!0});for(let u of m){let d=N__default.join(e,u.name),g=O(a,d);if(u.isDirectory()){if(u.name.startsWith("."))continue;let f=await this.walkDirectory(d,a,l,c);s.push(...f);}else if(u.isFile()){let f=await B__default.stat(d);s.push({path:d,relativePath:g,language:"",size:f.size});}else if(u.isSymbolicLink())try{let f=await B__default.realpath(d);if(!f.startsWith(l+N__default.sep)&&f!==l){console.warn(`${b} Skipping symlink pointing outside project: ${d} -> ${f}`);continue}let h=await B__default.stat(d);if(h.isDirectory()){if(u.name.startsWith(".")||c.has(f))continue;c.add(f);let x=await this.walkDirectory(d,a,l,c);s.push(...x);}else h.isFile()&&s.push({path:d,relativePath:g,language:"",size:h.size});}catch{console.warn(`${b} Skipping invalid symlink: ${d}`);}}}catch(m){console.error(`${I} Error walking directory ${e}:`,m);}return s}matchesLanguageExtension(e,t){let n=N__default.extname(e.path).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=N__default.extname(e).toLowerCase();for(let[o,s]of Object.entries(t))if(s.fileExtensions.includes(n))return o;return null}};});var jl,Ll,Fl,di,mi=y(()=>{Ae();jl=z.object({local:z.string(),original:z.string().optional(),isDefault:z.boolean(),isNamespace:z.boolean()}),Ll=z.object({source:z.string().min(1,"Import source cannot be empty"),resolvedPath:z.string().optional(),isExternal:z.boolean(),importType:z.enum(["relative","workspace","alias","external","builtin"]),specifiers:z.array(jl).optional()}),Fl=z.record(z.string(),Ll),di=z.object({file:z.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z.string().datetime({message:"Invalid ISO timestamp"}),ast:z.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Fl.optional(),classificationMap:Zt.optional()});});var kl,At,hi=y(()=>{kl=promisify(Sr__default.gunzip),At=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=Sr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(e);return await pipeline(s,n),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=Sr__default.createGzip();n.on("data",a=>t.push(a));let o=new Promise((a,l)=>{n.on("end",a),n.on("error",l);}),s=Readable.from(this.serializeASTChunks(e));return await pipeline(s,n),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await kl(t);return JSON.parse(n.toString("utf-8"))}};});function bi(i){let n=i>=5e4?27e5:i>=1e4?18e5:9e5,o=process.env.CONSTELLATION_AST_WAIT_MAX_MS,s=n;if(o!==void 0&&o!==""){let a=Number(o);Number.isFinite(a)&&Number.isInteger(a)&&a>0?s=a:yi||(console.warn(`[constellation] Ignoring invalid CONSTELLATION_AST_WAIT_MAX_MS=${o}; using default tier cap.`),yi=true);}return Math.min(12e4+i*1e3,s)}var yi,vi=y(()=>{yi=false;});var Cr,kt=y(()=>{Cr=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED","ENRICHMENT_FAILED"]);});function _r(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var We,Si=y(()=>{kt();We=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:p.unstyle(e.map(_r).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:p.unstyle(e.map(_r).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:p.unstyle(e.map(_r).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!Cr.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!Cr.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:p.unstyle(t),timestamp:new Date().toISOString(),code:n});let o=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?o.call(console,t):console[e==="info"?"log":e](t);}};});function xe(i,e){let t=e??i;return {line:t.startPosition.row+1,column:t.startPosition.column}}function Ee(i){return i?i.text:null}function wi(){return {language:"javascript",handlers:new Map(_i)}}function xi(){return {language:"typescript",handlers:new Map([..._i,["interface_declaration",Ml],["public_field_definition",Ci],["property_signature",Ci]])}}var Dl,Ol,Ml,Bl,Ci,Ul,_i,Ei=y(()=>{Dl=(i,e)=>{let t=i.childForFieldName("name"),n=Ee(t);n&&e.symbols.push({name:n,kind:"function",...xe(i,t)});},Ol=(i,e)=>{let t=i.childForFieldName("name"),n=Ee(t);if(n)return e.symbols.push({name:n,kind:"class",...xe(i,t)}),{...e,enclosingType:n}},Ml=(i,e)=>{let t=i.childForFieldName("name"),n=Ee(t);if(n)return e.symbols.push({name:n,kind:"interface",...xe(i,t)}),{...e,enclosingType:n}},Bl=(i,e)=>{let t=i.childForFieldName("name"),n=Ee(t);n&&e.symbols.push({name:n,kind:"method",...xe(i,t)});},Ci=(i,e)=>{let t=i.childForFieldName("name"),n=Ee(t);n&&e.symbols.push({name:n,kind:"property",...xe(i,t)});},Ul=(i,e)=>{let t=i.childForFieldName("name"),n=Ee(t);if(!n)return;let o=i.childForFieldName("value"),s=o?.type==="arrow_function"||o?.type==="function"||o?.type==="function_expression";e.symbols.push({name:n,kind:s?"function":"variable",...xe(i,t)});},_i=[["function_declaration",Dl],["class_declaration",Ol],["method_definition",Bl],["variable_declarator",Ul]];});function wr(i){return {line:i.startPosition.row+1,column:i.startPosition.column}}function Pi(){return {language:"python",handlers:new Map([["function_definition",Gl],["class_definition",zl],["assignment",Wl]])}}var Gl,zl,Wl,Ii=y(()=>{Gl=(i,e)=>{let t=i.childForFieldName("name");if(!t)return;let n=e.enclosingType?"method":"function";e.symbols.push({name:t.text,kind:n,...wr(t)});},zl=(i,e)=>{let t=i.childForFieldName("name");if(t)return e.symbols.push({name:t.text,kind:"class",...wr(t)}),{...e,enclosingType:t.text}},Wl=(i,e)=>{let t=i.childForFieldName("left");if(!t||t.type!=="identifier")return;let n=e.enclosingType?"property":"variable";e.symbols.push({name:t.text,kind:n,...wr(t)});};});var Ni,Ri=y(()=>{Ei();Ii();Ni=[wi(),xi(),Pi()];});var Ot,Ti=y(()=>{Ri();Ot=class{languageHandlers;constructor(e){this.languageHandlers=new Map;for(let t of e??Ni)this.languageHandlers.set(t.language,t.handlers);}extract(e,t){let n=this.languageHandlers.get(t);if(!n)return [];let o={symbols:[]};return this.walk(e.rootNode,o,n),o.symbols}walk(e,t,n){let s=n.get(e.type)?.(e,t)??t;for(let a=0;a<e.childCount;a++){let l=e.child(a);l&&this.walk(l,s,n);}}};});function Hl(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n){if(n.type==="identifier")e.push({local:n.text,original:"default",isDefault:true,isNamespace:false});else if(n.type==="namespace_import"){let o;for(let s=0;s<n.childCount;s++){let a=n.child(s);if(a?.type==="identifier"){o=a.text;break}}o!==void 0&&e.push({local:o,original:void 0,isDefault:false,isNamespace:true});}else if(n.type==="named_imports")for(let o=0;o<n.childCount;o++){let s=n.child(o);if(!s||s.type!=="import_specifier")continue;let a=s.childForFieldName("name"),l=s.childForFieldName("alias");if(!a)continue;let c=a.text,m=l?l.text:c,u=c==="default";e.push({local:m,original:c,isDefault:u,isNamespace:false});}}}return e}async function Kl(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,""),l=i.childForFieldName("import_clause"),c=l?Hl(l):[];await ae(a,s,e,t,n,c);}async function Jl(i,e,t,n){let o=i.childForFieldName("source");if(!o)return;let s=o.startPosition.row,a=o.text.replace(/['"]/g,"");await ae(a,s,e,t,n,[]);}function Mt(){return {language:"javascript",handlers:new Map([["import_statement",Kl],["export_statement",Jl]])}}function xr(){return {...Mt(),language:"typescript"}}var Er=y(()=>{Be();});var $i,ji=y(()=>{Er();Et();Be();Er();Et();$i=[Mt(),xr(),hr()];});var Li={};Xr(Li,{ImportExtractor:()=>Pr});var Pr,Fi=y(()=>{ji();Be();Pr=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??$i)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,o){if(!o)return {};let s=this.languageHandlers.get(n);if(!s)return {};let a=this.classifiers.get(n)??fr,l={};return await this.walkAST(e.rootNode,async c=>{let m=s.get(c.type);m&&await m(c,o,l,a);}),l}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let o=e.child(n);o&&await this.walkAST(o,t);}}};});var He,Ai,Ir,ki,Di,Bt=y(()=>{He=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),Ai=new Set(["true","false","null","undefined","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type"]),Ir={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},ki={language:"javascript",textIncludedTypes:Ai,fieldNames:Ir},Di={language:"typescript",textIncludedTypes:Ai,fieldNames:Ir};});var Vl,Oi,Mi,Nr=y(()=>{Vl=new Set(["true","false","none","None","True","False","yield","pass","continue","break","ellipsis","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","type","subscript","attribute","list","tuple","binary_operator","union_type","generic_type"]),Oi={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],list_splat_pattern:[],dictionary_splat_pattern:[],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]},Mi={language:"python",textIncludedTypes:Vl,fieldNames:Oi,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function Bi(i){return Ke.get(i)}function Ui(i){if(!i)return He;let e=Ke.get(i);if(!e)return He;let t=new Set(He);for(let n of e.textIncludedTypes)t.add(n);return t}function Rr(i){if(!i){let t=Array.from(Ke.values()).map(n=>n.fieldNames);return Je(...t)}let e=Ke.get(i);if(!e){let t=Array.from(Ke.values()).map(n=>n.fieldNames);return Je(...t)}return e.fieldNames}var Ke,Gi=y(()=>{Tr();Bt();Nr();Bt();Bt();Nr();Ke=new Map([["javascript",ki],["typescript",Di],["python",Mi]]);});var Ji={};Xr(Ji,{COMMON_FIELD_NAMES:()=>Lr,JS_TS_FIELD_NAMES:()=>Hi,PYTHON_FIELD_NAMES:()=>Ki,TEXT_INCLUDED_TYPES:()=>zi,mergeFieldMaps:()=>Je,serializeAST:()=>Yl,serializeASTStream:()=>ql});function*ql(i,e,t){yield*jr(i,e,t);}function*jr(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Wi(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let o=(t?Rr(t):Lr)[i.type]||[],s=new Set,a=true;for(let l of o){let c=i.childForFieldName(l);c&&(a||(yield ","),a=false,s.add(c),yield*jr(c,l,t));}for(let l=0;l<i.childCount;l++){let c=i.child(l);c&&!s.has(c)&&(a||(yield ","),a=false,yield*jr(c,void 0,t));}yield "]";}yield "}";}async function Yl(i,e,t){let n=$r(i,e,t),o=t?Rr(t):Lr,s=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;s.length>0;){let a=s[s.length-1];if(a.childIndex===0&&a.treeNode.childCount>0){let l=o[a.treeNode.type]||[];for(let c of l){let m=a.treeNode.childForFieldName(c);if(m){a.fieldChildren.add(m);let u=$r(m,c,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(u),s.push({treeNode:m,serializedNode:u,fieldName:c,childIndex:0,fieldChildren:new Set});}}}if(a.childIndex<a.treeNode.childCount){let l=a.treeNode.child(a.childIndex);if(a.childIndex++,l&&!a.fieldChildren.has(l)){let c=$r(l,void 0,t);a.serializedNode.children||(a.serializedNode.children=[]),a.serializedNode.children.push(c),s.push({treeNode:l,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else s.pop();}return n}function $r(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return Wi(i,t)&&(n.text=i.text),n}function Wi(i,e){if(e){let n=Bi(e);if(n?.shouldIncludeText){let s=n.shouldIncludeText(i);if(s===false)return false;if(s===true)return true}return Ui(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:zi.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Je(...i){let e={};for(let t of i)for(let[n,o]of Object.entries(t)){let a=[...e[n]||[]];for(let l of o)a.includes(l)||a.push(l);e[n]=a;}return e}var zi,Hi,Ki,Lr,Tr=y(()=>{Gi();zi=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","string_fragment","number","true","false","null","undefined","import_specifier","export_specifier","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","yield","pass","continue","break","None","none","True","False","ellipsis","type","string_content"]);Hi={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Ki={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]};Lr=Je(Hi,Ki);});var Ve,qi=y(()=>{ct();Nn();Tn();Un();Me();Tt();ci();ui();mi();hi();vi();ut();kt();Si();ue();ar();Ti();D();dt();Ve=class extends ie{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;logCollector=new We;discoveredFiles=[];parseSymbols=new Map;parseContent=new Map;symbolExtractor=new Ot;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new Ft(process.cwd()),this.parser=new Lt(this.langRegistry),this.compressor=new At;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let o=n.getBuildConfigManager(process.cwd(),this.config.languages);o&&this.buildConfigManagers.set(t,o);}}}async run(e=false,t=false,n=false){this.logCollector=new We,this.logCollector.start();let o="failed";try{let s=await this.getAccessKey();this.apiClient=new at(this.config,s,t),await this.validateProject(),this.logCollector.log(`${ee}Starting indexing procedure...
71
+ `);let a=performance.now();if(t?this.logCollector.log(`${b} Skipping git branch validation`):await this.validateGitBranch(),t?this.logCollector.log(`${b} Skipping git status validation`):await this.validateGitStatus(),t?this.logCollector.log(`${b} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){this.logCollector.log(`${v} Discovering language build configurations...`);let R=0;for(let[,T]of this.buildConfigManagers.entries()){let W=await T.initialize();R+=W.length;}R>0&&this.logCollector.log(`${S} Found ${R} configuration file(s)`);}let l=await this.determineIndexScope(e),c=await this.git.getLatestCommitHash(),m=await this.git.getCommitTimestamp();if(l.upToDate){this.logCollector.log(`
72
+ ${S} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${c.substring(0,8)}`),o="succeeded";return}let u=await this.apiClient.claimAstLock(this.config.projectId,this.config.branch,l.isIncremental,c,m);switch(u.remapped===!0&&(u.effectiveBranchName?this.logCollector.log(`${b} --dirty: server is indexing as default branch "${u.effectiveBranchName}" (transmitted "${this.config.branch}").`):this.logCollector.log(`${b} --dirty: server reported a branch remap but did not include the effective branch name.`)),u.status){case "current":this.logCollector.log(`${S} Index already up to date for branch ${this.config.branch} at commit ${c?.substring(0,8)||"unknown"}`),o="succeeded";return;case "duplicate":this.logCollector.log("\u2713 Index for this commit is already in progress."),o="succeeded";return;case "superseded":this.logCollector.log("\u2713 A newer commit is already being indexed."),o="succeeded";return;case "queued":if(!u.queuedAttemptId)throw new Error("Server returned queued status without an attempt ID");await this.handleQueuedUpload(u.queuedAttemptId,l.isIncremental,c),o="succeeded";return;default:break}let d=!1,g=()=>{d||this.logCollector.log(`${v} Uploading metadata, processing, and indexing...`);},f,h,x=new Promise((R,T)=>{f=R,h=T;}),_=new AbortController,w=this.createIndexPipeline(l.isIncremental,g,f),P=null;try{let[,R]=await Promise.all([this.uploadToAPI(w,l.isIncremental,c,u.attemptId).then(T=>(d=!0,T)).catch(T=>{throw _.abort(T),h(T),d=!0,T}),x.then(T=>{let W=this.getEnrichmentEligibleLanguages(n,T);return W?(u.attemptId&&this.apiClient.startEnrichment(u.attemptId,this.config.projectId,this.config.branch),this.runLspEnrichment(T,W,this.parseSymbols,this.parseContent,_.signal).catch(ce=>(_.signal.aborted||this.logCollector.warn(`${b} Index enrichment failed: ${ce instanceof Error?ce.message:String(ce)}`,{code:"ENRICHMENT_FAILED"}),null))):null}).catch(()=>null)]);P=R;}catch(R){throw d=!0,R}if(P&&P.length>0)try{let R=this.discoveredFiles.length,T=bi(R),W=Math.round(T/1e3);this.logCollector.log(`${v} Waiting for server to finish syntax tree processing (${R} files, timeout ${W}s)...`);let ce=await this.apiClient.pollIndexStatus(this.config.projectId,this.config.branch,c,T),Te=Rn(P);if(ce){this.logCollector.log(`${v} Uploading enrichment data (${P.length} files)...`);let pe=!1;try{pe=await this.apiClient.uploadEnrichment(Te,this.config.projectId,this.config.branch,c);}catch{}pe?this.logCollector.log(`${S} Enrichment data uploaded to Constellation Service, index enhancement in progress`):this.logCollector.warn(`${b} Enrichment upload failed \u2014 re-run 'constellation index --full' after the server finishes AST processing to retry.`,{code:"ENRICHMENT_FAILED"});}else {this.logCollector.log(`${b} AST processing not complete after ${W}s \u2014 attempting enrichment upload anyway.`);let pe=!1;try{pe=await this.apiClient.uploadEnrichment(Te,this.config.projectId,this.config.branch,c);}catch{}pe?this.logCollector.log(`${S} Enrichment data uploaded to Constellation Service, index enhancement in progress`):this.logCollector.warn(`${b} Enrichment upload failed \u2014 re-run 'constellation index --full' after the server finishes AST processing to retry.`,{code:"ENRICHMENT_FAILED"});}}catch(R){this.logCollector.warn(`${b} Enrichment upload failed: ${R instanceof Error?R.message:String(R)}`,{code:"ENRICHMENT_FAILED"});}let A=(performance.now()-a)/1e3,L=Math.floor(A/60),J=(A%60).toFixed(3),Z=L>0?`${L}m ${J}s`:`${J}s`;this.logCollector.log(`
73
+ ${S} Upload completed in ${Z}! Server indexing in progress.`),o="succeeded";}catch(s){if(s instanceof M)throw s;if(s instanceof ye){this.logIndexingInProgress(s.branchName||this.config?.branch),o="succeeded";return}if(s instanceof $)throw this.logCollector.error(`
74
74
  ${I} Authentication failed.`,{code:"AUTH_FAILURE"}),this.logCollector.log(`${v} Your access key may be invalid or expired. Run 'constellation auth'
75
- to set or update your access key.`),s;if(s instanceof ne)throw this.logCollector.error(`${I} Indexing failed: ${s.message}`,{code:s.errorCode}),s;if(s instanceof Error&&s.message==="Access key not configured")throw s;let a=s instanceof Error?s.message:"An unexpected error occurred";throw this.logCollector.error(`${I} Indexing failed: ${a}`),s}finally{this.parseSymbols.clear(),this.parseContent.clear(),this.logCollector.stop();try{let a=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",l=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,c=this.logCollector.getReportableErrors();if(!a&&l&&c.length>0){let d=this.logCollector.getEntries(),m=c.map(_=>({type:"CLI_ERROR",message:_.message,phase:"indexing"})).slice(0,100),u=d.filter(_=>_.level==="warn").map(_=>({type:"CLI_WARNING",message:_.message,phase:"indexing"})).slice(0,100),g=m.length,f=u.length,h=[];g>0&&h.push(`${g} error${g!==1?"s":""}`),f>0&&h.push(`${f} warning${f!==1?"s":""}`);let x=h.join(", "),w=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:x,errorData:{errors:m,warnings:u},logEntries:d.slice(0,1e3),cliVersion:w,outcome:o,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(ie);if(!e)throw this.logCollector.error(`
76
- ${I} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),this.logCollector.log(`${v} Set the ${ie} environment variable or run
77
- 'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.logCollector.log(`${v} Validating project access...`);try{await this.apiClient.getProjectState(),this.logCollector.log(`${S} Project validated successfully`);}catch(e){if(e instanceof M)throw this.displayProjectValidationError(e),e;if(e instanceof re){this.logCollector.log(`${S} Project validated (first index)`);return}if(e instanceof T)throw e;let t=e instanceof Error?e.message:String(e);throw t==="fetch failed"||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("ETIMEDOUT")||t.includes("EHOSTUNREACH")||t.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
75
+ to set or update your access key.`),s;if(s instanceof re)throw this.logCollector.error(`${I} Indexing failed: ${s.message}`,{code:s.errorCode}),s;if(s instanceof Error&&s.message==="Access key not configured")throw s;let a=s instanceof Error?s.message:"An unexpected error occurred";throw this.logCollector.error(`${I} Indexing failed: ${a}`),s}finally{this.parseSymbols.clear(),this.parseContent.clear(),this.logCollector.stop();try{let a=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",l=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,c=this.logCollector.getReportableErrors();if(!a&&l&&c.length>0){let m=this.logCollector.getEntries(),u=c.map(w=>({type:"CLI_ERROR",message:w.message,phase:"indexing"})).slice(0,100),d=m.filter(w=>w.level==="warn").map(w=>({type:"CLI_WARNING",message:w.message,phase:"indexing"})).slice(0,100),g=u.length,f=d.length,h=[];g>0&&h.push(`${g} error${g!==1?"s":""}`),f>0&&h.push(`${f} warning${f!==1?"s":""}`);let x=h.join(", "),_=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:x,errorData:{errors:u,warnings:d},logEntries:m.slice(0,1e3),cliVersion:_,outcome:o,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(){let e=await this.env.getKey(ne);if(!e)throw this.logCollector.error(`
76
+ ${I} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),this.logCollector.log(`${v} Set the ${ne} environment variable or run
77
+ 'constellation auth' to configure your access key.`),new Error("Access key not configured");return e}async validateProject(){this.logCollector.log(`${v} Validating project access...`);try{await this.apiClient.getProjectState(),this.logCollector.log(`${S} Project validated successfully`);}catch(e){if(e instanceof M)throw this.displayProjectValidationError(e),e;if(e instanceof te){this.logCollector.log(`${S} Project validated (first index)`);return}if(e instanceof $)throw e;let t=e instanceof Error?e.message:String(e);throw t==="fetch failed"||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("ETIMEDOUT")||t.includes("EHOSTUNREACH")||t.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
78
78
  Verify your network connection and that the API URL is correct.`):e}}displayProjectValidationError(e){let t=e.projectId||this.config.projectId,n=t.length>40?t.substring(0,37)+"...":t;switch(e.code){case "PROJECT_NOT_REGISTERED":this.logCollector.error(`
79
79
  ${I} Project not registered
80
80
  `,{code:"PROJECT_NOT_REGISTERED"}),this.logCollector.log(` The project ID "${n}" in constellation.json`),this.logCollector.log(` is not associated with your Constellation account.
@@ -89,7 +89,7 @@ ${I} Invalid project ID
89
89
  `),this.logCollector.log(" To resolve this:"),this.logCollector.log(" 1. Get your project ID from https://app.constellationdev.io"),this.logCollector.log(" 2. Update the projectId field in constellation.json"),this.logCollector.log(` 3. Run 'constellation index' again
90
90
  `);break;default:this.logCollector.error(`
91
91
  ${I} Project validation failed: ${e.message}
92
- `,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.logCollector.log(`${v} Another indexing operation is already in progress for branch ${e||"unknown"}. Your index is up to date with the current operation.`),this.logCollector.log(" Re-run this command after the current operation completes if you have newer changes.");}async validateGitBranch(){this.logCollector.log(`${v} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.logCollector.log(`${S} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.logCollector.log(`${v} Validating Git status...`),!(await this.git.status()).clean)throw new ne(`Outstanding changes detected.
92
+ `,{code:"PROJECT_VALIDATION_FAILED"});}}logIndexingInProgress(e){this.logCollector.log(`${v} Another indexing operation is already in progress for branch ${e||"unknown"}. Your index is up to date with the current operation.`),this.logCollector.log(" Re-run this command after the current operation completes if you have newer changes.");}async validateGitBranch(){this.logCollector.log(`${v} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),this.logCollector.log(`${S} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(this.logCollector.log(`${v} Validating Git status...`),!(await this.git.status()).clean)throw new re(`Outstanding changes detected.
93
93
  Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");this.logCollector.log(`${S} Working tree clean`);}async synchronizeChanges(){this.logCollector.log(`${v} Synchronizing latest changes...`);try{await this.git.pull()&&this.logCollector.log(`${S} Repository synchronized successfully`);}catch(e){throw this.logCollector.error(`${I} Failed to synchronize repository`,{code:"GIT_SYNC_FAILURE"}),e instanceof Error&&(e.message.includes("uncommitted changes")?(this.logCollector.log(`
94
94
  To resolve:`),this.logCollector.log(' 1. Commit your changes: git add . && git commit -m "your message"'),this.logCollector.log(" 2. Or stash them: git stash"),this.logCollector.log(` 3. Then run the index command again
95
95
  `)):e.message.includes("merge conflicts")?(this.logCollector.log(`
@@ -98,32 +98,32 @@ To resolve:`),this.logCollector.log(" 1. Fix the conflicted files manually"),th
98
98
  Please check your internet connection and try again
99
99
  `):e.message.includes("Authentication")&&this.logCollector.log(`
100
100
  Please check your git credentials and try again
101
- `)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.logCollector.log(`${v} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return this.logCollector.log(`${v} No previous index found, performing full index`),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(this.logCollector.log(`${S} Already up to date`),{isIncremental:!0,upToDate:!0}):(this.logCollector.log(`${v} Last indexed commit: ${n.substring(0,8)}`),this.logCollector.log(`${v} Current commit: ${o.substring(0,8)}`),this.logCollector.log(`${v} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof T)throw t;return this.logCollector.log(`${b} Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.logCollector.log(`${v} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)this.logCollector.log(`${b} Cannot determine changes (no latestCommit in project state), falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let o=await this.git.getChangedFiles(n.latestCommit),s=[...o.added,...o.modified,...o.renamed.map(l=>l.to)];this.logCollector.log(`${v} Found ${s.length} changed files`),t=await this.scanner.scanSpecificFiles(s,this.config);let a=[...o.deleted,...o.renamed.map(l=>l.from)];if(a.length>0){let l=o.deleted.length,c=o.renamed.length,d=c>0?`${v} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${v} Removing ${l} deleted file(s) from graph`;this.logCollector.log(d),await this.apiClient.deleteFiles(a);}}}catch(n){if(n instanceof T)throw n;this.logCollector.log(`${b} Cannot determine changes (${n instanceof Error?n.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.logCollector.log(`${v} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return this.logCollector.log(`${S} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),o=e.length,s=0,a=0;this.logCollector.log(`${v} Processing ${o} files...`);let l=await this.git.getLatestCommitHash(),c=o>1e4?5:o>5e3?7:10;c<10&&this.logCollector.log(`${v} Large project detected, using concurrency of ${c} to optimize memory usage`);let m=new ye(c).run(e,async(u,g)=>{let f=Math.round((g+1)/o*100);this.logCollector.log(`${v} Analyzing file ${u.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let{tree:h,classificationMap:x,content:w}=await this.parser.parseFile(u.path,u.language),_=this.symbolExtractor.extract(h,u.language);_.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(u.relativePath),_),w!==void 0&&this.parseContent.set(this.normalizePathToCanonical(u.relativePath),w),x.entries.length>5e4&&this.logCollector.warn(`${b} Large classification map for ${u.relativePath}: ${x.entries.length} entries`);let W=this.langRegistry.getPlugin(u.language),E;if(W?.getImportResolver){let Z=this.buildConfigManagers.get(u.language),ee=Z?await Z.getConfigForFile(u.path):null,Re=W.getImportResolver(u.path,ee);if(Re){let{ImportExtractor:Jr}=await Promise.resolve().then(()=>(Ni(),Ii));E=await new Jr().extractImportResolutions(h,u.path,u.language,Re);}}let{serializeASTStream:k}=await Promise.resolve().then(()=>(Er(),Ui)),j=k(h.rootNode,void 0,u.language),K=await this.compressor.compressStream(j),Q=this.normalizePathToCanonical(u.relativePath),R={file:Q,language:u.language,commit:l,timestamp:n,ast:K,importResolutions:E,classificationMap:{filePath:Q,entries:x.entries}},L=ci.safeParse(R);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return s++,L.data}catch(h){throw a++,this.logCollector.warn(` ${b} Failed to parse ${u.relativePath}: ${h.message}`,{code:"PARSE_FAILURE"}),h}});for await(let u of m)yield u;a>0?this.logCollector.log(`${b} Completed parsing with ${a} parsing errors`):this.logCollector.log(`${S} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n,o))throw new Error("Failed to upload data to Constellation Service");this.logCollector.log(`${S} Data uploaded to Constellation Service, indexing in progress`);}async*createIndexPipeline(e,t,n){let o=await this.discoverFiles(e);this.discoveredFiles=o,n(o),yield*this.generateASTs(o,t);}async handleQueuedUpload(e,t,n){this.logCollector.log("Generating AST data for queue upload...");let o=this.createIndexPipeline(t,()=>{},()=>{});await this.apiClient.uploadToQueue(o,this.config.projectId,this.config.branch,n,e),this.logCollector.log(`${S} Changes queued for indexing behind the current operation.`);}normalizePathToCanonical(e){return ut(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||se.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.logCollector.log(`${v} Index enrichment skipped`),null;if(this.config.lspEnrichment===false)return this.logCollector.log(`${v} Index enrichment disabled in constellation.json`),null;let o=[...new Set(t.map(s=>s.language))].filter(s=>this.isLanguageLspEligible(s));return o.length===0?null:(this.logCollector.log(`${v} Index enrichment enabled for: ${o.map(Ue).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,n,o,s){let a=new bt(process.cwd(),this.logCollector);try{if(s?.aborted)return null;this.logCollector.log(`${v} Starting index enrichment...`);let l=new Map,c=new Map;for(let f of e){if(!t.has(f.language))continue;let h=l.get(f.language)||[];h.push(this.normalizePathToCanonical(f.relativePath)),l.set(f.language,h);}for(let f of l.keys()){if(c.has(f))continue;let x=this.config.languages[f]?.lsp,w=await a.startServer(f,x);w&&c.set(f,w);}if(c.size===0)return this.logCollector.log(`${b} No language servers started, index enrichment skipped`),null;if(s?.aborted)return a.destroyAll(),null;this.logCollector.log(`${S} Language servers started: ${[...c.keys()].map(Ue).join(", ")}`);let d=new dt(process.cwd()),m=s?new Promise((f,h)=>{s.addEventListener("abort",()=>{a.destroyAll(),h(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,u=await(m?Promise.race([d.enrich(l,n,c,o),m]):d.enrich(l,n,c,o)),g=u.reduce((f,h)=>f+h.symbols.length,0);return this.logCollector.log(`${S} Index enrichment analysis completed: ${g} symbols across ${u.length} files`),u.length>0?u:null}catch(l){return this.logCollector.warn(`${b} Index enrichment failed: ${l instanceof Error?l.message:String(l)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await a.shutdownAll();}}};});function Rr(i){return stringify({name:"Constellation Index",on:{push:{branches:[i]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4"},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function Mt(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function Bt(i){let{includeEntry:e,job:t}=Mt(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var Tr=y(()=>{});var Ve,Ki=y(()=>{q();Tr();Ve=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([C.directoryExists(N__default.join(this.gitRoot,".github","workflows")),C.fileIsReadable(N__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return C.fileIsReadable(N__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=N__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(e))return false;try{let n=await C.readFile(e),s=parseDocument(n).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=N__default.join(this.gitRoot,".github","workflows");await B__default.mkdir(t,{recursive:true});let n=N__default.join(t,"constellation-index.yml");return await C.writeFile(n,Rr(e)),n}async createOrMergeGitLabCI(e){let t=N__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(t))return await C.writeFile(t,Bt(e)),t;let o=await C.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await C.writeFile(t,Bt(e)),t;let{includeEntry:a,job:l}=Mt(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await C.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let o=n.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});n.items=o,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var Ji=y(()=>{Ki();Tr();});function Vi(i,e){let t=Ie__default.homedir(),n=process.platform,o=Gl[i];switch(n){case "darwin":return N__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return N__default.join(process.env.APPDATA||N__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return N__default.join(t,".config",o,"User/globalStorage",e)}}function qi(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:N__default.join(Vi(t,i),"settings","cline_mcp_settings.json")}))}function Yi(){return N__default.join(Vi("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Gl,Xi=y(()=>{Gl={stable:"Code",insiders:"Code - Insiders"};});function Zi(i){return jr.find(e=>e.id===i)}var Qi,zl,jr,Lr=y(()=>{Xi();Qi={command:"npx",args:["-y","@constellationdev/mcp@latest"]},zl={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},jr=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",skipMcpServer:true,permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:zl},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Yi(),isGlobalConfig:true,getGlobalConfigPaths:qi,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","marketplace","add","ShiftinBits/constellation-copilot"]},pluginPostInstallCommands:[{command:"copilot",args:["plugin","install","constellation@constellation-plugins"]}]},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"gemini",args:["extensions","install","https://github.com/ShiftinBits/constellation-gemini"]},pluginUpdateCommand:{command:"gemini",args:["extensions","update","constellation"]},pluginPostInstallCommands:[{command:"gemini",args:["extensions","disable","--scope","user","constellation"]},{command:"gemini",args:["extensions","enable","--scope","workspace","constellation"]}]},{id:"jetbrains-ai",displayName:"JetBrains",configPath:".ai/mcp/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}},{id:"kilo-code",displayName:"Kilo Code",configPath:".kilocode/mcp.json",format:"json",permissionsConfig:{filePath:".kilocode/mcp.json",allowKeyPath:["mcpServers","constellation","alwaysAllow"],allowValue:"code_intel"},mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"opencode",displayName:"OpenCode",configPath:"opencode.jsonc",format:"jsonc",mcpServersKeyPath:["mcp"],skipMcpServer:true,pluginConfig:{pluginKeyPath:["plugin"],pluginValue:"@constellationdev/opencode"},configDefaults:{$schema:"https://opencode.ai/config.json"}},{id:"tabnine",displayName:"Tabnine",configPath:".tabnine/mcp_servers.json",format:"json",mcpServersKeyPath:["mcpServers"]},{id:"vscode-copilot",displayName:"VSCode",configPath:".vscode/mcp.json",format:"json",mcpServersKeyPath:["servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}}];});async function eo(){if(!Fr)try{let i=await import('@iarna/toml');Fr={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Fr}function Kl(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
102
- `;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Fr,Ut,to=y(()=>{q();Lr();Fr=null;Ut=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=N__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let s=await this.readConfig(t,e.format);if(e.configDefaults)for(let[a,l]of Object.entries(e.configDefaults))a in s||(s[a]=l);e.pluginConfig&&(s=this.addPluginToArray(s,e.pluginConfig)),e.skipMcpServer||(s=this.addConstellationServer(s,e),await this.configureEnvPolicy(s,e)),await this.writeConfig(t,s,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return n?o=t:e.permissionsConfig?o=N__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=N__default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:o,settingsPath:s}of t)try{await this.ensureDirectoryExists(s);let a=await this.readConfig(s,e.format);a=this.addConstellationServer(a,e),await this.writeConfig(s,a,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:s});}catch(a){let l=a instanceof Error?a.message:String(a);l.includes("ENOENT")||l.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return n}async ensureDirectoryExists(e){let t=N__default.dirname(e);await B__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await C.fileIsReadable(e))return {};let o=await C.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(Kl(o)):(await eo()).parse(o)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let s=n[o];if(!s.constellation){let a=t.mcpServerConfigOverride??Qi,l={...a};if(t.mcpServerExtras&&Object.assign(l,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",d=a[c];l[c]={...d,...t.mcpEnv};}s.constellation=l;}return e}async writeConfig(e,t,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await eo()).stringify(t),o=o.replace(/\r\n/g,`
101
+ `)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};this.logCollector.log(`${v} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return this.logCollector.log(`${v} No previous index found, performing full index`),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(this.logCollector.log(`${S} Already up to date`),{isIncremental:!0,upToDate:!0}):(this.logCollector.log(`${v} Last indexed commit: ${n.substring(0,8)}`),this.logCollector.log(`${v} Current commit: ${o.substring(0,8)}`),this.logCollector.log(`${v} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof $)throw t;return this.logCollector.log(`${b} Could not determine last index (${t instanceof Error?t.message:"unknown error"}), performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){this.logCollector.log(`${v} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)this.logCollector.log(`${b} Cannot determine changes (no latestCommit in project state), falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let o=await this.git.getChangedFiles(n.latestCommit),s=[...o.added,...o.modified,...o.renamed.map(l=>l.to)];this.logCollector.log(`${v} Found ${s.length} changed files`),t=await this.scanner.scanSpecificFiles(s,this.config);let a=[...o.deleted,...o.renamed.map(l=>l.from)];if(a.length>0){let l=o.deleted.length,c=o.renamed.length,m=c>0?`${v} Removing ${l} deleted file(s) and ${c} renamed file(s) from graph`:`${v} Removing ${l} deleted file(s) from graph`;this.logCollector.log(m),await this.apiClient.deleteFiles(a);}}}catch(n){if(n instanceof $)throw n;this.logCollector.log(`${b} Cannot determine changes (${n instanceof Error?n.message:"unknown"}), falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else this.logCollector.log(`${v} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return this.logCollector.log(`${S} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),o=e.length,s=0,a=0;this.logCollector.log(`${v} Processing ${o} files...`);let l=await this.git.getLatestCommitHash(),c=o>1e4?5:o>5e3?7:10;c<10&&this.logCollector.log(`${v} Large project detected, using concurrency of ${c} to optimize memory usage`);let u=new be(c).run(e,async(d,g)=>{let f=Math.round((g+1)/o*100);this.logCollector.log(`${v} Analyzing file ${d.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let{tree:h,classificationMap:x,content:_}=await this.parser.parseFile(d.path,d.language),w=this.symbolExtractor.extract(h,d.language);w.length>0&&this.parseSymbols.set(this.normalizePathToCanonical(d.relativePath),w),_!==void 0&&this.parseContent.set(this.normalizePathToCanonical(d.relativePath),_),x.entries.length>5e4&&this.logCollector.warn(`${b} Large classification map for ${d.relativePath}: ${x.entries.length} entries`);let K=this.langRegistry.getPlugin(d.language),E;if(K?.getImportResolver){let W=this.buildConfigManagers.get(d.language),ce=W?await W.getConfigForFile(d.path):null,Te=K.getImportResolver(d.path,ce);if(Te){let{ImportExtractor:pe}=await Promise.resolve().then(()=>(Fi(),Li));E=await new pe().extractImportResolutions(h,d.path,d.language,Te);}}let{serializeASTStream:A}=await Promise.resolve().then(()=>(Tr(),Ji)),L=A(h.rootNode,void 0,d.language),J=await this.compressor.compressStream(L),Z=this.normalizePathToCanonical(d.relativePath),R={file:Z,language:d.language,commit:l,timestamp:n,ast:J,importResolutions:E,classificationMap:{filePath:Z,entries:x.entries}},T=di.safeParse(R);if(!T.success)throw new Error(`AST validation failed: ${T.error.issues[0].message}`);return s++,T.data}catch(h){throw a++,this.logCollector.warn(` ${b} Failed to parse ${d.relativePath}: ${h.message}`,{code:"PARSE_FAILURE"}),h}});for await(let d of u)yield d;a>0?this.logCollector.log(`${b} Completed parsing with ${a} parsing errors`):this.logCollector.log(`${S} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n,o){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n,o))throw new Error("Failed to upload data to Constellation Service");this.logCollector.log(`${S} Data uploaded to Constellation Service, indexing in progress`);}async*createIndexPipeline(e,t,n){let o=await this.discoverFiles(e);this.discoveredFiles=o,n(o),yield*this.generateASTs(o,t);}async handleQueuedUpload(e,t,n){this.logCollector.log("Generating AST data for queue upload...");let o=this.createIndexPipeline(t,()=>{},()=>{});await this.apiClient.uploadToQueue(o,this.config.projectId,this.config.branch,n,e),this.logCollector.log(`${S} Changes queued for indexing behind the current operation.`);}normalizePathToCanonical(e){return mt(e)}isLanguageLspEligible(e){let t=this.config.languages[e];return t?.lspEnrichment===false?false:!!t?.lsp||oe.has(e)}getEnrichmentEligibleLanguages(e,t){if(e)return this.logCollector.log(`${v} Index enrichment skipped`),null;if(this.config.lspEnrichment===false)return this.logCollector.log(`${v} Index enrichment disabled in constellation.json`),null;let o=[...new Set(t.map(s=>s.language))].filter(s=>this.isLanguageLspEligible(s));return o.length===0?null:(this.logCollector.log(`${v} Index enrichment enabled for: ${o.map(Ge).join(", ")}`),new Set(o))}async runLspEnrichment(e,t,n,o,s){let a=new St(process.cwd(),this.logCollector);try{if(s?.aborted)return null;this.logCollector.log(`${v} Starting index enrichment...`);let l=new Map,c=new Map;for(let f of e){if(!t.has(f.language))continue;let h=l.get(f.language)||[];h.push(this.normalizePathToCanonical(f.relativePath)),l.set(f.language,h);}for(let f of l.keys()){if(c.has(f))continue;let x=this.config.languages[f]?.lsp,_=await a.startServer(f,x);_&&c.set(f,_);}if(c.size===0)return this.logCollector.log(`${b} No language servers started, index enrichment skipped`),null;if(s?.aborted)return a.destroyAll(),null;this.logCollector.log(`${S} Language servers started: ${[...c.keys()].map(Ge).join(", ")}`);let m=new gt(process.cwd()),u=s?new Promise((f,h)=>{s.addEventListener("abort",()=>{a.destroyAll(),h(s.reason||new Error("Indexing aborted"));},{once:!0});}):null,d=await(u?Promise.race([m.enrich(l,n,c,o),u]):m.enrich(l,n,c,o)),g=d.reduce((f,h)=>f+h.symbols.length,0);return this.logCollector.log(`${S} Index enrichment analysis completed: ${g} symbols across ${d.length} files`),d.length>0?d:null}catch(l){return this.logCollector.warn(`${b} Index enrichment failed: ${l instanceof Error?l.message:String(l)}`,{code:"ENRICHMENT_FAILED"}),null}finally{await a.shutdownAll();}}};});function Fr(i){return stringify({name:"Constellation Index",on:{push:{branches:[i]}},permissions:{contents:"read"},jobs:{index:{"runs-on":"ubuntu-latest",steps:[{uses:"actions/checkout@v4"},{uses:"ShiftinBits/constellation-github@v1",with:{"access-key":"${{ secrets.CONSTELLATION_ACCESS_KEY }}"}}]}}},{lineWidth:0})}function Ut(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function Gt(i){let{includeEntry:e,job:t}=Ut(i);return stringify({include:[e],"constellation-index":t},{lineWidth:0})}var Ar=y(()=>{});var qe,Qi=y(()=>{Y();Ar();qe=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([C.directoryExists(N__default.join(this.gitRoot,".github","workflows")),C.fileIsReadable(N__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return C.fileIsReadable(N__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=N__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(e))return false;try{let n=await C.readFile(e),s=parseDocument(n).contents;return isMap(s)&&s.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=N__default.join(this.gitRoot,".github","workflows");await B__default.mkdir(t,{recursive:true});let n=N__default.join(t,"constellation-index.yml");return await C.writeFile(n,Fr(e)),n}async createOrMergeGitLabCI(e){let t=N__default.join(this.gitRoot,".gitlab-ci.yml");if(!await C.fileIsReadable(t))return await C.writeFile(t,Gt(e)),t;let o=await C.readFile(t),s=parseDocument(o);if(!isMap(s.contents))return await C.writeFile(t,Gt(e)),t;let{includeEntry:a,job:l}=Ut(e);return this.mergeIncludeEntry(s,a),s.set("constellation-index",l),await C.writeFile(t,s.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let o=n.items.filter(s=>{if(isMap(s)){let a=s.get("component");return typeof a!="string"||!a.includes("constellation-gitlab")}return true});n.items=o,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var Zi=y(()=>{Qi();Ar();});function eo(i,e){let t=Ne__default.homedir(),n=process.platform,o=tc[i];switch(n){case "darwin":return N__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return N__default.join(process.env.APPDATA||N__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return N__default.join(t,".config",o,"User/globalStorage",e)}}function to(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:N__default.join(eo(t,i),"settings","cline_mcp_settings.json")}))}function ro(){return N__default.join(eo("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var tc,no=y(()=>{tc={stable:"Code",insiders:"Code - Insiders"};});function oo(i){return Dr.find(e=>e.id===i)}var io,rc,Dr,Or=y(()=>{no();io={command:"npx",args:["-y","@constellationdev/mcp@latest"]},rc={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},Dr=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",skipMcpServer:true,permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:rc},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:ro(),isGlobalConfig:true,getGlobalConfigPaths:to,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false}},{id:"codex-cli",displayName:"Codex CLI",configPath:".codex/config.toml",format:"toml",mcpServersKeyPath:["mcp_servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"$CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{enabled_tools:["code_intel"]},envPolicyConfig:{includeOnlyKeyPath:["shell_environment_policy","include_only"],envVarsToAllow:["CONSTELLATION_ACCESS_KEY"],globalConfigPath:"~/.codex/config.toml"}},{id:"copilot-cli",displayName:"Copilot CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","marketplace","add","ShiftinBits/constellation-copilot"]},pluginPostInstallCommands:[{command:"copilot",args:["plugin","install","constellation@constellation-plugins"]}]},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"gemini",args:["extensions","install","https://github.com/ShiftinBits/constellation-gemini"]},pluginUpdateCommand:{command:"gemini",args:["extensions","update","constellation"]},pluginPostInstallCommands:[{command:"gemini",args:["extensions","disable","--scope","user","constellation"]},{command:"gemini",args:["extensions","enable","--scope","workspace","constellation"]}]},{id:"jetbrains-ai",displayName:"JetBrains",configPath:".ai/mcp/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}},{id:"kilo-code",displayName:"Kilo Code",configPath:".kilocode/mcp.json",format:"json",permissionsConfig:{filePath:".kilocode/mcp.json",allowKeyPath:["mcpServers","constellation","alwaysAllow"],allowValue:"code_intel"},mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"}},{id:"opencode",displayName:"OpenCode",configPath:"opencode.jsonc",format:"jsonc",mcpServersKeyPath:["mcp"],skipMcpServer:true,pluginConfig:{pluginKeyPath:["plugin"],pluginValue:"@constellationdev/opencode"},configDefaults:{$schema:"https://opencode.ai/config.json"}},{id:"tabnine",displayName:"Tabnine",configPath:".tabnine/mcp_servers.json",format:"json",mcpServersKeyPath:["mcpServers"]},{id:"vscode-copilot",displayName:"VSCode",configPath:".vscode/mcp.json",format:"json",mcpServersKeyPath:["servers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"CONSTELLATION_ACCESS_KEY"},mcpServerExtras:{tools:["code_intel"]}}];});async function so(){if(!Mr)try{let i=await import('@iarna/toml');Mr={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Mr}function oc(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
102
+ `;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Mr,zt,ao=y(()=>{Y();Or();Mr=null;zt=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=N__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let s=await this.readConfig(t,e.format);if(e.configDefaults)for(let[a,l]of Object.entries(e.configDefaults))a in s||(s[a]=l);e.pluginConfig&&(s=this.addPluginToArray(s,e.pluginConfig)),e.skipMcpServer||(s=this.addConstellationServer(s,e),await this.configureEnvPolicy(s,e)),await this.writeConfig(t,s,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let o;return n?o=t:e.permissionsConfig?o=N__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?o=N__default.join(this.cwd,e.marketplaceConfig.filePath):o=t,{tool:e,success:!0,configuredPath:o}}catch(t){return {tool:e,success:false,error:t instanceof Error?t.message:String(t)}}}async configureGlobalTool(e){if(!e.getGlobalConfigPaths)return [{tool:e,success:false,error:"No global config paths defined"}];let t=e.getGlobalConfigPaths(),n=[];for(let{displayName:o,settingsPath:s}of t)try{await this.ensureDirectoryExists(s);let a=await this.readConfig(s,e.format);a=this.addConstellationServer(a,e),await this.writeConfig(s,a,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:s});}catch(a){let l=a instanceof Error?a.message:String(a);l.includes("ENOENT")||l.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:l});}return n}async ensureDirectoryExists(e){let t=N__default.dirname(e);await B__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await C.fileIsReadable(e))return {};let o=await C.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(oc(o)):(await so()).parse(o)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let a=0;a<t.mcpServersKeyPath.length-1;a++){let l=t.mcpServersKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let s=n[o];if(!s.constellation){let a=t.mcpServerConfigOverride??io,l={...a};if(t.mcpServerExtras&&Object.assign(l,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",m=a[c];l[c]={...m,...t.mcpEnv};}s.constellation=l;}return e}async writeConfig(e,t,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await so()).stringify(t),o=o.replace(/\r\n/g,`
103
103
  `),o.endsWith(`
104
104
  `)||(o+=`
105
105
  `),await C.writeFile(e,o);}async configurePermissions(e){let t=N__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await C.fileIsReadable(t)){let c=await C.readFile(t);n=JSON.parse(c);}}catch{}let o=n;for(let l=0;l<e.allowKeyPath.length-1;l++){let c=e.allowKeyPath[l];(!o[c]||typeof o[c]!="object")&&(o[c]={}),o=o[c];}let s=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(o[s])||(o[s]=[]);let a=o[s];a.includes(e.allowValue)||a.push(e.allowValue),await C.writeFile(t,JSON.stringify(n,null," ")+`
106
106
  `);}async configureMarketplace(e){let t=N__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await C.fileIsReadable(t)){let s=await C.readFile(t);n=JSON.parse(s);}}catch{}n=this.deepMerge(n,e.config),await C.writeFile(t,JSON.stringify(n,null," ")+`
107
- `);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let s=t[o],a=e[o];s&&typeof s=="object"&&!Array.isArray(s)&&a&&typeof a=="object"&&!Array.isArray(a)?n[o]=this.deepMerge(a,s):n[o]=s;}return n}addPluginToArray(e,t){let n=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let s=n[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),s&&await this.updateGlobalEnvPolicy(s,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let l=0;l<t.length-1;l++){let c=t[l];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let s=t[t.length-1];if(!Array.isArray(o[s]))return;let a=o[s];for(let l of n)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,n,o){let s=e.replace(/^~/,Ie__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,n);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function Gt(i,e){let t=N__default.normalize(i),n=N__default.normalize(e);return t.startsWith(n+N__default.sep)?N__default.relative(e,i):i}var Ql,Ye,io=y(()=>{Ji();Oe();Nt();to();Lr();q();D();pt();lt();Ql=promisify(execFile);Ye=class extends oe{async run(e={}){try{if(console.log(`${te}Initializing project configuration...
107
+ `);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let s=t[o],a=e[o];s&&typeof s=="object"&&!Array.isArray(s)&&a&&typeof a=="object"&&!Array.isArray(a)?n[o]=this.deepMerge(a,s):n[o]=s;}return n}addPluginToArray(e,t){let n=e;for(let a=0;a<t.pluginKeyPath.length-1;a++){let l=t.pluginKeyPath[a];(!n[l]||typeof n[l]!="object")&&(n[l]={}),n=n[l];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let s=n[o];return s.includes(t.pluginValue)||s.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:s}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),s&&await this.updateGlobalEnvPolicy(s,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let l=0;l<t.length-1;l++){let c=t[l];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let s=t[t.length-1];if(!Array.isArray(o[s]))return;let a=o[s];for(let l of n)a.includes(l)||a.push(l);}async updateGlobalEnvPolicy(e,t,n,o){let s=e.replace(/^~/,Ne__default.homedir()),a=await this.readConfig(s,o);if(Object.keys(a).length===0)return;let l=JSON.stringify(a);this.addToEnvPolicyWhitelist(a,t,n);let c=JSON.stringify(a);l!==c&&await this.writeConfig(s,a,o);}};});function Wt(i,e){let t=N__default.normalize(i),n=N__default.normalize(e);return t.startsWith(n+N__default.sep)?N__default.relative(e,i):i}var uc,Xe,po=y(()=>{Zi();Me();Tt();ao();Or();Y();D();dt();pt();uc=promisify(execFile);Xe=class extends ie{async run(e={}){try{if(console.log(`${ee}Initializing project configuration...
108
108
  `),!await this.git.isGitAvailable())throw new Error(`${b} Could not find git client installation.
109
109
  ${v} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=N__default.join(process.cwd(),"constellation.json"),o=null,s=await C.fileIsReadable(n);if(s)try{let E=await C.readFile(n);o=JSON.parse(E),console.log(`${v} Found existing constellation.json, current values will be used as defaults.
110
110
  `);}catch{console.log(`${b} Existing constellation.json is invalid, starting fresh.
111
111
  `);}if(!await this.git.isGitRepository())throw new Error(`${b} Current directory is not a git repository.
112
- ${v} Please run this command from the root directory of a git repository.`);let l=await this.git.getRootDir(),[c,d]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:m}=c,u=d.filter(E=>E!==m),g=m?[m,...u]:u,f=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:E=>E.trim().length>0||"Project ID is required",theme:F}),h=await select({message:"Branch to index:",choices:g.map(E=>({name:E,value:E})),default:o?.branch??g[0],theme:F}),w=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:F})).reduce((E,k)=>(E[k]={fileExtensions:Be[k]||[]},E),{});console.log(""),console.log(`${v} Checking for LSP servers...`);for(let[E,k]of Object.entries(w)){let j=se.get(E);if(!j)continue;let K=!1,Q="";if(gt(j.command)&&(K=!0,Q="system"),!K){let R=N__default.join(ht,j.command);existsSync(R)&&(K=!0,Q="managed");}if(K)console.log(` ${S} ${E}: Found ${j.command} (${Q})`),k.lsp={command:j.command,args:j.args};else if(await confirm({message:`${E}: ${j.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:F}))try{console.log(` ${v} Installing ${j.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",or,...j.npmPackages],{stdio:"pipe"}),console.log(` ${S} ${E}: Installed ${j.command}`),k.lsp={command:j.command,args:j.args};}catch{console.log(` ${I} ${E}: Installation failed`),k.lspEnrichment=!1;}else k.lspEnrichment=!1;}let _=Object.entries(w).filter(([,E])=>E.lspEnrichment!==!1).map(([E])=>E);_.length>0?console.log(`${S} Index enrichment enabled for: ${_.map(Ue).join(", ")}`):console.log(`${b} No language servers configured. Index enrichment will be skipped.`);let P={projectId:f.trim(),branch:h,languages:{...w},..._.length>0&&{lspEnrichment:!0}},W=JSON.stringify(P,void 0,2);await C.writeFile(n,W),console.log(`${S} ${s?"Updated":"Initialized"} configuration file at ${Gt(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${S} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&l&&await this.configureCICD(h,l);}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred";console.error(`${I} Failed to initialize configuration file.
113
- ${n}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:F}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:jr.map(m=>({name:m.displayName,value:m.id})),required:true,theme:F}),n=new Ut(process.cwd()),o=[];for(let m of t){let u=Zi(m);if(u)if(console.log(` ${v} Configuring ${u.displayName}...`),u.pluginInstallCommand){let g=await this.executePluginInstall(u);o.push(g),g.success?console.log(` ${S} ${u.displayName} plugin installed successfully`):console.log(` ${b} ${u.displayName}: ${g.error}`);}else if(u.isGlobalConfig&&u.getGlobalConfigPaths){let g=await n.configureGlobalTool(u),f=false;for(let h of g)o.push(h),h.success?(f=true,console.log(` ${S} ${h.tool.displayName} configured at ${Gt(h.configuredPath,process.cwd())}`)):h.error&&console.log(` ${b} ${h.tool.displayName}: ${h.error}`);if(f){let h=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${v} Note: ${u.displayName} uses ${h} (not project-level)`);}if(g.length===0){let h=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${b} ${u.displayName}: ${h}`);}}else {let g=await n.configureTool(u);o.push(g),g.success?(console.log(` ${S} ${u.displayName} configured at ${Gt(g.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${S} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${b} ${u.displayName}: ${g.error}`);}}if(o.find(m=>m.tool.id==="claude-code"&&m.success)){let m=N__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(m),console.log(` ${S} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${b} Could not stage .claude/settings.json in git`);}}if(o.find(m=>m.tool.id==="codex-cli"&&m.success)){let m=N__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(m),console.log(` ${S} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(m=>m.tool.id==="opencode"&&m.success)){let m=N__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(m),console.log(` ${S} Added opencode.jsonc to staged changes in git`);}catch{}}let c=o.filter(m=>m.success).length,d=o.filter(m=>!m.success).length;console.log(`
114
- ${S} Plugin + MCP configuration complete: ${c} configured`),d>0&&console.log(`${b} ${d} tool(s) could not be configured`),console.log(`
115
- ${v} Some tools may require restart to pick up new configuration.`);}async executePluginInstall(e){let t=e.pluginInstallCommand;try{await this.runPluginCommand(t);}catch(n){let o=n;if(e.pluginUpdateCommand&&this.isAlreadyInstalledError(o)){console.log(` ${v} ${e.displayName} extension already installed, attempting update...`);try{await this.runPluginCommand(e.pluginUpdateCommand);}catch(s){let a=s;return {tool:e,success:false,error:this.formatPluginCommandError(e.pluginUpdateCommand.command,a)}}}else if(this.isAlreadyInstalledError(o)&&(e.pluginPostInstallCommands?.length??0)>0)console.log(` ${v} ${e.displayName} plugin source already configured, continuing...`);else return {tool:e,success:false,error:this.formatPluginCommandError(t.command,o)}}for(let n of e.pluginPostInstallCommands??[])try{await this.runPluginCommand(n);}catch(o){let s=o;return {tool:e,success:false,error:this.formatPluginCommandError(n.command,s)}}return {tool:e,success:true}}async runPluginCommand(e){await Ql(e.command,e.args,{timeout:3e4,env:process.env});}isAlreadyInstalledError(e){let t=`${e.message??""}
116
- ${e.stderr??""}`.toLowerCase();return t.includes("already installed")||t.includes("already exists")||t.includes("already registered")}formatPluginCommandError(e,t){return t.code==="ENOENT"?`${e} not found. Is ${e} installed and on your PATH?`:t.killed?"Plugin installation timed out after 30 seconds":t.stderr?`Plugin installation failed: ${t.stderr.trim()}`:`Plugin installation failed: ${t.message}`}async configureCICD(e,t){if(!await confirm({message:"Set up a CI/CD pipeline to automatically index your project?",default:true,theme:F}))return;let o=new Ve(t),s=await o.detectPlatforms(),a;if(s.length===1){let m=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${m}. Configure Constellation CI/CD for this platform?`,default:true,theme:F}))return;a=s[0];}else a=await select({message:"Select CI/CD platform:",choices:[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],theme:F});let l=a==="github"?await o.githubWorkflowExists():await o.gitlabJobExists();if(l&&!await confirm({message:"Constellation CI/CD configuration already exists. Overwrite?",default:false,theme:F})){console.log(`${v} Skipping CI/CD configuration`);return}let c;try{c=a==="github"?await o.createGitHubWorkflow(e):await o.createOrMergeGitLabCI(e);}catch(m){console.log(`${b} Failed to configure CI/CD pipeline: ${m.message}`);return}let d=Gt(c,process.cwd());console.log(a==="github"?`${S} Created ${d}`:`${S} ${l?"Updated":"Created"} ${d} with Constellation indexing`);try{await this.git.stageFile(c),console.log(`${S} Added ${d} to staged changes in git`);}catch{console.log(`${b} Could not stage ${d} in git`);}a==="github"?(console.log(`${v} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${v} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(n=>({...n,checked:t.includes(n.value)}))}};});var zt,oo=y(()=>{at();Ft();q();D();zt=class i{constructor(e,t,n,o,s){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await C.fileIsReadable(e)){let n=await C.readFile(e),o=JSON.parse(n),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${I} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new ne("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new ne(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var Ht,Ar,Dr,Or,Wt,ao=y(()=>{q();Ht=class{getVariable(e){return Promise.resolve(process.env[e])}getSourceFile(){}isCIEnvironment(){return this.isCI()}isCI(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}validateInput(e,t){if(!e||typeof e!="string")throw new Error("Invalid key provided");if(t==null)throw new Error("Invalid value provided");if(!/^[A-Z_][A-Z0-9_]*$/i.test(e))throw new Error("Environment variable name must contain only letters, numbers, and underscores");if(t.includes("\0"))throw new Error("Value contains invalid characters");if(t.includes(`
117
- `)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Ar=class extends Ht{async getVariable(e){try{let t=await this.queryRegistry("HKCU\\Environment",e);if(t)return process.env[e]=t,t;delete process.env[e];return}catch{return}}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
118
- Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let s=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0?n():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let o=(await new Promise((s,a)=>{let l=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",d="";l.stdout?.on("data",m=>{c+=m.toString();}),l.stderr?.on("data",m=>{d+=m.toString();}),l.on("close",m=>{m===0?s(c):a(new Error(`reg query failed: ${d}`));}),l.on("error",m=>{a(m);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},Dr=class extends Ht{userConfigFiles;constructor(){super(),this.userConfigFiles=[N.join(Ie.homedir(),".zshenv"),N.join(Ie.homedir(),".profile")];}getSourceFile(){let e=process.env.SHELL??"";return e.endsWith("/zsh")||e.endsWith("/zsh5")?this.userConfigFiles.find(t=>t.endsWith(".zshenv")):this.userConfigFiles.find(t=>t.endsWith(".profile"))}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
112
+ ${v} Please run this command from the root directory of a git repository.`);let l=await this.git.getRootDir(),[c,m]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:u}=c,d=m.filter(E=>E!==u),g=u?[u,...d]:d,f=await input({message:"Constellation Project ID:",default:o?.projectId??"",validate:E=>E.trim().length>0||"Project ID is required",theme:F}),h=await select({message:"Branch to index:",choices:g.map(E=>({name:E,value:E})),default:o?.branch??g[0],theme:F}),_=(await checkbox({message:"Select Language(s):",choices:this.buildLanguageChoices(o),required:!0,theme:F})).reduce((E,A)=>(E[A]={fileExtensions:Ue[A]||[]},E),{});console.log(""),console.log(`${v} Checking for LSP servers...`);for(let[E,A]of Object.entries(_)){let L=oe.get(E);if(!L)continue;let J=!1,Z="";if(ht(L.command)&&(J=!0,Z="system"),!J){let R=N__default.join(bt,L.command);existsSync(R)&&(J=!0,Z="managed");}if(J)console.log(` ${S} ${E}: Found ${L.command} (${Z})`),A.lsp={command:L.command,args:L.args};else if(await confirm({message:`${E}: ${L.command} not found. Install to ~/.constellation/lsp-servers/?`,default:!0,theme:F}))try{console.log(` ${v} Installing ${L.npmPackages.join(", ")}...`),execFileSync("npm",["install","--prefix",pr,...L.npmPackages],{stdio:"pipe"}),console.log(` ${S} ${E}: Installed ${L.command}`),A.lsp={command:L.command,args:L.args};}catch{console.log(` ${I} ${E}: Installation failed`),A.lspEnrichment=!1;}else A.lspEnrichment=!1;}let w=Object.entries(_).filter(([,E])=>E.lspEnrichment!==!1).map(([E])=>E);w.length>0?console.log(`${S} Index enrichment enabled for: ${w.map(Ge).join(", ")}`):console.log(`${b} No language servers configured. Index enrichment will be skipped.`);let P={projectId:f.trim(),branch:h,languages:{..._},...w.length>0&&{lspEnrichment:!0}},K=JSON.stringify(P,void 0,2);await C.writeFile(n,K),console.log(`${S} ${s?"Updated":"Initialized"} configuration file at ${Wt(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${S} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&l&&await this.configureCICD(h,l);}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")return;let n=t.message??"An unexpected error occurred";console.error(`${I} Failed to initialize configuration file.
113
+ ${n}`);}}async configureMCPServers(){if(!await confirm({message:"Automatically configure Constellation for AI coding assistants?",default:true,theme:F}))return;let t=await checkbox({message:"Select AI coding assistants to configure:",choices:Dr.map(u=>({name:u.displayName,value:u.id})),required:true,theme:F}),n=new zt(process.cwd()),o=[];for(let u of t){let d=oo(u);if(d)if(console.log(` ${v} Configuring ${d.displayName}...`),d.pluginInstallCommand){let g=await this.executePluginInstall(d);o.push(g),g.success?console.log(` ${S} ${d.displayName} plugin installed successfully`):console.log(` ${b} ${d.displayName}: ${g.error}`);}else if(d.isGlobalConfig&&d.getGlobalConfigPaths){let g=await n.configureGlobalTool(d),f=false;for(let h of g)o.push(h),h.success?(f=true,console.log(` ${S} ${h.tool.displayName} configured at ${Wt(h.configuredPath,process.cwd())}`)):h.error&&console.log(` ${b} ${h.tool.displayName}: ${h.error}`);if(f){let h=d.id==="cline"?"global VS Code settings":"global settings";console.log(` ${v} Note: ${d.displayName} uses ${h} (not project-level)`);}if(g.length===0){let h=d.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${b} ${d.displayName}: ${h}`);}}else {let g=await n.configureTool(d);o.push(g),g.success?(console.log(` ${S} ${d.displayName} configured at ${Wt(g.configuredPath,process.cwd())}`),d.permissionsConfig&&console.log(` ${S} ${d.displayName} permissions set in ${d.permissionsConfig.filePath}`)):console.log(` ${b} ${d.displayName}: ${g.error}`);}}if(o.find(u=>u.tool.id==="claude-code"&&u.success)){let u=N__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(u),console.log(` ${S} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${b} Could not stage .claude/settings.json in git`);}}if(o.find(u=>u.tool.id==="codex-cli"&&u.success)){let u=N__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(u),console.log(` ${S} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(u=>u.tool.id==="opencode"&&u.success)){let u=N__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(u),console.log(` ${S} Added opencode.jsonc to staged changes in git`);}catch{}}let c=o.filter(u=>u.success).length,m=o.filter(u=>!u.success).length;console.log(`
114
+ ${S} Plugin + MCP configuration complete: ${c} configured`),m>0&&console.log(`${b} ${m} tool(s) could not be configured`),console.log(`
115
+ ${v} Some tools may require restart to pick up new configuration.`);}async executePluginInstall(e){let t=e.pluginInstallCommand;try{await this.runPluginCommand(t);}catch(n){let o=n;if(e.pluginUpdateCommand&&this.isAlreadyInstalledError(o)){console.log(` ${v} ${e.displayName} extension already installed, attempting update...`);try{await this.runPluginCommand(e.pluginUpdateCommand);}catch(s){let a=s;return {tool:e,success:false,error:this.formatPluginCommandError(e.pluginUpdateCommand.command,a)}}}else if(this.isAlreadyInstalledError(o)&&(e.pluginPostInstallCommands?.length??0)>0)console.log(` ${v} ${e.displayName} plugin source already configured, continuing...`);else return {tool:e,success:false,error:this.formatPluginCommandError(t.command,o)}}for(let n of e.pluginPostInstallCommands??[])try{await this.runPluginCommand(n);}catch(o){let s=o;return {tool:e,success:false,error:this.formatPluginCommandError(n.command,s)}}return {tool:e,success:true}}async runPluginCommand(e){await uc(e.command,e.args,{timeout:3e4,env:process.env});}isAlreadyInstalledError(e){let t=`${e.message??""}
116
+ ${e.stderr??""}`.toLowerCase();return t.includes("already installed")||t.includes("already exists")||t.includes("already registered")}formatPluginCommandError(e,t){return t.code==="ENOENT"?`${e} not found. Is ${e} installed and on your PATH?`:t.killed?"Plugin installation timed out after 30 seconds":t.stderr?`Plugin installation failed: ${t.stderr.trim()}`:`Plugin installation failed: ${t.message}`}async configureCICD(e,t){if(!await confirm({message:"Set up a CI/CD pipeline to automatically index your project?",default:true,theme:F}))return;let o=new qe(t),s=await o.detectPlatforms(),a;if(s.length===1){let u=s[0]==="github"?"GitHub Actions":"GitLab CI";if(!await confirm({message:`Detected ${u}. Configure Constellation CI/CD for this platform?`,default:true,theme:F}))return;a=s[0];}else a=await select({message:"Select CI/CD platform:",choices:[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],theme:F});let l=a==="github"?await o.githubWorkflowExists():await o.gitlabJobExists();if(l&&!await confirm({message:"Constellation CI/CD configuration already exists. Overwrite?",default:false,theme:F})){console.log(`${v} Skipping CI/CD configuration`);return}let c;try{c=a==="github"?await o.createGitHubWorkflow(e):await o.createOrMergeGitLabCI(e);}catch(u){console.log(`${b} Failed to configure CI/CD pipeline: ${u.message}`);return}let m=Wt(c,process.cwd());console.log(a==="github"?`${S} Created ${m}`:`${S} ${l?"Updated":"Created"} ${m} with Constellation indexing`);try{await this.git.stageFile(c),console.log(`${S} Added ${m} to staged changes in git`);}catch{console.log(`${b} Could not stage ${m} in git`);}a==="github"?(console.log(`${v} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${v} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){let t=e?.languages?Object.keys(e.languages):[];return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}].map(n=>({...n,checked:t.includes(n.value)}))}};});var Ht,uo=y(()=>{ct();kt();Y();D();Ht=class i{constructor(e,t,n,o,s){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.lspEnrichment=s;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await C.fileIsReadable(e)){let n=await C.readFile(e),o=JSON.parse(n),s=new i(o.branch,o.languages,o.projectId,o.exclude,o.lspEnrichment);return s.validate(),s}else throw new Error(`${I} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new re("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new re(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var Kt,Ur,Gr,zr,Jt,go=y(()=>{Y();Kt=class{getVariable(e){return Promise.resolve(process.env[e])}getSourceFile(){}isCIEnvironment(){return this.isCI()}isCI(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}validateInput(e,t){if(!e||typeof e!="string")throw new Error("Invalid key provided");if(t==null)throw new Error("Invalid value provided");if(!/^[A-Z_][A-Z0-9_]*$/i.test(e))throw new Error("Environment variable name must contain only letters, numbers, and underscores");if(t.includes("\0"))throw new Error("Value contains invalid characters");if(t.includes(`
117
+ `)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Ur=class extends Kt{async getVariable(e){try{let t=await this.queryRegistry("HKCU\\Environment",e);if(t)return process.env[e]=t,t;delete process.env[e];return}catch{return}}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
118
+ Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let s=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),a="";s.stderr?.on("data",l=>{a+=l.toString();}),s.on("close",l=>{l===0?n():o(new Error(`setx failed with code ${l}: ${a}`));}),s.on("error",l=>{o(l);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let o=(await new Promise((s,a)=>{let l=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",m="";l.stdout?.on("data",u=>{c+=u.toString();}),l.stderr?.on("data",u=>{m+=u.toString();}),l.on("close",u=>{u===0?s(c):a(new Error(`reg query failed: ${m}`));}),l.on("error",u=>{a(u);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},Gr=class extends Kt{userConfigFiles;constructor(){super(),this.userConfigFiles=[N.join(Ne.homedir(),".zshenv"),N.join(Ne.homedir(),".profile")];}getSourceFile(){let e=process.env.SHELL??"";return e.endsWith("/zsh")||e.endsWith("/zsh5")?this.userConfigFiles.find(t=>t.endsWith(".zshenv")):this.userConfigFiles.find(t=>t.endsWith(".profile"))}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
119
119
  Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),o=`export ${e}="${n}"`;try{for(let s of this.userConfigFiles)await this.writeToConfigFile(s,e,o);process.env[e]=t;}catch(s){throw new Error(`Failed to set environment variable ${e}: ${s}`)}}async writeToConfigFile(e,t,n){let o="";try{o=await C.readFile(e,"utf-8");}catch{}let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^export ${s}=.*$`,"gm");a.test(o)?o=o.replace(a,n):o=o.trimEnd()+`
120
120
  `+n+`
121
- `,await C.writeFile(e,o);}},Or=class{static create(){let e=Ie.platform();switch(e){case "win32":return new Ar;case "darwin":case "linux":return new Dr;default:throw new Error(`Unsupported platform: ${e}`)}}},Wt=class{manager;constructor(){this.manager=Or.create();}async setKey(e,t){await this.manager.setVariable(e.toUpperCase(),t);}async getKey(e){return this.manager.getVariable(e.toUpperCase())}isCI(){return this.manager.isCIEnvironment()}getSourceFile(){return this.manager.getSourceFile()}};});var Kt,lo=y(()=>{Kt=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let o of n.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=N__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function ec(){let i=Ie.platform();if(i==="darwin")return N.join(Ie.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||N.join(Ie.homedir(),"AppData","Local");return N.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||N.join(Ie.homedir(),".cache");return N.join(e,"constellation")}}var tc,rc,nc,Qe,Mr=y(()=>{tc=ec(),rc="update-state.json",nc=1440*60*1e3,Qe=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??tc,this.stateFile=N.join(this.stateDir,rc);}async load(){if(this.state)return this.state;try{let e=await B.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await B.mkdir(this.stateDir,{recursive:!0}),await B.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>nc}async recordCheck(){let e=await this.load();e.lastCheckTimestamp=Date.now(),await this.save(e);}async recordDecline(e){let t=await this.load();t.lastDeclinedVersion=e,t.lastDeclinedTimestamp=Date.now(),await this.save(t);}async wasVersionDeclined(e){return (await this.load()).lastDeclinedVersion===e}async clear(){try{await B.unlink(this.stateFile),this.state=null;}catch{}}};});var Ze,Br=y(()=>{Ze=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var et,Ur=y(()=>{lt();D();et=class{async promptForUpdate(e,t,n){console.log(""),console.log(p.cyan("\u2501".repeat(60))),console.log(`${te} ${p.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${p.dim(e)}`),console.log(` Latest version: ${p.green.bold(t)}`),console.log(""),console.log(` ${p.dim(`Package manager: ${n}`)}`),console.log(p.cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:F})}catch{return false}}};});async function Gr(i){return new Vt().check(i)}var sc,Jt,ac,Vt,co=y(()=>{D();Mr();Br();Ur();sc="https://registry.npmjs.org",Jt="@constellationdev/cli",ac=5e3,Vt=class{cache;packageManager;prompter;constructor(){this.cache=new Qe,this.packageManager=new Ze,this.prompter=new et;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,n=setTimeout(()=>t.abort(),ac);try{let o=await fetch(`${sc}/${Jt}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let a=(await o.json()).version;return {current:e,latest:a,hasUpdate:this.isNewerVersion(a,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=a=>a.split("-")[0],o=n(e).split(".").map(Number),s=n(t).split(".").map(Number);for(let a=0;a<3;a++){let l=o[a]||0,c=s[a]||0;if(l>c)return true;if(l<c)return false}return false}async performUpdate(){return console.log(`
122
- ${v} Updating ${Jt}...
123
- `),await this.packageManager.executeUpdate(Jt)?(console.log(`
121
+ `,await C.writeFile(e,o);}},zr=class{static create(){let e=Ne.platform();switch(e){case "win32":return new Ur;case "darwin":case "linux":return new Gr;default:throw new Error(`Unsupported platform: ${e}`)}}},Jt=class{manager;constructor(){this.manager=zr.create();}async setKey(e,t){await this.manager.setVariable(e.toUpperCase(),t);}async getKey(e){return this.manager.getVariable(e.toUpperCase())}isCI(){return this.manager.isCIEnvironment()}getSourceFile(){return this.manager.getSourceFile()}};});var Vt,fo=y(()=>{Vt=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let o of n.fileExtensions)this.extensionToLanguageMap.set(o,t);}detectLanguage(e){let t=N__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function mc(){let i=Ne.platform();if(i==="darwin")return N.join(Ne.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||N.join(Ne.homedir(),"AppData","Local");return N.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||N.join(Ne.homedir(),".cache");return N.join(e,"constellation")}}var gc,fc,hc,Ze,Wr=y(()=>{gc=mc(),fc="update-state.json",hc=1440*60*1e3,Ze=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??gc,this.stateFile=N.join(this.stateDir,fc);}async load(){if(this.state)return this.state;try{let e=await B.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await B.mkdir(this.stateDir,{recursive:!0}),await B.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>hc}async recordCheck(){let e=await this.load();e.lastCheckTimestamp=Date.now(),await this.save(e);}async recordDecline(e){let t=await this.load();t.lastDeclinedVersion=e,t.lastDeclinedTimestamp=Date.now(),await this.save(t);}async wasVersionDeclined(e){return (await this.load()).lastDeclinedVersion===e}async clear(){try{await B.unlink(this.stateFile),this.state=null;}catch{}}};});var et,Hr=y(()=>{et=class{detectedManager=null;detect(){if(this.detectedManager)return this.detectedManager;let e=process.env.npm_config_user_agent;return e?e.startsWith("yarn")?this.detectedManager="yarn":e.startsWith("pnpm")?this.detectedManager="pnpm":e.startsWith("bun")?this.detectedManager="bun":this.detectedManager="npm":this.detectedManager="npm",this.detectedManager}getUpdateCommand(e){switch(this.detect()){case "yarn":return ["yarn","global","add",`${e}@latest`];case "pnpm":return ["pnpm","add","-g",`${e}@latest`];case "bun":return ["bun","add","-g",`${e}@latest`];default:return ["npm","install","-g",`${e}@latest`]}}getUpdateCommandString(e){return this.getUpdateCommand(e).join(" ")}async executeUpdate(e){let[t,...n]=this.getUpdateCommand(e);return new Promise(o=>{let s=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});s.on("close",a=>{o(a===0);}),s.on("error",()=>{o(false);});})}};});var tt,Kr=y(()=>{pt();D();tt=class{async promptForUpdate(e,t,n){console.log(""),console.log(p.cyan("\u2501".repeat(60))),console.log(`${ee} ${p.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${p.dim(e)}`),console.log(` Latest version: ${p.green.bold(t)}`),console.log(""),console.log(` ${p.dim(`Package manager: ${n}`)}`),console.log(p.cyan("\u2501".repeat(60))),console.log("");try{return await confirm({message:"Would you like to update now?",default:!0,theme:F})}catch{return false}}};});async function Jr(i){return new Yt().check(i)}var vc,qt,Sc,Yt,ho=y(()=>{D();Wr();Hr();Kr();vc="https://registry.npmjs.org",qt="@constellationdev/cli",Sc=5e3,Yt=class{cache;packageManager;prompter;constructor(){this.cache=new Ze,this.packageManager=new et,this.prompter=new tt;}async check(e){if(!await this.cache.shouldCheck())return false;try{let t=await this.fetchLatestVersion(e);return await this.cache.recordCheck(),!t.hasUpdate||await this.cache.wasVersionDeclined(t.latest)?!1:await this.prompter.promptForUpdate(t.current,t.latest,this.packageManager.detect())?await this.performUpdate():(await this.cache.recordDecline(t.latest),!1)}catch{return false}}async fetchLatestVersion(e){let t=new AbortController,n=setTimeout(()=>t.abort(),Sc);try{let o=await fetch(`${vc}/${qt}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let a=(await o.json()).version;return {current:e,latest:a,hasUpdate:this.isNewerVersion(a,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=a=>a.split("-")[0],o=n(e).split(".").map(Number),s=n(t).split(".").map(Number);for(let a=0;a<3;a++){let l=o[a]||0,c=s[a]||0;if(l>c)return true;if(l<c)return false}return false}async performUpdate(){return console.log(`
122
+ ${v} Updating ${qt}...
123
+ `),await this.packageManager.executeUpdate(qt)?(console.log(`
124
124
  ${S} Update complete! Please re-run your command.
125
125
  `),true):(console.log(`
126
- ${b} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Jt)}
127
- `),false)}};});var po=y(()=>{Mr();Br();Ur();co();});function cc(){return lc.some(i=>!!process.env[i])}function pc(){return !!process.stdout.isTTY}function uo(){return !cc()&&pc()}var lc,mo=y(()=>{lc=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var tt,go=y(()=>{tt=class{git;constructor(e){let t={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(t);}async getLatestCommitHash(){let e=await this.git.log({maxCount:1});if(!e.latest)throw new Error("No commits found in repository");return e.latest.hash}async getCommitTimestamp(){let t=(await this.git.raw(["log","-1","--format=%aI"])).trim();if(!t)throw new Error("No commits found in repository");return t}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.split(" ");if(a.length<2)continue;let l=a[0];l==="A"?n.added.push(a[1]):l==="M"?n.modified.push(a[1]):l==="D"?n.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&n.renamed.push({from:a[1],to:a[2]});}return n}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(n=>n.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,n=e.current;return {clean:t,currentBranch:n}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(o,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
128
- Modified: ${o.modified}, Created: ${o.created}, Deleted: ${o.deleted}, Conflicted: ${o.conflicted}, Staged: ${o.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let o=await this.git.status();if(o.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",o.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${o.conflicted.length} file(s): ${o.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};});var fc={};var fo,Hr,Wr,rt,ho=y(async()=>{at();wn();zi();io();oo();ao();lo();Nt();po();qt();ct();mo();go();D();process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${I} An unexpected error occurred during the index attempt:
129
- ${i?.message??String(i)}`),process.exit(1);});fo=globalThis.__constellationVersion??(()=>{let i=N__default.dirname(fileURLToPath(import.meta.url)),e=N__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(uo()){let i=process.argv[2];["auth","help","init","index"].includes(i)?er(i):er(),nt.includes(i)||await Gr(fo)&&process.exit(0);}Hr=process.cwd(),Wr=new Wt,rt=new Command;rt.name("constellation").description("Connecting stars in your code into intelligent patterns").version(fo);rt.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new tt(Hr)};await new Ye(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){console.error(`${I} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});rt.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:Wr};await new De(e).run(i.manual);}catch(e){console.error(`${I} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});rt.command("index").description("Create or update the Constellation data indices for the current project").option("--full","Conduct a full project re-index").option("--incremental","Conduct an incremental project index update").option("--dirty","Skip git validation checks (branch and working tree status)").option("--no-enrich","Skip LSP enrichment (only perform parse tree indexing)").action(async i=>{try{let e=await zt.loadFromFile(N__default.join(Hr,"constellation.json")),t=new tt(Hr),n=new It(e),o=new Kt(e),s={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:Wr},a=Wr.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,d=!0;!i.full&&!i.incremental&&a&&console.log(`${v} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new Je(s).run(l,c,d);}catch(e){!(e instanceof T)&&!(e instanceof M)&&console.error(`${I} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});rt.parse();});var bo=/^>=\s*\d+\.\d+\.\d+$/;function Yr(i,e=process.version){if(!bo.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),n=e.replace(/^v/,""),o=t.split(".").map(Number),s=n.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,d=s[l]||0;if(d>c)break;if(d<c){a=false;break}}return {compatible:a,current:e,required:i}}qt();var Sc=dirname(fileURLToPath(import.meta.url)),Cc=join(Sc,"..","package.json"),Kr=JSON.parse(readFileSync(Cc,"utf-8")),wc=process.argv[2];if(!nt.includes(wc)&&Kr.engines?.node){let i=Yr(Kr.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=Kr.version;await ho().then(()=>fc);
126
+ ${b} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(qt)}
127
+ `),false)}};});var yo=y(()=>{Wr();Hr();Kr();ho();});function _c(){return Cc.some(i=>!!process.env[i])}function wc(){return !!process.stdout.isTTY}function bo(){return !_c()&&wc()}var Cc,vo=y(()=>{Cc=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var rt,So=y(()=>{rt=class{git;constructor(e){let t={baseDir:e,maxConcurrentProcesses:6};this.git=simpleGit(t);}async getLatestCommitHash(){let e=await this.git.log({maxCount:1});if(!e.latest)throw new Error("No commits found in repository");return e.latest.hash}async getCommitTimestamp(){let t=(await this.git.raw(["log","-1","--format=%aI"])).trim();if(!t)throw new Error("No commits found in repository");return t}async getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.split(" ");if(a.length<2)continue;let l=a[0];l==="A"?n.added.push(a[1]):l==="M"?n.modified.push(a[1]):l==="D"?n.deleted.push(a[1]):l.startsWith("R")&&a.length>=3&&n.renamed.push({from:a[1],to:a[2]});}return n}async getRemoteOriginUrl(){let t=(await this.git.getRemotes(true)).find(n=>n.name==="origin");if(!t||!t.refs.fetch)throw new Error("Remote origin URL not found or has no fetch URL");return t.refs.fetch}async getRootDir(){try{return (await this.git.revparse(["--show-toplevel"])).trim()}catch{return null}}async isGitAvailable(){try{return await this.git.version(),!0}catch{return false}}async isGitRepository(){try{return await this.git.checkIsRepo()}catch{return false}}async listBranches(){return (await this.git.branchLocal()).all}async stageFile(e){await this.git.add(e);}async status(){let e=await this.git.status(),t=e.files?.length===0,n=e.current;return {clean:t,currentBranch:n}}async pull(){try{let e=await this.git.status();if(!e.isClean()){let o={modified:e.modified.length,created:e.created.length,deleted:e.deleted.length,conflicted:e.conflicted.length,staged:e.staged.length};throw console.error("\u274C Cannot pull: Working directory has uncommitted changes"),console.error(" Details:",JSON.stringify(o,null,2)),e.conflicted.length>0&&console.error(" \u26A0\uFE0F Conflicted files:",e.conflicted.join(", ")),new Error(`Cannot pull with uncommitted changes. Please commit or stash your changes first.
128
+ Modified: ${o.modified}, Created: ${o.created}, Deleted: ${o.deleted}, Conflicted: ${o.conflicted}, Staged: ${o.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let o=await this.git.status();if(o.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",o.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${o.conflicted.length} file(s): ${o.conflicted.join(", ")}`)}t.summary.changes>0&&console.log(`\u2705 Pull successful: ${t.summary.changes} files changed, ${t.summary.insertions} insertions(+), ${t.summary.deletions} deletions(-)`);let n=await this.git.status();if(n.conflicted.length>0)throw console.error("\u274C Unexpected conflicts after pull:"),console.error(" Conflicted files:",n.conflicted.join(", ")),new Error(`Unexpected merge conflicts detected after pull: ${n.conflicted.join(", ")}`);return !0}catch(e){throw e instanceof Error?(e.message.includes("CONFLICT")?(console.error("\u274C Pull failed due to merge conflicts"),console.error(' Run "git status" to see conflicted files'),console.error(' Resolve conflicts, then run "git add" and "git commit"')):e.message.includes("not a git repository")?console.error("\u274C Pull failed: Not in a git repository"):e.message.includes("Could not resolve host")||e.message.includes("unable to access")?console.error("\u274C Pull failed: Network error - unable to reach remote repository"):e.message.includes("Authentication failed")?console.error("\u274C Pull failed: Authentication error - check your credentials"):e.message.includes("uncommitted changes")&&console.error("\u274C Pull failed: Uncommitted changes in working directory"),new Error(`Git pull operation failed: ${e.message}`,{cause:e})):new Error(`Git pull operation failed: ${String(e)}`)}}};});var Rc={};var Co,Vr,qr,Nc,nt,_o=y(async()=>{ct();En();qi();po();uo();go();fo();Tt();yo();Qt();ut();vo();So();D();process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${I} An unexpected error occurred during the index attempt:
129
+ ${i?.message??String(i)}`),process.exit(1);});Co=globalThis.__constellationVersion??(()=>{let i=N__default.dirname(fileURLToPath(import.meta.url)),e=N__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(bo()){let i=process.argv[2];["auth","help","init","index"].includes(i)?or(i):or(),it.includes(i)||await Jr(Co)&&process.exit(0);}Vr=process.cwd(),qr=new Jt,Nc=(()=>{let i=process.argv[1];return i&&N__default.basename(i).replace(/\.(c|m)?js$/i,"")==="const"?"const":"constellation"})(),nt=new Command;nt.name(Nc).description("Connecting stars in your code into intelligent patterns").version(Co);nt.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new rt(Vr)};await new Xe(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){console.error(`${I} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});nt.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:qr};await new Oe(e).run(i.manual);}catch(e){console.error(`${I} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});nt.command("index").description("Create or update the Constellation data indices for the current project").option("--full","Conduct a full project re-index").option("--incremental","Conduct an incremental project index update").option("--dirty","Skip git validation checks (branch and working tree status)").option("--no-enrich","Skip LSP enrichment (only perform parse tree indexing)").action(async i=>{try{let e=await Ht.loadFromFile(N__default.join(Vr,"constellation.json")),t=new rt(Vr),n=new Rt(e),o=new Vt(e),s={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:qr},a=qr.isCI(),l=i.full||!i.incremental&&a,c=i.dirty||!1,m=!0;!i.full&&!i.incremental&&a&&console.log(`${v} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new Ve(s).run(l,c,m);}catch(e){!(e instanceof $)&&!(e instanceof M)&&console.error(`${I} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});nt.parse();});var xo=/^>=\s*\d+\.\d+\.\d+$/;function Qr(i,e=process.version){if(!xo.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),n=e.replace(/^v/,""),o=t.split(".").map(Number),s=n.split(".").map(Number),a=true;for(let l=0;l<3;l++){let c=o[l]||0,m=s[l]||0;if(m>c)break;if(m<c){a=false;break}}return {compatible:a,current:e,required:i}}Qt();var Fc=dirname(fileURLToPath(import.meta.url)),Ac=join(Fc,"..","package.json"),Yr=JSON.parse(readFileSync(Ac,"utf-8")),kc=process.argv[2];if(!it.includes(kc)&&Yr.engines?.node){let i=Qr(Yr.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=Yr.version;await _o().then(()=>Rc);
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@constellationdev/cli",
3
3
  "description": "Codebase Understanding for AI Coding Agents",
4
- "version": "0.6.2",
4
+ "version": "0.7.1",
5
5
  "author": "ShiftinBits Inc",
6
6
  "main": "dist/main.js",
7
7
  "type": "module",
8
8
  "types": "dist/index.d.ts",
9
9
  "bin": {
10
- "constellation": "dist/main.js"
10
+ "constellation": "dist/main.js",
11
+ "const": "dist/main.js"
11
12
  },
12
13
  "scripts": {
13
14
  "build": "rimraf dist && tsup",
@@ -23,14 +24,14 @@
23
24
  "prepare": "node -e \"try{require('husky').default()}catch(e){}\""
24
25
  },
25
26
  "dependencies": {
26
- "@constellationdev/types": "^1.1.0",
27
+ "@constellationdev/types": "^1.1.1",
27
28
  "@iarna/toml": "^3.0.0",
28
29
  "@inquirer/prompts": "^8.4.1",
29
30
  "@scure/base": "^2.0.0",
30
31
  "ansi-colors": "^4.1.3",
31
32
  "commander": "^14.0.1",
32
33
  "ignore": "^7.0.5",
33
- "simple-git": "^3.28.0",
34
+ "simple-git": "^3.36.0",
34
35
  "tree-sitter": "^0.21.1",
35
36
  "tree-sitter-javascript": "^0.21.4",
36
37
  "tree-sitter-python": "^0.21.0",
@@ -62,8 +63,8 @@
62
63
  "typescript": "~5.9.3"
63
64
  },
64
65
  "engines": {
65
- "node": ">=24.0.0",
66
- "npm": ">=11.0.0"
66
+ "node": ">=20.0.0",
67
+ "npm": ">=10.0.0"
67
68
  },
68
69
  "files": [
69
70
  "dist"