@constellationdev/cli 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +54 -54
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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
|
-
`,
|
|
4
|
-
Caused by: ${
|
|
2
|
+
import*as w from'path';import w__default from'path';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import*as Be 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 Pn from'enquirer';import {performance}from'perf_hooks';import*as T from'fs/promises';import T__default from'fs/promises';import Vn from'tree-sitter';import Mt from'ignore';import {z as z$1}from'zod';import {promisify}from'util';import tt from'zlib';import {pipeline}from'stream/promises';import hr from'tree-sitter-javascript';import yr from'tree-sitter-python';import _r from'tree-sitter-typescript';import {findAll,parse}from'tsconfck';import {spawn}from'child_process';import {simpleGit}from'simple-git';var In=Object.defineProperty;var j=(s,e)=>()=>(s&&(e=s(s=0)),e);var kt=(s,e)=>{for(var t in e)In(s,t,{get:e[t],enumerable:true});};function Ft(s){return s.replace(/\\/g,"/")}function $e(s){return Ft(s).replace(/^\.?\//,"")}function H(s,e){return Ft(w.relative(s,e))}var Y=j(()=>{});async function U(s,e,t,n,r){let o=await t.resolve(s),i=Ut(s,o),a=r(s,o,i),c=i?void 0:$e(o);n[e.toString()]={source:s,resolvedPath:c,isExternal:i,importType:a};}function Ut(s,e){return s===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var nt,se=j(()=>{Y();nt=(s,e,t)=>t?s.startsWith("node:")?"builtin":"external":s.startsWith("./")||s.startsWith("../")?"relative":s.startsWith("@")?"workspace":"alias";});async function Zn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}async function Qn(s,e,t,n){let r=s.childForFieldName("source");if(!r)return;let o=r.startPosition.row,i=r.text.replace(/['"]/g,"");await U(i,o,e,t,n);}function Re(){return {language:"javascript",handlers:new Map([["import_statement",Zn],["export_statement",Qn]])}}function rt(){return {...Re(),language:"typescript"}}var ot=j(()=>{se();});async function nr(s,e,t,n){let r=s.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let i=r.childForFieldName("name");o=i?i.text:r.text;}else o=r.text;await U(o,s.startPosition.row,e,t,n);}async function rr(s,e,t,n){let r,o=s.childForFieldName("module_name");if(o)r=o.text;else {let i="";for(let a=0;a<s.childCount;a++){let c=s.child(a);if(c){if(c.type==="relative_import"){i=c.text;break}(c.type==="."||c.type==="import_prefix")&&(i+=c.text);}}r=i||".";}await U(r,s.startPosition.row,e,t,n);}async function or(s,e,t,n){await U("__future__",s.startPosition.row,e,t,n);}function it(){return {language:"python",handlers:new Map([["import_statement",nr],["import_from_statement",rr],["future_import_statement",or]]),classifyImportType:tr}}var tr,je=j(()=>{se();tr=(s,e,t)=>{if(t)return "external";if(/^\.+/.test(s))return "relative";let n=s.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Gt,Wt=j(()=>{ot();je();se();ot();je();Gt=[Re(),rt(),it()];});var Kt={};kt(Kt,{ImportExtractor:()=>st});var st,Vt=j(()=>{Wt();se();st=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Gt)this.languageHandlers.set(t.language,t.handlers),t.classifyImportType&&this.classifiers.set(t.language,t.classifyImportType);}async extractImportResolutions(e,t,n,r){if(!r)return {};let o=this.languageHandlers.get(n);if(!o)return {};let i=this.classifiers.get(n)??nt,a={};return await this.walkAST(e.rootNode,async c=>{let g=o.get(c.type);g&&await g(c,r,a,i);}),a}async walkAST(e,t){await t(e);for(let n=0;n<e.childCount;n++){let r=e.child(n);r&&await this.walkAST(r,t);}}};});var ae,Jt,at,Yt,qt,Ae=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"]),Jt=new Set(["true","false","null","undefined","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type"]),at={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},Yt={language:"javascript",textIncludedTypes:Jt,fieldNames:at},qt={language:"typescript",textIncludedTypes:Jt,fieldNames:at};});var ir,Xt,Zt,lt=j(()=>{ir=new Set(["true","false","none","None","True","False","yield","pass","continue","break","ellipsis","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","type","subscript","attribute","list","tuple","binary_operator","union_type","generic_type"]),Xt={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],list_splat_pattern:[],dictionary_splat_pattern:[],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]},Zt={language:"python",textIncludedTypes:ir,fieldNames:Xt,shouldIncludeText:s=>{if(s.type==="string"&&s.childCount>0)return false}};});function Qt(s){return le.get(s)}function en(s){if(!s)return 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 ct(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,tn=j(()=>{pt();Ae();lt();Ae();Ae();lt();le=new Map([["javascript",Yt],["typescript",qt],["python",Zt]]);});var an={};kt(an,{COMMON_FIELD_NAMES:()=>ut,JS_TS_FIELD_NAMES:()=>on,PYTHON_FIELD_NAMES:()=>sn,TEXT_INCLUDED_TYPES:()=>nn,mergeFieldMaps:()=>ce,serializeAST:()=>ar,serializeASTStream:()=>sr});function*sr(s,e,t){yield*dt(s,e,t);}function*dt(s,e,t){if(yield "{",yield `"type":${JSON.stringify(s.type)}`,yield `,"startPosition":${JSON.stringify({row:s.startPosition.row,column:s.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:s.endPosition.row,column:s.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),rn(s,t)&&(yield `,"text":${JSON.stringify(s.text)}`),s.childCount>0){yield ',"children":[';let r=(t?ct(t):ut)[s.type]||[],o=new Set,i=true;for(let a of r){let c=s.childForFieldName(a);c&&(i||(yield ","),i=false,o.add(c),yield*dt(c,a,t));}for(let a=0;a<s.childCount;a++){let c=s.child(a);c&&!o.has(c)&&(i||(yield ","),i=false,yield*dt(c,void 0,t));}yield "]";}yield "}";}async function ar(s,e,t){let n=gt(s,e,t),r=t?ct(t):ut,o=[{treeNode:s,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;o.length>0;){let i=o[o.length-1];if(i.childIndex===0&&i.treeNode.childCount>0){let a=r[i.treeNode.type]||[];for(let c of a){let g=i.treeNode.childForFieldName(c);if(g){i.fieldChildren.add(g);let d=gt(g,c,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(d),o.push({treeNode:g,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=gt(a,void 0,t);i.serializedNode.children||(i.serializedNode.children=[]),i.serializedNode.children.push(c),o.push({treeNode:a,serializedNode:c,childIndex:0,fieldChildren:new Set});}}else o.pop();}return n}function gt(s,e,t){let n={type:s.type,startPosition:{row:s.startPosition.row,column:s.startPosition.column},endPosition:{row:s.endPosition.row,column:s.endPosition.column},...e&&{fieldName:e}};return rn(s,t)&&(n.text=s.text),n}function rn(s,e){if(e){let n=Qt(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(s);if(o===false)return false;if(o===true)return true}return en(e).has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}return s.type==="string"&&s.childCount>0?false:nn.has(s.type)||s.type.endsWith("_keyword")||s.type.endsWith("_operator")}function ce(...s){let e={};for(let t of s)for(let[n,r]of Object.entries(t)){let i=[...e[n]||[]];for(let a of r)i.includes(a)||i.push(a);e[n]=i;}return e}var nn,on,sn,ut,pt=j(()=>{tn();nn=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","true","false","null","undefined","import_specifier","export_specifier","predefined_type","type_predicate","type_predicate_annotation","type_alias","type_annotation","return_type","type_arguments","type_parameters","array_type","union_type","intersection_type","generic_type","tuple_type","function_type","object_type","mapped_type","conditional_type","infer_type","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","dotted_name","aliased_import","not_operator","boolean_operator","comparison_operator","yield","pass","continue","break","None","none","True","False","ellipsis","type","string_content"]);on={function_declaration:["name","parameters","body","return_type","type_parameters"],function_expression:["name","parameters","body","return_type","type_parameters"],arrow_function:["parameters","body","return_type","type_parameters"],method_definition:["name","parameters","body","return_type","type_parameters"],method_signature:["name","parameters","return_type","type_parameters"],function_signature:["name","parameters","return_type","type_parameters"],type_predicate:["name","type"],class_declaration:["name","body","type_parameters","heritage"],interface_declaration:["name","body","type_parameters"],type_alias_declaration:["name","type_parameters","value"],property_signature:["name","type"],field_definition:["name","type","value"],public_field_definition:["name","type","value"],private_field_definition:["name","type","value"],required_parameter:["pattern","type","value"],optional_parameter:["pattern","type","value"],rest_parameter:["pattern","type"],variable_declarator:["name","type","value"],lexical_declaration:["kind"],call_expression:["function","arguments","type_arguments"],new_expression:["constructor","arguments","type_arguments"],member_expression:["object","property"],assignment_expression:["left","right"],binary_expression:["left","right","operator"],unary_expression:["operator","argument"],ternary_expression:["condition","consequence","alternative"],import_statement:["source","import"],import_specifier:["name","alias"],export_specifier:["name","alias"],export_statement:["source","declaration","value"],if_statement:["condition","consequence","alternative"],for_statement:["init","condition","update","body"],for_in_statement:["left","right","body"],while_statement:["condition","body"],do_statement:["body","condition"],switch_statement:["value","body"],try_statement:["body","handler","finalizer"],catch_clause:["parameter","body"],return_statement:["value"],throw_statement:["value"],type_annotation:["type"],type_parameter:["name","constraint","default"],generic_type:["name","type_arguments"]},sn={function_definition:["name","parameters","return_type","body","type_parameters"],async_function_definition:["name","parameters","return_type","body","type_parameters"],class_definition:["name","superclasses","body","type_parameters"],decorated_definition:["definition"],lambda:["parameters","body"],import_statement:["name"],import_from_statement:["module_name","name"],aliased_import:["name","alias"],assignment:["left","right","type"],augmented_assignment:["left","right"],type_alias_statement:["name","type_parameters","value"],annotated_assignment:["left","right","type"],except_clause:["cause"],except_group_clause:["cause"],return_statement:["value"],assert_statement:["condition","message"],delete_statement:["target"],global_statement:["name"],nonlocal_statement:["name"],typed_parameter:["name","type"],default_parameter:["name","value"],typed_default_parameter:["name","type","value"],call:["function","arguments"],attribute:["object","attribute"],binary_operator:["left","right"],unary_operator:["argument"],not_operator:["argument"],boolean_operator:["left","right"],comparison_operator:["operators"],named_expression:["name","value"],conditional_expression:["condition","consequence","alternative"],keyword_argument:["name","value"],if_statement:["condition","consequence","alternative"],while_statement:["condition","body","alternative"],for_statement:["left","right","body"],try_statement:["body"],with_statement:["body"],with_item:["value"],finally_clause:["body"],else_clause:["body"],match_statement:["subject","body"],case_clause:["pattern","guard"],raise_statement:["cause"],list_comprehension:["body"],dictionary_comprehension:["body","key","value"],set_comprehension:["body"],generator_expression:["body"],for_in_clause:["left","right"],if_clause:["condition"],pair:["key","value"],subscript:["value","subscript"],slice:["start","stop","step"]};ut=ce(on,sn);});function Nt(s){return base32.encode(Buffer.from(s))}function Rt(s,e,t){let n=`${s}:${e}${t?`:${t}`:""}`;return Nt(n)}var Se=class extends Readable{dataSource;sourceIterator;reading=false;constructor(e){super(),this.dataSource=e,this.sourceIterator=this.dataSource[Symbol.asyncIterator]();}async _read(){if(!this.reading){this.reading=true;try{for(;;){let{value:e,done:t}=await this.sourceIterator.next();if(t){this.push(null);break}let n=JSON.stringify(e)+`
|
|
3
|
+
`,r=Buffer.from(n,"utf8");if(!this.push(r))break}}catch(e){this.destroy(e);}finally{this.reading=false;}}}_destroy(e,t){this.dataSource.return?this.dataSource.return(null).then(()=>t(e),n=>t(e||n)):t(e);}};function kn(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true: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 Nn="\u2714",Rn="\u2717",jn="\u26A0",An="\u2139",Ln="\u26A1",On="[OK]",Fn="[ERR]",Mn="[WARN]",Dn="[INFO]",Bn="[>>]",oe=kn(),h=l.green(oe?Nn:On),C=l.red(oe?Rn:Fn),y=l.yellow(oe?jn:Mn),f=l.blue(oe?An:Dn),M=l.yellow(oe?Ln:Bn);var be=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 S||e instanceof $)throw e;return console.error(`${C} 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 $(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new $(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new $(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new 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 $||t instanceof O)throw t;if(e.status===404)throw new O("Project not found - no previous index exists")}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let r=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let o=await this.sendRequest(r,null,"GET");return !o||!o.ok?null:await o.json()}catch(o){if(o instanceof S)throw o;return null}}async deleteFiles(e){for(let t of e){let n=Rt(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,r,o,i){try{let{Readable:a}=await import('stream'),c=new Se(e),g=a.toWeb(c),d=new Agent({headersTimeout:0,bodyTimeout:0}),p=await fetch$1(`${this.config.apiUrl}/${this.apiVersion}/${t}`,{method:"POST",headers:{"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":n,"x-branch-name":r,"x-constellation-index":o?"incremental":"full",Authorization:`Bearer ${this.accessKey}`,...i&&{"x-commit-hash":i}},body:g,duplex:"half",dispatcher:d});if(p.status===401)throw new S("Authentication failed");if(p.status===409){let u="Indexing already in progress",m;try{let v=await p.json();u=v?.message||u,m=v?.details?.branchName;}catch{}throw new J(u,m)}if(p.status===200)try{let u=await p.json();if(u?.status==="current")return console.log(`${h} Index already up to date for ${r} at commit ${u.commitHash||"unknown"}`),!0}catch{}return p.ok===!0||p.status===202}catch(a){if(a instanceof S||a instanceof J)throw a;let c=a instanceof Error?a:new Error(String(a)),g="";if(c.message==="fetch failed"||a.code){let p=[],u=a.code||a.cause?.code;if(a.code&&p.push(`Error Code: ${a.code}`),a.cause){let m=a.cause;m.code&&p.push(`Cause Code: ${m.code}`),m.errno&&p.push(`Errno: ${m.errno}`),m.syscall&&p.push(`System Call: ${m.syscall}`),m.address&&p.push(`Address: ${m.address}`),m.port&&p.push(`Port: ${m.port}`);}u==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":u==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":u==="ENOTFOUND"?g="DNS lookup failed - check service URL":u==="ETIMEDOUT"?g="Connection timeout - service not responding":u==="ECONNRESET"?g="Connection reset by server":u==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",p.length>0&&(g+=` (${p.join(", ")})`);}else g=c.message;let d=new Error(`Failed to upload data to Constellation Service: ${g}`);throw d.cause=c,d.stack=`${d.stack}
|
|
4
|
+
Caused by: ${c.stack}`,d}}async sendRequest(e,t,n,r={},o=0,i=3,a=1e3,c=250){for(let g=1;g<=i;g++)try{let d=new AbortController,p;o>0&&(p=setTimeout(()=>d.abort(),o));let u={...r,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},m=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:u,body:t?JSON.stringify(t):void 0,signal:d.signal});if(p&&clearTimeout(p),m.status===401)throw new S("Authentication failed");if(!m.ok&&this.retryableStatusCodes.includes(m.status))throw new Ee(`${m.statusText} (${m.status})`);return m}catch(d){if(!(d instanceof S)){let p=d instanceof Error?`${d.message}${d.cause?` (Cause: ${d.cause})`:""}`:String(d);console.log(`HTTP request attempt ${g}/${i} failed: ${p}`);}if(g<i&&d instanceof Ee){let p=a+Math.floor(Math.random()*c);await new Promise(u=>setTimeout(u,p));}else throw d}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Ee=class extends Error{constructor(e){super(e),this.name="RetryableError";}},S=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},O=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},$=class extends Error{constructor(t,n,r){super(t);this.code=n;this.projectId=r;this.name="ProjectValidationError";}},J=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}};function Qe(s){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
5
5
|
\u2502 ${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
6
|
\u2502 _____ ${l.yellowBright("*")} ${l.dim("`")} __${l.whiteBright(".")} ${l.whiteBright("'")} ____ ${l.dim(".")} __ _ ${l.gray("`")} . . ${l.yellowBright("o")} ${l.blueBright("+")} \u2502
|
|
7
7
|
\u2502 ${l.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${l.gray(".")} ${l.yellowBright("'")} ${l.gray("+")} ${l.gray("\\")} ${l.gray("`")} \u2502
|
|
@@ -27,8 +27,8 @@ ${l.gray(" \\")}
|
|
|
27
27
|
${l.blueBright(" o")}${l.blueBright("----")}${l.yellowBright("o")} ${l.gray("o")}
|
|
28
28
|
${l.gray(" \\ \\ ")}${l.blueBright("/")}
|
|
29
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:
|
|
31
|
-
`),this.env.isCI()){console.error(`${
|
|
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:At}=Pn,Gn=/^ak:[0-9a-f]{32}$/i;function Wn(s){return Gn.test(s)}function Kn(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(`${C} Cannot configure authentication in CI/CD environments
|
|
32
32
|
|
|
33
33
|
The ${D} environment variable must be configured
|
|
34
34
|
directly in your pipeline settings:
|
|
@@ -38,33 +38,33 @@ ${l.whiteBright(" o o")}${l.blueBright("-")}${l.blueBright("o")}
|
|
|
38
38
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
39
39
|
- Jenkins: Manage Jenkins -> Credentials
|
|
40
40
|
- CircleCI: Project Settings -> Environment Variables
|
|
41
|
-
`);return}if(await this.env.getKey(D)){let{replaceKey:
|
|
42
|
-
`),n++;continue}if(!
|
|
43
|
-
Attempts remaining: ${
|
|
44
|
-
`);else {console.error(`${
|
|
45
|
-
Please verify your access key and try again.`);return}continue}break}await this.env.setKey(D,t),console.log(`${
|
|
46
|
-
${n}`);}}};var
|
|
47
|
-
`);let
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${
|
|
41
|
+
`);return}if(await this.env.getKey(D)){let{replaceKey:o}=await At({message:"Replace existing Constellation access key?",name:"replaceKey",type:"confirm",initial:!1});if(!o){console.log(`${h} Keeping existing Constellation access key`);return}}let t,n=0,r=3;for(;n<r;){if(t=(await At({message:"Constellation Access Key:",name:"accessKey",type:"password",required:!0})).accessKey.trim(),!t){console.log(`${y} Access key cannot be empty.
|
|
42
|
+
`),n++;continue}if(!Wn(t)){if(n++,n<r)console.log(`${y} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
43
|
+
Attempts remaining: ${r-n}
|
|
44
|
+
`);else {console.error(`${C} Invalid access key format after ${r} attempts.
|
|
45
|
+
Please verify your access key and try again.`);return}continue}break}await this.env.setKey(D,t),console.log(`${h} 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=Kn(t);console.error(`${C} Failed to store Constellation access key
|
|
46
|
+
${n}`);}}};var _={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 Ie=class{constructor(e){this.langRegistry=e;}async parseFile(e,t){let n=this.langRegistry[t]?.language;if(!n)throw new Error(`Unsupported language: ${t}`);let r=await n();if(!r)throw new Error(`Failed to load language: ${t}`);let o=new Vn;o.setLanguage(r);let i=await _.getFileStats(e),a=10*1024*1024;if(i.size<=a){let c=await _.readFile(e),g={bufferSize:1024*1024};return o.parse(c,void 0,g)}else return this.parseWithStream(o,e,i.size)}async parseWithStream(e,t,n){let r=null;try{r=await T.open(t,"r");let o=r.fd,i=64*1024,a=Buffer.alloc(i),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 p=Be.readSync(o,a,0,i,d);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(r)try{await r.close();}catch(i){console.error(`Warning: Failed to close file handle for ${t}:`,i);}throw o}finally{if(r)try{await r.close();}catch{}}}};Y();var Te=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Mt();return await this.loadGitignoreRules(t,this.rootPath),e.exclude&&e.exclude.length>0&&t.add(e.exclude),(await this.walkDirectory(this.rootPath)).filter(o=>!t.ignores(o.relativePath)&&this.matchesLanguageExtension(o,e.languages))}async scanSpecificFiles(e,t){let n=[],r=null;t.exclude&&t.exclude.length>0&&(r=Mt().add(t.exclude));let o=await T__default.realpath(this.rootPath);for(let i of e)try{let a=w__default.isAbsolute(i)?i:w__default.join(this.rootPath,i),c=await T__default.lstat(a);if(c.isSymbolicLink()){let g=await T__default.realpath(a);if(!g.startsWith(o+w__default.sep)&&g!==o){console.warn(`${y} Skipping symlink pointing outside project: ${i} -> ${g}`);continue}let d=await T__default.stat(a);if(!d.isFile())continue;let p=H(this.rootPath,a);if(r&&r.ignores(p))continue;let u=this.detectLanguage(p,t.languages);if(!u)continue;n.push({path:a,relativePath:p,language:u,size:d.size});}else if(c.isFile()){let g=H(this.rootPath,a);if(r&&r.ignores(g))continue;let d=this.detectLanguage(g,t.languages);if(!d)continue;n.push({path:a,relativePath:g,language:d,size:c.size});}}catch{console.warn(`${y} Skipping inaccessible file: ${i}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let o=w__default.join(r,".gitignore");await _.fileIsReadable(o)&&n.unshift(o);let i=w__default.dirname(r);if(i===r)break;r=i;let a=w__default.join(r,".git");if(await _.directoryExists(a)){let c=w__default.join(r,".gitignore");await _.fileIsReadable(c)&&!n.includes(c)&&n.unshift(c);break}}for(let o of n)try{let i=await _.readFile(o);e.add(i);}catch{console.warn(`${y} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,n){let r=[],o=t||e,i=n||await T__default.realpath(this.rootPath);try{let a=await T__default.readdir(e,{withFileTypes:!0});for(let c of a){let g=w__default.join(e,c.name),d=H(o,g);if(c.isDirectory()){if(c.name.startsWith("."))continue;let p=await this.walkDirectory(g,o,i);r.push(...p);}else if(c.isFile()){let p=await T__default.stat(g);r.push({path:g,relativePath:d,language:"",size:p.size});}else if(c.isSymbolicLink())try{let p=await T__default.realpath(g);if(!p.startsWith(i+w__default.sep)&&p!==i){console.warn(`${y} Skipping symlink pointing outside project: ${g} -> ${p}`);continue}let u=await T__default.stat(g);if(u.isDirectory()){if(c.name.startsWith("."))continue;let m=await this.walkDirectory(g,o,i);r.push(...m);}else u.isFile()&&r.push({path:g,relativePath:d,language:"",size:u.size});}catch{console.warn(`${y} Skipping invalid symlink: ${g}`);}}}catch(a){console.error(`${C} Error walking directory ${e}:`,a);}return r}matchesLanguageExtension(e,t){let n=w__default.extname(e.path).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return e.language=r,true;return false}detectLanguage(e,t){let n=w__default.extname(e).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return r;return null}};var Jn=z$1.object({source:z$1.string().min(1,"Import source cannot be empty"),resolvedPath:z$1.string().optional(),isExternal:z$1.boolean(),importType:z$1.enum(["relative","workspace","alias","external","builtin"])}),Yn=z$1.record(z$1.string(),Jn),Dt=z$1.object({file:z$1.string().min(1,"File path cannot be empty").max(1e3,"File path too long"),language:z$1.string().regex(/^(bash|c|c-sharp|cpp|go|java|javascript|json|php|python|ruby|typescript)$/,"Invalid language identifier"),commit:z$1.string().regex(/^[a-f0-9]{40}$/,"Invalid git commit hash"),timestamp:z$1.string().datetime({message:"Invalid ISO timestamp"}),ast:z$1.string().min(1,"AST data cannot be empty").max(1e7,"AST data exceeds 10MB limit"),importResolutions:Yn.optional()});var Xn=promisify(tt.gunzip),ke=class{*serializeASTChunks(e){if(yield "{",yield `"type":"${e.type}"`,yield `,"startPosition":${JSON.stringify(e.startPosition)}`,yield `,"endPosition":${JSON.stringify(e.endPosition)}`,e.fieldName!==void 0&&(yield `,"fieldName":"${e.fieldName}"`),e.text!==void 0&&(yield `,"text":${JSON.stringify(e.text)}`),e.children&&e.children.length>0){yield ',"children":[';for(let t=0;t<e.children.length;t++)t>0&&(yield ","),yield*this.serializeASTChunks(e.children[t]);yield "]";}yield "}";}async compressStream(e){let t=[],n=tt.createGzip();n.on("data",i=>t.push(i));let r=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),o=Readable.from(e);return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async compress(e){let t=[],n=tt.createGzip();n.on("data",i=>t.push(i));let r=new Promise((i,a)=>{n.on("end",i),n.on("error",a);}),o=Readable.from(this.serializeASTChunks(e));return await pipeline(o,n),await r,Buffer.concat(t).toString("base64")}async decompress(e){let t=Buffer.from(e,"base64"),n=await Xn(t);return JSON.parse(n.toString("utf-8"))}};var Ne=class{constructor(e=10){this.concurrency=e;if(e<1)throw new Error("Concurrency must be at least 1")}async*run(e,t){if(e.length===0)return;let n=new Map,r=0,o=0;for(;o<e.length&&n.size<this.concurrency;){let i=r++,a=this.processItem(e[o],o,t).then(c=>({result:c!==null?c.result:null,promiseId:i}));n.set(i,a),o++;}for(;n.size>0;){let i=await Promise.race(n.values());if(n.delete(i.promiseId),i.result!==null&&(yield i.result),o<e.length){let a=r++,c=this.processItem(e[o],o,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,c),o++;}}}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 Te(process.cwd()),this.parser=new Ie(this.langRegistry),this.compressor=new ke;for(let t of Object.keys(this.config.languages)){let n=this.langRegistry.getPlugin(t);if(n?.getBuildConfigManager){let r=n.getBuildConfigManager(process.cwd(),this.config.languages);r&&this.buildConfigManagers.set(t,r);}}}async run(e=false,t=false){try{let n=await this.getAccessKey();this.apiClient=new be(this.config,n),await this.validateProject(),console.log(`${M}Starting indexing procedure...
|
|
47
|
+
`);let r=performance.now();if(t?console.log(`${y} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${y} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${y} Skipping repository synchronization`):await this.synchronizeChanges(),this.buildConfigManagers.size>0){console.log(`${f} Discovering language build configurations...`);let x=0;for(let[xe,ne]of this.buildConfigManagers.entries()){let b=await ne.initialize();x+=b.length;}x>0&&console.log(`${h} Found ${x} configuration file(s)`);}let o=await this.determineIndexScope(e),i=await this.git.getLatestCommitHash();if(o.upToDate){console.log(`
|
|
48
|
+
${h} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${i.substring(0,8)}`);return}if(o.isIncremental&&i){let x=await this.apiClient.getIndexStatus(this.config.branch,i);if(x?.status==="current"||x?.status==="processing"&&x?.commitHash===i){console.log(`${h} Index already up to date for branch ${this.config.branch} at commit ${i.substring(0,8)}`);return}}let a=await this.discoverFiles(o.isIncremental),c=!1,g=()=>{c||console.log(`${f} Uploading metadata, processing, and indexing...`);},d=this.generateASTs(a,g);try{await this.uploadToAPI(d,o.isIncremental,i),c=!0;}catch(x){throw c=!0,x}let m=(performance.now()-r)/1e3,v=Math.floor(m/60),P=(m%60).toFixed(3),te=v>0?`${v}m ${P}s`:`${P}s`;console.log(`
|
|
49
|
+
${h} Upload completed in ${te}! Server indexing in progress.`);}catch(n){if(n instanceof $)throw n;if(n instanceof J)throw console.error(`${C} Indexing failed: Another indexing operation is currently in progress for branch ${n.branchName||this.config?.branch||"unknown"}.`),console.log(" Your index may be out of date. Re-run this command after the current operation completes."),n;if(n instanceof S)throw console.error(`
|
|
50
|
+
${C} Authentication failed.`),console.log(`${f} Run 'constellation auth' to set or update your access key.`),n;let r=n instanceof Error?n.message:"An unexpected error occurred";throw console.error(`${C} Indexing failed: ${r}`),n}}async getAccessKey(){let e=await this.env.getKey(D);if(!e)throw new Error(`Access key not found.
|
|
51
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(`${
|
|
53
|
-
${
|
|
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(`${h} Project validated successfully`);}catch(e){if(e instanceof $)throw this.displayProjectValidationError(e),e;if(e instanceof O){console.log(`${h} Project validated (first index)`);return}if(e instanceof S)throw e;console.log(`${y} 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
|
+
${C} Project not registered
|
|
54
54
|
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not associated with your Constellation account.
|
|
55
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
56
|
`);break;case "PROJECT_INACTIVE":console.error(`
|
|
57
|
-
${
|
|
57
|
+
${C} Project is inactive
|
|
58
58
|
`),console.error(` The project "${n}" has been deactivated.
|
|
59
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
60
|
`);break;case "INVALID_PROJECT_ID":console.error(`
|
|
61
|
-
${
|
|
61
|
+
${C} Invalid project ID
|
|
62
62
|
`),console.error(` The project ID "${n}" in constellation.json`),console.error(` is not a valid Constellation project identifier.
|
|
63
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
64
|
`);break;default:console.error(`
|
|
65
|
-
${
|
|
66
|
-
`);}}async validateGitBranch(){console.log(`${f} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${
|
|
67
|
-
Commit or stash changes first to ensure consistent indexing.`);console.log(`${
|
|
65
|
+
${C} 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(`${h} 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(`${h} Working tree clean`);}async synchronizeChanges(){console.log(`${f} Synchronizing latest changes...`);try{await this.git.pull()&&console.log(`${h} Repository synchronized successfully`);}catch(e){throw console.error(`${C} Failed to synchronize repository`),e instanceof Error&&(e.message.includes("uncommitted changes")?(console.error(`
|
|
68
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
69
|
`)):e.message.includes("merge conflicts")?(console.error(`
|
|
70
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
|
|
@@ -72,7 +72,7 @@ To resolve:`),console.error(" 1. Fix the conflicted files manually"),console.er
|
|
|
72
72
|
Please check your internet connection and try again
|
|
73
73
|
`):e.message.includes("Authentication")&&console.error(`
|
|
74
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
|
|
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 r=await this.git.getLatestCommitHash();return n===r?(console.log(`${h} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${f} Last indexed commit: ${n.substring(0,8)}`),console.log(`${f} Current commit: ${r.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 S)throw t;return console.log(`${y} 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(`${y} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);else {let r=await this.git.getChangedFiles(n.latestCommit),o=[...r.added,...r.modified,...r.renamed.map(a=>a.to)];console.log(`${f} Found ${o.length} changed files`),t=await this.scanner.scanSpecificFiles(o,this.config);let i=[...r.deleted,...r.renamed.map(a=>a.from)];if(i.length>0){let a=r.deleted.length,c=r.renamed.length,g=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(g),await this.apiClient.deleteFiles(i);}}}catch(n){if(n instanceof S)throw n;console.log(`${y} 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(`${h} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),r=e.length,o=0,i=0;console.log(`${f} Processing ${r} files...`);let a=await this.git.getLatestCommitHash(),c=r>1e4?5:r>5e3?7:10;c<10&&console.log(`${f} Large project detected - using concurrency of ${c} to optimize memory usage`);let d=new Ne(c).run(e,async(p,u)=>{let m=Math.round((u+1)/r*100);console.log(`${f} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${m}%)...`);try{let v=await this.parser.parseFile(p.path,p.language),P=this.langRegistry.getPlugin(p.language),te;if(P?.getImportResolver){let Xe=this.buildConfigManagers.get(p.language),Ze=Xe?await Xe.getConfigForFile(p.path):null,Tt=P.getImportResolver(p.path,Ze);if(Tt){let{ImportExtractor:En}=await Promise.resolve().then(()=>(Vt(),Kt));te=await new En().extractImportResolutions(v,p.path,p.language,Tt);}}let{serializeASTStream:x}=await Promise.resolve().then(()=>(pt(),an)),xe=x(v.rootNode,void 0,p.language),ne=await this.compressor.compressStream(xe),b={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:n,ast:ne,importResolutions:te},L=Dt.safeParse(b);if(!L.success)throw new Error(`AST validation failed: ${L.error.issues[0].message}`);return o++,L.data}catch(v){throw i++,console.error(` ${y} Failed to parse ${p.relativePath}: ${v.message}`,v),v}});for await(let p of d)yield p;i>0?console.log(`${y} Completed parsing with ${i} parsing errors`):console.log(`${h} All files analyzed successfully`),t&&t();}async uploadToAPI(e,t,n){if(!await this.apiClient.streamToApi(e,"ast",this.config.projectId,this.config.branch,t,n))throw new Error("Failed to upload data to Constellation Service");console.log(`${h} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return $e(e)}};var cn=[{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
76
|
|
|
77
77
|
Mental model:
|
|
78
78
|
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
@@ -80,7 +80,7 @@ Mental model:
|
|
|
80
80
|
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
81
81
|
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
82
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
|
|
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 mt(){return cn}var pn={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},lr="code_intel";function cr(s){return pn[s]}var ge=class{id="cline";displayName="Cline";mapEventName(e){return pn[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,lr)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let r=cr(n.event);if(!r)continue;let o=`.clinerules/hooks/${r}`,i=this.generateScript(n);t.set(o,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
84
|
# Constellation ${e.event} Hook for Cline
|
|
85
85
|
# Generated by constellation-cli - DO NOT EDIT
|
|
86
86
|
#
|
|
@@ -93,7 +93,7 @@ cat << 'CONSTELLATION_EOF'
|
|
|
93
93
|
"contextModification": "${n}"
|
|
94
94
|
}
|
|
95
95
|
CONSTELLATION_EOF
|
|
96
|
-
`}};var
|
|
96
|
+
`}};var pr={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},gr="constellation__code_intel",q=class{id="cursor";displayName="Cursor";mapEventName(e){return pr[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let o={type:n.type};n.type==="prompt"&&(o.prompt=this.customizePrompt(n)),n.matcher&&(o.matcher=n.matcher),t[r].push(o);}return {version:1,hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,gr)}};var dr={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},ur={SessionStart:"startup",SubagentStart:"",PreCompact:""},mr="code_intel";function gn(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 dr[e]}generateConfig(e){let t={};for(let n of e){let r=this.mapEventName(n.event);if(!r)continue;t[r]||(t[r]=[]);let o=ur[n.event]??"",i=gn(n.event),a=t[r].find(c=>c.matcher===o);a||(a={matcher:o,hooks:[]},t[r].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,mr)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){if(!this.mapEventName(n.event))continue;let i=`.gemini/hooks/${gn(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
97
|
# Constellation ${e.event} Hook for Gemini CLI
|
|
98
98
|
# Generated by constellation-cli - DO NOT EDIT
|
|
99
99
|
#
|
|
@@ -116,37 +116,37 @@ cat << 'CONSTELLATION_EOF'
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
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
|
|
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 fr=new Map([["cline",new ge],["cursor",new q],["gemini",new de]]);function ft(s){return fr.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=ft(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let r=w__default.join(this.cwd,e.hooksConfig.filePath),o=n.generateConfig(t),i=Object.keys(o).some(c=>{let g=o[c];return g!=null&&(typeof g!="object"||Object.keys(g).length>0)});if(i){await this.ensureDirectoryExists(r);let c=await this.readConfig(r),g=this.mergeHooksConfig(c,o);await this.writeConfig(r,g);}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?r:void 0,auxiliaryPaths:a}}catch(r){return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:r instanceof Error?r.message:String(r)}}}async ensureDirectoryExists(e){let t=w__default.dirname(e);await T__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await _.fileIsReadable(e))return {};let n=await _.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},r=t.hooks??{},o={...n,...r},i={...e,hooks:o};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
120
|
`),n.endsWith(`
|
|
121
121
|
`)||(n+=`
|
|
122
|
-
`),await
|
|
123
|
-
`);
|
|
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.replaceAll("*",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.replaceAll("*",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(`
|
|
122
|
+
`),await _.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let r=w__default.join(this.cwd,t);await this.ensureDirectoryExists(r);let o=n.replace(/\r\n/g,`
|
|
123
|
+
`);o.endsWith(`
|
|
128
124
|
`)||(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
|
-
|
|
131
|
-
`)
|
|
132
|
-
`)
|
|
133
|
-
|
|
134
|
-
`);}
|
|
135
|
-
`);}if(!await this.
|
|
136
|
-
|
|
137
|
-
${
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
${f}
|
|
141
|
-
`)
|
|
142
|
-
|
|
143
|
-
|
|
125
|
+
`),await _.writeFile(r,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await T__default.chmod(r,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(`${y} 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 r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await parse(e,{root:this.projectRoot,configName:"jsconfig.json"});return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let o=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,o),o}throw r}if(this.isTypeScriptEnabled){let r=await parse(e,{root:this.projectRoot,configName:"tsconfig.json"});return this.parseCache.set(e,r),r}}return this.parseCache.set(e,null),null}catch(t){return console.warn(`${y} 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 Oe=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 r=e.substring(t.length+1),o=await this.resolveSubPath(n,r);if(o)return this.toProjectRelative(o)}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[r,o]of Object.entries(t)){if(r.includes("*")||!Array.isArray(o))continue;let i=o[0];if(!i)continue;let a=w.resolve(n,i),c=await this.findEntryPoint(a);c&&(e[r]=c);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=w.join(this.projectRoot,"package.json"),n=await T.readFile(t,"utf-8"),o=JSON.parse(n).workspaces;if(!o)return e;let i=Array.isArray(o)?o:o.packages||[];for(let a of i){let c=await this.findWorkspaceDirs(a);for(let g of c){let d=await this.loadWorkspacePackage(g);d&&Object.assign(e,d);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),r=w.join(this.projectRoot,n);try{let o=await T.readdir(r,{withFileTypes:!0});for(let i of o)i.isDirectory()&&t.push(w.join(r,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"),r=JSON.parse(n),o=r.name;if(!o)return null;let i=await this.findPackageEntryPoint(e,r);return i?{[o]:i}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return w.join(e,r);if(typeof r=="object"){let o=r["."]||r["./index"];if(typeof o=="string")return w.join(e,o);if(typeof o=="object"){let i=o.import||o.default||o.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 r of n){let o=w.join(e,r);try{if((await T.stat(o)).isFile())return o}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 r=w.join(e,n);try{if((await T.stat(r)).isFile())return r}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),r=[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 o of r)try{if((await T.stat(o)).isFile())return o}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 Oe(this.projectRoot,t);let n=e.toLowerCase(),r=n.endsWith(".ts")||n.endsWith(".tsx")||n.endsWith(".d.ts"),o=n.endsWith(".js")||n.endsWith(".jsx")||n.endsWith(".mjs")||n.endsWith(".cjs");if(r?this.extensions=[".ts",".tsx",".d.ts"]:o?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),r=await this.findFileWithExtensions(n);return r?this.toProjectRelative(r):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 r=this.matchPathPattern(e,t);if(r!==null)for(let o of n){let i=await this.trySubstitution(e,t,o,r);if(i)return i}}return null}matchPathPattern(e,t){if(!t.includes("*"))return e===t?"":null;let[n,r]=t.split("*");if(!e.startsWith(n)||r&&!e.endsWith(r))return null;let o=n.length,i=r?e.length-r.length:e.length;return e.substring(o,i)}async trySubstitution(e,t,n,r){let o=n.replaceAll("*",r),i=w.resolve(this.tsconfigDir,o);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"],r=n.some(i=>e.endsWith(i)),o=e;if(r&&!t){for(let i of n)if(e.endsWith(i)){o=e.slice(0,-i.length);break}}if(!t)for(let i of this.extensions){let a=o+i;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let i of this.extensions){let a=w.join(o,`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 r=w.dirname(t);if(r===t)break;t=r;}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 r=this.matchPathPattern(e,t);if(r!==null){if(typeof n=="string"){let o=await this.tryPackageImportSubstitution(n,r);if(o)return o}if(Array.isArray(n)){for(let o of n)if(typeof o=="string"){let i=await this.tryPackageImportSubstitution(o,r);if(i)return i}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=w.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};var Fe=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 Me=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)}};je();var De=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,"/"),r=await this.tryResolveFile(w.resolve(this.projectRoot,n));return r?w.relative(this.projectRoot,r).replace(/\\/g,"/"):e}async resolveRelative(e){let t=0;for(;t<e.length&&e[t]===".";)t++;let n=e.slice(t),r=t<=1?"":"../".repeat(t-1),o=n?r+n.replace(/\./g,"/"):r.slice(0,-1)||".",i=w.resolve(this.sourceDir,o),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 Be.promises.access(n,Be.constants.F_OK),n}catch{continue}return null}};var He=class extends z{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new De(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"]},Ue=class{constructor(e){this.config=e;this.registerPlugin(new Fe),this.registerPlugin(new Me),this.registerPlugin(new He);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>hr,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??me.javascript};typescript={language:()=>_r.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??me.typescript};python={language:()=>yr,fileExtensions:()=>this.config?.languages.python?.fileExtensions??me.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};var wr={stable:"Code",insiders:"Code - Insiders"};function fn(s,e){let t=Q__default.homedir(),n=process.platform,r=wr[s];switch(n){case "darwin":return w__default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return w__default.join(process.env.APPDATA||w__default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return w__default.join(t,".config",r,"User/globalStorage",e)}}function hn(){let s="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:w__default.join(fn(t,s),"settings","cline_mcp_settings.json")}))}function yn(){return w__default.join(fn("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}function yt(){let s=Q__default.homedir();return w__default.join(s,".copilot","mcp-config.json")}function _n(){return [{displayName:"Copilot CLI",settingsPath:yt()}]}var wn={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Cr={extraKnownMarketplaces:{"constellation-marketplace":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},_t=[{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:Cr},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:yn(),isGlobalConfig:true,getGlobalConfigPaths:hn,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:yt(),isGlobalConfig:true,getGlobalConfigPaths:_n,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 wt(s){return _t.find(e=>e.id===s)}var Ct=null;async function Cn(){if(!Ct)try{let s=await import('@iarna/toml');Ct={parse:s.parse,stringify:s.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Ct}function xr(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 Ge=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[r,o]of Object.entries(e.configDefaults))r in n||(n[r]=o);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:r,settingsPath:o}of t)try{await this.ensureDirectoryExists(o);let i=await this.readConfig(o,e.format);i=this.addConstellationServer(i,e),await this.writeConfig(o,i,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${r})`},success:!0,configuredPath:o});}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} (${r})`},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 _.fileIsReadable(e))return {};let r=await _.readFile(e);return t==="json"?JSON.parse(r):t==="jsonc"?JSON.parse(xr(r)):(await Cn()).parse(r)}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 r=t.mcpServersKeyPath[t.mcpServersKeyPath.length-1];(!n[r]||typeof n[r]!="object")&&(n[r]={});let o=n[r];if(!o.constellation){let i=t.mcpServerConfigOverride??wn,a={...i};if(t.mcpServerExtras&&Object.assign(a,t.mcpServerExtras),t.mcpEnv){let c=t.mcpEnvKey??"env",g=i[c];a[c]={...g,...t.mcpEnv};}o.constellation=a;}return e}async writeConfig(e,t,n){let r;n==="json"||n==="jsonc"?r=JSON.stringify(t,null,2):r=(await Cn()).stringify(t),r=r.replace(/\r\n/g,`
|
|
127
|
+
`),r.endsWith(`
|
|
128
|
+
`)||(r+=`
|
|
129
|
+
`),await _.writeFile(e,r);}async configurePermissions(e){let t=w__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await _.fileIsReadable(t)){let c=await _.readFile(t);n=JSON.parse(c);}}catch{}let r=n;for(let a=0;a<e.allowKeyPath.length-1;a++){let c=e.allowKeyPath[a];(!r[c]||typeof r[c]!="object")&&(r[c]={}),r=r[c];}let o=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(r[o])||(r[o]=[]);let i=r[o];i.includes(e.allowValue)||i.push(e.allowValue),await _.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 _.fileIsReadable(t)){let o=await _.readFile(t);n=JSON.parse(o);}}catch{}n=this.deepMerge(n,e.config),await _.writeFile(t,JSON.stringify(n,null," ")+`
|
|
131
|
+
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],i=e[r];o&&typeof o=="object"&&!Array.isArray(o)&&i&&typeof i=="object"&&!Array.isArray(i)?n[r]=this.deepMerge(i,o):n[r]=o;}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 r=t.pluginKeyPath[t.pluginKeyPath.length-1];Array.isArray(n[r])||(n[r]=[]);let o=n[r];return o.includes(t.pluginValue)||o.push(t.pluginValue),e}async configureEnvPolicy(e,t){if(!t.envPolicyConfig)return;let{includeOnlyKeyPath:n,envVarsToAllow:r,globalConfigPath:o}=t.envPolicyConfig;this.addToEnvPolicyWhitelist(e,n,r),o&&await this.updateGlobalEnvPolicy(o,n,r,t.format);}addToEnvPolicyWhitelist(e,t,n){let r=e;for(let a=0;a<t.length-1;a++){let c=t[a];if(!r[c]||typeof r[c]!="object")return;r=r[c];}let o=t[t.length-1];if(!Array.isArray(r[o]))return;let i=r[o];for(let a of n)i.includes(a)||i.push(a);}async updateGlobalEnvPolicy(e,t,n,r){let o=e.replace(/^~/,Q__default.homedir()),i=await this.readConfig(o,r);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(o,i,r);}};var{prompt:vn}=Pn;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(`${y} 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"),r=null,o=await _.fileIsReadable(n);if(o)try{let b=await _.readFile(n);r=JSON.parse(b),console.log(`${f} Found existing constellation.json, current values will be used as defaults.
|
|
134
|
+
`);}catch{console.log(`${y} Existing constellation.json is invalid, starting fresh.
|
|
135
|
+
`);}if(!await this.git.isGitRepository())throw new Error(`${y} 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,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=c,p=g.filter(b=>b!==d),u=d?[d,...p]:p,m=this.getBranchInitialIndex(u,r?.branch),v=this.getInitialLanguages(r),P=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:r?.projectId??"",validate:b=>b.trim().length>0||"Project ID is required"},{choices:u,initial:m,limit:10,maxChoices:1,message:"Branch to index:",name:"branch",scroll:!0,type:"select"},{type:"multiselect",name:"languages",multiple:!0,message:"Select Language(s):",choices:this.buildLanguageChoices(r),initial:v,result(b){return b.map(L=>this.choices.find(Ze=>Ze.name===L)?.value??L)}}],x=await new Pn().prompt(P),xe={projectId:x.projectId.trim(),branch:x.branch,languages:{...x.languages.reduce((b,L)=>(b[L]={fileExtensions:me[L]||[]},b),{})}},ne=JSON.stringify(xe,void 0,2);await _.writeFile(n,ne),console.log(`${h} ${o?"Updated":"Initialized"} configuration file at ${fe(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${h} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers();}catch(t){let n=t.message??"An unexpected error occurred";console.error(`${C} Failed to initialize configuration file.
|
|
137
|
+
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await vn({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=_t.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await vn({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(p){return p.map(u=>this.choices.find(v=>v.name===u)?.value??u)}});if(n.length===0){console.log(`${f} No tools selected, skipping MCP configuration`);return}let r=new Ge(process.cwd()),o=[];for(let p of n){let u=wt(p);if(u)if(console.log(` ${f} Configuring ${u.displayName}...`),u.isGlobalConfig&&u.getGlobalConfigPaths){let m=await r.configureGlobalTool(u),v=false;for(let P of m)o.push(P),P.success?(v=true,console.log(` ${h} ${P.tool.displayName} configured at ${fe(P.configuredPath,process.cwd())}`)):P.error&&console.log(` ${y} ${P.tool.displayName}: ${P.error}`);if(v){let P=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${f} Note: ${u.displayName} uses ${P} (not project-level)`);}if(m.length===0){let P=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${y} ${u.displayName}: ${P}`);}}else {let m=await r.configureTool(u);o.push(m),m.success?(console.log(` ${h} ${u.displayName} configured at ${fe(m.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${h} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${y} ${u.displayName}: ${m.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=w__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),console.log(` ${h} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${y} Could not stage .claude/settings.json in git`);}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=w__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),console.log(` ${h} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=w__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${h} Added opencode.jsonc to staged changes in git`);}catch{}}let g=o.filter(p=>p.success).length,d=o.filter(p=>!p.success).length;console.log(`
|
|
138
|
+
${h} MCP configuration complete: ${g} configured`),d>0&&console.log(`${y} ${d} tool(s) could not be configured`),await this.configureHooks(n,o),console.log(`
|
|
139
|
+
${f} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new ue(process.cwd()),r=mt(),o=e.map(c=>wt(c)).filter(c=>c!==void 0&&c.hooksConfig!==void 0&&t.some(g=>g.tool.id===c.id&&g.success));if(o.length===0)return;console.log(`
|
|
140
|
+
${f} Configuring AI hooks...`);let i=[];for(let c of o){let g=await n.configureHooks(c,r);if(i.push(g),g.success){let d=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(d.length>0){let p=g.configuredPath?fe(g.configuredPath,process.cwd()):w__default.dirname(d[0]);console.log(` ${h} ${c.displayName} hooks configured at ${p}`);for(let u of d){let m=w__default.isAbsolute(u)?fe(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${h} Added ${m} to staged changes in git`);}catch{console.log(` ${y} Could not stage ${m} in git`);}}}else console.log(` ${h} ${c.displayName} hooks configured`);}else console.log(` ${y} ${c.displayName}: ${g.error}`);}let a=i.filter(c=>c.success).length;a>0&&console.log(`${h} Hooks configuration complete: ${a} configured`);}buildLanguageChoices(e){return [{name:"JavaScript",value:"javascript"},{name:"Python",value:"python"},{name:"TypeScript",value:"typescript"}]}getInitialLanguages(e){if(!e?.languages)return [];let t={c:"C","c-sharp":"C#",cpp:"C++",go:"Go",json:"JSON",java:"Java",javascript:"JavaScript",php:"PHP",python:"Python",ruby:"Ruby",bash:"Shell (Bash)",typescript:"TypeScript"};return Object.keys(e.languages).filter(n=>e.languages[n]!==void 0).map(n=>t[n]).filter(n=>n!==void 0)}getBranchInitialIndex(e,t){if(t){let n=e.indexOf(t);if(n!==-1)return n}return 0}};var We=class s{constructor(e,t,n,r){this.branch=e;this.languages=t;this.projectId=n;this.exclude=r;this.apiUrl=process.env.CONSTELLATION_API_URL||"https://api.constellationdev.io";}apiUrl;static async loadFromFile(e){if(await _.fileIsReadable(e)){let n=await _.readFile(e),r=JSON.parse(n),o=new s(r.branch,r.languages,r.projectId,r.exclude);return o.validate(),o}else throw new Error(`${C} Unable to find constellation config at ${e}`)}validate(){if(!this.apiUrl)throw new Error("Invalid configuration: apiUrl is missing");if(!this.branch)throw new Error("Invalid configuration: branch is missing");if(!this.languages||Object.keys(this.languages).length===0)throw new Error("Invalid configuration: no languages configured");if(!this.projectId)throw new Error("Invalid configuration: projectId is missing");try{new URL(this.apiUrl);}catch{throw new Error(`Invalid configuration: apiUrl "${this.apiUrl}" is not a valid URL`)}for(let[e,t]of Object.entries(this.languages)){if(!t.fileExtensions||t.fileExtensions.length===0)throw new Error(`Invalid configuration: language "${e}" has no file extensions`);for(let n of t.fileExtensions)if(!n.startsWith("."))throw new Error(`Invalid configuration: file extension "${n}" for language "${e}" must start with a dot`)}if(this.exclude&&this.exclude.length>0){if(!Array.isArray(this.exclude))throw new Error("Invalid configuration: exclude must be an array of strings");for(let e of this.exclude)if(typeof e!="string")throw new Error("Invalid configuration: exclude patterns must be strings")}}validateBranch(e){if(!e)throw new Error("Not on a Git branch (detached HEAD state)");if(this.branch!==e)throw new Error(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`)}};var Ke=class{getVariable(e){return Promise.resolve(process.env[e])}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,"\\$&")}},Pt=class extends Ke{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,r)=>{let o=spawn("setx",[e,t],{shell:!1,windowsHide:!0}),i="";o.stderr?.on("data",a=>{i+=a.toString();}),o.on("close",a=>{a===0?n():r(new Error(`setx failed with code ${a}: ${i}`));}),o.on("error",a=>{r(a);});}),process.env[e]=t;}catch(n){throw new Error(`Failed to set environment variable ${e}: ${n}`)}}async queryRegistry(e,t){try{let r=(await new Promise((o,i)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),c="",g="";a.stdout?.on("data",d=>{c+=d.toString();}),a.stderr?.on("data",d=>{g+=d.toString();}),a.on("close",d=>{d===0?o(c):i(new Error(`reg query failed: ${g}`));}),a.on("error",d=>{i(d);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return r?r[1].trim():void 0}catch{return}}},xt=class extends Ke{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),r=`export ${e}="${n}"`;try{for(let o of this.userConfigFiles)await this.writeToConfigFile(o,e,r);process.env[e]=t;}catch(o){throw new Error(`Failed to set environment variable ${e}: ${o}`)}}async writeToConfigFile(e,t,n){let r="";try{r=await _.readFile(e,"utf-8");}catch{}let o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^export ${o}=.*$`,"gm");i.test(r)?r=r.replace(i,n):r=r.trimEnd()+`
|
|
144
144
|
`+n+`
|
|
145
|
-
`,await
|
|
146
|
-
${f} Updating ${
|
|
147
|
-
`),await this.packageManager.executeUpdate(
|
|
148
|
-
${
|
|
145
|
+
`,await _.writeFile(e,r);}},St=class{static create(){let e=Q.platform();switch(e){case "win32":return new Pt;case "darwin":case "linux":return new xt;default:throw new Error(`Unsupported platform: ${e}`)}}},Ve=class{manager;constructor(){this.manager=St.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 Je=class{extensionToLanguageMap;constructor(e){this.extensionToLanguageMap=new Map;for(let[t,n]of Object.entries(e.languages))for(let r of n.fileExtensions)this.extensionToLanguageMap.set(r,t);}detectLanguage(e){let t=w__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};function br(){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 Er=br(),Ir="update-state.json",$r=1440*60*1e3,_e=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??Er,this.stateFile=w.join(this.stateDir,Ir);}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>$r}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(r=>{let o=spawn(t,n,{stdio:"inherit",shell:process.platform==="win32"});o.on("close",i=>{r(i===0);}),o.on("error",()=>{r(false);});})}};var{prompt:Nr}=Pn,Ce=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:r}=await Nr({type:"confirm",name:"shouldUpdate",message:"Would you like to update now?",initial:!0});return r}catch{return false}}};var Rr="https://registry.npmjs.org",Ye="@constellationdev/cli",jr=5e3,qe=class{cache;packageManager;prompter;constructor(){this.cache=new _e,this.packageManager=new we,this.prompter=new Ce;}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(),jr);try{let r=await fetch(`${Rr}/${Ye}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Registry returned ${r.status}`);let i=(await r.json()).version;return {current:e,latest:i,hasUpdate:this.isNewerVersion(i,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=i=>i.split("-")[0],r=n(e).split(".").map(Number),o=n(t).split(".").map(Number);for(let i=0;i<3;i++){let a=r[i]||0,c=o[i]||0;if(a>c)return true;if(a<c)return false}return false}async performUpdate(){return console.log(`
|
|
146
|
+
${f} Updating ${Ye}...
|
|
147
|
+
`),await this.packageManager.executeUpdate(Ye)?(console.log(`
|
|
148
|
+
${h} Update complete! Please re-run your command.
|
|
149
149
|
`),true):(console.log(`
|
|
150
|
-
${
|
|
151
|
-
`),false)}};async function
|
|
152
|
-
Modified: ${
|
|
150
|
+
${y} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(Ye)}
|
|
151
|
+
`),false)}};async function bt(s){return new qe().check(s)}var Ar=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];function Lr(){return Ar.some(s=>!!process.env[s])}function Or(){return !!process.stdout.isTTY}function Sn(){return !Lr()&&Or()}var ve=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:[]},r=t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);for(let o of r){let i=o.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 r={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(r,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: ${r.modified}, Created: ${r.created}, Deleted: ${r.deleted}, Conflicted: ${r.conflicted}, Staged: ${r.staged}`)}let t=await this.git.pull();if(t.summary.changes===0&&t.summary.insertions===0&&t.summary.deletions===0){let r=await this.git.status();if(r.conflicted.length>0)throw console.error("\u274C Pull failed: Merge conflicts detected"),console.error(" Conflicted files:",r.conflicted.join(", ")),console.error(" Please resolve conflicts manually and commit the result"),new Error(`Pull resulted in merge conflicts in ${r.conflicted.length} file(s): ${r.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 Hr=w__default.dirname(fileURLToPath(import.meta.url)),Ur=w__default.join(Hr,"..","package.json"),zr=JSON.parse(readFileSync(Ur,"utf-8")),bn=zr.version,Gr=["help","--help","-h","--version","-V","-v"];if(Sn()){let s=process.argv[2];["auth","help","init","index"].includes(s)?Qe(s):Qe(),Gr.includes(s)||await bt(bn)&&process.exit(0);}var Et=process.cwd(),It=new Ve,Pe=new Command;Pe.name("constellation").description("Connecting stars in your code into intelligent patterns").version(bn);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 ve(Et)};await new he(t).run({skipMcp:s.skipMcp});}catch(e){console.error(`${C} 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:It};await new ie(s).run();}catch(s){console.error(`${C} 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 We.loadFromFile(w__default.join(Et,"constellation.json")),t=new ve(Et),n=new Ue(e),r=new Je(e),o={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:r,Environment:It},i=It.isCI(),a=s.full||!s.incremental&&i,c=s.dirty||!1;!s.full&&!s.incremental&&i&&console.log(`${f} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new pe(o).run(a,c);}catch(e){!(e instanceof S)&&!(e instanceof $)&&console.error(`${C} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});Pe.parse();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@constellationdev/cli",
|
|
3
|
-
"description": "Code Intelligence Platform for AI Coding
|
|
4
|
-
"version": "0.1.
|
|
3
|
+
"description": "Code Intelligence Platform for AI Coding Agents",
|
|
4
|
+
"version": "0.1.4",
|
|
5
5
|
"author": "ShiftinBits Inc",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"type": "module",
|