@constellationdev/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +662 -0
- package/README.md +287 -0
- package/dist/index.js +152 -0
- package/package.json +101 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import*as w from'path';import w__default from'path';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import*as De 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 l from'ansi-colors';import*as Q from'os';import Q__default from'os';import vn from'enquirer';import {performance}from'perf_hooks';import*as T from'fs/promises';import T__default from'fs/promises';import Kn from'tree-sitter';import Ot from'ignore';import {z as z$1}from'zod';import {promisify}from'util';import et from'zlib';import {pipeline}from'stream/promises';import ho from'tree-sitter-javascript';import yo from'tree-sitter-python';import _o from'tree-sitter-typescript';import {findAll,parse}from'tsconfck';import {spawn}from'child_process';import {simpleGit}from'simple-git';var En=Object.defineProperty;var j=(s,e)=>()=>(s&&(e=s(s=0)),e);var $t=(s,e)=>{for(var t in e)En(s,t,{get:e[t],enumerable:true});};function Lt(s){return s.replace(/\\/g,"/")}function Ie(s){return Lt(s).replace(/^\.?\//,"")}function H(s,e){return Lt(w.relative(s,e))}var Y=j(()=>{});async function U(s,e,t,n,o){let r=await t.resolve(s),i=Bt(s,r),a=o(s,r,i),c=i?void 0:Ie(r);n[e.toString()]={source:s,resolvedPath:c,isExternal:i,importType:a};}function Bt(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var tt,se=j(()=>{Y();tt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function Xn(s,e,t,n){let o=s.childForFieldName("source");if(!o)return;let r=o.startPosition.row,i=o.text.replace(/['"]/g,"");await U(i,r,e,t,n);}async function Zn(s,e,t,n){let o=s.childForFieldName("source");if(!o)return;let r=o.startPosition.row,i=o.text.replace(/['"]/g,"");await U(i,r,e,t,n);}function Ne(){return {language:"javascript",handlers:new Map([["import_statement",Xn],["export_statement",Zn]])}}function nt(){return {...Ne(),language:"typescript"}}var ot=j(()=>{se();});async function to(s,e,t,n){let o=s.childForFieldName("name");if(!o)return;let r;if(o.type==="aliased_import"){let i=o.childForFieldName("name");r=i?i.text:o.text;}else r=o.text;await U(r,s.startPosition.row,e,t,n);}async function no(s,e,t,n){let o,r=s.childForFieldName("module_name");if(r)o=r.text;else {let i="";for(let a=0;a<s.childCount;a++){let c=s.child(a);if(c){if(c.type==="relative_import"){i=c.text;break}(c.type==="."||c.type==="import_prefix")&&(i+=c.text);}}o=i||".";}await U(o,s.startPosition.row,e,t,n);}async function oo(s,e,t,n){await U("__future__",s.startPosition.row,e,t,n);}function rt(){return {language:"python",handlers:new Map([["import_statement",to],["import_from_statement",no],["future_import_statement",oo]]),classifyImportType:eo}}var eo,Re=j(()=>{se();eo=(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 Ut,zt=j(()=>{ot();Re();se();ot();Re();Ut=[Ne(),nt(),rt()];});var Gt={};$t(Gt,{ImportExtractor:()=>it});var it,Wt=j(()=>{zt();se();it=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Ut)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 r=this.languageHandlers.get(n);if(!r)return {};let i=this.classifiers.get(n)??tt,a={};return await this.walkAST(e.rootNode,async c=>{let p=r.get(c.type);p&&await p(c,o,a,i);}),a}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 ae,Kt,st,Vt,Jt,je=j(()=>{ae=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"]),Kt=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"]),st={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"]},Vt={language:"javascript",textIncludedTypes:Kt,fieldNames:st},Jt={language:"typescript",textIncludedTypes:Kt,fieldNames:st};});var ro,Yt,qt,at=j(()=>{ro=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"]),Yt={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"]},qt={language:"python",textIncludedTypes:ro,fieldNames:Yt,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function Xt(s){return le.get(s)}function Zt(s){if(!s)return ae;let e=le.get(s);if(!e)return ae;let t=new Set(ae);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 ce(...t)}let e=le.get(s);if(!e){let t=Array.from(le.values()).map(n=>n.fieldNames);return ce(...t)}return e.fieldNames}var le,Qt=j(()=>{ct();je();at();je();je();at();le=new Map([["javascript",Vt],["typescript",Jt],["python",qt]]);});var rn={};$t(rn,{COMMON_FIELD_NAMES:()=>dt,JS_TS_FIELD_NAMES:()=>nn,PYTHON_FIELD_NAMES:()=>on,TEXT_INCLUDED_TYPES:()=>en,mergeFieldMaps:()=>ce,serializeAST:()=>so,serializeASTStream:()=>io});function*io(s,e,t){yield*gt(s,e,t);}function*gt(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)}`),tn(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let o=(t?lt(t):dt)[s.type]||[],r=new Set,i=true;for(let a of o){let c=s.childForFieldName(a);c&&(i||(yield ","),i=false,r.add(c),yield*gt(c,a,t));}for(let a=0;a<s.childCount;a++){let c=s.child(a);c&&!r.has(c)&&(i||(yield ","),i=false,yield*gt(c,void 0,t));}yield "]";}yield "}";}async function so(s,e,t){let n=pt(s,e,t),o=t?lt(t):dt,r=[{treeNode:s,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;r.length>0;){let i=r[r.length-1];if(i.childIndex===0&&i.treeNode.childCount>0){let a=o[i.treeNode.type]||[];for(let c of a){let p=i.treeNode.childForFieldName(c);if(p){i.fieldChildren.add(p);let d=pt(p,c,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(d),r.push({treeNode:p,serializedNode:d,fieldName:c,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 c=pt(a,void 0,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(c),r.push({treeNode:a,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else r.pop();}return n}function pt(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 tn(s,t)&&(n.text=s.text),n}function tn(s,e){if(e){let n=Xt(e);if(n?.shouldIncludeText){let r=n.shouldIncludeText(s);if(r===false)return false;if(r===true)return true}return Zt(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:en.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function ce(...s){let e={};for(let t of s)for(let[n,o]of Object.entries(t)){let i=[...e[n]||[]];for(let a of o)i.includes(a)||i.push(a);e[n]=i;}return e}var en,nn,on,dt,ct=j(()=>{Qt();en=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"]);nn={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"]},on={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"]};dt=ce(nn,on);});function Tt(s){return base32.encode(Buffer.from(s))}function kt(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Tt(n)}var xe=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 Tn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:Q.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 kn="\u2714",Nn="\u2717",Rn="\u26A0",jn="\u2139",An="\u26A1",Ln="[OK]",On="[ERR]",Fn="[WARN]",Mn="[INFO]",Dn="[>>]",re=Tn(),y=l.green(re?kn:Ln),v=l.red(re?Nn:On),m=l.yellow(re?Rn:Fn),f=l.blue(re?jn:Mn),M=l.yellow(re?An:Dn);var Se=class{constructor(e,t){this.config=e;this.accessKey=t;}apiVersion="intel/v1";async getProjectState(){try{let e=new URLSearchParams({branchName:this.config.branch}),t={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,Authorization:`Bearer ${this.accessKey}`},n=await this.sendRequest("project",void 0,"GET",t);return n&&!n.ok&&await this.handleProjectStateError(n),n?.ok?n.json():null}catch(e){if(e instanceof O||e instanceof x||e instanceof I)throw e;return console.error(`${v} Failed to query current project state`,e),null}}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new I(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new I(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new I(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new O("Project not found - no previous index exists");default:if(e.status===404)throw new O("Project not found - no previous index exists");break}}catch(t){if(t instanceof I||t instanceof O)throw t;if(e.status===404)throw new O("Project not found - no previous index exists")}}async deleteFiles(e){for(let t of e){let n=kt(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,o,r){try{let{Readable:i}=await import('stream'),a=new xe(e),c=i.toWeb(a),p=new Agent({headersTimeout:0,bodyTimeout:0}),d=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":r?"incremental":"full",Authorization:`Bearer ${this.accessKey}`},body:c,duplex:"half",dispatcher:p});if(d.status===401)throw new x("Authentication failed");return d.ok===!0||d.status===202}catch(i){if(i instanceof x)throw i;let a=i instanceof Error?i:new Error(String(i)),c="";if(a.message==="fetch failed"||i.code){let d=[],g=i.code||i.cause?.code;if(i.code&&d.push(`Error Code: ${i.code}`),i.cause){let u=i.cause;u.code&&d.push(`Cause Code: ${u.code}`),u.errno&&d.push(`Errno: ${u.errno}`),u.syscall&&d.push(`System Call: ${u.syscall}`),u.address&&d.push(`Address: ${u.address}`),u.port&&d.push(`Port: ${u.port}`);}g==="ERR_INVALID_ARG_VALUE"?c="Invalid argument value - check stream/body format and duplex option":g==="ECONNREFUSED"?c="Connection refused - service may be down or unreachable":g==="ENOTFOUND"?c="DNS lookup failed - check service URL":g==="ETIMEDOUT"?c="Connection timeout - service not responding":g==="ECONNRESET"?c="Connection reset by server":g==="EHOSTUNREACH"?c="Host unreachable - check network connectivity":c="Network failure",d.length>0&&(c+=` (${d.join(", ")})`);}else c=a.message;let p=new Error(`Failed to upload data to Constellation Service: ${c}`);throw p.cause=a,p.stack=`${p.stack}
|
|
4
|
+
Caused by: ${a.stack}`,p}}async sendRequest(e,t,n,o={},r=0,i=3,a=1e3,c=250){for(let p=1;p<=i;p++)try{let d=new AbortController,g;r>0&&(g=setTimeout(()=>d.abort(),r));let u={...o,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},_=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:u,body:t?JSON.stringify(t):void 0,signal:d.signal});if(g&&clearTimeout(g),_.status===401)throw new x("Authentication failed");if(!_.ok&&this.retryableStatusCodes.includes(_.status))throw new be(`${_.statusText} (${_.status})`);return _}catch(d){if(!(d instanceof x)){let g=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);console.log(`HTTP request attempt ${p}/${i} failed: ${g}`);}if(p<i&&d instanceof be){let g=a+Math.floor(Math.random()*c);await new Promise(u=>setTimeout(u,g));}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}`)}},be=class extends Error{constructor(e){super(e),this.name="RetryableError";}},x=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},O=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},I=class extends Error{constructor(t,n,o){super(t);this.code=n;this.projectId=o;this.name="ProjectValidationError";}};function Ze(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
|
+
\u2502 ${l.gray("'")} ${l.blueBright(".")} ${l.dim("`")} ${l.yellowBright("'")} ${l.blueBright("+")} ${l.whiteBright(".")} ${l.gray(".")} ${l.yellowBright("'")} ${l.yellowBright("*")} ${l.whiteBright("'")} ${l.blueBright("+")} ${l.gray(".")} ${l.yellowBright("*")} ${l.whiteBright(",")} ${l.gray.dim(".")}\u2502
|
|
6
|
+
\u2502 _____ ${l.yellowBright("*")} ${l.dim("`")} __${l.whiteBright(".")} ${l.whiteBright("'")} ____ ${l.dim(".")} __ _ ${l.gray("`")} . . ${l.yellowBright("o")} ${l.blueBright("+")} \u2502
|
|
7
|
+
\u2502 ${l.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${l.gray(".")} ${l.yellowBright("'")} ${l.gray("+")} ${l.gray("\\")} ${l.gray("`")} \u2502
|
|
8
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${l.gray("'")} ${l.blueBright("o")}${l.gray("\u2014\u2014\u2014\u2014")}${l.yellowBright("o")} ${l.whiteBright("o")} ${l.whiteBright(".")} \u2502
|
|
9
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${l.gray(".")} ${l.whiteBright("*")} ${l.gray(" \\ \\ ")}${l.gray("/")} \u2502
|
|
10
|
+
\u2502 ${l.whiteBright("'")} ${l.blueBright(".")} ${l.gray("'")} ${l.whiteBright(".")} ${l.blueBright(".")} ${l.gray(".")} ${l.yellowBright("*")} ${l.blueBright.dim("+")} ${l.whiteBright("o o")}${l.gray("\u2014")}${l.blueBright("o")} ${l.yellowBright("*")} \u2502
|
|
11
|
+
\u2502${l.yellowBright("'")} ${l.whiteBright("*")} ${l.blueBright("+")} ${l.yellowBright("*")} ${l.gray(",")} ${l.whiteBright("'")} + ${l.whiteBright("constellationdev.io")} ${l.whiteBright("' .")} ${l.gray(",")} ${l.blueBright("*")} ${l.yellowBright(".")} ${l.whiteBright("+")} \u2502`),s&&s.length>0?console.log(`\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(s.length)}\u2500\u252C${"\u2500".repeat(59-s.length)}\u256F
|
|
12
|
+
\u2502 ${l.bold(`constellation \u203A ${s}`)} \u2502
|
|
13
|
+
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(s.length)}\u2500\u256F
|
|
14
|
+
`):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");}`
|
|
15
|
+
\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
|
|
16
|
+
\u2502 ${l.gray("'")} ${l.blueBright(".")} ${l.dim("`")} ${l.yellowBright("'")} ${l.blueBright("+")} ${l.whiteBright(".")} ${l.gray(".")} ${l.yellowBright("'")} ${l.yellowBright("*")} ${l.whiteBright("'")} ${l.blueBright("+")} ${l.gray(".")} ${l.yellowBright("*")} ${l.whiteBright(",")} ${l.gray.dim(".")}\u2502
|
|
17
|
+
\u2502 _____ ${l.yellowBright("*")} ${l.dim("`")} __${l.whiteBright(".")} ${l.whiteBright("'")} ____ ${l.dim(".")} __ _ ${l.gray("`")} . . ${l.yellowBright("o")} ${l.blueBright("+")} \u2502
|
|
18
|
+
\u2502 ${l.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${l.gray(".")} ${l.yellowBright("'")} ${l.gray("+")} ${l.gray("\\")} ${l.gray("`")} \u2502
|
|
19
|
+
\u2502 / /__/ _ \\/ _ \\(_-</ __/ -_) / / _ \`/ __/ / _ \\/ _ \\ ${l.gray("'")} ${l.blueBright("o")}${l.gray("\u2014\u2014\u2014\u2014")}${l.yellowBright("o")} ${l.whiteBright("o")} ${l.whiteBright(".")} \u2502
|
|
20
|
+
\u2502 \\___/\\___/_//_/___/\\__/\\__/_/_/\\_,_/\\__/_/\\___/_//_/ ${l.gray(".")} ${l.whiteBright("*")} ${l.gray(" \\ \\ ")}${l.gray("/")} \u2502
|
|
21
|
+
\u2502 ${l.whiteBright("'")} ${l.blueBright(".")} ${l.gray("'")} ${l.whiteBright(".")} ${l.blueBright(".")} ${l.gray(".")} ${l.yellowBright("*")} ${l.blueBright.dim("+")} ${l.whiteBright("o o")}${l.gray("\u2014")}${l.blueBright("o")} ${l.yellowBright("*")} \u2502
|
|
22
|
+
\u2502${l.yellowBright("'")} ${l.whiteBright("*")} ${l.blueBright("+")} ${l.yellowBright("*")} ${l.gray(",")} ${l.whiteBright("'")} + ${l.whiteBright("constellationdev.io")} ${l.whiteBright("' .")} ${l.gray(",")} ${l.blueBright("*")} ${l.yellowBright(".")} ${l.whiteBright("+")} \u2502
|
|
23
|
+
\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
|
|
24
|
+
`;`
|
|
25
|
+
${l.yellowBright(" o")}
|
|
26
|
+
${l.gray(" \\")}
|
|
27
|
+
${l.blueBright(" o")}${l.blueBright("----")}${l.yellowBright("o")} ${l.gray("o")}
|
|
28
|
+
${l.gray(" \\ \\ ")}${l.blueBright("/")}
|
|
29
|
+
${l.whiteBright(" o o")}${l.blueBright("-")}${l.blueBright("o")}
|
|
30
|
+
`;var D="CONSTELLATION_ACCESS_KEY";var B=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};var{prompt:Rt}=vn,zn=/^ak:[0-9a-f]{32}$/i;function Gn(s){return zn.test(s)}function Wn(s){return s.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var ie=class extends B{async run(){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${M}Configuring access key authentication...
|
|
31
|
+
`),this.env.isCI()){console.error(`${v} Cannot configure authentication in CI/CD environments
|
|
32
|
+
|
|
33
|
+
The ${D} environment variable must be configured
|
|
34
|
+
directly in your pipeline settings:
|
|
35
|
+
|
|
36
|
+
- GitHub Actions: Repository Settings -> Secrets and variables -> Actions
|
|
37
|
+
- GitLab CI: Settings -> CI/CD -> Variables
|
|
38
|
+
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
39
|
+
- Jenkins: Manage Jenkins -> Credentials
|
|
40
|
+
- CircleCI: Project Settings -> Environment Variables
|
|
41
|
+
`);return}if(await this.env.getKey(D)){let{replaceKey:r}=await Rt({message:"Replace existing Constellation access key?",name:"replaceKey",type:"confirm",initial:!1});if(!r){console.log(`${y} Keeping existing Constellation access key`);return}}let t,n=0,o=3;for(;n<o;){if(t=(await Rt({message:"Constellation Access Key:",name:"accessKey",type:"password",required:!0})).accessKey.trim(),!t){console.log(`${m} Access key cannot be empty.
|
|
42
|
+
`),n++;continue}if(!Gn(t)){if(n++,n<o)console.log(`${m} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
43
|
+
Attempts remaining: ${o-n}
|
|
44
|
+
`);else {console.error(`${v} Invalid access key format after ${o} attempts.
|
|
45
|
+
Please verify your access key and try again.`);return}continue}break}await this.env.setKey(D,t),console.log(`${y} Stored access key in ${D} user environment variable`),console.log(`${f} You must restart this terminal session to properly load the new access key value.`);}catch(e){let t=e.message??"An unexpected error occurred",n=Wn(t);console.error(`${v} Failed to store Constellation access key
|
|
46
|
+
${n}`);}}};var h={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 Ee=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}`);let r=new Kn;r.setLanguage(o);let i=await h.getFileStats(e),a=10*1024*1024;if(i.size<=a){let c=await h.readFile(e),p={bufferSize:1024*1024};return r.parse(c,void 0,p)}else return this.parseWithStream(r,e,i.size)}async parseWithStream(e,t,n){let o=null;try{o=await T.open(t,"r");let r=o.fd,i=64*1024,a=Buffer.alloc(i),c=0;return e.parse(d=>{if(n>50*1024*1024){let u=Math.round(d/n*100);u>c+10&&(console.log(` Parsing large file: ${u}%...`),c=u);}let g=De.readSync(r,a,0,i,d);return g===0?null:a.subarray(0,g).toString("utf-8")})}catch(r){if(o)try{await o.close();}catch(i){console.error(`Warning: Failed to close file handle for ${t}:`,i);}throw r}finally{if(o)try{await o.close();}catch{}}}};Y();var $e=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Ot();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(r=>!t.ignores(r.relativePath)&&this.matchesLanguageExtension(r,e.languages))}async scanSpecificFiles(e,t){let n=[],o=null;t.exclude&&t.exclude.length>0&&(o=Ot().add(t.exclude));let r=await T__default.realpath(this.rootPath);for(let i of e)try{let a=w__default.isAbsolute(i)?i:w__default.join(this.rootPath,i),c=await T__default.lstat(a);if(c.isSymbolicLink()){let p=await T__default.realpath(a);if(!p.startsWith(r+w__default.sep)&&p!==r){console.warn(`${m} Skipping symlink pointing outside project: ${i} -> ${p}`);continue}let d=await T__default.stat(a);if(!d.isFile())continue;let g=H(this.rootPath,a);if(o&&o.ignores(g))continue;let u=this.detectLanguage(g,t.languages);if(!u)continue;n.push({path:a,relativePath:g,language:u,size:d.size});}else if(c.isFile()){let p=H(this.rootPath,a);if(o&&o.ignores(p))continue;let d=this.detectLanguage(p,t.languages);if(!d)continue;n.push({path:a,relativePath:p,language:d,size:c.size});}}catch{console.warn(`${m} Skipping inaccessible file: ${i}`);}return n}async loadGitignoreRules(e,t){let n=[],o=t;for(;;){let r=w__default.join(o,".gitignore");await h.fileIsReadable(r)&&n.unshift(r);let i=w__default.dirname(o);if(i===o)break;o=i;let a=w__default.join(o,".git");if(await h.directoryExists(a)){let c=w__default.join(o,".gitignore");await h.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let r of n)try{let i=await h.readFile(r);e.add(i);}catch{console.warn(`${m} Failed to load .gitignore: ${r}`);}e.add(".git");}async walkDirectory(e,t,n){let o=[],r=t||e,i=n||await T__default.realpath(this.rootPath);try{let a=await T__default.readdir(e,{withFileTypes:!0});for(let c of a){let p=w__default.join(e,c.name),d=H(r,p);if(c.isDirectory()){if(c.name.startsWith("."))continue;let g=await this.walkDirectory(p,r,i);o.push(...g);}else if(c.isFile()){let g=await T__default.stat(p);o.push({path:p,relativePath:d,language:"",size:g.size});}else if(c.isSymbolicLink())try{let g=await T__default.realpath(p);if(!g.startsWith(i+w__default.sep)&&g!==i){console.warn(`${m} Skipping symlink pointing outside project: ${p} -> ${g}`);continue}let u=await T__default.stat(p);if(u.isDirectory()){if(c.name.startsWith("."))continue;let _=await this.walkDirectory(p,r,i);o.push(..._);}else u.isFile()&&o.push({path:p,relativePath:d,language:"",size:u.size});}catch{console.warn(`${m} Skipping invalid symlink: ${p}`);}}}catch(a){console.error(`${v} Error walking directory ${e}:`,a);}return o}matchesLanguageExtension(e,t){let n=w__default.extname(e.path).toLowerCase();for(let[o,r]of Object.entries(t))if(r.fileExtensions.includes(n))return e.language=o,true;return false}detectLanguage(e,t){let n=w__default.extname(e).toLowerCase();for(let[o,r]of Object.entries(t))if(r.fileExtensions.includes(n))return o;return null}};var Vn=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"])}),Jn=z$1.record(z$1.string(),Vn),Ft=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:Jn.optional()});var qn=promisify(et.gunzip),Te=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=et.createGzip();n.on("data",i=>t.push(i));let o=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),r=Readable.from(e);return await pipeline(r,n),await o,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=et.createGzip();n.on("data",i=>t.push(i));let o=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),r=Readable.from(this.serializeASTChunks(e));return await pipeline(r,n),await o,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await qn(t);return JSON.parse(n.toString("utf-8"))}};var ke=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,r=0;for(;r<e.length&&n.size<this.concurrency;){let i=o++,a=this.processItem(e[r],r,t).then(c=>({result:c!==null?c.result:null,promiseId:i}));n.set(i,a),r++;}for(;n.size>0;){let i=await Promise.race(n.values());if(n.delete(i.promiseId),i.result!==null&&(yield i.result),r<e.length){let a=o++,c=this.processItem(e[r],r,t).then(p=>({result:p!==null?p.result:null,promiseId:a}));n.set(a,c),r++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};Y();var pe=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 $e(process.cwd()),this.parser=new Ee(this.langRegistry),this.compressor=new Te;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){try{let n=await this.getAccessKey();this.apiClient=new Se(this.config,n),await this.validateProject(),console.log(`${M}Starting indexing procedure...
|
|
47
|
+
`);let o=performance.now();if(t?console.log(`${m} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${m} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${m} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){console.log(`${f} Discovering language build configurations...`);let $=0;for(let[J,te]of this.buildConfigManagers.entries()){let ne=await te.initialize();$+=ne.length;}$>0&&console.log(`${y} Found ${$} configuration file(s)`);}let r=await this.determineIndexScope(e);if(r.upToDate){let $=await this.git.getLatestCommitHash();console.log(`
|
|
48
|
+
${y} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${$.substring(0,8)}`);return}let i=await this.discoverFiles(r.isIncremental),a=!1,c=()=>{a||console.log(`${f} Uploading metadata, processing, and indexing...`);},p=this.generateASTs(i,c);try{await this.uploadToAPI(p,r.isIncremental),a=!0;}catch($){throw a=!0,$}let u=(performance.now()-o)/1e3,_=Math.floor(u/60),P=(u%60).toFixed(3),C=_>0?`${_}m ${P}s`:`${P}s`;console.log(`
|
|
49
|
+
${y} Upload completed in ${C}! Server indexing in progress.`);}catch(n){if(n instanceof I)throw n;if(n instanceof x)throw console.error(`
|
|
50
|
+
${v} Authentication failed.`),console.log(`${f} Run 'constellation auth' to set or update your access key.`),n;let o=n instanceof Error?n.message:"An unexpected error occurred";throw console.error(`${v} Indexing failed: ${o}`),n}}async getAccessKey(){let e=await this.env.getKey(D);if(!e)throw new Error(`Access key not found.
|
|
51
|
+
${f} To configure your access key, set ${D} environment
|
|
52
|
+
variable to the value of your access key or run 'constellation auth'.`);return e}async validateProject(){console.log(`${f} Validating project access...`);try{await this.apiClient.getProjectState(),console.log(`${y} Project validated successfully`);}catch(e){if(e instanceof I)throw this.displayProjectValidationError(e),e;if(e instanceof O){console.log(`${y} Project validated (first index)`);return}if(e instanceof x)throw e;console.log(`${m} Could not validate project \u2014 will attempt indexing`);}}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":console.error(`
|
|
53
|
+
${v} Project not registered
|
|
54
|
+
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not associated with your Constellation account.
|
|
55
|
+
`),console.error(" To resolve this:"),console.error(" 1. Verify the project exists at https://app.constellationdev.io"),console.error(" 2. Check that the project ID in constellation.json is correct"),console.error(` 3. Run 'constellation index' again
|
|
56
|
+
`);break;case "PROJECT_INACTIVE":console.error(`
|
|
57
|
+
${v} Project is inactive
|
|
58
|
+
`),console.error(` The project "${n}" has been deactivated.
|
|
59
|
+
`),console.error(" To resolve this:"),console.error(" 1. Reactivate the project at https://app.constellationdev.io"),console.error(` 2. Run 'constellation index' again
|
|
60
|
+
`);break;case "INVALID_PROJECT_ID":console.error(`
|
|
61
|
+
${v} Invalid project ID
|
|
62
|
+
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not a valid Constellation project identifier.
|
|
63
|
+
`),console.error(" To resolve this:"),console.error(" 1. Get your project ID from https://app.constellationdev.io"),console.error(" 2. Update the projectId field in constellation.json"),console.error(` 3. Run 'constellation index' again
|
|
64
|
+
`);break;default:console.error(`
|
|
65
|
+
${v} Project validation failed: ${e.message}
|
|
66
|
+
`);}}async validateGitBranch(){console.log(`${f} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${y} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(console.log(`${f} Validating Git status...`),!(await this.git.status()).clean)throw new Error(`Outstanding changes detected.
|
|
67
|
+
Commit or stash changes first to ensure consistent indexing.`);console.log(`${y} Working tree clean`);}async synchronizeChanges(){console.log(`${f} Synchronizing latest changes...`);try{await this.git.pull()&&console.log(`${y} Repository synchronized successfully`);}catch(e){throw console.error(`${v} Failed to synchronize repository`),e instanceof Error&&(e.message.includes("uncommitted changes")?(console.error(`
|
|
68
|
+
To resolve:`),console.error(' 1. Commit your changes: git add . && git commit -m "your message"'),console.error(" 2. Or stash them: git stash"),console.error(` 3. Then run the index command again
|
|
69
|
+
`)):e.message.includes("merge conflicts")?(console.error(`
|
|
70
|
+
To resolve:`),console.error(" 1. Fix the conflicted files manually"),console.error(" 2. Stage the resolved files: git add <resolved-files>"),console.error(" 3. Complete the merge: git commit"),console.error(` 4. Then run the index command again
|
|
71
|
+
`)):e.message.includes("Network error")?console.error(`
|
|
72
|
+
Please check your internet connection and try again
|
|
73
|
+
`):e.message.includes("Authentication")&&console.error(`
|
|
74
|
+
Please check your git credentials and try again
|
|
75
|
+
`)),e}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${f} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${f} No previous index found - performing full index`),{isIncremental:!1,upToDate:!1};let o=await this.git.getLatestCommitHash();return n===o?(console.log(`${y} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${f} Last indexed commit: ${n.substring(0,8)}`),console.log(`${f} Current commit: ${o.substring(0,8)}`),console.log(`${f} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof x)throw t;return console.log(`${m} Could not determine last index - performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${f} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${m} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let o=await this.git.getChangedFiles(n.latestCommit),r=[...o.added,...o.modified,...o.renamed.map(a=>a.to)];console.log(`${f} Found ${r.length} changed files`),t=await this.scanner.scanSpecificFiles(r,this.config);let i=[...o.deleted,...o.renamed.map(a=>a.from)];if(i.length>0){let a=o.deleted.length,c=o.renamed.length,p=c>0?`${f} Removing ${a} deleted file(s) and ${c} renamed file(s) from graph`:`${f} Removing ${a} deleted file(s) from graph`;console.log(p),await this.apiClient.deleteFiles(i);}}}catch(n){if(n instanceof x)throw n;console.log(`${m} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${f} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${y} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),o=e.length,r=0,i=0;console.log(`${f} Processing ${o} files...`);let a=await this.git.getLatestCommitHash(),c=o>1e4?5:o>5e3?7:10;c<10&&console.log(`${f} Large project detected - using concurrency of ${c} to optimize memory usage`);let d=new ke(c).run(e,async(g,u)=>{let _=Math.round((u+1)/o*100);console.log(`${f} Analyzing file ${g.path.replace(process.cwd()+"/","")} (${_}%)...`);try{let P=await this.parser.parseFile(g.path,g.language),C=this.langRegistry.getPlugin(g.language),$;if(C?.getImportResolver){let qe=this.buildConfigManagers.get(g.language),Xe=qe?await qe.getConfigForFile(g.path):null,It=C.getImportResolver(g.path,Xe);if(It){let{ImportExtractor:bn}=await Promise.resolve().then(()=>(Wt(),Gt));$=await new bn().extractImportResolutions(P,g.path,g.language,It);}}let{serializeASTStream:J}=await Promise.resolve().then(()=>(ct(),rn)),te=J(P.rootNode,void 0,g.language),ne=await this.compressor.compressStream(te),E={file:this.normalizePathToCanonical(g.relativePath),language:g.language,commit:a,timestamp:n,ast:ne,importResolutions:$},L=Ft.safeParse(E);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return r++,L.data}catch(P){throw i++,console.error(` ${m} Failed to parse ${g.relativePath}: ${P.message}`,P),P}});for await(let g of d)yield g;i>0?console.log(`${m} Completed parsing with ${i} parsing errors`):console.log(`${y} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t))throw new Error("Failed to upload data to Constellation Service");console.log(`${y} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Ie(e)}};var an=[{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.
|
|
76
|
+
|
|
77
|
+
Mental model:
|
|
78
|
+
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
79
|
+
- "What uses X?" \u2192 {MCP_TOOL_NAME}
|
|
80
|
+
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
81
|
+
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
82
|
+
|
|
83
|
+
Grep is for literal text. Everything else starts with {MCP_TOOL_NAME}.`,matcher:".*"},{event:"SubagentStart",type:"prompt",content:"You have access to Constellation's {MCP_TOOL_NAME} MCP tool. For structural code questions\u2014symbol definitions, callers/callees, dependencies, dependents, impact analysis, architecture overview\u2014use {MCP_TOOL_NAME} instead of Grep/Glob. It answers in one call what would take 3-5 text searches. Use Grep/Glob only for literal string search, config values, or when the tool is unavailable.",matcher:"Explore|Plan|explore|shell"},{event:"PreCompact",type:"prompt",content:"Preserve: (1) The instruction that {MCP_TOOL_NAME} is the PRIMARY tool for code understanding\u2014Grep is only for literal text, (2) Any architectural insights, dependency relationships, or impact analysis results discovered via Constellation.",matcher:".*"}];function ut(){return an}var ln={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},ao="code_intel";function lo(s){return ln[s]}var ge=class{id="cline";displayName="Cline";mapEventName(e){return ln[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,ao)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let o=lo(n.event);if(!o)continue;let r=`.clinerules/hooks/${o}`,i=this.generateScript(n);t.set(r,i);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return `#!/bin/bash
|
|
84
|
+
# Constellation ${e.event} Hook for Cline
|
|
85
|
+
# Generated by constellation-cli - DO NOT EDIT
|
|
86
|
+
#
|
|
87
|
+
# This script injects Constellation guidance at task start.
|
|
88
|
+
# It reads JSON input from stdin (ignored) and outputs JSON with contextModification.
|
|
89
|
+
|
|
90
|
+
cat << 'CONSTELLATION_EOF'
|
|
91
|
+
{
|
|
92
|
+
"cancel": false,
|
|
93
|
+
"contextModification": "${n}"
|
|
94
|
+
}
|
|
95
|
+
CONSTELLATION_EOF
|
|
96
|
+
`}};var co={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},po="constellation__code_intel",q=class{id="cursor";displayName="Cursor";mapEventName(e){return co[e]}generateConfig(e){let t={};for(let n of e){let o=this.mapEventName(n.event);if(!o)continue;t[o]||(t[o]=[]);let r={type:n.type};n.type==="prompt"&&(r.prompt=this.customizePrompt(n)),n.matcher&&(r.matcher=n.matcher),t[o].push(r);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,po)}};var go={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},uo={SessionStart:"startup",SubagentStart:"",PreCompact:""},mo="code_intel";function cn(s){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[s]}.sh`}var de=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return go[e]}generateConfig(e){let t={};for(let n of e){let o=this.mapEventName(n.event);if(!o)continue;t[o]||(t[o]=[]);let r=uo[n.event]??"",i=cn(n.event),a=t[o].find(c=>c.matcher===r);a||(a={matcher:r,hooks:[]},t[o].push(a)),a.hooks.push({name:`constellation-${n.event.toLowerCase()}`,type:"command",command:`$GEMINI_PROJECT_DIR/.gemini/hooks/${i}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(n.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,mo)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){if(!this.mapEventName(n.event))continue;let i=`.gemini/hooks/${cn(n.event)}`,a=this.generateScript(n);t.set(i,a);}return t.size>0?t:void 0}generateScript(e){let n=this.customizePrompt(e).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n");return e.event==="PreCompact"?`#!/bin/bash
|
|
97
|
+
# Constellation ${e.event} Hook for Gemini CLI
|
|
98
|
+
# Generated by constellation-cli - DO NOT EDIT
|
|
99
|
+
#
|
|
100
|
+
# Note: PreCompress is advisory-only in Gemini CLI and cannot inject context.
|
|
101
|
+
# This hook outputs a systemMessage reminder instead.
|
|
102
|
+
|
|
103
|
+
cat << 'CONSTELLATION_EOF'
|
|
104
|
+
{
|
|
105
|
+
"systemMessage": "${n}"
|
|
106
|
+
}
|
|
107
|
+
CONSTELLATION_EOF
|
|
108
|
+
`:`#!/bin/bash
|
|
109
|
+
# Constellation ${e.event} Hook for Gemini CLI
|
|
110
|
+
# Generated by constellation-cli - DO NOT EDIT
|
|
111
|
+
|
|
112
|
+
cat << 'CONSTELLATION_EOF'
|
|
113
|
+
{
|
|
114
|
+
"hookSpecificOutput": {
|
|
115
|
+
"additionalContext": "${n}"
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
CONSTELLATION_EOF
|
|
119
|
+
`}getHookDescription(e){return {SessionStart:"Inject code intelligence guidance at session start",SubagentStart:"Inject guidance for agent planning",PreCompact:"Context preservation reminder",PreToolUse:"Pre-tool execution hook",PostToolUse:"Post-tool execution hook",SessionEnd:"Session end hook"}[e]}};var fo=new Map([["cline",new ge],["cursor",new q],["gemini",new de]]);function mt(s){return fo.get(s)}var ue=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureHooks(e,t){if(!e.hooksConfig)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:"Tool does not support hooks configuration"};let n=mt(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let o=w__default.join(this.cwd,e.hooksConfig.filePath),r=n.generateConfig(t),i=Object.keys(r).some(c=>{let p=r[c];return p!=null&&(typeof p!="object"||Object.keys(p).length>0)});if(i){await this.ensureDirectoryExists(o);let c=await this.readConfig(o),p=this.mergeHooksConfig(c,r);await this.writeConfig(o,p);}let a;if(n.generateAuxiliaryFiles){let c=n.generateAuxiliaryFiles(t);c&&(await this.writeAuxiliaryFiles(c),a=Array.from(c.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:i?o:void 0,auxiliaryPaths:a}}catch(o){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:o instanceof Error?o.message:String(o)}}}async ensureDirectoryExists(e){let t=w__default.dirname(e);await T__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await h.fileIsReadable(e))return {};let n=await h.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},o=t.hooks??{},r={...n,...o},i={...e,hooks:r};return t.version!==void 0&&(i.version=t.version),i}async writeConfig(e,t){let n=JSON.stringify(t,null," ");n=n.replace(/\r\n/g,`
|
|
120
|
+
`),n.endsWith(`
|
|
121
|
+
`)||(n+=`
|
|
122
|
+
`),await h.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let o=w__default.join(this.cwd,t);await this.ensureDirectoryExists(o);let r=n.replace(/\r\n/g,`
|
|
123
|
+
`);r.endsWith(`
|
|
124
|
+
`)||(r+=`
|
|
125
|
+
`),await h.writeFile(o,r),(t.endsWith(".sh")||r.startsWith("#!"))&&await T__default.chmod(o,493);}}};var z=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};var X=class{configPaths=[];parseCache=new Map;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(`${m} 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 parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}if(n){if(this.isJavaScriptEnabled)try{let o=await parse(e,{root:this.projectRoot,configName:"jsconfig.json"});return this.parseCache.set(e,o),o}catch(o){if(this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}throw o}if(this.isTypeScriptEnabled){let o=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}}return this.parseCache.set(e,null),null}catch(t){return console.warn(`${m} Failed to parse config for ${e}:`,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear();}};Y();Y();var Le=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),r=await this.resolveSubPath(n,o);if(r)return this.toProjectRelative(r)}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?w.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[o,r]of Object.entries(t)){if(o.includes("*")||!Array.isArray(r))continue;let i=r[0];if(!i)continue;let a=w.resolve(n,i),c=await this.findEntryPoint(a);c&&(e[o]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=w.join(this.projectRoot,"package.json"),n=await T.readFile(t,"utf-8"),r=JSON.parse(n).workspaces;if(!r)return e;let i=Array.isArray(r)?r:r.packages||[];for(let a of i){let c=await this.findWorkspaceDirs(a);for(let p of c){let d=await this.loadWorkspacePackage(p);d&&Object.assign(e,d);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),o=w.join(this.projectRoot,n);try{let r=await T.readdir(o,{withFileTypes:!0});for(let i of r)i.isDirectory()&&t.push(w.join(o,i.name));}catch{}}else {let n=w.join(this.projectRoot,e);try{(await T.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=w.join(e,"package.json"),n=await T.readFile(t,"utf-8"),o=JSON.parse(n),r=o.name;if(!r)return null;let i=await this.findPackageEntryPoint(e,o);return i?{[r]:i}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let o=t.exports;if(typeof o=="string")return w.join(e,o);if(typeof o=="object"){let r=o["."]||o["./index"];if(typeof r=="string")return w.join(e,r);if(typeof r=="object"){let i=r.import||r.default||r.require;if(i)return w.join(e,i)}}}if(t.main)return w.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 r=w.join(e,o);try{if((await T.stat(r)).isFile())return r}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=w.join(e,n);try{if((await T.stat(o)).isFile())return o}catch{}}try{if((await T.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")?w.dirname(e):w.dirname(e),o=[w.join(n,t+".ts"),w.join(n,t+".tsx"),w.join(n,t+".js"),w.join(n,t+".jsx"),w.join(n,t+".d.ts"),w.join(n,t,"index.ts"),w.join(n,t,"index.tsx"),w.join(n,t,"index.js"),w.join(n,t,"index.jsx")];for(let r of o)try{if((await T.stat(r)).isFile())return r}catch{}return null}toProjectRelative(e){let t=H(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};var Z=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=w.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Le(this.projectRoot,t);let n=e.toLowerCase(),o=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),r=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(o?this.extensions=[".ts",".tsx",".d.ts"]:r?this.extensions=[".js",".jsx",".mjs",".cjs"]:this.extensions=[".ts",".tsx",".d.ts"],!t?.tsconfigFile){this.tsconfigDir=this.sourceDir;return}this.tsconfigDir=w.dirname(t.tsconfigFile);let i=t.tsconfig?.compilerOptions;i&&(i.baseUrl&&(this.baseUrl=w.resolve(this.tsconfigDir,i.baseUrl)),i.paths&&typeof i.paths=="object"&&(this.paths=i.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=w.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=H(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 r of n){let i=await this.trySubstitution(e,t,r,o);if(i)return i}}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 r=n.length,i=o?e.length-o.length:e.length;return e.substring(r,i)}async trySubstitution(e,t,n,o){let r=n.replace("*",o),i=w.resolve(this.tsconfigDir,r);return await this.findFileWithExtensions(i)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=w.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(i=>e.endsWith(i));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],o=n.some(i=>e.endsWith(i)),r=e;if(o&&!t){for(let i of n)if(e.endsWith(i)){r=e.slice(0,-i.length);break}}if(!t)for(let i of this.extensions){let a=r+i;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let i of this.extensions){let a=w.join(r,`index${i}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await T.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await T.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=w.join(t,"package.json");try{if((await T.stat(n)).isFile())return n}catch{}let o=w.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 T.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=w.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 r=await this.tryPackageImportSubstitution(n,o);if(r)return r}if(Array.isArray(n)){for(let r of n)if(typeof r=="string"){let i=await this.tryPackageImportSubstitution(r,o);if(i)return i}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replace("*",t),o=w.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(o)}};var Oe=class extends z{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new X(e,t)}getImportResolver(e,t){return new Z(e,t)}};var Fe=class extends z{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new X(e,t)}getImportResolver(e,t){return new Z(e,t)}};Re();var Me=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=w.dirname(e),this.projectRoot=t;}async resolve(e){let t=e.split(".")[0];if(PYTHON_STDLIB_MODULES.has(t))return e;if(e.startsWith("."))return this.resolveRelative(e);let n=e.replace(/\./g,"/"),o=await this.tryResolveFile(w.resolve(this.projectRoot,n));return o?w.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),r=n?o+n.replace(/\./g,"/"):o.slice(0,-1)||".",i=w.resolve(this.sourceDir,r),a=await this.tryResolveFile(i);return a?w.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,w.join(e,"__init__.py"),w.join(e,"__init__.pyi")];for(let n of t)try{return await De.promises.access(n,De.constants.F_OK),n}catch{continue}return null}};var Be=class extends z{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new Me(e,process.cwd())}};var me={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"]},He=class{constructor(e){this.config=e;this.registerPlugin(new Oe),this.registerPlugin(new Fe),this.registerPlugin(new Be);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>ho,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??me.javascript};typescript={language:()=>_o.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??me.typescript};python={language:()=>yo,fileExtensions:()=>this.config?.languages.python?.fileExtensions??me.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};var wo={stable:"Code",insiders:"Code - Insiders"};function un(s,e){let t=Q__default.homedir(),n=process.platform,o=wo[s];switch(n){case "darwin":return w__default.join(t,"Library/Application Support",o,"User/globalStorage",e);case "win32":return w__default.join(process.env.APPDATA||w__default.join(t,"AppData/Roaming"),o,"User/globalStorage",e);default:return w__default.join(t,".config",o,"User/globalStorage",e)}}function mn(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:w__default.join(un(t,s),"settings","cline_mcp_settings.json")}))}function fn(){return w__default.join(un("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}function ht(){let s=Q__default.homedir();return w__default.join(s,".copilot","mcp-config.json")}function hn(){return [{displayName:"Copilot CLI",settingsPath:ht()}]}var yn={command:"npx",args:["-y","@constellationdev/mcp@latest"]},vo={extraKnownMarketplaces:{"constellation-marketplace":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},yt=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:vo},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:fn(),isGlobalConfig:true,getGlobalConfigPaths:mn,format:"json",mcpServersKeyPath:["mcpServers"],mcpServerExtras:{alwaysAllow:["code_intel"],disabled:false},hooksConfig:{filePath:".clinerules/hooks/placeholder",schemaVersion:1,adapterId:"cline"}},{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:ht(),isGlobalConfig:true,getGlobalConfigPaths:hn,format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${CONSTELLATION_ACCESS_KEY}"},mcpServerExtras:{tools:["code_intel"],type:"local"}},{id:"cursor",displayName:"Cursor",configPath:".cursor/mcp.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${env:CONSTELLATION_ACCESS_KEY}"},hooksConfig:{filePath:".cursor/hooks.json",schemaVersion:1,adapterId:"cursor"}},{id:"gemini-cli",displayName:"Gemini CLI",configPath:".gemini/settings.json",format:"json",mcpServersKeyPath:["mcpServers"],mcpEnv:{CONSTELLATION_ACCESS_KEY:"${CONSTELLATION_ACCESS_KEY}"},mcpServerExtras:{trust:true},hooksConfig:{filePath:".gemini/settings.json",schemaVersion:1,adapterId:"gemini"}},{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"]}}];function _t(s){return yt.find(e=>e.id===s)}var wt=null;async function _n(){if(!wt)try{let s=await import('@iarna/toml');wt={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return wt}function xo(s){let e="",t=0,n=s.length;for(;t<n;)if(s[t]==='"'){for(e+='"',t++;t<n&&s[t]!=='"';)s[t]==="\\"?(e+=s[t++],t<n&&(e+=s[t++])):e+=s[t++];t<n&&(e+=s[t++]);}else if(s[t]==="/"&&t+1<n&&s[t+1]==="/")for(t+=2;t<n&&s[t]!==`
|
|
126
|
+
`;)t++;else if(s[t]==="/"&&t+1<n&&s[t+1]==="*"){for(t+=2;t<n&&!(s[t]==="*"&&t+1<n&&s[t+1]==="/");)t++;t<n&&(t+=2);}else e+=s[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var ze=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=w__default.join(this.cwd,e.configPath);await this.ensureDirectoryExists(t);let n=await this.readConfig(t,e.format);if(e.configDefaults)for(let[o,r]of Object.entries(e.configDefaults))o in n||(n[o]=r);return e.pluginConfig&&(n=this.addPluginToArray(n,e.pluginConfig)),e.skipMcpServer||(n=this.addConstellationServer(n,e),await this.configureEnvPolicy(n,e)),await this.writeConfig(t,n,e.format),!e.skipMcpServer&&e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig),{tool:e,success:!0,configuredPath:t}}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:r}of t)try{await this.ensureDirectoryExists(r);let i=await this.readConfig(r,e.format);i=this.addConstellationServer(i,e),await this.writeConfig(r,i,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:!0,configuredPath:r});}catch(i){let a=i instanceof Error?i.message:String(i);a.includes("ENOENT")||a.includes("no such file")||n.push({tool:{...e,displayName:`${e.displayName} (${o})`},success:false,error:a});}return n}async ensureDirectoryExists(e){let t=w__default.dirname(e);await T__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await h.fileIsReadable(e))return {};let o=await h.readFile(e);return t==="json"?JSON.parse(o):t==="jsonc"?JSON.parse(xo(o)):(await _n()).parse(o)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let i=0;i<t.mcpServersKeyPath.length-1;i++){let a=t.mcpServersKeyPath[i];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let o=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[o]||typeof n[o]!="object")&&(n[o]={});let r=n[o];if(!r.constellation){let i=t.mcpServerConfigOverride??yn,a={...i};if(t.mcpServerExtras&&Object.assign(a,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",p=i[c];a[c]={...p,...t.mcpEnv};}r.constellation=a;}return e}async writeConfig(e,t,n){let o;n==="json"||n==="jsonc"?o=JSON.stringify(t,null,2):o=(await _n()).stringify(t),o=o.replace(/\r\n/g,`
|
|
127
|
+
`),o.endsWith(`
|
|
128
|
+
`)||(o+=`
|
|
129
|
+
`),await h.writeFile(e,o);}async configurePermissions(e){let t=w__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await h.fileIsReadable(t)){let c=await h.readFile(t);n=JSON.parse(c);}}catch{}let o=n;for(let a=0;a<e.allowKeyPath.length-1;a++){let c=e.allowKeyPath[a];(!o[c]||typeof o[c]!="object")&&(o[c]={}),o=o[c];}let r=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(o[r])||(o[r]=[]);let i=o[r];i.includes(e.allowValue)||i.push(e.allowValue),await h.writeFile(t,JSON.stringify(n,null," ")+`
|
|
130
|
+
`);}async configureMarketplace(e){let t=w__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await h.fileIsReadable(t)){let r=await h.readFile(t);n=JSON.parse(r);}}catch{}n=this.deepMerge(n,e.config),await h.writeFile(t,JSON.stringify(n,null," ")+`
|
|
131
|
+
`);}deepMerge(e,t){let n={...e};for(let o of Object.keys(t)){let r=t[o],i=e[o];r&&typeof r=="object"&&!Array.isArray(r)&&i&&typeof i=="object"&&!Array.isArray(i)?n[o]=this.deepMerge(i,r):n[o]=r;}return n}addPluginToArray(e,t){let n=e;for(let i=0;i<t.pluginKeyPath.length-1;i++){let a=t.pluginKeyPath[i];(!n[a]||typeof n[a]!="object")&&(n[a]={}),n=n[a];}let o=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[o])||(n[o]=[]);let r=n[o];return r.includes(t.pluginValue)||r.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:o,globalConfigPath:r}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,o),r&&await this.updateGlobalEnvPolicy(r,n,o,t.format);}addToEnvPolicyWhitelist(e,t,n){let o=e;for(let a=0;a<t.length-1;a++){let c=t[a];if(!o[c]||typeof o[c]!="object")return;o=o[c];}let r=t[t.length-1];if(!Array.isArray(o[r]))return;let i=o[r];for(let a of n)i.includes(a)||i.push(a);}async updateGlobalEnvPolicy(e,t,n,o){let r=e.replace(/^~/,Q__default.homedir()),i=await this.readConfig(r,o);if(Object.keys(i).length===0)return;let a=JSON.stringify(i);this.addToEnvPolicyWhitelist(i,t,n);let c=JSON.stringify(i);a!==c&&await this.writeConfig(r,i,o);}};var{prompt:wn}=vn;function fe(s,e){let t=w__default.normalize(s),n=w__default.normalize(e);return t.startsWith(n+w__default.sep)?w__default.relative(e,s):s}var he=class extends B{async run(e={}){try{if(console.log(`${M}Initializing project configuration...
|
|
132
|
+
`),!await this.git.isGitAvailable())throw new Error(`${m} Could not find git client installation.
|
|
133
|
+
${f} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=w__default.join(process.cwd(),"constellation.json"),o=null,r=await h.fileIsReadable(n);if(r)try{let E=await h.readFile(n);o=JSON.parse(E),console.log(`${f} Found existing constellation.json, current values will be used as defaults.
|
|
134
|
+
`);}catch{console.log(`${m} Existing constellation.json is invalid, starting fresh.
|
|
135
|
+
`);}if(!await this.git.isGitRepository())throw new Error(`${m} Current directory is not a git repository.
|
|
136
|
+
${f} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[c,p]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=c,g=p.filter(E=>E!==d),u=d?[d,...g]:g,_=this.getBranchInitialIndex(u,o?.branch),P=this.getInitialLanguages(o),C=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:o?.projectId??"",validate:E=>E.trim().length>0||"Project ID is required"},{choices:u,initial:_,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(o),initial:P,result(E){return E.map(L=>this.choices.find(Xe=>Xe.name===L)?.value??L)}}],J=await new vn().prompt(C),te={projectId:J.projectId.trim(),branch:J.branch,languages:{...J.languages.reduce((E,L)=>(E[L]={fileExtensions:me[L]||[]},E),{})}},ne=JSON.stringify(te,void 0,2);await h.writeFile(n,ne),console.log(`${y} ${r?"Updated":"Initialized"} configuration file at ${fe(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${y} 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(`${v} Failed to initialize configuration file.
|
|
137
|
+
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await wn({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=yt.map(g=>({name:g.displayName,value:g.id})),{selectedTools:n}=await wn({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(g){return g.map(u=>this.choices.find(P=>P.name===u)?.value??u)}});if(n.length===0){console.log(`${f} No tools selected, skipping MCP configuration`);return}let o=new ze(process.cwd()),r=[];for(let g of n){let u=_t(g);if(u)if(console.log(` ${f} Configuring ${u.displayName}...`),u.isGlobalConfig&&u.getGlobalConfigPaths){let _=await o.configureGlobalTool(u),P=false;for(let C of _)r.push(C),C.success?(P=true,console.log(` ${y} ${C.tool.displayName} configured at ${fe(C.configuredPath,process.cwd())}`)):C.error&&console.log(` ${m} ${C.tool.displayName}: ${C.error}`);if(P){let C=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${f} Note: ${u.displayName} uses ${C} (not project-level)`);}if(_.length===0){let C=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${m} ${u.displayName}: ${C}`);}}else {let _=await o.configureTool(u);r.push(_),_.success?(console.log(` ${y} ${u.displayName} configured at ${fe(_.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${y} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${m} ${u.displayName}: ${_.error}`);}}if(r.find(g=>g.tool.id==="claude-code"&&g.success)){let g=w__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(g),console.log(` ${y} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${m} Could not stage .claude/settings.json in git`);}}if(r.find(g=>g.tool.id==="codex-cli"&&g.success)){let g=w__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(g),console.log(` ${y} Added .codex/config.toml to staged changes in git`);}catch{}}if(r.find(g=>g.tool.id==="opencode"&&g.success)){let g=w__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(g),console.log(` ${y} Added opencode.jsonc to staged changes in git`);}catch{}}let p=r.filter(g=>g.success).length,d=r.filter(g=>!g.success).length;console.log(`
|
|
138
|
+
${y} MCP configuration complete: ${p} configured`),d>0&&console.log(`${m} ${d} tool(s) could not be configured`),await this.configureHooks(n,r),console.log(`
|
|
139
|
+
${f} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new ue(process.cwd()),o=ut(),r=e.map(c=>_t(c)).filter(c=>c!==void 0&&c.hooksConfig!==void 0&&t.some(p=>p.tool.id===c.id&&p.success));if(r.length===0)return;console.log(`
|
|
140
|
+
${f} Configuring AI hooks...`);let i=[];for(let c of r){let p=await n.configureHooks(c,o);if(i.push(p),p.success){let d=p.configuredPath?[p.configuredPath]:p.auxiliaryPaths??[];if(d.length>0){let g=p.configuredPath?fe(p.configuredPath,process.cwd()):w__default.dirname(d[0]);console.log(` ${y} ${c.displayName} hooks configured at ${g}`);for(let u of d){let _=w__default.isAbsolute(u)?fe(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${y} Added ${_} to staged changes in git`);}catch{console.log(` ${m} Could not stage ${_} in git`);}}}else console.log(` ${y} ${c.displayName} hooks configured`);}else console.log(` ${m} ${c.displayName}: ${p.error}`);}let a=i.filter(c=>c.success).length;a>0&&console.log(`${y} Hooks configuration complete: ${a} configured`);}buildLanguageChoices(e){return [{name:"C",value:"c"},{name:"C#",value:"c-sharp"},{name:"C++",value:"cpp"},{name:"Go",value:"go"},{name:"Java",value:"java"},{name:"JavaScript",value:"javascript"},{name:"PHP",value:"php"},{name:"Python",value:"python"},{name:"Ruby",value:"ruby"},{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 Ge=class s{constructor(e,t,n,o){this.branch=e;this.languages=t;this.projectId=n;this.exclude=o;this.apiUrl=process.env.CONSTELLATION_API_URL||"http://localhost:3000";}apiUrl;static async loadFromFile(e){if(await h.fileIsReadable(e)){let n=await h.readFile(e),o=JSON.parse(n),r=new s(o.branch,o.languages,o.projectId,o.exclude);return r.validate(),r}else throw new Error(`${v} 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 We=class{getVariable(e){return Promise.resolve(process.env[e])}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(`
|
|
141
|
+
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Ct=class extends We{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.
|
|
142
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);try{await new Promise((n,o)=>{let r=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),i="";r.stderr?.on("data",a=>{i+=a.toString();}),r.on("close",a=>{a===0?n():o(new Error(`setx failed with code ${a}: ${i}`));}),r.on("error",a=>{o(a);});}),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((r,i)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",p="";a.stdout?.on("data",d=>{c+=d.toString();}),a.stderr?.on("data",d=>{p+=d.toString();}),a.on("close",d=>{d===0?r(c):i(new Error(`reg query failed: ${p}`));}),a.on("error",d=>{i(d);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return o?o[1].trim():void 0}catch{return}}},Pt=class extends We{userConfigFiles;constructor(){super(),this.userConfigFiles=[w.join(Q.homedir(),".zshenv"),w.join(Q.homedir(),".profile")];}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
|
|
143
|
+
Configure CONSTELLATION_ACCESS_KEY directly in your pipeline settings.`);let n=this.escapeShellValue(t),o=`export ${e}="${n}"`;try{for(let r of this.userConfigFiles)await this.writeToConfigFile(r,e,o);process.env[e]=t;}catch(r){throw new Error(`Failed to set environment variable ${e}: ${r}`)}}async writeToConfigFile(e,t,n){let o="";try{o=await h.readFile(e,"utf-8");}catch{}let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^export ${r}=.*$`,"gm");i.test(o)?o=o.replace(i,n):o=o.trimEnd()+`
|
|
144
|
+
`+n+`
|
|
145
|
+
`,await h.writeFile(e,o);}},xt=class{static create(){let e=Q.platform();switch(e){case "win32":return new Ct;case "darwin":case "linux":return new Pt;default:throw new Error(`Unsupported platform: ${e}`)}}},Ke=class{manager;constructor(){this.manager=xt.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()}};var Ve=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=w__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};function bo(){let s=Q.platform();if(s==="darwin")return w.join(Q.homedir(),"Library","Caches","constellation");if(s==="win32"){let e=process.env.LOCALAPPDATA||w.join(Q.homedir(),"AppData","Local");return w.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||w.join(Q.homedir(),".cache");return w.join(e,"constellation")}}var Eo=bo(),Io="update-state.json",$o=1440*60*1e3,_e=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Eo,this.stateFile=w.join(this.stateDir,Io);}async load(){if(this.state)return this.state;try{let e=await T.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await T.mkdir(this.stateDir,{recursive:!0}),await T.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>$o}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 T.unlink(this.stateFile),this.state=null;}catch{}}};var we=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 r=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});r.on("close",i=>{o(i===0);}),r.on("error",()=>{o(false);});})}};var{prompt:No}=vn,ve=class{async promptForUpdate(e,t,n){console.log(""),console.log(l.cyan("\u2501".repeat(60))),console.log(`${M} ${l.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${l.dim(e)}`),console.log(` Latest version: ${l.green.bold(t)}`),console.log(""),console.log(` ${l.dim(`Package manager: ${n}`)}`),console.log(l.cyan("\u2501".repeat(60))),console.log("");try{let{shouldUpdate:o}=await No({type:"confirm",name:"shouldUpdate",message:"Would you like to update now?",initial:!0});return o}catch{return false}}};var Ro="https://registry.npmjs.org",Je="@constellationdev/cli",jo=5e3,Ye=class{cache;packageManager;prompter;constructor(){this.cache=new _e,this.packageManager=new we,this.prompter=new ve;}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(),jo);try{let o=await fetch(`${Ro}/${Je}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`Registry returned ${o.status}`);let i=(await o.json()).version;return {current:e,latest:i,hasUpdate:this.isNewerVersion(i,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=i=>i.split("-")[0],o=n(e).split(".").map(Number),r=n(t).split(".").map(Number);for(let i=0;i<3;i++){let a=o[i]||0,c=r[i]||0;if(a>c)return true;if(a<c)return false}return false}async performUpdate(){return console.log(`
|
|
146
|
+
${f} Updating ${Je}...
|
|
147
|
+
`),await this.packageManager.executeUpdate(Je)?(console.log(`
|
|
148
|
+
${y} Update complete! Please re-run your command.
|
|
149
|
+
`),true):(console.log(`
|
|
150
|
+
${m} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Je)}
|
|
151
|
+
`),false)}};async function St(s){return new Ye().check(s)}var Ao=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];function Lo(){return Ao.some(s=>!!process.env[s])}function Oo(){return !!process.stdout.isTTY}function Pn(){return !Lo()&&Oo()}var Ce=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 getChangedFiles(e){let t=await this.git.diff(["--name-status",e,"HEAD"]),n={added:[],modified:[],deleted:[],renamed:[]},o=t.split(/\r?\n/).map(r=>r.trim()).filter(Boolean);for(let r of o){let i=r.split(" ");if(i.length<2)continue;let a=i[0];a==="A"?n.added.push(i[1]):a==="M"?n.modified.push(i[1]):a==="D"?n.deleted.push(i[1]):a.startsWith("R")&&i.length>=3&&n.renamed.push({from:i[1],to:i[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.
|
|
152
|
+
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 Ho=w__default.dirname(fileURLToPath(import.meta.url)),Uo=w__default.join(Ho,"..","package.json"),zo=JSON.parse(readFileSync(Uo,"utf-8")),xn=zo.version,Go=["help","--help","-h","--version","-V","-v"];if(Pn()){let s=process.argv[2];["auth","help","init","index"].includes(s)?Ze(s):Ze(),Go.includes(s)||await St(xn)&&process.exit(0);}var bt=process.cwd(),Sn=new Ke,Pe=new Command;Pe.name("constellation").description("Connecting stars in your code into intelligent patterns").version(xn);Pe.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").action(async s=>{try{let t={GitClient:new Ce(bt)};await new he(t).run({skipMcp:s.skipMcp});}catch(e){console.error(`${v} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Pe.command("auth").description("Configure authentication for the Constellation CLI").action(async()=>{try{let s={Environment:Sn};await new ie(s).run();}catch(s){console.error(`${v} Failed to configure authentication: ${s instanceof Error?s.message:String(s)}`),process.exit(1);}});Pe.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)").action(async s=>{try{let e=await Ge.loadFromFile(w__default.join(bt,"constellation.json")),t=new Ce(bt),n=new He(e),o=new Ve(e),r={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:o,Environment:Sn},i=s.full||!1,a=s.dirty||!1;await new pe(r).run(i,a);}catch(e){!(e instanceof x)&&!(e instanceof I)&&console.error(`${v} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Pe.parse();
|
package/package.json
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@constellationdev/cli",
|
|
3
|
+
"description": "Transform your codebase into a constellation of intelligence - secure knowledge extraction and code navigation for AI assistants",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"author": "ShiftinBits Inc",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"bin": {
|
|
10
|
+
"constellation": "dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "rimraf dist && tsup",
|
|
14
|
+
"start": "tsx src/index.ts",
|
|
15
|
+
"lint": "eslint",
|
|
16
|
+
"lint:fix": "eslint --fix",
|
|
17
|
+
"lint:errors": "eslint --quiet",
|
|
18
|
+
"test": "jest",
|
|
19
|
+
"test:watch": "jest --watch",
|
|
20
|
+
"test:coverage": "jest --coverage",
|
|
21
|
+
"test:ci": "jest --ci --coverage --maxWorkers=2",
|
|
22
|
+
"type-check": "tsc --noEmit -p tsconfig.build.json",
|
|
23
|
+
"prepare": "husky",
|
|
24
|
+
"postinstall": "node -e \"if(process.env.CI) { console.log('Using github sourced @constellationdev/types') } else { try { require('child_process').execSync('npm link @constellationdev/types', {stdio: 'inherit'}); console.log('Using locally linked @constellationdev/types') } catch(e) { console.log('Note: @constellationdev/types not linked globally, using GitHub version') } }\""
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@constellationdev/types": "github:ShiftinBits/constellation-types#main",
|
|
28
|
+
"@iarna/toml": "^3.0.0",
|
|
29
|
+
"@scure/base": "^2.0.0",
|
|
30
|
+
"ansi-colors": "^4.1.3",
|
|
31
|
+
"commander": "^14.0.1",
|
|
32
|
+
"enquirer": "^2.4.1",
|
|
33
|
+
"ignore": "^7.0.5",
|
|
34
|
+
"simple-git": "^3.28.0",
|
|
35
|
+
"tree-sitter": "^0.21.1",
|
|
36
|
+
"tree-sitter-javascript": "^0.21.4",
|
|
37
|
+
"tree-sitter-python": "^0.21.0",
|
|
38
|
+
"tree-sitter-typescript": "^0.21.2",
|
|
39
|
+
"tsconfck": "^3.1.6",
|
|
40
|
+
"undici": "^7.22.0",
|
|
41
|
+
"zod": "^3.23.8"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@eslint/compat": "^1",
|
|
45
|
+
"@jest/globals": "^30.2.0",
|
|
46
|
+
"@types/iarna__toml": "^2.0.4",
|
|
47
|
+
"@types/jest": "^30.0.0",
|
|
48
|
+
"@types/node": "^24",
|
|
49
|
+
"eslint": "^9.38.0",
|
|
50
|
+
"eslint-config-prettier": "^10.1.8",
|
|
51
|
+
"eslint-plugin-prettier": "^5.5.4",
|
|
52
|
+
"husky": "^9.1.7",
|
|
53
|
+
"jest": "^30.2.0",
|
|
54
|
+
"lint-staged": "^16.2.7",
|
|
55
|
+
"prettier": "^3.7.4",
|
|
56
|
+
"rimraf": "^6.0.1",
|
|
57
|
+
"ts-jest": "^29.4.5",
|
|
58
|
+
"ts-node": "^10.9.2",
|
|
59
|
+
"tsup": "^8.5.1",
|
|
60
|
+
"tsx": "^4.20.6",
|
|
61
|
+
"typescript": "~5.9.3"
|
|
62
|
+
},
|
|
63
|
+
"engines": {
|
|
64
|
+
"node": ">=24.0.0",
|
|
65
|
+
"npm": ">=11.0.0"
|
|
66
|
+
},
|
|
67
|
+
"files": [
|
|
68
|
+
"dist"
|
|
69
|
+
],
|
|
70
|
+
"homepage": "https://constellationdev.io",
|
|
71
|
+
"bugs": "https://github.com/ShiftinBits/constellation-cli/issues",
|
|
72
|
+
"repository": {
|
|
73
|
+
"type": "git",
|
|
74
|
+
"url": "git+https://github.com/ShiftinBits/constellation-cli.git"
|
|
75
|
+
},
|
|
76
|
+
"keywords": [
|
|
77
|
+
"constellation",
|
|
78
|
+
"mcp",
|
|
79
|
+
"model",
|
|
80
|
+
"context",
|
|
81
|
+
"protocol",
|
|
82
|
+
"ai",
|
|
83
|
+
"server",
|
|
84
|
+
"tree-sitter",
|
|
85
|
+
"shiftinbits"
|
|
86
|
+
],
|
|
87
|
+
"license": "AGPL-3.0-only",
|
|
88
|
+
"lint-staged": {
|
|
89
|
+
"*.{ts,tsx}": [
|
|
90
|
+
"eslint --fix --quiet",
|
|
91
|
+
"prettier --write"
|
|
92
|
+
],
|
|
93
|
+
"*.{js,jsx,mjs}": [
|
|
94
|
+
"eslint --fix --quiet",
|
|
95
|
+
"prettier --write"
|
|
96
|
+
],
|
|
97
|
+
"*.{json,md,css}": [
|
|
98
|
+
"prettier --write"
|
|
99
|
+
]
|
|
100
|
+
}
|
|
101
|
+
}
|