@constellationdev/cli 0.1.6 → 0.1.7

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 (2) hide show
  1. package/dist/index.js +5 -5
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import*as _ from'path';import ___default from'path';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import*as He from'fs';import {readFileSync}from'fs';import {fileURLToPath}from'url';import {Command}from'commander';import {Agent,fetch as fetch$1}from'undici';import {base32}from'@scure/base';import {Readable}from'stream';import c from'ansi-colors';import*as ee from'os';import ee__default from'os';import Pn from'enquirer';import {performance}from'perf_hooks';import*as T from'fs/promises';import T__default from'fs/promises';import Vn from'tree-sitter';import Mt from'ignore';import {z as z$1}from'zod';import {promisify}from'util';import tt from'zlib';import {pipeline}from'stream/promises';import hr from'tree-sitter-javascript';import yr from'tree-sitter-python';import wr from'tree-sitter-typescript';import {findAll,parse}from'tsconfck';import {spawn}from'child_process';import {simpleGit}from'simple-git';var In=Object.defineProperty;var j=(s,e)=>()=>(s&&(e=s(s=0)),e);var kt=(s,e)=>{for(var t in e)In(s,t,{get:e[t],enumerable:true});};function Ft(s){return s.replace(/\\/g,"/")}function Te(s){return Ft(s).replace(/^\.?\//,"")}function H(s,e){return Ft(_.relative(s,e))}var Y=j(()=>{});async function U(s,e,t,n,r){let o=await t.resolve(s),i=Ut(s,o),a=r(s,o,i),l=i?void 0:Te(o);n[e.toString()]={source:s,resolvedPath:l,isExternal:i,importType:a};}function Ut(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var nt,ae=j(()=>{Y();nt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function Zn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}async function Qn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}function je(){return {language:"javascript",handlers:new Map([["import_statement",Zn],["export_statement",Qn]])}}function rt(){return {...je(),language:"typescript"}}var ot=j(()=>{ae();});async function nr(s,e,t,n){let r=s.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let i=r.childForFieldName("name");o=i?i.text:r.text;}else o=r.text;await U(o,s.startPosition.row,e,t,n);}async function rr(s,e,t,n){let r,o=s.childForFieldName("module_name");if(o)r=o.text;else {let i="";for(let a=0;a<s.childCount;a++){let l=s.child(a);if(l){if(l.type==="relative_import"){i=l.text;break}(l.type==="."||l.type==="import_prefix")&&(i+=l.text);}}r=i||".";}await U(r,s.startPosition.row,e,t,n);}async function or(s,e,t,n){await U("__future__",s.startPosition.row,e,t,n);}function it(){return {language:"python",handlers:new Map([["import_statement",nr],["import_from_statement",rr],["future_import_statement",or]]),classifyImportType:tr}}var tr,Ae=j(()=>{ae();tr=(s,e,t)=>{if(t)return "external";if(/^\.+/.test(s))return "relative";let n=s.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Gt,Wt=j(()=>{ot();Ae();ae();ot();Ae();Gt=[je(),rt(),it()];});var Kt={};kt(Kt,{ImportExtractor:()=>st});var st,Vt=j(()=>{Wt();ae();st=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Gt)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,r){if(!r)return {};let o=this.languageHandlers.get(n);if(!o)return {};let i=this.classifiers.get(n)??nt,a={};return await this.walkAST(e.rootNode,async l=>{let g=o.get(l.type);g&&await g(l,r,a,i);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let r=e.child(n);r&&await this.walkAST(r,t);}}};});var ce,Jt,at,Yt,qt,Le=j(()=>{ce=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"]),Jt=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"]),at={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"]},Yt={language:"javascript",textIncludedTypes:Jt,fieldNames:at},qt={language:"typescript",textIncludedTypes:Jt,fieldNames:at};});var ir,Xt,Zt,ct=j(()=>{ir=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"]),Xt={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"]},Zt={language:"python",textIncludedTypes:ir,fieldNames:Xt,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function Qt(s){return le.get(s)}function en(s){if(!s)return ce;let e=le.get(s);if(!e)return ce;let t=new Set(ce);for(let n of e.textIncludedTypes)t.add(n);return t}function lt(s){if(!s){let t=Array.from(le.values()).map(n=>n.fieldNames);return pe(...t)}let e=le.get(s);if(!e){let t=Array.from(le.values()).map(n=>n.fieldNames);return pe(...t)}return e.fieldNames}var le,tn=j(()=>{pt();Le();ct();Le();Le();ct();le=new Map([["javascript",Yt],["typescript",qt],["python",Zt]]);});var an={};kt(an,{COMMON_FIELD_NAMES:()=>ut,JS_TS_FIELD_NAMES:()=>on,PYTHON_FIELD_NAMES:()=>sn,TEXT_INCLUDED_TYPES:()=>nn,mergeFieldMaps:()=>pe,serializeAST:()=>ar,serializeASTStream:()=>sr});function*sr(s,e,t){yield*dt(s,e,t);}function*dt(s,e,t){if(yield "{",yield `"type":${JSON.stringify(s.type)}`,yield `,"startPosition":${JSON.stringify({row:s.startPosition.row,column:s.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:s.endPosition.row,column:s.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),rn(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let r=(t?lt(t):ut)[s.type]||[],o=new Set,i=true;for(let a of r){let l=s.childForFieldName(a);l&&(i||(yield ","),i=false,o.add(l),yield*dt(l,a,t));}for(let a=0;a<s.childCount;a++){let l=s.child(a);l&&!o.has(l)&&(i||(yield ","),i=false,yield*dt(l,void 0,t));}yield "]";}yield "}";}async function ar(s,e,t){let n=gt(s,e,t),r=t?lt(t):ut,o=[{treeNode:s,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;o.length>0;){let i=o[o.length-1];if(i.childIndex===0&&i.treeNode.childCount>0){let a=r[i.treeNode.type]||[];for(let l of a){let g=i.treeNode.childForFieldName(l);if(g){i.fieldChildren.add(g);let d=gt(g,l,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(d),o.push({treeNode:g,serializedNode:d,fieldName:l,childIndex:0,fieldChildren:new Set});}}}if(i.childIndex<i.treeNode.childCount){let a=i.treeNode.child(i.childIndex);if(i.childIndex++,a&&!i.fieldChildren.has(a)){let l=gt(a,void 0,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(l),o.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else o.pop();}return n}function gt(s,e,t){let n={type:s.type,startPosition:{row:s.startPosition.row,column:s.startPosition.column},endPosition:{row:s.endPosition.row,column:s.endPosition.column},...e&&{fieldName:e}};return rn(s,t)&&(n.text=s.text),n}function rn(s,e){if(e){let n=Qt(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(s);if(o===false)return false;if(o===true)return true}return en(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:nn.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function pe(...s){let e={};for(let t of s)for(let[n,r]of Object.entries(t)){let i=[...e[n]||[]];for(let a of r)i.includes(a)||i.push(a);e[n]=i;}return e}var nn,on,sn,ut,pt=j(()=>{tn();nn=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","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"]);on={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"]},sn={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"]};ut=pe(on,sn);});function Nt(s){return base32.encode(Buffer.from(s))}function Rt(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Nt(n)}var Ee=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
- `,r=Buffer.from(n,"utf8");if(!this.push(r))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 kn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:ee.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 Nn="\u2714",Rn="\u2717",jn="\u26A0",An="\u2139",Ln="\u26A1",On="[OK]",Fn="[ERR]",Mn="[WARN]",Dn="[INFO]",Bn="[>>]",ie=kn(),h=c.green(ie?Nn:On),C=c.red(ie?Rn:Fn),y=c.yellow(ie?jn:Mn),m=c.blue(ie?An:Dn),F=c.yellow(ie?Ln:Bn);var be=class{constructor(e,t){this.config=e;this.accessKey=t;}apiVersion="intel/v1";async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new $(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new $(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new $(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new M("Project not found - no previous index exists");default:throw e.status===404?new M("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof $||t instanceof M?t:e.status===404?new M("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 r=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let o=await this.sendRequest(r,null,"GET");return !o||!o.ok?null:await o.json()}catch(o){if(o instanceof E)throw o;return null}}async deleteFiles(e){for(let t of e){let n=Rt(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,r,o,i){try{let{Readable:a}=await import('stream'),l=new Ee(e),g=a.toWeb(l),d=new Agent({headersTimeout:0,bodyTimeout:0}),p=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":r,"x-constellation-index":o?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...i&&{"x-commit-hash":i}},body:g,duplex:"half",dispatcher:d});if(p.status===401)throw new E("Authentication failed");if(p.status===409){let u="Indexing already in progress",f;try{let v=await p.json();u=v?.message||u,f=v?.details?.branchName;}catch{}throw new J(u,f)}if(p.status===200)try{let u=await p.json();if(u?.status==="current")return console.log(`${h} Index already up to date for ${r} at commit ${u.commitHash||"unknown"}`),!0}catch{}return p.ok===!0||p.status===202}catch(a){if(a instanceof E||a instanceof J)throw a;let l=a instanceof Error?a:new Error(String(a)),g="";if(l.message==="fetch failed"||a.code){let p=[],u=a.code||a.cause?.code;if(a.code&&p.push(`Error Code: ${a.code}`),a.cause){let f=a.cause;f.code&&p.push(`Cause Code: ${f.code}`),f.errno&&p.push(`Errno: ${f.errno}`),f.syscall&&p.push(`System Call: ${f.syscall}`),f.address&&p.push(`Address: ${f.address}`),f.port&&p.push(`Port: ${f.port}`);}u==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":u==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":u==="ENOTFOUND"?g="DNS lookup failed - check service URL":u==="ETIMEDOUT"?g="Connection timeout - service not responding":u==="ECONNRESET"?g="Connection reset by server":u==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",p.length>0&&(g+=` (${p.join(", ")})`);}else g=l.message;let d=new Error(`Failed to upload data to Constellation Service: ${g}`);throw d.cause=l,d.stack=`${d.stack}
3
+ `,r=Buffer.from(n,"utf8");if(!this.push(r))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 kn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:ee.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 Nn="\u2714",Rn="\u2717",jn="\u26A0",An="\u2139",Ln="\u26A1",On="[OK]",Fn="[ERR]",Mn="[WARN]",Dn="[INFO]",Bn="[>>]",ie=kn(),h=c.green(ie?Nn:On),C=c.red(ie?Rn:Fn),y=c.yellow(ie?jn:Mn),m=c.blue(ie?An:Dn),F=c.yellow(ie?Ln:Bn);var be=class{constructor(e,t){this.config=e;this.accessKey=t;}apiVersion="intel/v1";async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new $(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new $(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new $(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new M("Project not found - no previous index exists");default:throw e.status===404?new M("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof $||t instanceof M?t:e.status===404?new M("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 r=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let o=await this.sendRequest(r,null,"GET");return !o||!o.ok?null:await o.json()}catch(o){if(o instanceof E)throw o;return null}}async deleteFiles(e){for(let t of e){let n=Rt(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,r,o,i){try{let{Readable:a}=await import('stream'),l=new Ee(e),g=a.toWeb(l),d=new Agent({headersTimeout:0,bodyTimeout:0}),p=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":r,"x-constellation-index":o?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...i&&{"x-commit-hash":i}},body:g,duplex:"half",dispatcher:d});if(p.status===401)throw new E("Authentication failed");if(p.status===409){let f="Indexing already in progress",P;try{let v=await p.json();f=v?.message||f,P=v?.details?.branchName;}catch{}throw new J(f,P)}if(p.status===200)try{let f=await p.json();if(f?.status==="current")return console.log(`${h} Index already up to date for ${r} at commit ${f.commitHash||"unknown"}`),!0}catch{}if(p.ok||p.status===202)return !0;let u=`Server returned ${p.status}`;try{let f=await p.json();f?.message&&(u=Array.isArray(f.message)?f.message.join("; "):f.message);}catch{}throw new Error(u)}catch(a){if(a instanceof E||a instanceof J)throw a;let l=a instanceof Error?a:new Error(String(a)),g="";if(l.message==="fetch failed"||a.code){let p=[],u=a.code||a.cause?.code;if(a.code&&p.push(`Error Code: ${a.code}`),a.cause){let f=a.cause;f.code&&p.push(`Cause Code: ${f.code}`),f.errno&&p.push(`Errno: ${f.errno}`),f.syscall&&p.push(`System Call: ${f.syscall}`),f.address&&p.push(`Address: ${f.address}`),f.port&&p.push(`Port: ${f.port}`);}u==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":u==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":u==="ENOTFOUND"?g="DNS lookup failed - check service URL":u==="ETIMEDOUT"?g="Connection timeout - service not responding":u==="ECONNRESET"?g="Connection reset by server":u==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",p.length>0&&(g+=` (${p.join(", ")})`);}else g=l.message;let d=new Error(`Failed to upload data to Constellation Service: ${g}`);throw d.cause=l,d.stack=`${d.stack}
4
4
  Caused by: ${l.stack}`,d}}async sendRequest(e,t,n,r={},o=0,i=3,a=1e3,l=250){for(let g=1;g<=i;g++)try{let d=new AbortController,p;o>0&&(p=setTimeout(()=>d.abort(),o));let u={...r,"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:u,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),f.status===401)throw new E("Authentication failed");if(!f.ok&&this.retryableStatusCodes.includes(f.status))throw new Ie(`${f.statusText} (${f.status})`);return f}catch(d){if(!(d instanceof E)){let p=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);console.log(`HTTP request attempt ${g}/${i} failed: ${p}`);}if(g<i&&d instanceof Ie){let p=a+Math.floor(Math.random()*l);await new Promise(u=>setTimeout(u,p));}else throw d}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Ie=class extends Error{constructor(e){super(e),this.name="RetryableError";}},E=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},M=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},$=class extends Error{constructor(t,n,r){super(t);this.code=n;this.projectId=r;this.name="ProjectValidationError";}},J=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}};function Qe(s){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
5
5
  \u2502 ${c.gray("'")} ${c.blueBright(".")} ${c.dim("`")} ${c.yellowBright("'")} ${c.blueBright("+")} ${c.whiteBright(".")} ${c.gray(".")} ${c.yellowBright("'")} ${c.yellowBright("*")} ${c.whiteBright("'")} ${c.blueBright("+")} ${c.gray(".")} ${c.yellowBright("*")} ${c.whiteBright(",")} ${c.gray.dim(".")}\u2502
6
6
  \u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
@@ -49,7 +49,7 @@ ${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
49
49
  New terminal sessions will load it automatically.`);}catch(e){let t=e.message??"An unexpected error occurred",n=Kn(t);console.error(`${C} Failed to store Constellation access key
50
50
  ${n}`);}}};var w={async directoryExists(s){try{return (await T__default.stat(s)).isDirectory()}catch{return false}},async fileIsReadable(s){try{return await T__default.access(s,T__default.constants.R_OK),!0}catch{return false}},async readFile(s,e="utf-8"){let t=await T__default.readFile(s,{encoding:e,flag:T__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(s,e,t="utf-8"){let n=Buffer.from(e,t);await T__default.writeFile(s,n,{encoding:t,flag:T__default.constants.O_WRONLY|T__default.constants.O_CREAT|T__default.constants.O_TRUNC});},async getFileStats(s){return await T__default.stat(s)},async getFileHandle(s,e,t){return await T__default.open(s,e,t)}};var $e=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 r=await n();if(!r)throw new Error(`Failed to load language: ${t}`);let o=new Vn;o.setLanguage(r);let i=await w.getFileStats(e),a=10*1024*1024;if(i.size<=a){let l=await w.readFile(e),g={bufferSize:1024*1024};return o.parse(l,void 0,g)}else return this.parseWithStream(o,e,i.size)}async parseWithStream(e,t,n){let r=null;try{r=await T.open(t,"r");let o=r.fd,i=64*1024,a=Buffer.alloc(i),l=0;return e.parse(d=>{if(n>50*1024*1024){let u=Math.round(d/n*100);u>l+10&&(console.log(` Parsing large file: ${u}%...`),l=u);}let p=He.readSync(o,a,0,i,d);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(r)try{await r.close();}catch(i){console.error(`Warning: Failed to close file handle for ${t}:`,i);}throw o}finally{if(r)try{await r.close();}catch{}}}};Y();var ke=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Mt();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(o=>!t.ignores(o.relativePath)&&this.matchesLanguageExtension(o,e.languages))}async scanSpecificFiles(e,t){let n=[],r=null;t.exclude&&t.exclude.length>0&&(r=Mt().add(t.exclude));let o=await T__default.realpath(this.rootPath);for(let i of e)try{let a=___default.isAbsolute(i)?i:___default.join(this.rootPath,i),l=await T__default.lstat(a);if(l.isSymbolicLink()){let g=await T__default.realpath(a);if(!g.startsWith(o+___default.sep)&&g!==o){console.warn(`${y} Skipping symlink pointing outside project: ${i} -> ${g}`);continue}let d=await T__default.stat(a);if(!d.isFile())continue;let p=H(this.rootPath,a);if(r&&r.ignores(p))continue;let u=this.detectLanguage(p,t.languages);if(!u)continue;n.push({path:a,relativePath:p,language:u,size:d.size});}else if(l.isFile()){let g=H(this.rootPath,a);if(r&&r.ignores(g))continue;let d=this.detectLanguage(g,t.languages);if(!d)continue;n.push({path:a,relativePath:g,language:d,size:l.size});}}catch{console.warn(`${y} Skipping inaccessible file: ${i}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let o=___default.join(r,".gitignore");await w.fileIsReadable(o)&&n.unshift(o);let i=___default.dirname(r);if(i===r)break;r=i;let a=___default.join(r,".git");if(await w.directoryExists(a)){let l=___default.join(r,".gitignore");await w.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let o of n)try{let i=await w.readFile(o);e.add(i);}catch{console.warn(`${y} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,n){let r=[],o=t||e,i=n||await T__default.realpath(this.rootPath);try{let a=await T__default.readdir(e,{withFileTypes:!0});for(let l of a){let g=___default.join(e,l.name),d=H(o,g);if(l.isDirectory()){if(l.name.startsWith("."))continue;let p=await this.walkDirectory(g,o,i);r.push(...p);}else if(l.isFile()){let p=await T__default.stat(g);r.push({path:g,relativePath:d,language:"",size:p.size});}else if(l.isSymbolicLink())try{let p=await T__default.realpath(g);if(!p.startsWith(i+___default.sep)&&p!==i){console.warn(`${y} Skipping symlink pointing outside project: ${g} -> ${p}`);continue}let u=await T__default.stat(g);if(u.isDirectory()){if(l.name.startsWith("."))continue;let f=await this.walkDirectory(g,o,i);r.push(...f);}else u.isFile()&&r.push({path:g,relativePath:d,language:"",size:u.size});}catch{console.warn(`${y} Skipping invalid symlink: ${g}`);}}}catch(a){console.error(`${C} Error walking directory ${e}:`,a);}return r}matchesLanguageExtension(e,t){let n=___default.extname(e.path).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return e.language=r,true;return false}detectLanguage(e,t){let n=___default.extname(e).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return r;return null}};var Jn=z$1.object({source:z$1.string().min(1,"Import source cannot be empty"),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:z$1.enum(["relative","workspace","alias","external","builtin"])}),Yn=z$1.record(z$1.string(),Jn),Dt=z$1.object({file:z$1.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z$1.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z$1.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z$1.string().datetime({message:"Invalid ISO timestamp"}),ast:z$1.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Yn.optional()});var Xn=promisify(tt.gunzip),Ne=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=tt.createGzip();n.on("data",i=>t.push(i));let r=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),o=Readable.from(e);return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=tt.createGzip();n.on("data",i=>t.push(i));let r=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),o=Readable.from(this.serializeASTChunks(e));return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await Xn(t);return JSON.parse(n.toString("utf-8"))}};var Re=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,r=0,o=0;for(;o<e.length&&n.size<this.concurrency;){let i=r++,a=this.processItem(e[o],o,t).then(l=>({result:l!==null?l.result:null,promiseId:i}));n.set(i,a),o++;}for(;n.size>0;){let i=await Promise.race(n.values());if(n.delete(i.promiseId),i.result!==null&&(yield i.result),o<e.length){let a=r++,l=this.processItem(e[o],o,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),o++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};Y();var ge=class extends B{scanner;parser;apiClient;compressor;buildConfigManagers=new Map;constructor(e){if(super(e),!this.config||!this.langRegistry)throw new Error("index command requires a valid configuration");this.scanner=new ke(process.cwd()),this.parser=new $e(this.langRegistry),this.compressor=new Ne;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let r=n.getBuildConfigManager(process.cwd(),this.config.languages);r&&this.buildConfigManagers.set(t,r);}}}async run(e=false,t=false){try{let n=await this.getAccessKey();this.apiClient=new be(this.config,n),await this.validateProject(),console.log(`${F}Starting indexing procedure...
51
51
  `);let r=performance.now();if(t?console.log(`${y} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${y} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${y} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){console.log(`${m} Discovering language build configurations...`);let x=0;for(let[Se,re]of this.buildConfigManagers.entries()){let S=await re.initialize();x+=S.length;}x>0&&console.log(`${h} Found ${x} configuration file(s)`);}let o=await this.determineIndexScope(e),i=await this.git.getLatestCommitHash();if(o.upToDate){console.log(`
52
- ${h} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${i.substring(0,8)}`);return}if(o.isIncremental&&i){let x=await this.apiClient.getIndexStatus(this.config.branch,i);if(x?.status==="current"||x?.status==="processing"&&x?.commitHash===i){console.log(`${h} Index already up to date for branch ${this.config.branch} at commit ${i.substring(0,8)}`);return}}let a=await this.discoverFiles(o.isIncremental),l=!1,g=()=>{l||console.log(`${m} Uploading metadata, processing, and indexing...`);},d=this.generateASTs(a,g);try{await this.uploadToAPI(d,o.isIncremental,i),l=!0;}catch(x){throw l=!0,x}let f=(performance.now()-r)/1e3,v=Math.floor(f/60),P=(f%60).toFixed(3),ne=v>0?`${v}m ${P}s`:`${P}s`;console.log(`
52
+ ${h} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${i.substring(0,8)}`);return}if(o.isIncremental&&i){let x=await this.apiClient.getIndexStatus(this.config.branch,i);if(x?.status==="current"||x?.status==="processing"&&x?.commitHash===i){console.log(`${h} Index already up to date for branch ${this.config.branch} at commit ${i.substring(0,8)}`);return}}let a=await this.discoverFiles(o.isIncremental),l=!1,g=()=>{l||console.log(`${m} Uploading metadata, processing, and indexing...`);},d=this.generateASTs(a,g);try{await this.uploadToAPI(d,o.isIncremental,i),l=!0;}catch(x){throw l=!0,x}let f=(performance.now()-r)/1e3,P=Math.floor(f/60),v=(f%60).toFixed(3),ne=P>0?`${P}m ${v}s`:`${v}s`;console.log(`
53
53
  ${h} Upload completed in ${ne}! Server indexing in progress.`);}catch(n){if(n instanceof $)throw n;if(n instanceof J)throw console.error(`${C} Indexing failed: Another indexing operation is currently in progress for branch ${n.branchName||this.config?.branch||"unknown"}.`),console.log(" Your index may be out of date. Re-run this command after the current operation completes."),n;if(n instanceof E)throw console.error(`
54
54
  ${C} Authentication failed.`),console.log(`${m} Your access key may be invalid or expired. Run 'constellation auth'
55
55
  to set or update your access key.`),n;if(n instanceof Error&&n.message==="Access key not configured")throw n;let r=n instanceof Error?n.message:"An unexpected error occurred";throw console.error(`${C} Indexing failed: ${r}`),n}}async getAccessKey(){let e=await this.env.getKey(D);if(!e)throw console.error(`
@@ -78,7 +78,7 @@ To resolve:`),console.error(" 1. Fix the conflicted files manually"),console.er
78
78
  Please check your internet connection and try again
79
79
  `):e.message.includes("Authentication")&&console.error(`
80
80
  Please check your git credentials and try again
81
- `)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${m} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${m} No previous index found - performing full index`),{isIncremental:!1,upToDate:!1};let r=await this.git.getLatestCommitHash();return n===r?(console.log(`${h} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${m} Last indexed commit: ${n.substring(0,8)}`),console.log(`${m} Current commit: ${r.substring(0,8)}`),console.log(`${m} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof E)throw t;return console.log(`${y} Could not determine last index - performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${m} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let r=await this.git.getChangedFiles(n.latestCommit),o=[...r.added,...r.modified,...r.renamed.map(a=>a.to)];console.log(`${m} Found ${o.length} changed files`),t=await this.scanner.scanSpecificFiles(o,this.config);let i=[...r.deleted,...r.renamed.map(a=>a.from)];if(i.length>0){let a=r.deleted.length,l=r.renamed.length,g=l>0?`${m} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${m} Removing ${a} deleted file(s) from graph`;console.log(g),await this.apiClient.deleteFiles(i);}}}catch(n){if(n instanceof E)throw n;console.log(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${m} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${h} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),r=e.length,o=0,i=0;console.log(`${m} Processing ${r} files...`);let a=await this.git.getLatestCommitHash(),l=r>1e4?5:r>5e3?7:10;l<10&&console.log(`${m} Large project detected - using concurrency of ${l} to optimize memory usage`);let d=new Re(l).run(e,async(p,u)=>{let f=Math.round((u+1)/r*100);console.log(`${m} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let v=await this.parser.parseFile(p.path,p.language),P=this.langRegistry.getPlugin(p.language),ne;if(P?.getImportResolver){let Xe=this.buildConfigManagers.get(p.language),Ze=Xe?await Xe.getConfigForFile(p.path):null,Tt=P.getImportResolver(p.path,Ze);if(Tt){let{ImportExtractor:bn}=await Promise.resolve().then(()=>(Vt(),Kt));ne=await new bn().extractImportResolutions(v,p.path,p.language,Tt);}}let{serializeASTStream:x}=await Promise.resolve().then(()=>(pt(),an)),Se=x(v.rootNode,void 0,p.language),re=await this.compressor.compressStream(Se),S={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:n,ast:re,importResolutions:ne},L=Dt.safeParse(S);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return o++,L.data}catch(v){throw i++,console.error(` ${y} Failed to parse ${p.relativePath}: ${v.message}`,v),v}});for await(let p of d)yield p;i>0?console.log(`${y} Completed parsing with ${i} parsing errors`):console.log(`${h} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n))throw new Error("Failed to upload data to Constellation Service");console.log(`${h} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Te(e)}};var ln=[{event:"SessionStart",type:"prompt",content:`You have Constellation access. \`{MCP_TOOL_NAME}\` is your PRIMARY tool for understanding this codebase\u2014not an alternative, not a fallback, THE DEFAULT.
81
+ `)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${m} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${m} No previous index found - performing full index`),{isIncremental:!1,upToDate:!1};let r=await this.git.getLatestCommitHash();return n===r?(console.log(`${h} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${m} Last indexed commit: ${n.substring(0,8)}`),console.log(`${m} Current commit: ${r.substring(0,8)}`),console.log(`${m} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof E)throw t;return console.log(`${y} Could not determine last index - performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${m} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let r=await this.git.getChangedFiles(n.latestCommit),o=[...r.added,...r.modified,...r.renamed.map(a=>a.to)];console.log(`${m} Found ${o.length} changed files`),t=await this.scanner.scanSpecificFiles(o,this.config);let i=[...r.deleted,...r.renamed.map(a=>a.from)];if(i.length>0){let a=r.deleted.length,l=r.renamed.length,g=l>0?`${m} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${m} Removing ${a} deleted file(s) from graph`;console.log(g),await this.apiClient.deleteFiles(i);}}}catch(n){if(n instanceof E)throw n;console.log(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${m} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${h} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),r=e.length,o=0,i=0;console.log(`${m} Processing ${r} files...`);let a=await this.git.getLatestCommitHash(),l=r>1e4?5:r>5e3?7:10;l<10&&console.log(`${m} Large project detected - using concurrency of ${l} to optimize memory usage`);let d=new Re(l).run(e,async(p,u)=>{let f=Math.round((u+1)/r*100);console.log(`${m} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${f}%)...`);try{let P=await this.parser.parseFile(p.path,p.language),v=this.langRegistry.getPlugin(p.language),ne;if(v?.getImportResolver){let Xe=this.buildConfigManagers.get(p.language),Ze=Xe?await Xe.getConfigForFile(p.path):null,Tt=v.getImportResolver(p.path,Ze);if(Tt){let{ImportExtractor:bn}=await Promise.resolve().then(()=>(Vt(),Kt));ne=await new bn().extractImportResolutions(P,p.path,p.language,Tt);}}let{serializeASTStream:x}=await Promise.resolve().then(()=>(pt(),an)),Se=x(P.rootNode,void 0,p.language),re=await this.compressor.compressStream(Se),S={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:n,ast:re,importResolutions:ne},L=Dt.safeParse(S);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return o++,L.data}catch(P){throw i++,console.error(` ${y} Failed to parse ${p.relativePath}: ${P.message}`,P),P}});for await(let p of d)yield p;i>0?console.log(`${y} Completed parsing with ${i} parsing errors`):console.log(`${h} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n))throw new Error("Failed to upload data to Constellation Service");console.log(`${h} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Te(e)}};var ln=[{event:"SessionStart",type:"prompt",content:`You have Constellation access. \`{MCP_TOOL_NAME}\` is your PRIMARY tool for understanding this codebase\u2014not an alternative, not a fallback, THE DEFAULT.
82
82
 
83
83
  Mental model:
84
84
  - "Where is X defined?" \u2192 {MCP_TOOL_NAME}
@@ -139,8 +139,8 @@ CONSTELLATION_EOF
139
139
  ${m} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=___default.join(process.cwd(),"constellation.json"),r=null,o=await w.fileIsReadable(n);if(o)try{let S=await w.readFile(n);r=JSON.parse(S),console.log(`${m} Found existing constellation.json, current values will be used as defaults.
140
140
  `);}catch{console.log(`${y} Existing constellation.json is invalid, starting fresh.
141
141
  `);}if(!await this.git.isGitRepository())throw new Error(`${y} Current directory is not a git repository.
142
- ${m} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=l,p=g.filter(S=>S!==d),u=d?[d,...p]:p,f=this.getBranchInitialIndex(u,r?.branch),v=this.getInitialLanguages(r),P=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:r?.projectId??"",validate:S=>S.trim().length>0||"Project ID is required"},{choices:u,initial:f,limit:10,maxChoices:1,message:"Branch to index:",name:"branch",scroll:!0,type:"select"},{type:"multiselect",name:"languages",multiple:!0,message:"Select Language(s):",choices:this.buildLanguageChoices(r),initial:v,result(S){return S.map(L=>this.choices.find(Ze=>Ze.name===L)?.value??L)}}],x=await new Pn().prompt(P),Se={projectId:x.projectId.trim(),branch:x.branch,languages:{...x.languages.reduce((S,L)=>(S[L]={fileExtensions:me[L]||[]},S),{})}},re=JSON.stringify(Se,void 0,2);await w.writeFile(n,re),console.log(`${h} ${o?"Updated":"Initialized"} configuration file at ${he(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${h} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers();}catch(t){let n=t.message??"An unexpected error occurred";console.error(`${C} Failed to initialize configuration file.
143
- ${n}`);}}async configureMCPServers(){let{configureMcp:e}=await vn({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=wt.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await vn({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(p){return p.map(u=>this.choices.find(v=>v.name===u)?.value??u)}});if(n.length===0){console.log(`${m} No tools selected, skipping MCP configuration`);return}let r=new Ge(process.cwd()),o=[];for(let p of n){let u=_t(p);if(u)if(console.log(` ${m} Configuring ${u.displayName}...`),u.isGlobalConfig&&u.getGlobalConfigPaths){let f=await r.configureGlobalTool(u),v=false;for(let P of f)o.push(P),P.success?(v=true,console.log(` ${h} ${P.tool.displayName} configured at ${he(P.configuredPath,process.cwd())}`)):P.error&&console.log(` ${y} ${P.tool.displayName}: ${P.error}`);if(v){let P=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${m} Note: ${u.displayName} uses ${P} (not project-level)`);}if(f.length===0){let P=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${y} ${u.displayName}: ${P}`);}}else {let f=await r.configureTool(u);o.push(f),f.success?(console.log(` ${h} ${u.displayName} configured at ${he(f.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${h} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${y} ${u.displayName}: ${f.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=___default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),console.log(` ${h} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${y} Could not stage .claude/settings.json in git`);}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=___default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),console.log(` ${h} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=___default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${h} Added opencode.jsonc to staged changes in git`);}catch{}}let g=o.filter(p=>p.success).length,d=o.filter(p=>!p.success).length;console.log(`
142
+ ${m} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=l,p=g.filter(S=>S!==d),u=d?[d,...p]:p,f=this.getBranchInitialIndex(u,r?.branch),P=this.getInitialLanguages(r),v=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:r?.projectId??"",validate:S=>S.trim().length>0||"Project ID is required"},{choices:u,initial:f,limit:10,maxChoices:1,message:"Branch to index:",name:"branch",scroll:!0,type:"select"},{type:"multiselect",name:"languages",multiple:!0,message:"Select Language(s):",choices:this.buildLanguageChoices(r),initial:P,result(S){return S.map(L=>this.choices.find(Ze=>Ze.name===L)?.value??L)}}],x=await new Pn().prompt(v),Se={projectId:x.projectId.trim(),branch:x.branch,languages:{...x.languages.reduce((S,L)=>(S[L]={fileExtensions:me[L]||[]},S),{})}},re=JSON.stringify(Se,void 0,2);await w.writeFile(n,re),console.log(`${h} ${o?"Updated":"Initialized"} configuration file at ${he(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${h} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers();}catch(t){let n=t.message??"An unexpected error occurred";console.error(`${C} Failed to initialize configuration file.
143
+ ${n}`);}}async configureMCPServers(){let{configureMcp:e}=await vn({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=wt.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await vn({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(p){return p.map(u=>this.choices.find(P=>P.name===u)?.value??u)}});if(n.length===0){console.log(`${m} No tools selected, skipping MCP configuration`);return}let r=new Ge(process.cwd()),o=[];for(let p of n){let u=_t(p);if(u)if(console.log(` ${m} Configuring ${u.displayName}...`),u.isGlobalConfig&&u.getGlobalConfigPaths){let f=await r.configureGlobalTool(u),P=false;for(let v of f)o.push(v),v.success?(P=true,console.log(` ${h} ${v.tool.displayName} configured at ${he(v.configuredPath,process.cwd())}`)):v.error&&console.log(` ${y} ${v.tool.displayName}: ${v.error}`);if(P){let v=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${m} Note: ${u.displayName} uses ${v} (not project-level)`);}if(f.length===0){let v=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${y} ${u.displayName}: ${v}`);}}else {let f=await r.configureTool(u);o.push(f),f.success?(console.log(` ${h} ${u.displayName} configured at ${he(f.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${h} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${y} ${u.displayName}: ${f.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=___default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),console.log(` ${h} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${y} Could not stage .claude/settings.json in git`);}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=___default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),console.log(` ${h} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=___default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${h} Added opencode.jsonc to staged changes in git`);}catch{}}let g=o.filter(p=>p.success).length,d=o.filter(p=>!p.success).length;console.log(`
144
144
  ${h} MCP configuration complete: ${g} configured`),d>0&&console.log(`${y} ${d} tool(s) could not be configured`),await this.configureHooks(n,o),console.log(`
145
145
  ${m} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new fe(process.cwd()),r=ft(),o=e.map(l=>_t(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(g=>g.tool.id===l.id&&g.success));if(o.length===0)return;console.log(`
146
146
  ${m} Configuring AI hooks...`);let i=[];for(let l of o){let g=await n.configureHooks(l,r);if(i.push(g),g.success){let d=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(d.length>0){let p=g.configuredPath?he(g.configuredPath,process.cwd()):___default.dirname(d[0]);console.log(` ${h} ${l.displayName} hooks configured at ${p}`);for(let u of d){let f=___default.isAbsolute(u)?he(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${h} Added ${f} to staged changes in git`);}catch{console.log(` ${y} Could not stage ${f} in git`);}}}else console.log(` ${h} ${l.displayName} hooks configured`);}else console.log(` ${y} ${l.displayName}: ${g.error}`);}let a=i.filter(l=>l.success).length;a>0&&console.log(`${h} Hooks configuration complete: ${a} configured`);}buildLanguageChoices(e){return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}]}getInitialLanguages(e){if(!e?.languages)return [];let t={c:"C","c-sharp":"C#",cpp:"C++",go:"Go",json:"JSON",java:"Java",javascript:"JavaScript",php:"PHP",python:"Python",ruby:"Ruby",bash:"Shell (Bash)",typescript:"TypeScript"};return Object.keys(e.languages).filter(n=>e.languages[n]!==void 0).map(n=>t[n]).filter(n=>n!==void 0)}getBranchInitialIndex(e,t){if(t){let n=e.indexOf(t);if(n!==-1)return n}return 0}};var We=class s{constructor(e,t,n,r){this.branch=e;this.languages=t;this.projectId=n;this.exclude=r;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await w.fileIsReadable(e)){let n=await w.readFile(e),r=JSON.parse(n),o=new s(r.branch,r.languages,r.projectId,r.exclude);return o.validate(),o}else throw new Error(`${C} 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 Error("Not on a Git branch (detached HEAD state)");if(this.branch!==e)throw new Error(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`)}};var Ke=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(`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@constellationdev/cli",
3
3
  "description": "Code Intelligence Platform for AI Coding Agents",
4
- "version": "0.1.6",
4
+ "version": "0.1.7",
5
5
  "author": "ShiftinBits Inc",
6
6
  "main": "dist/index.js",
7
7
  "type": "module",