@constellationdev/cli 0.2.3 → 0.2.6
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/main.js +99 -99
- package/package.json +2 -2
package/dist/main.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {base32}from'@scure/base';import {Readable}from'stream';import c from'ansi-colors';import*as
|
|
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
|
|
4
|
-
Caused by: ${l.stack}`,
|
|
2
|
+
import {base32}from'@scure/base';import {Readable}from'stream';import c from'ansi-colors';import*as le from'os';import le__default from'os';import {Agent,fetch as fetch$1}from'undici';import {execFile,spawn}from'child_process';import {promisify}from'util';import {createServer}from'http';import {randomBytes}from'crypto';import Tr from'enquirer';import*as A from'fs/promises';import A__default from'fs/promises';import*as nt from'fs';import {readFileSync}from'fs';import ho from'tree-sitter';import*as S from'path';import S__default,{dirname,join}from'path';import Rn from'ignore';import {z as z$1}from'zod';import yt from'zlib';import {pipeline}from'stream/promises';import {PYTHON_STDLIB_MODULES}from'@constellationdev/types';import {performance}from'perf_hooks';import {parseDocument,isMap,isSeq}from'yaml';import {findAll,find,parse}from'tsconfck';import Wo from'tree-sitter-javascript';import zo from'tree-sitter-python';import Ko from'tree-sitter-typescript';import {simpleGit}from'simple-git';import {fileURLToPath}from'url';import {Command}from'commander';var Hr=Object.defineProperty;var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var pn=(i,e)=>{for(var t in e)Hr(i,t,{get:e[t],enumerable:true});};var Ne,ut=m(()=>{Ne=["help","--help","-h","--version","-V","-v"];});function dn(i){return base32.encode(Buffer.from(i))}var un=m(()=>{});function fn(i,e,t){let n=`${i}:${e}${t?`:${t}`:""}`;return dn(n)}var mn=m(()=>{un();});var Ae,hn=m(()=>{Ae=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 Kr(){return process.env.CONSTELLATION_ASCII_MODE==="1"?false:process.env.CI?true:le.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 Vr,Jr,Yr,qr,Xr,Zr,Qr,eo,to,no,ue,w,E,C,y,U,k=m(()=>{Vr="\u2714",Jr="\u2717",Yr="\u26A0",qr="\u2139",Xr="\u26A1",Zr="[OK]",Qr="[ERR]",eo="[WARN]",to="[INFO]",no="[>>]",ue=Kr(),w=c.green(ue?Vr:Zr),E=c.red(ue?Jr:Qr),C=c.yellow(ue?Yr:eo),y=c.blue(ue?qr:to),U=c.yellow(ue?Xr:no);});var je,Oe,b,H,N,Q,G,Le=m(()=>{mn();hn();k();je=class{constructor(e,t){this.config=e;this.accessKey=t;}apiVersion="intel/v1";features={};isFeatureEnabled(e){return this.features[e]===true}parseFeatureHeader(e){if(Object.keys(this.features).length>0)return;let t=e.headers.get("X-Features");if(t)for(let n of t.split(",")){let[r,o]=n.split("=");r&&o!==void 0&&(this.features[r]=o==="true");}}async getProjectState(){let e={"Content-Type":"application/x-ndjson; charset=utf-8","x-project-id":this.config.projectId,"x-branch-name":this.config.branch,Authorization:`Bearer ${this.accessKey}`},t=await this.sendRequest("project",void 0,"GET",e);return t&&!t.ok&&await this.handleProjectStateError(t),this.parseFeatureHeader(t),t.json()}async handleProjectStateError(e){try{let t=await e.json(),n=t?.code;switch(n){case "PROJECT_NOT_REGISTERED":throw new N(t?.message||"Project not registered",n,this.config.projectId);case "PROJECT_INACTIVE":throw new N(t?.message||"Project is inactive",n,this.config.projectId);case "INVALID_PROJECT_ID":throw new N(t?.message||"Invalid project ID format",n,this.config.projectId);case "PROJECT_NOT_FOUND":throw new H("Project not found - no previous index exists");default:throw e.status===404?new H("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status}): ${t?.message||e.statusText}`)}}catch(t){throw t instanceof N||t instanceof H?t:e.status===404?new H("Project not found - no previous index exists"):new Error(`Unexpected API response (${e.status})`)}}async getIndexStatus(e,t){let n=new URLSearchParams({branch:e});t&&n.set("commit",t);let r=`projects/${encodeURIComponent(this.config.projectId)}/index-status?${n.toString()}`;try{let o=await this.sendRequest(r,null,"GET");return !o||!o.ok?null:await o.json()}catch(o){if(o instanceof b)throw o;return null}}async deleteFiles(e){for(let t of e){let n=fn(this.config.projectId,this.config.branch,t);await this.delete(`/ast/${n}`);}}retryableStatusCodes=[500,502,503,504];async streamToApi(e,t,n,r,o,s){try{let{Readable:a}=await import('stream'),l=new Ae(e),g=a.toWeb(l),f=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}`,...s&&{"x-commit-hash":s}},body:g,duplex:"half",dispatcher:f});if(p.status===401)throw new b("Authentication failed");if(p.status===409){let d="Indexing already in progress",v;try{let _=await p.json();d=_?.message||d,v=_?.details?.branchName;}catch{}throw new Q(d,v)}if(p.status===200)try{let d=await p.json();if(d?.status==="current")return console.log(`${w} Index already up to date for ${r} at commit ${d.commitHash||"unknown"}`),!0}catch{}if(p.ok||p.status===202)return !0;let u=`Server returned ${p.status}`;try{let d=await p.json();d?.message&&(u=Array.isArray(d.message)?d.message.join("; "):d.message);}catch{}throw new Error(u)}catch(a){if(a instanceof b||a instanceof Q)throw a;let l=a instanceof Error?a:new Error(String(a)),g="";if(l.message==="fetch failed"||a.code){let p=[],u=a.code||a.cause?.code;if(a.code&&p.push(`Error Code: ${a.code}`),a.cause){let d=a.cause;d.code&&p.push(`Cause Code: ${d.code}`),d.errno&&p.push(`Errno: ${d.errno}`),d.syscall&&p.push(`System Call: ${d.syscall}`),d.address&&p.push(`Address: ${d.address}`),d.port&&p.push(`Port: ${d.port}`);}u==="ERR_INVALID_ARG_VALUE"?g="Invalid argument value - check stream/body format and duplex option":u==="ECONNREFUSED"?g="Connection refused - service may be down or unreachable":u==="ENOTFOUND"?g="DNS lookup failed - check service URL":u==="ETIMEDOUT"?g="Connection timeout - service not responding":u==="ECONNRESET"?g="Connection reset by server":u==="EHOSTUNREACH"?g="Host unreachable - check network connectivity":g="Network failure",p.length>0&&(g+=` (${p.join(", ")})`);}else g=l.message;let f=new Error(`Failed to upload data to Constellation Service: ${g}`);throw f.cause=l,f.stack=`${f.stack}
|
|
4
|
+
Caused by: ${l.stack}`,f}}async sendRequest(e,t,n,r={},o=0,s=3,a=1e3,l=250){for(let g=1;g<=s;g++){let f;try{let p=new AbortController;o>0&&(f=setTimeout(()=>p.abort(),o));let u={...r,"Content-Type":"application/json; charset=utf-8",Accepts:"application/json; charset=utf-8",Authorization:`Bearer ${this.accessKey}`},d=await fetch(`${this.config.apiUrl}/${this.apiVersion}/${e}`,{method:n,headers:u,body:t?JSON.stringify(t):void 0,signal:p.signal});if(f&&clearTimeout(f),d.status===401)throw new b("Authentication failed");if(!d.ok&&this.retryableStatusCodes.includes(d.status))throw new Oe(`${d.statusText} (${d.status})`);return d}catch(p){if(f&&clearTimeout(f),!(p instanceof b)){let u=p instanceof Error?`${p.message}${p.cause?` (Cause: ${p.cause})`:""}`:String(p);console.log(`HTTP request attempt ${g}/${s} failed: ${u}`);}if(g<s&&p instanceof Oe){let u=a+Math.floor(Math.random()*l);await new Promise(d=>setTimeout(d,u));}else throw p}}}async reportErrors(e){try{let t=await this.sendRequest("error-reports",e,"POST",{"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},1e4,1,0,0);if(!t){console.warn("Failed to upload error report: no response received");return}if(t.status===403){console.warn("Error reporting is not available on your current plan");return}t.ok||console.warn(`Failed to upload error report: ${t.statusText} (${t.status})`);}catch(t){console.warn(`Failed to upload error report: ${t?.message||"Unknown error"}`);}}async delete(e){let t={"x-project-id":this.config.projectId,"x-branch-name":this.config.branch},n=await this.sendRequest(e,void 0,"DELETE",t);if(n&&!n.ok)throw new Error(`Failed sending HTTP DELETE to ${e}`)}},Oe=class extends Error{constructor(e){super(e),this.name="RetryableError";}},b=class extends Error{constructor(e){super(e),this.name="AuthenticationError";}},H=class extends Error{constructor(e){super(e),this.name="NotFoundError";}},N=class extends Error{constructor(t,n,r){super(t);this.code=n;this.projectId=r;this.name="ProjectValidationError";}},Q=class extends Error{constructor(t,n){super(t);this.branchName=n;this.name="IndexingInProgressError";}},G=class extends Error{constructor(t,n){super(t);this.errorCode=n;this.name="GitValidationError";}};});async function Cn(i){if(!i.startsWith("http://")&&!i.startsWith("https://"))return false;try{switch(process.platform){case "darwin":return await ft("open",[i]),!0;case "linux":return await ft("xdg-open",[i]),!0;case "win32":return await ft("cmd",["/c","start","",i]),!0;default:return !1}}catch{return false}}var ft,wn=m(()=>{ft=promisify(execFile);});function _n(){return new Promise((i,e)=>{let t=createServer(),n,r=false;t.listen(0,"127.0.0.1",()=>{let o=t.address();if(!o||typeof o=="string"){t.close(),e(new Error("Failed to bind callback server"));return}i({port:o.port,close(){n&&(clearTimeout(n),n=void 0),t.close(),t.closeAllConnections();},waitForCallback(s,a=3e5){return new Promise((l,g)=>{n=setTimeout(()=>{n=void 0,r=true,t.close(),t.closeAllConnections(),g(new Error("Authentication timed out"));},a),t.on("request",(f,p)=>{let u=new URL(f.url??"/",`http://127.0.0.1:${o.port}`);if(u.pathname!=="/callback"){p.writeHead(404,{"Content-Type":"text/plain"}),p.end("Not found");return}let d=u.searchParams.get("key");if(u.searchParams.get("state")!==s){p.writeHead(400,{"Content-Type":"text/plain"}),p.end("Invalid state parameter");return}if(!d||!lo.test(d)){p.writeHead(400,{"Content-Type":"text/plain"}),p.end("Invalid key format");return}if(r)return;r=true;let _=u.searchParams.get("return_url");_?(p.writeHead(302,{Location:_}),p.end()):(p.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),p.end(co)),n&&(clearTimeout(n),n=void 0),t.close(),t.closeAllConnections(),l(d);});})}});}),t.on("error",o=>{e(o);});})}var lo,co,vn=m(()=>{lo=/^ak:[0-9a-f]{32}$/i,co=`<!DOCTYPE html>
|
|
5
5
|
<html><head><title>Authentication Successful</title></head>
|
|
6
|
-
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function
|
|
6
|
+
<body><h1>Authentication successful! You can close this tab.</h1></body></html>`;});function mt(i){console.log(`\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
7
7
|
\u2502 ${c.gray("'")} ${c.blueBright(".")} ${c.dim("`")} ${c.yellowBright("'")} ${c.blueBright("+")} ${c.whiteBright(".")} ${c.gray(".")} ${c.yellowBright("'")} ${c.yellowBright("*")} ${c.whiteBright("'")} ${c.blueBright("+")} ${c.gray(".")} ${c.yellowBright("*")} ${c.whiteBright(",")} ${c.gray.dim(".")}\u2502
|
|
8
8
|
\u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
|
|
9
9
|
\u2502 ${c.blueBright(".")} / ___/__ ___ ___ / /____ / / /__ _/ /_(_)__ ___ ${c.gray(".")} ${c.yellowBright("'")} ${c.gray("+")} ${c.gray("\\")} ${c.gray("`")} \u2502
|
|
@@ -13,7 +13,7 @@ Caused by: ${l.stack}`,d}}async sendRequest(e,t,n,r={},o=0,s=3,a=1e3,l=250){for(
|
|
|
13
13
|
\u2502${c.yellowBright("'")} ${c.whiteBright("*")} ${c.blueBright("+")} ${c.yellowBright("*")} ${c.gray(",")} ${c.whiteBright("'")} + ${c.whiteBright("constellationdev.io")} ${c.whiteBright("' .")} ${c.gray(",")} ${c.blueBright("*")} ${c.yellowBright(".")} ${c.whiteBright("+")} \u2502`),i&&i.length>0?console.log(`\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u252C${"\u2500".repeat(59-i.length)}\u256F
|
|
14
14
|
\u2502 ${c.bold(`constellation \u203A ${i}`)} \u2502
|
|
15
15
|
\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${"\u2500".repeat(i.length)}\u2500\u256F
|
|
16
|
-
`):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var
|
|
16
|
+
`):console.log("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");}var W,En,Fe=m(()=>{`
|
|
17
17
|
\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E
|
|
18
18
|
\u2502 ${c.gray("'")} ${c.blueBright(".")} ${c.dim("`")} ${c.yellowBright("'")} ${c.blueBright("+")} ${c.whiteBright(".")} ${c.gray(".")} ${c.yellowBright("'")} ${c.yellowBright("*")} ${c.whiteBright("'")} ${c.blueBright("+")} ${c.gray(".")} ${c.yellowBright("*")} ${c.whiteBright(",")} ${c.gray.dim(".")}\u2502
|
|
19
19
|
\u2502 _____ ${c.yellowBright("*")} ${c.dim("`")} __${c.whiteBright(".")} ${c.whiteBright("'")} ____ ${c.dim(".")} __ _ ${c.gray("`")} . . ${c.yellowBright("o")} ${c.blueBright("+")} \u2502
|
|
@@ -29,10 +29,10 @@ ${c.gray(" \\")}
|
|
|
29
29
|
${c.blueBright(" o")}${c.blueBright("----")}${c.yellowBright("o")} ${c.gray("o")}
|
|
30
30
|
${c.gray(" \\ \\ ")}${c.blueBright("/")}
|
|
31
31
|
${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
|
|
32
|
-
`,
|
|
33
|
-
`),this.env.isCI()){console.error(`${
|
|
32
|
+
`,W="CONSTELLATION_ACCESS_KEY",En="CONSTELLATION_WEB_URL";});var z,De=m(()=>{z=class{git;config;langRegistry;env;constructor(e){this.git=e.GitClient,this.config=e.Config,this.langRegistry=e.LanguageRegistry,this.env=e.Environment;}};});function fo(i){return uo.test(i)}function mo(i){return i.replace(/ak:[0-9a-f]{32}/gi,"[REDACTED]")}var Sn,uo,fe,Pn=m(()=>{wn();vn();Fe();k();De();(({prompt:Sn}=Tr)),uo=/^ak:[0-9a-f]{32}$/i;fe=class extends z{async run(e){try{if(!this.env)throw new Error("Environment manager not initialized");if(console.log(`${U}Configuring access key authentication...
|
|
33
|
+
`),this.env.isCI()){console.error(`${E} Cannot configure authentication in CI/CD environments
|
|
34
34
|
|
|
35
|
-
The ${
|
|
35
|
+
The ${W} environment variable must be configured
|
|
36
36
|
directly in your pipeline settings:
|
|
37
37
|
|
|
38
38
|
- GitHub Actions: Repository Settings -> Secrets and variables -> Actions
|
|
@@ -40,53 +40,79 @@ ${c.whiteBright(" o o")}${c.blueBright("-")}${c.blueBright("o")}
|
|
|
40
40
|
- Azure DevOps: Pipelines -> Library -> Variable groups
|
|
41
41
|
- Jenkins: Manage Jenkins -> Credentials
|
|
42
42
|
- CircleCI: Project Settings -> Environment Variables
|
|
43
|
-
`);return}if(await this.env.getKey(
|
|
44
|
-
${r}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await
|
|
45
|
-
`),t++;continue}if(!
|
|
43
|
+
`);return}if(await this.env.getKey(W)){let{replaceKey:n}=await Sn({message:"Replace existing Constellation access key?",name:"replaceKey",type:"confirm",initial:!1});if(!n){console.log(`${w} Keeping existing Constellation access key`);return}}e?await this.manualAuthFlow():await this.browserAuthFlow();}catch(t){if(t==="")return;let n=t.message??"An unexpected error occurred",r=mo(n);console.error(`${E} Failed to store Constellation access key
|
|
44
|
+
${r}`);}}async manualAuthFlow(){let e,t=0,n=3;for(;t<n;){if(e=(await Sn({message:"Constellation Access Key:",name:"accessKey",type:"password",required:true})).accessKey.trim(),!e){console.log(`${C} Access key cannot be empty.
|
|
45
|
+
`),t++;continue}if(!fo(e)){if(t++,t<n)console.log(`${C} Invalid access key format. Expected format: ak:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
|
46
46
|
Attempts remaining: ${n-t}
|
|
47
|
-
`);else {console.error(`${
|
|
48
|
-
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),{port:t,waitForCallback:n}=await
|
|
47
|
+
`);else {console.error(`${E} Invalid access key format after ${n} attempts.
|
|
48
|
+
Please verify your access key and try again.`);return}continue}break}await this.storeKey(e);}async browserAuthFlow(){let e=randomBytes(16).toString("hex"),{port:t,waitForCallback:n}=await _n(),o=`${process.env[En]||"https://app.constellationdev.io"}/auth/cli?callback_port=${t}&state=${e}`;console.log(`${y} Opening browser for authentication...`),await Cn(o)||console.log(`${C} Could not open browser automatically.
|
|
49
49
|
Please open this URL manually:
|
|
50
50
|
|
|
51
51
|
${o}
|
|
52
52
|
`),console.log(`${y} Waiting for authentication... (press Ctrl+C to cancel)
|
|
53
|
-
`);try{let a=await n(e);await this.storeKey(a);}catch{console.error(`${
|
|
54
|
-
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(
|
|
53
|
+
`);try{let a=await n(e);await this.storeKey(a);}catch{console.error(`${E} Authentication timed out.
|
|
54
|
+
Try again or use \`constellation auth --manual\` to paste your key directly.`);}}async storeKey(e){await this.env.setKey(W,e),console.log(`${w} Stored access key in ${W} user environment variable`);let t=this.env.getSourceFile();t&&console.log(`${y} To activate in this session, run:
|
|
55
55
|
|
|
56
56
|
source ${t}
|
|
57
57
|
|
|
58
|
-
New terminal sessions will load it automatically.`);}};});var h,M=m(()=>{h={async directoryExists(i){try{return (await A__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await A__default.access(i,A__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await A__default.readFile(i,{encoding:e,flag:A__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await A__default.writeFile(i,n,{encoding:t,flag:A__default.constants.O_WRONLY|A__default.constants.O_CREAT|A__default.constants.O_TRUNC});},async getFileStats(i){return await A__default.stat(i)},async getFileHandle(i,e,t){return await A__default.open(i,e,t)}};});var Fe,Sn=m(()=>{M();Fe=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 mo;o.setLanguage(r);let s=await h.getFileStats(e),a=10*1024*1024;if(s.size<=a){let l=await h.readFile(e),g={bufferSize:1024*1024};return o.parse(l,void 0,g)}else return this.parseWithStream(o,e,s.size)}async parseWithStream(e,t,n){let r=null;try{r=await A.open(t,"r");let o=r.fd,s=64*1024,a=Buffer.alloc(s),l=0;return e.parse(d=>{if(n>50*1024*1024){let f=Math.round(d/n*100);f>l+10&&(console.log(` Parsing large file: ${f}%...`),l=f);}let p=Xe.readSync(o,a,0,s,d);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(r)try{await r.close();}catch(s){console.error(`Warning: Failed to close file handle for ${t}:`,s);}throw o}finally{if(r)try{await r.close();}catch{}}}};});function xn(i){return i.replace(/\\/g,"/")}function De(i){return xn(i).replace(/^\.?\//,"")}function z(i,e){return xn(_.relative(i,e))}var ee=m(()=>{});var Me,In=m(()=>{M();ee();N();Me=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=En();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=En().add(t.exclude));let o=await A__default.realpath(this.rootPath);for(let s of e)try{let a=___default.isAbsolute(s)?s:___default.join(this.rootPath,s),l=await A__default.lstat(a);if(l.isSymbolicLink()){let g=await A__default.realpath(a);if(!g.startsWith(o+___default.sep)&&g!==o){console.warn(`${w} Skipping symlink pointing outside project: ${s} -> ${g}`);continue}let d=await A__default.stat(a);if(!d.isFile())continue;let p=z(this.rootPath,a);if(r&&r.ignores(p))continue;let f=this.detectLanguage(p,t.languages);if(!f)continue;n.push({path:a,relativePath:p,language:f,size:d.size});}else if(l.isFile()){let g=z(this.rootPath,a);if(r&&r.ignores(g))continue;let d=this.detectLanguage(g,t.languages);if(!d)continue;n.push({path:a,relativePath:g,language:d,size:l.size});}}catch{console.warn(`${w} Skipping inaccessible file: ${s}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let o=___default.join(r,".gitignore");await h.fileIsReadable(o)&&n.unshift(o);let s=___default.dirname(r);if(s===r)break;r=s;let a=___default.join(r,".git");if(await h.directoryExists(a)){let l=___default.join(r,".gitignore");await h.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let o of n)try{let s=await h.readFile(o);e.add(s);}catch{console.warn(`${w} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,n,r){let o=[],s=t||e,a=n||await A__default.realpath(this.rootPath),l=r||new Set([a]);try{let g=await A__default.readdir(e,{withFileTypes:!0});for(let d of g){let p=___default.join(e,d.name),f=z(s,p);if(d.isDirectory()){if(d.name.startsWith("."))continue;let u=await this.walkDirectory(p,s,a,l);o.push(...u);}else if(d.isFile()){let u=await A__default.stat(p);o.push({path:p,relativePath:f,language:"",size:u.size});}else if(d.isSymbolicLink())try{let u=await A__default.realpath(p);if(!u.startsWith(a+___default.sep)&&u!==a){console.warn(`${w} Skipping symlink pointing outside project: ${p} -> ${u}`);continue}let P=await A__default.stat(p);if(P.isDirectory()){if(d.name.startsWith(".")||l.has(u))continue;l.add(u);let v=await this.walkDirectory(p,s,a,l);o.push(...v);}else P.isFile()&&o.push({path:p,relativePath:f,language:"",size:P.size});}catch{console.warn(`${w} Skipping invalid symlink: ${p}`);}}}catch(g){console.error(`${b} Error walking directory ${e}:`,g);}return o}matchesLanguageExtension(e,t){let n=___default.extname(e.path).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return e.language=r,true;return false}detectLanguage(e,t){let n=___default.extname(e).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return r;return null}};});var ho,yo,$n,kn=m(()=>{ho=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"])}),yo=z$1.record(z$1.string(),ho),$n=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:yo.optional()});});var Co,Be,Rn=m(()=>{Co=promisify(ft.gunzip),Be=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=ft.createGzip();n.on("data",s=>t.push(s));let r=new Promise((s,a)=>{n.on("end",s),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=ft.createGzip();n.on("data",s=>t.push(s));let r=new Promise((s,a)=>{n.on("end",s),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 Co(t);return JSON.parse(n.toString("utf-8"))}};});var He,An=m(()=>{He=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 s=r++,a=this.processItem(e[o],o,t).then(l=>({result:l!==null?l.result:null,promiseId:s}));n.set(s,a),o++;}for(;n.size>0;){let s=await Promise.race(n.values());if(n.delete(s.promiseId),s.result!==null&&(yield s.result),o<e.length){let a=r++,l=this.processItem(e[o],o,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),o++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});function mt(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var Ue,jn=m(()=>{Ue=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:e.map(mt).join(" "),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:e.map(mt).join(" "),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:e.map(mt).join(" "),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}};});async function K(i,e,t,n,r){let o=await t.resolve(i),s=Ln(i,o),a=r(i,o,s),l=s?void 0:De(o);n[e.toString()]={source:i,resolvedPath:l,isExternal:s,importType:a};}function Ln(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var ht,fe=m(()=>{ee();ht=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function vo(i,e,t,n){let r=i.childForFieldName("source");if(!r)return;let o=r.startPosition.row,s=r.text.replace(/['"]/g,"");await K(s,o,e,t,n);}async function _o(i,e,t,n){let r=i.childForFieldName("source");if(!r)return;let o=r.startPosition.row,s=r.text.replace(/['"]/g,"");await K(s,o,e,t,n);}function Ge(){return {language:"javascript",handlers:new Map([["import_statement",vo],["export_statement",_o]])}}function yt(){return {...Ge(),language:"typescript"}}var wt=m(()=>{fe();});async function So(i,e,t,n){let r=i.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let s=r.childForFieldName("name");o=s?s.text:r.text;}else o=r.text;await K(o,i.startPosition.row,e,t,n);}async function xo(i,e,t,n){let r,o=i.childForFieldName("module_name");if(o)r=o.text;else {let s="";for(let a=0;a<i.childCount;a++){let l=i.child(a);if(l){if(l.type==="relative_import"){s=l.text;break}(l.type==="."||l.type==="import_prefix")&&(s+=l.text);}}r=s||".";}await K(r,i.startPosition.row,e,t,n);}async function Eo(i,e,t,n){await K("__future__",i.startPosition.row,e,t,n);}function Ct(){return {language:"python",handlers:new Map([["import_statement",So],["import_from_statement",xo],["future_import_statement",Eo]]),classifyImportType:Po}}var Po,We=m(()=>{fe();Po=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Fn,Dn=m(()=>{wt();We();fe();wt();We();Fn=[Ge(),yt(),Ct()];});var Mn={};an(Mn,{ImportExtractor:()=>vt});var vt,Bn=m(()=>{Dn();fe();vt=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Fn)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 s=this.classifiers.get(n)??ht,a={};return await this.walkAST(e.rootNode,async l=>{let g=o.get(l.type);g&&await g(l,r,a,s);}),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 me,Hn,_t,Un,Gn,ze=m(()=>{me=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"]),Hn=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"]),_t={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"]},Un={language:"javascript",textIncludedTypes:Hn,fieldNames:_t},Gn={language:"typescript",textIncludedTypes:Hn,fieldNames:_t};});var Io,Wn,zn,bt=m(()=>{Io=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"]),Wn={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"]},zn={language:"python",textIncludedTypes:Io,fieldNames:Wn,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function Kn(i){return he.get(i)}function Vn(i){if(!i)return me;let e=he.get(i);if(!e)return me;let t=new Set(me);for(let n of e.textIncludedTypes)t.add(n);return t}function Pt(i){if(!i){let t=Array.from(he.values()).map(n=>n.fieldNames);return ye(...t)}let e=he.get(i);if(!e){let t=Array.from(he.values()).map(n=>n.fieldNames);return ye(...t)}return e.fieldNames}var he,Jn=m(()=>{St();ze();bt();ze();ze();bt();he=new Map([["javascript",Un],["typescript",Gn],["python",zn]]);});var Qn={};an(Qn,{COMMON_FIELD_NAMES:()=>It,JS_TS_FIELD_NAMES:()=>Xn,PYTHON_FIELD_NAMES:()=>Zn,TEXT_INCLUDED_TYPES:()=>Yn,mergeFieldMaps:()=>ye,serializeAST:()=>ko,serializeASTStream:()=>$o});function*$o(i,e,t){yield*Et(i,e,t);}function*Et(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),qn(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let r=(t?Pt(t):It)[i.type]||[],o=new Set,s=true;for(let a of r){let l=i.childForFieldName(a);l&&(s||(yield ","),s=false,o.add(l),yield*Et(l,a,t));}for(let a=0;a<i.childCount;a++){let l=i.child(a);l&&!o.has(l)&&(s||(yield ","),s=false,yield*Et(l,void 0,t));}yield "]";}yield "}";}async function ko(i,e,t){let n=xt(i,e,t),r=t?Pt(t):It,o=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;o.length>0;){let s=o[o.length-1];if(s.childIndex===0&&s.treeNode.childCount>0){let a=r[s.treeNode.type]||[];for(let l of a){let g=s.treeNode.childForFieldName(l);if(g){s.fieldChildren.add(g);let d=xt(g,l,t);s.serializedNode.children||(s.serializedNode.children=[]),s.serializedNode.children.push(d),o.push({treeNode:g,serializedNode:d,fieldName:l,childIndex:0,fieldChildren:new Set});}}}if(s.childIndex<s.treeNode.childCount){let a=s.treeNode.child(s.childIndex);if(s.childIndex++,a&&!s.fieldChildren.has(a)){let l=xt(a,void 0,t);s.serializedNode.children||(s.serializedNode.children=[]),s.serializedNode.children.push(l),o.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else o.pop();}return n}function xt(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return qn(i,t)&&(n.text=i.text),n}function qn(i,e){if(e){let n=Kn(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(i);if(o===false)return false;if(o===true)return true}return Vn(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Yn.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function ye(...i){let e={};for(let t of i)for(let[n,r]of Object.entries(t)){let s=[...e[n]||[]];for(let a of r)s.includes(a)||s.push(a);e[n]=s;}return e}var Yn,Xn,Zn,It,St=m(()=>{Jn();Yn=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"]);Xn={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"]},Zn={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"]};It=ye(Xn,Zn);});var we,tr=m(()=>{pt();Sn();In();kn();Rn();Le();An();ee();N();jn();Oe();we=class extends W{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 Me(process.cwd()),this.parser=new Fe(this.langRegistry),this.compressor=new Be;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){let n=new Ue;n.start();let r="failed";try{let o=await this.getAccessKey();this.apiClient=new Ae(this.config,o),await this.validateProject(),console.log(`${H}Starting indexing procedure...
|
|
59
|
-
`);let s=performance.now();if(t?console.log(`${
|
|
60
|
-
${
|
|
61
|
-
${
|
|
62
|
-
${
|
|
63
|
-
to set or update your access key.`),o;if(o instanceof Error&&o.message==="Access key not configured")throw o;let s=o instanceof Error?o.message:"An unexpected error occurred";throw
|
|
64
|
-
${
|
|
65
|
-
'constellation auth' to configure your access key.`),new Error("Access key not configured");return
|
|
66
|
-
Verify your network connection and that the API URL is correct.`):
|
|
67
|
-
${
|
|
68
|
-
|
|
69
|
-
`),console.
|
|
70
|
-
`);break;case "PROJECT_INACTIVE":
|
|
71
|
-
${
|
|
72
|
-
|
|
73
|
-
`),console.
|
|
74
|
-
`);break;case "INVALID_PROJECT_ID":
|
|
75
|
-
${
|
|
76
|
-
|
|
77
|
-
`),console.
|
|
78
|
-
`);break;default:
|
|
79
|
-
${
|
|
80
|
-
`);}}async validateGitBranch(){console.log(`${y} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${
|
|
81
|
-
Commit or stash changes first to ensure consistent indexing
|
|
82
|
-
To resolve:`),console.
|
|
83
|
-
`)):
|
|
84
|
-
To resolve:`),console.
|
|
85
|
-
`)):
|
|
58
|
+
New terminal sessions will load it automatically.`);}};});var h,D=m(()=>{h={async directoryExists(i){try{return (await A__default.stat(i)).isDirectory()}catch{return false}},async fileIsReadable(i){try{return await A__default.access(i,A__default.constants.R_OK),!0}catch{return false}},async readFile(i,e="utf-8"){let t=await A__default.readFile(i,{encoding:e,flag:A__default.constants.O_RDONLY});return t.charCodeAt(0)===65279&&(t=t.slice(1)),t},async writeFile(i,e,t="utf-8"){let n=Buffer.from(e,t);await A__default.writeFile(i,n,{encoding:t,flag:A__default.constants.O_WRONLY|A__default.constants.O_CREAT|A__default.constants.O_TRUNC});},async getFileStats(i){return await A__default.stat(i)},async getFileHandle(i,e,t){return await A__default.open(i,e,t)}};});var Me,In=m(()=>{D();Me=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 ho;o.setLanguage(r);let s=await h.getFileStats(e),a=10*1024*1024;if(s.size<=a){let l=await h.readFile(e),g={bufferSize:1024*1024};return o.parse(l,void 0,g)}else return this.parseWithStream(o,e,s.size)}async parseWithStream(e,t,n){let r=null;try{r=await A.open(t,"r");let o=r.fd,s=64*1024,a=Buffer.alloc(s),l=0;return e.parse(f=>{if(n>50*1024*1024){let u=Math.round(f/n*100);u>l+10&&(console.log(` Parsing large file: ${u}%...`),l=u);}let p=nt.readSync(o,a,0,s,f);return p===0?null:a.subarray(0,p).toString("utf-8")})}catch(o){if(r)try{await r.close();}catch(s){console.error(`Warning: Failed to close file handle for ${t}:`,s);}throw o}finally{if(r)try{await r.close();}catch{}}}};});function Tn(i){return i.replace(/\\/g,"/")}function Be(i){return Tn(i).replace(/^\.?\//,"")}function K(i,e){return Tn(S.relative(i,e))}var ee=m(()=>{});var Ue,$n=m(()=>{D();ee();k();Ue=class{rootPath;constructor(e){this.rootPath=e||process.cwd();}async scanFiles(e){let t=Rn();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=Rn().add(t.exclude));let o=await A__default.realpath(this.rootPath);for(let s of e)try{let a=S__default.isAbsolute(s)?s:S__default.join(this.rootPath,s),l=await A__default.lstat(a);if(l.isSymbolicLink()){let g=await A__default.realpath(a);if(!g.startsWith(o+S__default.sep)&&g!==o){console.warn(`${C} Skipping symlink pointing outside project: ${s} -> ${g}`);continue}let f=await A__default.stat(a);if(!f.isFile())continue;let p=K(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:f.size});}else if(l.isFile()){let g=K(this.rootPath,a);if(r&&r.ignores(g))continue;let f=this.detectLanguage(g,t.languages);if(!f)continue;n.push({path:a,relativePath:g,language:f,size:l.size});}}catch{console.warn(`${C} Skipping inaccessible file: ${s}`);}return n}async loadGitignoreRules(e,t){let n=[],r=t;for(;;){let o=S__default.join(r,".gitignore");await h.fileIsReadable(o)&&n.unshift(o);let s=S__default.dirname(r);if(s===r)break;r=s;let a=S__default.join(r,".git");if(await h.directoryExists(a)){let l=S__default.join(r,".gitignore");await h.fileIsReadable(l)&&!n.includes(l)&&n.unshift(l);break}}for(let o of n)try{let s=await h.readFile(o);e.add(s);}catch{console.warn(`${C} Failed to load .gitignore: ${o}`);}e.add(".git");}async walkDirectory(e,t,n,r){let o=[],s=t||e,a=n||await A__default.realpath(this.rootPath),l=r||new Set([a]);try{let g=await A__default.readdir(e,{withFileTypes:!0});for(let f of g){let p=S__default.join(e,f.name),u=K(s,p);if(f.isDirectory()){if(f.name.startsWith("."))continue;let d=await this.walkDirectory(p,s,a,l);o.push(...d);}else if(f.isFile()){let d=await A__default.stat(p);o.push({path:p,relativePath:u,language:"",size:d.size});}else if(f.isSymbolicLink())try{let d=await A__default.realpath(p);if(!d.startsWith(a+S__default.sep)&&d!==a){console.warn(`${C} Skipping symlink pointing outside project: ${p} -> ${d}`);continue}let v=await A__default.stat(p);if(v.isDirectory()){if(f.name.startsWith(".")||l.has(d))continue;l.add(d);let _=await this.walkDirectory(p,s,a,l);o.push(..._);}else v.isFile()&&o.push({path:p,relativePath:u,language:"",size:v.size});}catch{console.warn(`${C} Skipping invalid symlink: ${p}`);}}}catch(g){console.error(`${E} Error walking directory ${e}:`,g);}return o}matchesLanguageExtension(e,t){let n=S__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=S__default.extname(e).toLowerCase();for(let[r,o]of Object.entries(t))if(o.fileExtensions.includes(n))return r;return null}};});var yo,Co,kn,Nn=m(()=>{yo=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"])}),Co=z$1.record(z$1.string(),yo),kn=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:Co.optional()});});var _o,He,On=m(()=>{_o=promisify(yt.gunzip),He=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=yt.createGzip();n.on("data",s=>t.push(s));let r=new Promise((s,a)=>{n.on("end",s),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=yt.createGzip();n.on("data",s=>t.push(s));let r=new Promise((s,a)=>{n.on("end",s),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 _o(t);return JSON.parse(n.toString("utf-8"))}};});var Ct,Ge=m(()=>{Ct=new Set(["ACCESS_KEY_MISSING","AUTH_FAILURE","PROJECT_NOT_REGISTERED","PROJECT_INACTIVE","INVALID_PROJECT_ID","DIRTY_WORKTREE","CONCURRENT_INDEXING","GIT_SYNC_FAILURE","BRANCH_NOT_CONFIGURED"]);});var We,Ln=m(()=>{We=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 s=r++,a=this.processItem(e[o],o,t).then(l=>({result:l!==null?l.result:null,promiseId:s}));n.set(s,a),o++;}for(;n.size>0;){let s=await Promise.race(n.values());if(n.delete(s.promiseId),s.result!==null&&(yield s.result),o<e.length){let a=r++,l=this.processItem(e[o],o,t).then(g=>({result:g!==null?g.result:null,promiseId:a}));n.set(a,l),o++;}}}async processItem(e,t,n){try{return {result:await n(e,t),index:t}}catch{return null}}};});function wt(i){if(typeof i=="string")return i;if(i instanceof Error)return i.message;if(typeof i=="object"&&i!==null)try{return JSON.stringify(i)}catch{return String(i)}return String(i)}var Ke,Fn=m(()=>{Ge();Ke=class{entries=[];originalLog;originalWarn;originalError;capturing=false;start(){this.capturing||(this.capturing=true,this.originalLog=console.log,this.originalWarn=console.warn,this.originalError=console.error,console.log=(...e)=>{this.entries.push({level:"info",message:c.unstyle(e.map(wt).join(" ")),timestamp:new Date().toISOString()}),this.originalLog.apply(console,e);},console.warn=(...e)=>{this.entries.push({level:"warn",message:c.unstyle(e.map(wt).join(" ")),timestamp:new Date().toISOString()}),this.originalWarn.apply(console,e);},console.error=(...e)=>{this.entries.push({level:"error",message:c.unstyle(e.map(wt).join(" ")),timestamp:new Date().toISOString()}),this.originalError.apply(console,e);});}stop(){this.capturing&&(this.capturing=false,console.log=this.originalLog,console.warn=this.originalWarn,console.error=this.originalError);}log(e){this.capture("info",e);}warn(e,t){this.capture("warn",e,t?.code);}error(e,t){this.capture("error",e,t?.code);}getEntries(){return [...this.entries]}hasErrors(){return this.entries.some(e=>e.level==="error")}hasWarnings(){return this.entries.some(e=>e.level==="warn")}getReportableErrors(){return this.entries.filter(e=>e.level==="error"&&(!e.code||!Ct.has(e.code)))}hasReportableErrors(){return this.entries.some(e=>e.level==="error"&&(!e.code||!Ct.has(e.code)))}capture(e,t,n){this.entries.push({level:e,message:c.unstyle(t),timestamp:new Date().toISOString(),code:n});let r=e==="info"?this.originalLog:e==="warn"?this.originalWarn:this.originalError;this.capturing?r.call(console,t):console[e==="info"?"log":e](t);}};});async function V(i,e,t,n,r){let o=await t.resolve(i),s=Dn(i,o),a=r(i,o,s),l=s?void 0:Be(o);n[e.toString()]={source:i,resolvedPath:l,isExternal:s,importType:a};}function Dn(i,e){return i===e?true:!(!e.startsWith(".")&&!e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))}var _t,me=m(()=>{ee();_t=(i,e,t)=>t?i.startsWith("node:")?"builtin":"external":i.startsWith("./")||i.startsWith("../")?"relative":i.startsWith("@")?"workspace":"alias";});async function vo(i,e,t,n){let r=i.childForFieldName("source");if(!r)return;let o=r.startPosition.row,s=r.text.replace(/['"]/g,"");await V(s,o,e,t,n);}async function Eo(i,e,t,n){let r=i.childForFieldName("source");if(!r)return;let o=r.startPosition.row,s=r.text.replace(/['"]/g,"");await V(s,o,e,t,n);}function Ve(){return {language:"javascript",handlers:new Map([["import_statement",vo],["export_statement",Eo]])}}function vt(){return {...Ve(),language:"typescript"}}var Et=m(()=>{me();});async function bo(i,e,t,n){let r=i.childForFieldName("name");if(!r)return;let o;if(r.type==="aliased_import"){let s=r.childForFieldName("name");o=s?s.text:r.text;}else o=r.text;await V(o,i.startPosition.row,e,t,n);}async function xo(i,e,t,n){let r,o=i.childForFieldName("module_name");if(o)r=o.text;else {let s="";for(let a=0;a<i.childCount;a++){let l=i.child(a);if(l){if(l.type==="relative_import"){s=l.text;break}(l.type==="."||l.type==="import_prefix")&&(s+=l.text);}}r=s||".";}await V(r,i.startPosition.row,e,t,n);}async function Io(i,e,t,n){await V("__future__",i.startPosition.row,e,t,n);}function St(){return {language:"python",handlers:new Map([["import_statement",bo],["import_from_statement",xo],["future_import_statement",Io]]),classifyImportType:Po}}var Po,Je=m(()=>{me();Po=(i,e,t)=>{if(t)return "external";if(/^\.+/.test(i))return "relative";let n=i.split(".")[0];return PYTHON_STDLIB_MODULES.has(n)?"builtin":"alias"};});var Bn,Un=m(()=>{Et();Je();me();Et();Je();Bn=[Ve(),vt(),St()];});var Hn={};pn(Hn,{ImportExtractor:()=>Pt});var Pt,Gn=m(()=>{Un();me();Pt=class{languageHandlers;classifiers;constructor(e){this.languageHandlers=new Map,this.classifiers=new Map;for(let t of e??Bn)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 s=this.classifiers.get(n)??_t,a={};return await this.walkAST(e.rootNode,async l=>{let g=o.get(l.type);g&&await g(l,r,a,s);}),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 he,Wn,bt,zn,Kn,Ye=m(()=>{he=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","string","string_literal","template_string","number","import_specifier","export_specifier","accessibility_modifier","readonly","static","async","await","const","let","var","decorator","=","=>","...","?","!","string_content"]),Wn=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"]),bt={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"]},zn={language:"javascript",textIncludedTypes:Wn,fieldNames:bt},Kn={language:"typescript",textIncludedTypes:Wn,fieldNames:bt};});var To,Vn,Jn,xt=m(()=>{To=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"]),Vn={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"]},Jn={language:"python",textIncludedTypes:To,fieldNames:Vn,shouldIncludeText:i=>{if(i.type==="string"&&i.childCount>0)return false}};});function Yn(i){return ye.get(i)}function qn(i){if(!i)return he;let e=ye.get(i);if(!e)return he;let t=new Set(he);for(let n of e.textIncludedTypes)t.add(n);return t}function It(i){if(!i){let t=Array.from(ye.values()).map(n=>n.fieldNames);return Ce(...t)}let e=ye.get(i);if(!e){let t=Array.from(ye.values()).map(n=>n.fieldNames);return Ce(...t)}return e.fieldNames}var ye,Xn=m(()=>{Tt();Ye();xt();Ye();Ye();xt();ye=new Map([["javascript",zn],["typescript",Kn],["python",Jn]]);});var nr={};pn(nr,{COMMON_FIELD_NAMES:()=>kt,JS_TS_FIELD_NAMES:()=>er,PYTHON_FIELD_NAMES:()=>tr,TEXT_INCLUDED_TYPES:()=>Zn,mergeFieldMaps:()=>Ce,serializeAST:()=>$o,serializeASTStream:()=>Ro});function*Ro(i,e,t){yield*$t(i,e,t);}function*$t(i,e,t){if(yield "{",yield `"type":${JSON.stringify(i.type)}`,yield `,"startPosition":${JSON.stringify({row:i.startPosition.row,column:i.startPosition.column})}`,yield `,"endPosition":${JSON.stringify({row:i.endPosition.row,column:i.endPosition.column})}`,e&&(yield `,"fieldName":${JSON.stringify(e)}`),Qn(i,t)&&(yield `,"text":${JSON.stringify(i.text)}`),i.childCount>0){yield ',"children":[';let r=(t?It(t):kt)[i.type]||[],o=new Set,s=true;for(let a of r){let l=i.childForFieldName(a);l&&(s||(yield ","),s=false,o.add(l),yield*$t(l,a,t));}for(let a=0;a<i.childCount;a++){let l=i.child(a);l&&!o.has(l)&&(s||(yield ","),s=false,yield*$t(l,void 0,t));}yield "]";}yield "}";}async function $o(i,e,t){let n=Rt(i,e,t),r=t?It(t):kt,o=[{treeNode:i,serializedNode:n,fieldName:e,childIndex:0,fieldChildren:new Set}];for(;o.length>0;){let s=o[o.length-1];if(s.childIndex===0&&s.treeNode.childCount>0){let a=r[s.treeNode.type]||[];for(let l of a){let g=s.treeNode.childForFieldName(l);if(g){s.fieldChildren.add(g);let f=Rt(g,l,t);s.serializedNode.children||(s.serializedNode.children=[]),s.serializedNode.children.push(f),o.push({treeNode:g,serializedNode:f,fieldName:l,childIndex:0,fieldChildren:new Set});}}}if(s.childIndex<s.treeNode.childCount){let a=s.treeNode.child(s.childIndex);if(s.childIndex++,a&&!s.fieldChildren.has(a)){let l=Rt(a,void 0,t);s.serializedNode.children||(s.serializedNode.children=[]),s.serializedNode.children.push(l),o.push({treeNode:a,serializedNode:l,childIndex:0,fieldChildren:new Set});}}else o.pop();}return n}function Rt(i,e,t){let n={type:i.type,startPosition:{row:i.startPosition.row,column:i.startPosition.column},endPosition:{row:i.endPosition.row,column:i.endPosition.column},...e&&{fieldName:e}};return Qn(i,t)&&(n.text=i.text),n}function Qn(i,e){if(e){let n=Yn(e);if(n?.shouldIncludeText){let o=n.shouldIncludeText(i);if(o===false)return false;if(o===true)return true}return qn(e).has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}return i.type==="string"&&i.childCount>0?false:Zn.has(i.type)||i.type.endsWith("_keyword")||i.type.endsWith("_operator")}function Ce(...i){let e={};for(let t of i)for(let[n,r]of Object.entries(t)){let s=[...e[n]||[]];for(let a of r)s.includes(a)||s.push(a);e[n]=s;}return e}var Zn,er,tr,kt,Tt=m(()=>{Xn();Zn=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"]);er={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"]},tr={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"]};kt=Ce(er,tr);});var we,or=m(()=>{Le();In();$n();Nn();On();Fe();Ge();Ln();ee();k();Fn();De();we=class extends z{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 Ue(process.cwd()),this.parser=new Me(this.langRegistry),this.compressor=new He;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){let n=new Ke;n.start();let r="failed";try{let o=await this.getAccessKey(n);this.apiClient=new je(this.config,o),await this.validateProject(n),console.log(`${U}Starting indexing procedure...
|
|
59
|
+
`);let s=performance.now();if(t?console.log(`${C} Skipping git branch validation`):await this.validateGitBranch(),t?console.log(`${C} Skipping git status validation`):await this.validateGitStatus(),t?console.log(`${C} Skipping repository synchronization`):await this.synchronizeChanges(n),this.buildConfigManagers.size>0){console.log(`${y} Discovering language build configurations...`);let I=0;for(let[T,$]of this.buildConfigManagers.entries()){let ge=await $.initialize();I+=ge.length;}I>0&&console.log(`${w} Found ${I} configuration file(s)`);}let a=await this.determineIndexScope(e),l=await this.git.getLatestCommitHash();if(a.upToDate){console.log(`
|
|
60
|
+
${w} Index is already up-to-date for ${this.config.projectId} on ${this.config.branch} commit ${l.substring(0,8)}`);return}if(a.isIncremental&&l){let I=await this.apiClient.getIndexStatus(this.config.branch,l);if(I?.status==="current"||I?.status==="processing"&&I?.commitHash===l){console.log(`${w} Index already up to date for branch ${this.config.branch} at commit ${l.substring(0,8)}`);return}}let g=await this.discoverFiles(a.isIncremental),f=!1,p=()=>{f||console.log(`${y} Uploading metadata, processing, and indexing...`);},u=this.generateASTs(g,p);try{await this.uploadToAPI(u,a.isIncremental,l),f=!0;}catch(I){throw f=!0,I}let _=(performance.now()-s)/1e3,B=Math.floor(_/60),P=(_%60).toFixed(3),pe=B>0?`${B}m ${P}s`:`${P}s`;console.log(`
|
|
61
|
+
${w} Upload completed in ${pe}! Server indexing in progress.`),r="succeeded";}catch(o){if(o instanceof N)throw o;if(o instanceof Q)throw n.error(`${E} Indexing failed: Another indexing operation is currently in progress for branch ${o.branchName||this.config?.branch||"unknown"}.`,{code:"CONCURRENT_INDEXING"}),console.log(" Your index may be out of date. Re-run this command after the current operation completes."),o;if(o instanceof b)throw n.error(`
|
|
62
|
+
${E} Authentication failed.`,{code:"AUTH_FAILURE"}),console.log(`${y} Your access key may be invalid or expired. Run 'constellation auth'
|
|
63
|
+
to set or update your access key.`),o;if(o instanceof G)throw n.error(`${E} Indexing failed: ${o.message}`,{code:o.errorCode}),o;if(o instanceof Error&&o.message==="Access key not configured")throw o;let s=o instanceof Error?o.message:"An unexpected error occurred";throw n.error(`${E} Indexing failed: ${s}`),o}finally{n.stop();try{let s=process.env.CONSTELLATION_ERROR_REPORTING?.toLowerCase()==="false",a=this.apiClient?.isFeatureEnabled("cli_error_reporting")??!1,l=n.getReportableErrors();if(!s&&a&&l.length>0){let g=n.getEntries(),f=l.map(P=>({type:"CLI_ERROR",message:P.message,phase:"indexing"})).slice(0,100),p=g.filter(P=>P.level==="warn").map(P=>({type:"CLI_WARNING",message:P.message,phase:"indexing"})).slice(0,100),u=f.length,d=p.length,v=[];u>0&&v.push(`${u} error${u!==1?"s":""}`),d>0&&v.push(`${d} warning${d!==1?"s":""}`);let _=v.join(", "),B=globalThis.__constellationVersion??"unknown";await this.apiClient.reportErrors({errorSummary:_,errorData:{errors:f,warnings:p},logEntries:g.slice(0,1e3),cliVersion:B,outcome:r,indexType:e?"full":"incremental"});}}catch{}}}async getAccessKey(e){let t=await this.env.getKey(W);if(!t)throw e.error(`
|
|
64
|
+
${E} Access key not found.`,{code:"ACCESS_KEY_MISSING"}),console.log(`${y} Set the ${W} environment variable or run
|
|
65
|
+
'constellation auth' to configure your access key.`),new Error("Access key not configured");return t}async validateProject(e){console.log(`${y} Validating project access...`);try{await this.apiClient.getProjectState(),console.log(`${w} Project validated successfully`);}catch(t){if(t instanceof N)throw this.displayProjectValidationError(t,e),t;if(t instanceof H){console.log(`${w} Project validated (first index)`);return}if(t instanceof b)throw t;let n=t instanceof Error?t.message:String(t);throw n==="fetch failed"||n.includes("ECONNREFUSED")||n.includes("ENOTFOUND")||n.includes("ETIMEDOUT")||n.includes("EHOSTUNREACH")||n.includes("ECONNRESET")?new Error(`Unable to connect to the Constellation service.
|
|
66
|
+
Verify your network connection and that the API URL is correct.`):t}}displayProjectValidationError(e,t){let n=e.projectId||this.config.projectId,r=n.length>40?n.substring(0,37)+"...":n;switch(e.code){case "PROJECT_NOT_REGISTERED":t.error(`
|
|
67
|
+
${E} Project not registered
|
|
68
|
+
`,{code:"PROJECT_NOT_REGISTERED"}),console.log(` The project ID "${r}" in constellation.json`),console.log(` is not associated with your Constellation account.
|
|
69
|
+
`),console.log(" To resolve this:"),console.log(" 1. Verify the project exists at https://app.constellationdev.io"),console.log(" 2. Check that the project ID in constellation.json is correct"),console.log(` 3. Run 'constellation index' again
|
|
70
|
+
`);break;case "PROJECT_INACTIVE":t.error(`
|
|
71
|
+
${E} Project is inactive
|
|
72
|
+
`,{code:"PROJECT_INACTIVE"}),console.log(` The project "${r}" has been deactivated.
|
|
73
|
+
`),console.log(" To resolve this:"),console.log(" 1. Reactivate the project at https://app.constellationdev.io"),console.log(` 2. Run 'constellation index' again
|
|
74
|
+
`);break;case "INVALID_PROJECT_ID":t.error(`
|
|
75
|
+
${E} Invalid project ID
|
|
76
|
+
`,{code:"INVALID_PROJECT_ID"}),console.log(` The project ID "${r}" in constellation.json`),console.log(` is not a valid Constellation project identifier.
|
|
77
|
+
`),console.log(" To resolve this:"),console.log(" 1. Get your project ID from https://app.constellationdev.io"),console.log(" 2. Update the projectId field in constellation.json"),console.log(` 3. Run 'constellation index' again
|
|
78
|
+
`);break;default:t.error(`
|
|
79
|
+
${E} Project validation failed: ${e.message}
|
|
80
|
+
`);}}async validateGitBranch(){console.log(`${y} Validating Git repository and branch...`);let t=(await this.git.status()).currentBranch;this.config.validateBranch(t),console.log(`${w} Current branch "${t}" is configured for indexing`);}async validateGitStatus(){if(console.log(`${y} Validating Git status...`),!(await this.git.status()).clean)throw new G(`Outstanding changes detected.
|
|
81
|
+
Commit or stash changes first to ensure consistent indexing.`,"DIRTY_WORKTREE");console.log(`${w} Working tree clean`);}async synchronizeChanges(e){console.log(`${y} Synchronizing latest changes...`);try{await this.git.pull()&&console.log(`${w} Repository synchronized successfully`);}catch(t){throw e.error(`${E} Failed to synchronize repository`,{code:"GIT_SYNC_FAILURE"}),t instanceof Error&&(t.message.includes("uncommitted changes")?(console.log(`
|
|
82
|
+
To resolve:`),console.log(' 1. Commit your changes: git add . && git commit -m "your message"'),console.log(" 2. Or stash them: git stash"),console.log(` 3. Then run the index command again
|
|
83
|
+
`)):t.message.includes("merge conflicts")?(console.log(`
|
|
84
|
+
To resolve:`),console.log(" 1. Fix the conflicted files manually"),console.log(" 2. Stage the resolved files: git add <resolved-files>"),console.log(" 3. Complete the merge: git commit"),console.log(` 4. Then run the index command again
|
|
85
|
+
`)):t.message.includes("Network error")?console.log(`
|
|
86
86
|
Please check your internet connection and try again
|
|
87
|
-
`):
|
|
87
|
+
`):t.message.includes("Authentication")&&console.log(`
|
|
88
88
|
Please check your git credentials and try again
|
|
89
|
-
`)),
|
|
89
|
+
`)),t}}async determineIndexScope(e){if(e)return {isIncremental:false,upToDate:false};console.log(`${y} Determining index scope...`);try{let n=(await this.apiClient.getProjectState())?.latestCommit;if(!n)return console.log(`${y} No previous index found - performing full index`),{isIncremental:!1,upToDate:!1};let r=await this.git.getLatestCommitHash();return n===r?(console.log(`${w} Already up to date`),{isIncremental:!0,upToDate:!0}):(console.log(`${y} Last indexed commit: ${n.substring(0,8)}`),console.log(`${y} Current commit: ${r.substring(0,8)}`),console.log(`${y} Performing incremental index starting from commit ${n.substring(0,8)}`),{isIncremental:!0,upToDate:!1})}catch(t){if(t instanceof b)throw t;return console.log(`${C} Could not determine last index - performing full index`),{isIncremental:false,upToDate:false}}}async discoverFiles(e){console.log(`${y} Analyzing codebase...`);let t;if(e)try{let n=await this.apiClient.getProjectState();if(!n?.latestCommit)console.log(`${C} 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(`${y} Found ${o.length} changed files`),t=await this.scanner.scanSpecificFiles(o,this.config);let s=[...r.deleted,...r.renamed.map(a=>a.from)];if(s.length>0){let a=r.deleted.length,l=r.renamed.length,g=l>0?`${y} Removing ${a} deleted file(s) and ${l} renamed file(s) from graph`:`${y} Removing ${a} deleted file(s) from graph`;console.log(g),await this.apiClient.deleteFiles(s);}}}catch(n){if(n instanceof b)throw n;console.log(`${C} Cannot determine changes - falling back to full scan`),t=await this.scanner.scanFiles(this.config);}else console.log(`${y} Scanning all project files...`),t=await this.scanner.scanFiles(this.config);return console.log(`${w} Found ${t.length} files to index`),t}async*generateASTs(e,t){let n=new Date().toISOString(),r=e.length,o=0,s=0;console.log(`${y} Processing ${r} files...`);let a=await this.git.getLatestCommitHash(),l=r>1e4?5:r>5e3?7:10;l<10&&console.log(`${y} Large project detected - using concurrency of ${l} to optimize memory usage`);let f=new We(l).run(e,async(p,u)=>{let d=Math.round((u+1)/r*100);console.log(`${y} Analyzing file ${p.path.replace(process.cwd()+"/","")} (${d}%)...`);try{let v=await this.parser.parseFile(p.path,p.language),_=this.langRegistry.getPlugin(p.language),B;if(_?.getImportResolver){let ge=this.buildConfigManagers.get(p.language),dt=ge?await ge.getConfigForFile(p.path):null,cn=_.getImportResolver(p.path,dt);if(cn){let{ImportExtractor:Ur}=await Promise.resolve().then(()=>(Gn(),Hn));B=await new Ur().extractImportResolutions(v,p.path,p.language,cn);}}let{serializeASTStream:P}=await Promise.resolve().then(()=>(Tt(),nr)),pe=P(v.rootNode,void 0,p.language),I=await this.compressor.compressStream(pe),T={file:this.normalizePathToCanonical(p.relativePath),language:p.language,commit:a,timestamp:n,ast:I,importResolutions:B},$=kn.safeParse(T);if(!$.success)throw new Error(`AST validation failed: ${$.error.issues[0].message}`);return o++,$.data}catch(v){throw s++,console.error(` ${C} Failed to parse ${p.relativePath}: ${v.message}`,v),v}});for await(let p of f)yield p;s>0?console.log(`${C} Completed parsing with ${s} parsing errors`):console.log(`${w} 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(`${w} Data uploaded to Constellation Service, indexing in progress`);}normalizePathToCanonical(e){return Be(e)}};});function Nt(i){return `name: Constellation Index
|
|
90
|
+
|
|
91
|
+
on:
|
|
92
|
+
push:
|
|
93
|
+
branches: ["${i}"]
|
|
94
|
+
|
|
95
|
+
permissions:
|
|
96
|
+
contents: read
|
|
97
|
+
|
|
98
|
+
jobs:
|
|
99
|
+
index:
|
|
100
|
+
runs-on: ubuntu-latest
|
|
101
|
+
steps:
|
|
102
|
+
- uses: actions/checkout@v4
|
|
103
|
+
|
|
104
|
+
- uses: ShiftinBits/constellation-github@v1
|
|
105
|
+
with:
|
|
106
|
+
access-key: \${{ secrets.CONSTELLATION_ACCESS_KEY }}
|
|
107
|
+
`}function At(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function qe(i){return `include:
|
|
108
|
+
- component: gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1
|
|
109
|
+
inputs:
|
|
110
|
+
access_key: $CONSTELLATION_ACCESS_KEY
|
|
111
|
+
|
|
112
|
+
constellation-index:
|
|
113
|
+
rules:
|
|
114
|
+
- if: $CI_COMMIT_BRANCH == "${i}"
|
|
115
|
+
`}var jt=m(()=>{});var _e,sr=m(()=>{D();jt();_e=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([h.directoryExists(S__default.join(this.gitRoot,".github","workflows")),h.fileIsReadable(S__default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return h.fileIsReadable(S__default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=S__default.join(this.gitRoot,".gitlab-ci.yml");if(!await h.fileIsReadable(e))return false;try{let n=await h.readFile(e),o=parseDocument(n).contents;return isMap(o)&&o.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=S__default.join(this.gitRoot,".github","workflows");await A__default.mkdir(t,{recursive:true});let n=S__default.join(t,"constellation-index.yml");return await h.writeFile(n,Nt(e)),n}async createOrMergeGitLabCI(e){let t=S__default.join(this.gitRoot,".gitlab-ci.yml");if(!await h.fileIsReadable(t))return await h.writeFile(t,qe(e)),t;let r=await h.readFile(t),o=parseDocument(r);if(!isMap(o.contents))return await h.writeFile(t,qe(e)),t;let{includeEntry:s,job:a}=At(e);return this.mergeIncludeEntry(o,s),o.set("constellation-index",a),await h.writeFile(t,o.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let r=n.items.filter(o=>{if(isMap(o)){let s=o.get("component");return typeof s!="string"||!s.includes("constellation-gitlab")}return true});n.items=r,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var ar=m(()=>{sr();jt();});function Lt(){return lr}var lr,cr=m(()=>{lr=[{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.
|
|
90
116
|
|
|
91
117
|
Mental model:
|
|
92
118
|
- "Where is X defined?" \u2192 {MCP_TOOL_NAME}
|
|
@@ -94,7 +120,7 @@ Mental model:
|
|
|
94
120
|
- "What would break?" \u2192 {MCP_TOOL_NAME}
|
|
95
121
|
- "Find the string 'ERROR_CODE_123'" \u2192 Grep
|
|
96
122
|
|
|
97
|
-
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
|
|
123
|
+
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 Oo(i){return pr[i]}var pr,jo,ve,Ft=m(()=>{pr={SessionStart:"TaskStart",SubagentStart:void 0,PreCompact:void 0,PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",SessionEnd:"TaskComplete"},jo="code_intel";ve=class{id="cline";displayName="Cline";mapEventName(e){return pr[e]}generateConfig(e){return {}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,jo)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){let r=Oo(n.event);if(!r)continue;let o=`.clinerules/hooks/${r}`,s=this.generateScript(n);t.set(o,s);}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
|
|
98
124
|
# Constellation ${e.event} Hook for Cline
|
|
99
125
|
# Generated by constellation-cli - DO NOT EDIT
|
|
100
126
|
#
|
|
@@ -107,7 +133,7 @@ cat << 'CONSTELLATION_EOF'
|
|
|
107
133
|
"contextModification": "${n}"
|
|
108
134
|
}
|
|
109
135
|
CONSTELLATION_EOF
|
|
110
|
-
`}};});var
|
|
136
|
+
`}};});var Lo,Fo,te,Dt=m(()=>{Lo={SessionStart:"sessionStart",SubagentStart:"subagentStart",PreCompact:"preCompact",PreToolUse:"preToolUse",PostToolUse:"postToolUse",SessionEnd:"sessionEnd"},Fo="constellation__code_intel",te=class{id="cursor";displayName="Cursor";mapEventName(e){return Lo[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,Fo)}};});function gr(i){return `constellation-${{SessionStart:"session-start",SubagentStart:"before-agent",PreCompact:"pre-compress",PreToolUse:"before-tool",PostToolUse:"after-tool",SessionEnd:"session-end"}[i]}.sh`}var Do,Mo,Bo,Ee,Mt=m(()=>{Do={SessionStart:"SessionStart",SubagentStart:"BeforeAgent",PreCompact:"PreCompress",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",SessionEnd:"SessionEnd"},Mo={SessionStart:"startup",SubagentStart:"",PreCompact:""},Bo="code_intel";Ee=class{id="gemini";displayName="Gemini CLI";mapEventName(e){return Do[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=Mo[n.event]??"",s=gr(n.event),a=t[r].find(l=>l.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/${s}`,timeout:5e3,description:`Constellation: ${this.getHookDescription(n.event)}`});}return {hooks:t}}customizePrompt(e){return e.content.replace(/\{MCP_TOOL_NAME\}/g,Bo)}generateAuxiliaryFiles(e){let t=new Map;for(let n of e){if(!this.mapEventName(n.event))continue;let s=`.gemini/hooks/${gr(n.event)}`,a=this.generateScript(n);t.set(s,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
|
|
111
137
|
# Constellation ${e.event} Hook for Gemini CLI
|
|
112
138
|
# Generated by constellation-cli - DO NOT EDIT
|
|
113
139
|
#
|
|
@@ -130,64 +156,38 @@ cat << 'CONSTELLATION_EOF'
|
|
|
130
156
|
}
|
|
131
157
|
}
|
|
132
158
|
CONSTELLATION_EOF
|
|
133
|
-
`}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]}};});function
|
|
159
|
+
`}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]}};});function Bt(i){return Uo.get(i)}var Uo,Ut=m(()=>{Ft();Dt();Mt();Ft();Dt();Mt();Uo=new Map([["cline",new ve],["cursor",new te],["gemini",new Ee]]);});var Se,ur=m(()=>{D();Ut();Se=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=Bt(e.hooksConfig.adapterId);if(!n)return {toolId:e.id,toolDisplayName:e.displayName,success:false,error:`Unknown adapter: ${e.hooksConfig.adapterId}`};try{let r=S__default.join(this.cwd,e.hooksConfig.filePath),o=n.generateConfig(t),s=Object.keys(o).some(l=>{let g=o[l];return g!=null&&(typeof g!="object"||Object.keys(g).length>0)});if(s){await this.ensureDirectoryExists(r);let l=await this.readConfig(r),g=this.mergeHooksConfig(l,o);await this.writeConfig(r,g);}let a;if(n.generateAuxiliaryFiles){let l=n.generateAuxiliaryFiles(t);l&&(await this.writeAuxiliaryFiles(l),a=Array.from(l.keys()));}return {toolId:e.id,toolDisplayName:e.displayName,success:!0,configuredPath:s?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=S__default.dirname(e);await A__default.mkdir(t,{recursive:true});}async readConfig(e){try{if(!await h.fileIsReadable(e))return {};let n=await h.readFile(e);return JSON.parse(n)}catch{return {}}}mergeHooksConfig(e,t){if(Object.keys(e).length===0)return t;let n=e.hooks??{},r=t.hooks??{},o={...n,...r},s={...e,hooks:o};return t.version!==void 0&&(s.version=t.version),s}async writeConfig(e,t){let n=JSON.stringify(t,null," ");n=n.replace(/\r\n/g,`
|
|
134
160
|
`),n.endsWith(`
|
|
135
161
|
`)||(n+=`
|
|
136
|
-
`),await h.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let r=
|
|
162
|
+
`),await h.writeFile(e,n);}async writeAuxiliaryFiles(e){for(let[t,n]of e){let r=S__default.join(this.cwd,t);await this.ensureDirectoryExists(r);let o=n.replace(/\r\n/g,`
|
|
137
163
|
`);o.endsWith(`
|
|
138
164
|
`)||(o+=`
|
|
139
|
-
`),await h.writeFile(r,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await A__default.chmod(r,493);}}};});var lr=m(()=>{rr();ar();At();});var V,Ke=m(()=>{V=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var ne,Lt=m(()=>{N();ne=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${w} 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 this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}throw r}if(this.isTypeScriptEnabled){let r=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let r=t instanceof Error?t.message:String(t);console.warn(`${w} Failed to parse ${n}: ${r}`),console.warn(`${w} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${w} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var Ve,pr=m(()=>{ee();Ve=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?_.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[r,o]of Object.entries(t)){if(r.includes("*")||!Array.isArray(o))continue;let s=o[0];if(!s)continue;let a=_.resolve(n,s),l=await this.findEntryPoint(a);l&&(e[r]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=_.join(this.projectRoot,"package.json"),n=await A.readFile(t,"utf-8"),o=JSON.parse(n).workspaces;if(!o)return e;let s=Array.isArray(o)?o:o.packages||[];for(let a of s){let l=await this.findWorkspaceDirs(a);for(let g of l){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=_.join(this.projectRoot,n);try{let o=await A.readdir(r,{withFileTypes:!0});for(let s of o)s.isDirectory()&&t.push(_.join(r,s.name));}catch{}}else {let n=_.join(this.projectRoot,e);try{(await A.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=_.join(e,"package.json"),n=await A.readFile(t,"utf-8"),r=JSON.parse(n),o=r.name;if(!o)return null;let s=await this.findPackageEntryPoint(e,r);return s?{[o]:s}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return _.join(e,r);if(typeof r=="object"){let o=r["."]||r["./index"];if(typeof o=="string")return _.join(e,o);if(typeof o=="object"){let s=o.import||o.default||o.require;if(s)return _.join(e,s)}}}if(t.main)return _.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=_.join(e,r);try{if((await A.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=_.join(e,n);try{if((await A.stat(r)).isFile())return r}catch{}}try{if((await A.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")?_.dirname(e):_.dirname(e),r=[_.join(n,t+".ts"),_.join(n,t+".tsx"),_.join(n,t+".js"),_.join(n,t+".jsx"),_.join(n,t+".d.ts"),_.join(n,t,"index.ts"),_.join(n,t,"index.tsx"),_.join(n,t,"index.js"),_.join(n,t,"index.jsx")];for(let o of r)try{if((await A.stat(o)).isFile())return o}catch{}return null}toProjectRelative(e){let t=z(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var re,Ot=m(()=>{ee();pr();re=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=_.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Ve(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=_.dirname(t.tsconfigFile);let s=t.tsconfig?.compilerOptions;s&&(s.baseUrl&&(this.baseUrl=_.resolve(this.tsconfigDir,s.baseUrl)),s.paths&&typeof s.paths=="object"&&(this.paths=s.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=_.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=z(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 s=await this.trySubstitution(e,t,o,r);if(s)return s}}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,s=r?e.length-r.length:e.length;return e.substring(o,s)}async trySubstitution(e,t,n,r){let o=n.replaceAll("*",r),s=_.resolve(this.tsconfigDir,o);return await this.findFileWithExtensions(s)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=_.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(s=>e.endsWith(s));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],r=n.some(s=>e.endsWith(s)),o=e;if(r&&!t){for(let s of n)if(e.endsWith(s)){o=e.slice(0,-s.length);break}}if(!t)for(let s of this.extensions){let a=o+s;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let s of this.extensions){let a=_.join(o,`index${s}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await A.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await A.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=_.join(t,"package.json");try{if((await A.stat(n)).isFile())return n}catch{}let r=_.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 A.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=_.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 s=await this.tryPackageImportSubstitution(o,r);if(s)return s}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=_.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};});var Je,gr=m(()=>{Ke();Lt();Ot();Je=class extends V{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new ne(e,t)}getImportResolver(e,t){return new re(e,t)}};});var Ye,dr=m(()=>{Ke();Lt();Ot();Ye=class extends V{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new ne(e,t)}getImportResolver(e,t){return new re(e,t)}};});var qe,ur=m(()=>{We();qe=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=_.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(_.resolve(this.projectRoot,n));return r?_.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)||".",s=_.resolve(this.sourceDir,o),a=await this.tryResolveFile(s);return a?_.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,_.join(e,"__init__.py"),_.join(e,"__init__.pyi")];for(let n of t)try{return await Xe.promises.access(n,Xe.constants.F_OK),n}catch{continue}return null}};});var Ze,fr=m(()=>{Ke();ur();Ze=class extends V{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new qe(e,process.cwd())}};});var be,Qe,Ft=m(()=>{gr();dr();fr();be={bash:[".sh",".bash"],c:[".c",".h"],"c-sharp":[".cs"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],go:[".go"],java:[".java"],javascript:[".js",".jsx"],json:[".json"],php:[".php"],python:[".py",".pyi",".pyw"],ruby:[".rb"],typescript:[".ts",".tsx"]},Qe=class{constructor(e){this.config=e;this.registerPlugin(new Je),this.registerPlugin(new Ye),this.registerPlugin(new Ze);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Bo,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??be.javascript};typescript={language:()=>Uo.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??be.typescript};python={language:()=>Ho,fileExtensions:()=>this.config?.languages.python?.fileExtensions??be.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function hr(i,e){let t=ae__default.homedir(),n=process.platform,r=Go[i];switch(n){case "darwin":return ___default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return ___default.join(process.env.APPDATA||___default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return ___default.join(t,".config",r,"User/globalStorage",e)}}function yr(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:___default.join(hr(t,i),"settings","cline_mcp_settings.json")}))}function wr(){return ___default.join(hr("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}function Dt(){let i=ae__default.homedir();return ___default.join(i,".copilot","mcp-config.json")}function Cr(){return [{displayName:"Copilot CLI",settingsPath:Dt()}]}var Go,vr=m(()=>{Go={stable:"Code",insiders:"Code - Insiders"};});function Bt(i){return Mt.find(e=>e.id===i)}var _r,Wo,Mt,Ht=m(()=>{vr();_r={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Wo={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},Mt=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",skipMcpServer:true,permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:Wo},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:wr(),isGlobalConfig:true,getGlobalConfigPaths:yr,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:Dt(),isGlobalConfig:true,getGlobalConfigPaths:Cr,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"]}}];});async function br(){if(!Ut)try{let i=await import('@iarna/toml');Ut={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Ut}function Vo(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
|
|
140
|
-
`;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var
|
|
165
|
+
`),await h.writeFile(r,o),(t.endsWith(".sh")||o.startsWith("#!"))&&await A__default.chmod(r,493);}}};});var fr=m(()=>{cr();ur();Ut();});var J,Xe=m(()=>{J=class{getBuildConfigManager(e,t){return null}getImportResolver(e,t){return null}};});var ne,Gt=m(()=>{k();ne=class{configPaths=[];parseCache=new Map;failedConfigFiles=new Set;initialized=false;isTypeScriptEnabled;isJavaScriptEnabled;isPathResolutionEnabled;projectRoot;constructor(e,t){this.projectRoot=e,this.isTypeScriptEnabled="typescript"in t,this.isJavaScriptEnabled="javascript"in t,this.isPathResolutionEnabled=this.isTypeScriptEnabled||this.isJavaScriptEnabled;}async initialize(){if(this.initialized)return this.configPaths;if(this.initialized=true,!this.isPathResolutionEnabled)return [];try{let e=[];if(this.isTypeScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["tsconfig.json"]});e.push(...t);}if(this.isJavaScriptEnabled){let t=await findAll(this.projectRoot,{skip:n=>n==="node_modules"||n===".git",configNames:["jsconfig.json"]});e.push(...t);}return this.configPaths=e,this.configPaths}catch(e){return console.warn(`${C} 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 this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}if(n){if(this.isJavaScriptEnabled)try{let r=await this.findAndParse(e,"jsconfig.json");return this.parseCache.set(e,r),r}catch(r){if(this.isTypeScriptEnabled){let o=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,o),o}throw r}if(this.isTypeScriptEnabled){let r=await this.findAndParse(e,"tsconfig.json");return this.parseCache.set(e,r),r}}return this.parseCache.set(e,null),null}catch(t){return this.handleConfigError(e,t),this.parseCache.set(e,null),null}}isEnabled(){return this.isPathResolutionEnabled}getConfigPaths(){return [...this.configPaths]}getTsconfigPaths(){return this.getConfigPaths()}clearCache(){this.parseCache.clear(),this.failedConfigFiles.clear();}async findAndParse(e,t){let n=await find(e,{root:this.projectRoot,configName:t});return !n||this.failedConfigFiles.has(n)?null:parse(e,{root:this.projectRoot,configName:t})}handleConfigError(e,t){let n=t&&typeof t=="object"&&"tsconfigFile"in t?t.tsconfigFile:null;if(n&&!this.failedConfigFiles.has(n)){this.failedConfigFiles.add(n);let r=t instanceof Error?t.message:String(t);console.warn(`${C} Failed to parse ${n}: ${r}`),console.warn(`${C} Path alias resolution will be skipped for files using this config`);}else n||console.warn(`${C} Failed to parse config for ${e}:`,t instanceof Error?t.message:t);}};});var Ze,hr=m(()=>{ee();Ze=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?S.dirname(this.tsconfigResult.tsconfigFile):this.projectRoot;for(let[r,o]of Object.entries(t)){if(r.includes("*")||!Array.isArray(o))continue;let s=o[0];if(!s)continue;let a=S.resolve(n,s),l=await this.findEntryPoint(a);l&&(e[r]=l);}return e}async loadFromPackageJsonWorkspaces(){let e={};try{let t=S.join(this.projectRoot,"package.json"),n=await A.readFile(t,"utf-8"),o=JSON.parse(n).workspaces;if(!o)return e;let s=Array.isArray(o)?o:o.packages||[];for(let a of s){let l=await this.findWorkspaceDirs(a);for(let g of l){let f=await this.loadWorkspacePackage(g);f&&Object.assign(e,f);}}}catch{}return e}async findWorkspaceDirs(e){let t=[];if(e.endsWith("/*")){let n=e.slice(0,-2),r=S.join(this.projectRoot,n);try{let o=await A.readdir(r,{withFileTypes:!0});for(let s of o)s.isDirectory()&&t.push(S.join(r,s.name));}catch{}}else {let n=S.join(this.projectRoot,e);try{(await A.stat(n)).isDirectory()&&t.push(n);}catch{}}return t}async loadWorkspacePackage(e){try{let t=S.join(e,"package.json"),n=await A.readFile(t,"utf-8"),r=JSON.parse(n),o=r.name;if(!o)return null;let s=await this.findPackageEntryPoint(e,r);return s?{[o]:s}:null}catch{return null}}async findPackageEntryPoint(e,t){if(t.exports){let r=t.exports;if(typeof r=="string")return S.join(e,r);if(typeof r=="object"){let o=r["."]||r["./index"];if(typeof o=="string")return S.join(e,o);if(typeof o=="object"){let s=o.import||o.default||o.require;if(s)return S.join(e,s)}}}if(t.main)return S.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=S.join(e,r);try{if((await A.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=S.join(e,n);try{if((await A.stat(r)).isFile())return r}catch{}}try{if((await A.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")?S.dirname(e):S.dirname(e),r=[S.join(n,t+".ts"),S.join(n,t+".tsx"),S.join(n,t+".js"),S.join(n,t+".jsx"),S.join(n,t+".d.ts"),S.join(n,t,"index.ts"),S.join(n,t,"index.tsx"),S.join(n,t,"index.js"),S.join(n,t,"index.jsx")];for(let o of r)try{if((await A.stat(o)).isFile())return o}catch{}return null}toProjectRelative(e){let t=K(this.projectRoot,e);return t.startsWith("./")?t:`./${t}`}};});var re,Wt=m(()=>{ee();hr();re=class{baseUrl=null;paths={};sourceDir;tsconfigDir;projectRoot;extensions;packageImports={};packageJsonDir=null;sourceFilePath;workspaceResolver;constructor(e,t){this.sourceFilePath=e,this.sourceDir=S.dirname(e),this.projectRoot=process.cwd(),this.workspaceResolver=new Ze(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=S.dirname(t.tsconfigFile);let s=t.tsconfig?.compilerOptions;s&&(s.baseUrl&&(this.baseUrl=S.resolve(this.tsconfigDir,s.baseUrl)),s.paths&&typeof s.paths=="object"&&(this.paths=s.paths));}async resolve(e){if(e.startsWith("./")||e.startsWith("../")){let n=S.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=K(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 s=await this.trySubstitution(e,t,o,r);if(s)return s}}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,s=r?e.length-r.length:e.length;return e.substring(o,s)}async trySubstitution(e,t,n,r){let o=n.replaceAll("*",r),s=S.resolve(this.tsconfigDir,o);return await this.findFileWithExtensions(s)}async resolveWithBaseUrl(e){if(!this.baseUrl)return null;let t=S.resolve(this.baseUrl,e);return await this.findFileWithExtensions(t)}async findFileWithExtensions(e){let t=this.extensions.some(s=>e.endsWith(s));if(t&&await this.fileExists(e))return await this.resolveSymlink(e);let n=[".js",".jsx",".mjs",".cjs"],r=n.some(s=>e.endsWith(s)),o=e;if(r&&!t){for(let s of n)if(e.endsWith(s)){o=e.slice(0,-s.length);break}}if(!t)for(let s of this.extensions){let a=o+s;if(await this.fileExists(a))return await this.resolveSymlink(a)}for(let s of this.extensions){let a=S.join(o,`index${s}`);if(await this.fileExists(a))return await this.resolveSymlink(a)}return null}async fileExists(e){try{return (await A.stat(e)).isFile()}catch{return false}}async resolveSymlink(e){try{return await A.realpath(e)}catch{return e}}async findPackageJson(e){let t=e;for(;t.startsWith(this.projectRoot);){let n=S.join(t,"package.json");try{if((await A.stat(n)).isFile())return n}catch{}let r=S.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 A.readFile(e,"utf-8"),n=JSON.parse(t);this.packageJsonDir=S.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 s=await this.tryPackageImportSubstitution(o,r);if(s)return s}}}}return null}async tryPackageImportSubstitution(e,t){if(!this.packageJsonDir)return null;let n=e.replaceAll("*",t),r=S.resolve(this.packageJsonDir,n);return await this.findFileWithExtensions(r)}};});var Qe,yr=m(()=>{Xe();Gt();Wt();Qe=class extends J{language="typescript";extensions=[".ts",".tsx",".d.ts"];getBuildConfigManager(e,t){return new ne(e,t)}getImportResolver(e,t){return new re(e,t)}};});var et,Cr=m(()=>{Xe();Gt();Wt();et=class extends J{language="javascript";extensions=[".js",".jsx",".mjs",".cjs"];getBuildConfigManager(e,t){return new ne(e,t)}getImportResolver(e,t){return new re(e,t)}};});var tt,wr=m(()=>{Je();tt=class{sourceDir;projectRoot;constructor(e,t){this.sourceDir=S.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(S.resolve(this.projectRoot,n));return r?S.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)||".",s=S.resolve(this.sourceDir,o),a=await this.tryResolveFile(s);return a?S.relative(this.projectRoot,a).replace(/\\/g,"/"):e}async tryResolveFile(e){let t=[`${e}.py`,`${e}.pyi`,`${e}.pyw`,S.join(e,"__init__.py"),S.join(e,"__init__.pyi")];for(let n of t)try{return await nt.promises.access(n,nt.constants.F_OK),n}catch{continue}return null}};});var rt,_r=m(()=>{Xe();wr();rt=class extends J{language="python";extensions=[".py",".pyi",".pyw"];getBuildConfigManager(e,t){return null}getImportResolver(e,t){return new tt(e,process.cwd())}};});var Pe,ot,zt=m(()=>{yr();Cr();_r();Pe={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"]},ot=class{constructor(e){this.config=e;this.registerPlugin(new Qe),this.registerPlugin(new et),this.registerPlugin(new rt);}plugins=new Map;registerPlugin(e){this.plugins.set(e.language,e);}getPlugin(e){return this.plugins.get(e)}javascript={language:()=>Wo,fileExtensions:()=>this.config?.languages.javascript?.fileExtensions??Pe.javascript};typescript={language:()=>Ko.typescript,fileExtensions:()=>this.config?.languages.typescript?.fileExtensions??Pe.typescript};python={language:()=>zo,fileExtensions:()=>this.config?.languages.python?.fileExtensions??Pe.python};php;json;java;go;cpp;"c-sharp";c;bash;ruby};});function vr(i,e){let t=le__default.homedir(),n=process.platform,r=Jo[i];switch(n){case "darwin":return S__default.join(t,"Library/Application Support",r,"User/globalStorage",e);case "win32":return S__default.join(process.env.APPDATA||S__default.join(t,"AppData/Roaming"),r,"User/globalStorage",e);default:return S__default.join(t,".config",r,"User/globalStorage",e)}}function Er(){let i="saoudrizwan.claude-dev";return ["stable","insiders"].map(t=>({variant:t,displayName:t==="stable"?"VS Code":"VS Code Insiders",settingsPath:S__default.join(vr(t,i),"settings","cline_mcp_settings.json")}))}function Sr(){return S__default.join(vr("stable","saoudrizwan.claude-dev"),"settings","cline_mcp_settings.json")}var Jo,Pr=m(()=>{Jo={stable:"Code",insiders:"Code - Insiders"};});function Vt(i){return Kt.find(e=>e.id===i)}var br,Yo,Kt,Jt=m(()=>{Pr();br={command:"npx",args:["-y","@constellationdev/mcp@latest"]},Yo={extraKnownMarketplaces:{"constellation-plugins":{source:{source:"github",repo:"ShiftinBits/constellation-claude"}}},enabledPlugins:{"constellation@constellation-plugins":true}},Kt=[{id:"claude-code",displayName:"Claude Code",configPath:".mcp.json",format:"json",skipMcpServer:true,permissionsConfig:{filePath:".claude/settings.json",allowKeyPath:["permissions","allow"],allowValue:"mcp__plugin_constellation_*"},marketplaceConfig:{filePath:".claude/settings.json",config:Yo},mcpServersKeyPath:["mcpServers"]},{id:"cline",displayName:"Cline",configPath:Sr(),isGlobalConfig:true,getGlobalConfigPaths:Er,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:"",format:"json",mcpServersKeyPath:[],skipMcpServer:true,pluginInstallCommand:{command:"copilot",args:["plugin","install","ShiftinBits/constellation-copilot"]}},{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"]}}];});async function xr(){if(!Yt)try{let i=await import('@iarna/toml');Yt={parse:i.parse,stringify:i.stringify};}catch{throw new Error("TOML support requires @iarna/toml package. Install with: npm install @iarna/toml")}return Yt}function Zo(i){let e="",t=0,n=i.length;for(;t<n;)if(i[t]==='"'){for(e+='"',t++;t<n&&i[t]!=='"';)i[t]==="\\"?(e+=i[t++],t<n&&(e+=i[t++])):e+=i[t++];t<n&&(e+=i[t++]);}else if(i[t]==="/"&&t+1<n&&i[t+1]==="/")for(t+=2;t<n&&i[t]!==`
|
|
166
|
+
`;)t++;else if(i[t]==="/"&&t+1<n&&i[t+1]==="*"){for(t+=2;t<n&&!(i[t]==="*"&&t+1<n&&i[t+1]==="/");)t++;t<n&&(t+=2);}else e+=i[t++];return e.replace(/,(\s*[}\]])/g,"$1")}var Yt,it,Ir=m(()=>{D();Jt();Yt=null;it=class{cwd;constructor(e=process.cwd()){this.cwd=e;}async configureTool(e){try{let t=S__default.join(this.cwd,e.configPath),n=!e.skipMcpServer||!!e.pluginConfig||!!e.configDefaults;if(n){await this.ensureDirectoryExists(t);let o=await this.readConfig(t,e.format);if(e.configDefaults)for(let[s,a]of Object.entries(e.configDefaults))s in o||(o[s]=a);e.pluginConfig&&(o=this.addPluginToArray(o,e.pluginConfig)),e.skipMcpServer||(o=this.addConstellationServer(o,e),await this.configureEnvPolicy(o,e)),await this.writeConfig(t,o,e.format);}e.permissionsConfig&&await this.configurePermissions(e.permissionsConfig),e.marketplaceConfig&&await this.configureMarketplace(e.marketplaceConfig);let r;return n?r=t:e.permissionsConfig?r=S__default.join(this.cwd,e.permissionsConfig.filePath):e.marketplaceConfig?r=S__default.join(this.cwd,e.marketplaceConfig.filePath):r=t,{tool:e,success:!0,configuredPath:r}}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 s=await this.readConfig(o,e.format);s=this.addConstellationServer(s,e),await this.writeConfig(o,s,e.format),n.push({tool:{...e,displayName:`${e.displayName} (${r})`},success:!0,configuredPath:o});}catch(s){let a=s instanceof Error?s.message:String(s);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=S__default.dirname(e);await A__default.mkdir(t,{recursive:true});}async readConfig(e,t){try{if(!await h.fileIsReadable(e))return {};let r=await h.readFile(e);return t==="json"?JSON.parse(r):t==="jsonc"?JSON.parse(Zo(r)):(await xr()).parse(r)}catch{return {}}}addConstellationServer(e,t){let n=e;for(let s=0;s<t.mcpServersKeyPath.length-1;s++){let a=t.mcpServersKeyPath[s];(!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 s=t.mcpServerConfigOverride??br,a={...s};if(t.mcpServerExtras&&Object.assign(a,t.mcpServerExtras),t.mcpEnv){let l=t.mcpEnvKey??"env",g=s[l];a[l]={...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 xr()).stringify(t),r=r.replace(/\r\n/g,`
|
|
141
167
|
`),r.endsWith(`
|
|
142
168
|
`)||(r+=`
|
|
143
|
-
`),await h.writeFile(e,r);}async configurePermissions(e){let t=
|
|
144
|
-
`);}async configureMarketplace(e){let t=
|
|
145
|
-
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],s=e[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=this.deepMerge(s,o):n[r]=o;}return n}addPluginToArray(e,t){let n=e;for(let s=0;s<t.pluginKeyPath.length-1;s++){let a=t.pluginKeyPath[s];(!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 l=t[a];if(!r[l]||typeof r[l]!="object")return;r=r[l];}let o=t[t.length-1];if(!Array.isArray(r[o]))return;let s=r[o];for(let a of n)s.includes(a)||s.push(a);}async updateGlobalEnvPolicy(e,t,n,r){let o=e.replace(/^~/,
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
permissions:
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
steps:
|
|
158
|
-
- uses: actions/checkout@v4
|
|
159
|
-
|
|
160
|
-
- uses: ShiftinBits/constellation-github@v1
|
|
161
|
-
with:
|
|
162
|
-
access-key: \${{ secrets.CONSTELLATION_ACCESS_KEY }}
|
|
163
|
-
`}function Wt(i){return {includeEntry:{component:"gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1",inputs:{access_key:"$CONSTELLATION_ACCESS_KEY"}},job:{rules:[{if:`$CI_COMMIT_BRANCH == "${i}"`}]}}}function tt(i){return `include:
|
|
164
|
-
- component: gitlab.com/shiftinbits/constellation-gitlab/constellation-index@1
|
|
165
|
-
inputs:
|
|
166
|
-
access_key: $CONSTELLATION_ACCESS_KEY
|
|
167
|
-
|
|
168
|
-
constellation-index:
|
|
169
|
-
rules:
|
|
170
|
-
- if: $CI_COMMIT_BRANCH == "${i}"
|
|
171
|
-
`}var zt=m(()=>{});var Pe,xr=m(()=>{M();zt();Pe=class{constructor(e){this.gitRoot=e;}async detectPlatforms(){let e=[],[t,n]=await Promise.all([h.directoryExists(___default.join(this.gitRoot,".github","workflows")),h.fileIsReadable(___default.join(this.gitRoot,".gitlab-ci.yml"))]);return t&&e.push("github"),n&&e.push("gitlab"),e}async githubWorkflowExists(){return h.fileIsReadable(___default.join(this.gitRoot,".github","workflows","constellation-index.yml"))}async gitlabJobExists(){let e=___default.join(this.gitRoot,".gitlab-ci.yml");if(!await h.fileIsReadable(e))return false;try{let n=await h.readFile(e),o=parseDocument(n).contents;return isMap(o)&&o.has("constellation-index")}catch{return false}}async createGitHubWorkflow(e){let t=___default.join(this.gitRoot,".github","workflows");await A__default.mkdir(t,{recursive:true});let n=___default.join(t,"constellation-index.yml");return await h.writeFile(n,Gt(e)),n}async createOrMergeGitLabCI(e){let t=___default.join(this.gitRoot,".gitlab-ci.yml");if(!await h.fileIsReadable(t))return await h.writeFile(t,tt(e)),t;let r=await h.readFile(t),o=parseDocument(r);if(!isMap(o.contents))return await h.writeFile(t,tt(e)),t;let{includeEntry:s,job:a}=Wt(e);return this.mergeIncludeEntry(o,s),o.set("constellation-index",a),await h.writeFile(t,o.toString()),t}mergeIncludeEntry(e,t){let n=e.get("include");if(!n){e.set("include",[t]);return}if(isSeq(n)){let r=n.items.filter(o=>{if(isMap(o)){let s=o.get("component");return typeof s!="string"||!s.includes("constellation-gitlab")}return true});n.items=r,n.items.push(e.createNode(t));return}e.set("include",[n,t]);}};});var Er=m(()=>{xr();zt();});function se(i,e){let t=___default.normalize(i),n=___default.normalize(e);return t.startsWith(n+___default.sep)?___default.relative(e,i):i}var ie,Se,$r=m(()=>{lr();Ft();Pr();Ht();M();N();Er();Oe();({prompt:ie}=Ir);Se=class extends W{async run(e={}){try{if(console.log(`${H}Initializing project configuration...
|
|
172
|
-
`),!await this.git.isGitAvailable())throw new Error(`${w} Could not find git client installation.
|
|
173
|
-
${y} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=___default.join(process.cwd(),"constellation.json"),r=null,o=await h.fileIsReadable(n);if(o)try{let $=await h.readFile(n);r=JSON.parse($),console.log(`${y} Found existing constellation.json, current values will be used as defaults.
|
|
174
|
-
`);}catch{console.log(`${w} Existing constellation.json is invalid, starting fresh.
|
|
175
|
-
`);}if(!await this.git.isGitRepository())throw new Error(`${w} Current directory is not a git repository.
|
|
176
|
-
${y} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:d}=l,p=g.filter($=>$!==d),f=d?[d,...p]:p,u=this.getBranchInitialIndex(f,r?.branch),P=this.getInitialLanguages(r),v=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:r?.projectId??"",validate:$=>$.trim().length>0||"Project ID is required"},{choices:f,initial:u,limit:10,maxChoices:1,message:"Branch to index:",name:"branch",scroll:!0,type:"select"},{type:"multiselect",name:"languages",multiple:!0,message:"Select Language(s):",choices:this.buildLanguageChoices(r),initial:P,result($){return $.map(T=>this.choices.find(lt=>lt.name===T)?.value??T)}}],D=await new Ir().prompt(v),ce={projectId:D.projectId.trim(),branch:D.branch,languages:{...D.languages.reduce(($,T)=>($[T]={fileExtensions:be[T]||[]},$),{})}},I=JSON.stringify(ce,void 0,2);await h.writeFile(n,I),console.log(`${C} ${o?"Updated":"Initialized"} configuration file at ${se(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${C} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&a&&await this.configureCICD(D.branch,a);}catch(t){if(t==="")return;let n=t.message??"An unexpected error occurred";console.error(`${b} Failed to initialize configuration file.
|
|
177
|
-
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await ie({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=Mt.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await ie({type:"multiselect",name:"selectedTools",message:"Select AI coding assistants to configure:",choices:t,result(p){return p.map(f=>this.choices.find(P=>P.name===f)?.value??f)}});if(n.length===0){console.log(`${y} No tools selected, skipping MCP configuration`);return}let r=new et(process.cwd()),o=[];for(let p of n){let f=Bt(p);if(f)if(console.log(` ${y} Configuring ${f.displayName}...`),f.isGlobalConfig&&f.getGlobalConfigPaths){let u=await r.configureGlobalTool(f),P=false;for(let v of u)o.push(v),v.success?(P=true,console.log(` ${C} ${v.tool.displayName} configured at ${se(v.configuredPath,process.cwd())}`)):v.error&&console.log(` ${w} ${v.tool.displayName}: ${v.error}`);if(P){let v=f.id==="cline"?"global VS Code settings":"global settings";console.log(` ${y} Note: ${f.displayName} uses ${v} (not project-level)`);}if(u.length===0){let v=f.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${w} ${f.displayName}: ${v}`);}}else {let u=await r.configureTool(f);o.push(u),u.success?(console.log(` ${C} ${f.displayName} configured at ${se(u.configuredPath,process.cwd())}`),f.permissionsConfig&&console.log(` ${C} ${f.displayName} permissions set in ${f.permissionsConfig.filePath}`)):console.log(` ${w} ${f.displayName}: ${u.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=___default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),console.log(` ${C} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${w} Could not stage .claude/settings.json in git`);}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=___default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),console.log(` ${C} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=___default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${C} 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(`
|
|
178
|
-
${C} MCP configuration complete: ${g} configured`),d>0&&console.log(`${w} ${d} tool(s) could not be configured`),await this.configureHooks(n,o),console.log(`
|
|
179
|
-
${y} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new _e(process.cwd()),r=$t(),o=e.map(l=>Bt(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(g=>g.tool.id===l.id&&g.success));if(o.length===0)return;console.log(`
|
|
180
|
-
${y} Configuring AI hooks...`);let s=[];for(let l of o){let g=await n.configureHooks(l,r);if(s.push(g),g.success){let d=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(d.length>0){let p=g.configuredPath?se(g.configuredPath,process.cwd()):___default.dirname(d[0]);console.log(` ${C} ${l.displayName} hooks configured at ${p}`);for(let f of d){let u=___default.isAbsolute(f)?se(f,process.cwd()):f;try{await this.git.stageFile(f),console.log(` ${C} Added ${u} to staged changes in git`);}catch{console.log(` ${w} Could not stage ${u} in git`);}}}else console.log(` ${C} ${l.displayName} hooks configured`);}else console.log(` ${w} ${l.displayName}: ${g.error}`);}let a=s.filter(l=>l.success).length;a>0&&console.log(`${C} Hooks configuration complete: ${a} configured`);}async configureCICD(e,t){let{setupCicd:n}=await ie({type:"confirm",name:"setupCicd",message:"Set up a CI/CD pipeline to automatically index your project?",initial:true});if(!n)return;let r=new Pe(t),o=await r.detectPlatforms(),s;if(o.length===1){let d=o[0]==="github"?"GitHub Actions":"GitLab CI",{useDetected:p}=await ie({type:"confirm",name:"useDetected",message:`Detected ${d}. Configure Constellation CI/CD for this platform?`,initial:true});if(!p)return;s=o[0];}else {let d=[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],{platform:p}=await ie({type:"select",name:"platform",message:"Select CI/CD platform:",choices:d,result(f){let u=Array.isArray(f)?f[0]:f;return this.choices.find(v=>v.name===u)?.value??u}});s=p;}let a=s==="github"?await r.githubWorkflowExists():await r.gitlabJobExists();if(a){let{overwrite:d}=await ie({type:"confirm",name:"overwrite",message:"Constellation CI/CD configuration already exists. Overwrite?",initial:false});if(!d){console.log(`${y} Skipping CI/CD configuration`);return}}let l;try{l=s==="github"?await r.createGitHubWorkflow(e):await r.createOrMergeGitLabCI(e);}catch(d){console.log(`${w} Failed to configure CI/CD pipeline: ${d.message}`);return}let g=se(l,process.cwd());console.log(s==="github"?`${C} Created ${g}`:`${C} ${a?"Updated":"Created"} ${g} with Constellation indexing`);try{await this.git.stageFile(l),console.log(`${C} Added ${g} to staged changes in git`);}catch{console.log(`${w} Could not stage ${g} in git`);}s==="github"?(console.log(`${y} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${y} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){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 nt,kr=m(()=>{M();N();nt=class i{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 h.fileIsReadable(e)){let n=await h.readFile(e),r=JSON.parse(n),o=new i(r.branch,r.languages,r.projectId,r.exclude);return o.validate(),o}else throw new Error(`${b} 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 rt,Jt,Yt,qt,ot,Nr=m(()=>{M();rt=class{getVariable(e){return Promise.resolve(process.env[e])}getSourceFile(){}isCIEnvironment(){return this.isCI()}isCI(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}validateInput(e,t){if(!e||typeof e!="string")throw new Error("Invalid key provided");if(t==null)throw new Error("Invalid value provided");if(!/^[A-Z_][A-Z0-9_]*$/i.test(e))throw new Error("Environment variable name must contain only letters, numbers, and underscores");if(t.includes("\0"))throw new Error("Value contains invalid characters");if(t.includes(`
|
|
181
|
-
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Jt=class extends rt{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.
|
|
182
|
-
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}),s="";o.stderr?.on("data",a=>{s+=a.toString();}),o.on("close",a=>{a===0?n():r(new Error(`setx failed with code ${a}: ${s}`));}),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,s)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),l="",g="";a.stdout?.on("data",d=>{l+=d.toString();}),a.stderr?.on("data",d=>{g+=d.toString();}),a.on("close",d=>{d===0?o(l):s(new Error(`reg query failed: ${g}`));}),a.on("error",d=>{s(d);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return r?r[1].trim():void 0}catch{return}}},Yt=class extends rt{userConfigFiles;constructor(){super(),this.userConfigFiles=[_.join(ae.homedir(),".zshenv"),_.join(ae.homedir(),".profile")];}getSourceFile(){let e=process.env.SHELL??"";return e.endsWith("/zsh")||e.endsWith("/zsh5")?this.userConfigFiles.find(t=>t.endsWith(".zshenv")):this.userConfigFiles.find(t=>t.endsWith(".profile"))}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
|
|
169
|
+
`),await h.writeFile(e,r);}async configurePermissions(e){let t=S__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await h.fileIsReadable(t)){let l=await h.readFile(t);n=JSON.parse(l);}}catch{}let r=n;for(let a=0;a<e.allowKeyPath.length-1;a++){let l=e.allowKeyPath[a];(!r[l]||typeof r[l]!="object")&&(r[l]={}),r=r[l];}let o=e.allowKeyPath[e.allowKeyPath.length-1];Array.isArray(r[o])||(r[o]=[]);let s=r[o];s.includes(e.allowValue)||s.push(e.allowValue),await h.writeFile(t,JSON.stringify(n,null," ")+`
|
|
170
|
+
`);}async configureMarketplace(e){let t=S__default.join(this.cwd,e.filePath);await this.ensureDirectoryExists(t);let n={};try{if(await h.fileIsReadable(t)){let o=await h.readFile(t);n=JSON.parse(o);}}catch{}n=this.deepMerge(n,e.config),await h.writeFile(t,JSON.stringify(n,null," ")+`
|
|
171
|
+
`);}deepMerge(e,t){let n={...e};for(let r of Object.keys(t)){let o=t[r],s=e[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=this.deepMerge(s,o):n[r]=o;}return n}addPluginToArray(e,t){let n=e;for(let s=0;s<t.pluginKeyPath.length-1;s++){let a=t.pluginKeyPath[s];(!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 l=t[a];if(!r[l]||typeof r[l]!="object")return;r=r[l];}let o=t[t.length-1];if(!Array.isArray(r[o]))return;let s=r[o];for(let a of n)s.includes(a)||s.push(a);}async updateGlobalEnvPolicy(e,t,n,r){let o=e.replace(/^~/,le__default.homedir()),s=await this.readConfig(o,r);if(Object.keys(s).length===0)return;let a=JSON.stringify(s);this.addToEnvPolicyWhitelist(s,t,n);let l=JSON.stringify(s);a!==l&&await this.writeConfig(o,s,r);}};});function ae(i,e){let t=S__default.normalize(i),n=S__default.normalize(e);return t.startsWith(n+S__default.sep)?S__default.relative(e,i):i}var ti,se,be,Rr=m(()=>{ar();fr();zt();Ir();Jt();D();k();De();ti=promisify(execFile),{prompt:se}=Tr;be=class extends z{async run(e={}){try{if(console.log(`${U}Initializing project configuration...
|
|
172
|
+
`),!await this.git.isGitAvailable())throw new Error(`${C} Could not find git client installation.
|
|
173
|
+
${y} Constellation requires git, please install git and try again (https://git-scm.com/downloads).`);let n=S__default.join(process.cwd(),"constellation.json"),r=null,o=await h.fileIsReadable(n);if(o)try{let T=await h.readFile(n);r=JSON.parse(T),console.log(`${y} Found existing constellation.json, current values will be used as defaults.
|
|
174
|
+
`);}catch{console.log(`${C} Existing constellation.json is invalid, starting fresh.
|
|
175
|
+
`);}if(!await this.git.isGitRepository())throw new Error(`${C} Current directory is not a git repository.
|
|
176
|
+
${y} Please run this command from the root directory of a git repository.`);let a=await this.git.getRootDir(),[l,g]=await Promise.all([this.git.status(),this.git.listBranches()]),{currentBranch:f}=l,p=g.filter(T=>T!==f),u=f?[f,...p]:p,d=this.getBranchInitialIndex(u,r?.branch),v=this.getInitialLanguages(r),_=[{message:"Constellation Project ID:",name:"projectId",type:"input",initial:r?.projectId??"",validate:T=>T.trim().length>0||"Project ID is required"},{choices:u,initial:d,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(T){return T.map($=>this.choices.find(dt=>dt.name===$)?.value??$)}}],P=await new Tr().prompt(_),pe={projectId:P.projectId.trim(),branch:P.branch,languages:{...P.languages.reduce((T,$)=>(T[$]={fileExtensions:Pe[$]||[]},T),{})}},I=JSON.stringify(pe,void 0,2);await h.writeFile(n,I),console.log(`${w} ${o?"Updated":"Initialized"} configuration file at ${ae(n,process.cwd())}`),await this.git.stageFile(n),console.log(`${w} Added constellation.json to staged changes in git`),e.skipMcp||await this.configureMCPServers(),!e.skipCi&&a&&await this.configureCICD(P.branch,a);}catch(t){if(t==="")return;let n=t.message??"An unexpected error occurred";console.error(`${E} Failed to initialize configuration file.
|
|
177
|
+
${n}`);}}async configureMCPServers(){let{configureMcp:e}=await se({type:"confirm",name:"configureMcp",message:"Automatically configure Constellation for AI coding assistants?",initial:true});if(!e)return;let t=Kt.map(p=>({name:p.displayName,value:p.id})),{selectedTools:n}=await se({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(`${y} No tools selected, skipping MCP configuration`);return}let r=new it(process.cwd()),o=[];for(let p of n){let u=Vt(p);if(u)if(console.log(` ${y} Configuring ${u.displayName}...`),u.pluginInstallCommand){let d=await this.executePluginInstall(u);o.push(d),d.success?console.log(` ${w} ${u.displayName} plugin installed successfully`):console.log(` ${C} ${u.displayName}: ${d.error}`);}else if(u.isGlobalConfig&&u.getGlobalConfigPaths){let d=await r.configureGlobalTool(u),v=false;for(let _ of d)o.push(_),_.success?(v=true,console.log(` ${w} ${_.tool.displayName} configured at ${ae(_.configuredPath,process.cwd())}`)):_.error&&console.log(` ${C} ${_.tool.displayName}: ${_.error}`);if(v){let _=u.id==="cline"?"global VS Code settings":"global settings";console.log(` ${y} Note: ${u.displayName} uses ${_} (not project-level)`);}if(d.length===0){let _=u.id==="cline"?"No VS Code installations found":"Configuration directory not found";console.log(` ${C} ${u.displayName}: ${_}`);}}else {let d=await r.configureTool(u);o.push(d),d.success?(console.log(` ${w} ${u.displayName} configured at ${ae(d.configuredPath,process.cwd())}`),u.permissionsConfig&&console.log(` ${w} ${u.displayName} permissions set in ${u.permissionsConfig.filePath}`)):console.log(` ${C} ${u.displayName}: ${d.error}`);}}if(o.find(p=>p.tool.id==="claude-code"&&p.success)){let p=S__default.join(process.cwd(),".claude/settings.json");try{await this.git.stageFile(p),console.log(` ${w} Added .claude/settings.json to staged changes in git`);}catch{console.log(` ${C} Could not stage .claude/settings.json in git`);}}if(o.find(p=>p.tool.id==="codex-cli"&&p.success)){let p=S__default.join(process.cwd(),".codex/config.toml");try{await this.git.stageFile(p),console.log(` ${w} Added .codex/config.toml to staged changes in git`);}catch{}}if(o.find(p=>p.tool.id==="opencode"&&p.success)){let p=S__default.join(process.cwd(),"opencode.jsonc");try{await this.git.stageFile(p),console.log(` ${w} Added opencode.jsonc to staged changes in git`);}catch{}}let g=o.filter(p=>p.success).length,f=o.filter(p=>!p.success).length;console.log(`
|
|
178
|
+
${w} Plugin + MCP configuration complete: ${g} configured`),f>0&&console.log(`${C} ${f} tool(s) could not be configured`),await this.configureHooks(n,o),console.log(`
|
|
179
|
+
${y} Some tools may require restart to pick up new configuration.`);}async configureHooks(e,t){let n=new Se(process.cwd()),r=Lt(),o=e.map(l=>Vt(l)).filter(l=>l!==void 0&&l.hooksConfig!==void 0&&t.some(g=>g.tool.id===l.id&&g.success));if(o.length===0)return;console.log(`
|
|
180
|
+
${y} Configuring AI hooks...`);let s=[];for(let l of o){let g=await n.configureHooks(l,r);if(s.push(g),g.success){let f=g.configuredPath?[g.configuredPath]:g.auxiliaryPaths??[];if(f.length>0){let p=g.configuredPath?ae(g.configuredPath,process.cwd()):S__default.dirname(f[0]);console.log(` ${w} ${l.displayName} hooks configured at ${p}`);for(let u of f){let d=S__default.isAbsolute(u)?ae(u,process.cwd()):u;try{await this.git.stageFile(u),console.log(` ${w} Added ${d} to staged changes in git`);}catch{console.log(` ${C} Could not stage ${d} in git`);}}}else console.log(` ${w} ${l.displayName} hooks configured`);}else console.log(` ${C} ${l.displayName}: ${g.error}`);}let a=s.filter(l=>l.success).length;a>0&&console.log(`${w} Hooks configuration complete: ${a} configured`);}async executePluginInstall(e){let{command:t,args:n}=e.pluginInstallCommand;try{return await ti(t,n,{timeout:3e4,env:process.env}),{tool:e,success:!0}}catch(r){let o=r,s;return o.code==="ENOENT"?s=`${t} not found. Is ${e.displayName} installed and on your PATH?`:o.killed?s="Plugin installation timed out after 30 seconds":o.stderr?s=`Plugin installation failed: ${o.stderr.trim()}`:s=`Plugin installation failed: ${o.message}`,{tool:e,success:false,error:s}}}async configureCICD(e,t){let{setupCicd:n}=await se({type:"confirm",name:"setupCicd",message:"Set up a CI/CD pipeline to automatically index your project?",initial:true});if(!n)return;let r=new _e(t),o=await r.detectPlatforms(),s;if(o.length===1){let f=o[0]==="github"?"GitHub Actions":"GitLab CI",{useDetected:p}=await se({type:"confirm",name:"useDetected",message:`Detected ${f}. Configure Constellation CI/CD for this platform?`,initial:true});if(!p)return;s=o[0];}else {let f=[{name:"GitHub Actions",value:"github"},{name:"GitLab CI",value:"gitlab"}],{platform:p}=await se({type:"select",name:"platform",message:"Select CI/CD platform:",choices:f,result(u){let d=Array.isArray(u)?u[0]:u;return this.choices.find(_=>_.name===d)?.value??d}});s=p;}let a=s==="github"?await r.githubWorkflowExists():await r.gitlabJobExists();if(a){let{overwrite:f}=await se({type:"confirm",name:"overwrite",message:"Constellation CI/CD configuration already exists. Overwrite?",initial:false});if(!f){console.log(`${y} Skipping CI/CD configuration`);return}}let l;try{l=s==="github"?await r.createGitHubWorkflow(e):await r.createOrMergeGitLabCI(e);}catch(f){console.log(`${C} Failed to configure CI/CD pipeline: ${f.message}`);return}let g=ae(l,process.cwd());console.log(s==="github"?`${w} Created ${g}`:`${w} ${a?"Updated":"Created"} ${g} with Constellation indexing`);try{await this.git.stageFile(l),console.log(`${w} Added ${g} to staged changes in git`);}catch{console.log(`${C} Could not stage ${g} in git`);}s==="github"?(console.log(`${y} Add your access key as a repository secret:`),console.log(" Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret"),console.log(" Name: CONSTELLATION_ACCESS_KEY")):(console.log(`${y} Add your access key as a CI/CD variable:`),console.log(" Settings \u2192 CI/CD \u2192 Variables \u2192 Add variable"),console.log(" Key: CONSTELLATION_ACCESS_KEY"));}buildLanguageChoices(e){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 st,$r=m(()=>{Le();Ge();D();k();st=class i{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 h.fileIsReadable(e)){let n=await h.readFile(e),r=JSON.parse(n),o=new i(r.branch,r.languages,r.projectId,r.exclude);return o.validate(),o}else throw new Error(`${E} 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 G("Not on a Git branch (detached HEAD state)","BRANCH_NOT_CONFIGURED");if(this.branch!==e)throw new G(`Current branch "${e}" does not match configured branch "${this.branch}". Update constellation.json or switch to "${this.branch}" branch.`,"BRANCH_NOT_CONFIGURED")}};});var at,Xt,Zt,Qt,lt,Nr=m(()=>{D();at=class{getVariable(e){return Promise.resolve(process.env[e])}getSourceFile(){}isCIEnvironment(){return this.isCI()}isCI(){return !!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.GITLAB_CI||process.env.JENKINS_URL||process.env.CIRCLECI||process.env.TRAVIS||process.env.BUILDKITE||process.env.DRONE||process.env.TF_BUILD||process.env.BITBUCKET_BUILD_NUMBER||process.env.TEAMCITY_VERSION||process.env.CODEBUILD_BUILD_ID)}validateInput(e,t){if(!e||typeof e!="string")throw new Error("Invalid key provided");if(t==null)throw new Error("Invalid value provided");if(!/^[A-Z_][A-Z0-9_]*$/i.test(e))throw new Error("Environment variable name must contain only letters, numbers, and underscores");if(t.includes("\0"))throw new Error("Value contains invalid characters");if(t.includes(`
|
|
181
|
+
`)||t.includes("\r"))throw new Error("Value cannot contain newline characters")}escapeShellValue(e){return e.replace(/[\\'\"$`]/g,"\\$&")}},Xt=class extends at{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.
|
|
182
|
+
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}),s="";o.stderr?.on("data",a=>{s+=a.toString();}),o.on("close",a=>{a===0?n():r(new Error(`setx failed with code ${a}: ${s}`));}),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,s)=>{let a=spawn("reg",["query",e,"/v",t],{shell:!1,windowsHide:!0}),l="",g="";a.stdout?.on("data",f=>{l+=f.toString();}),a.stderr?.on("data",f=>{g+=f.toString();}),a.on("close",f=>{f===0?o(l):s(new Error(`reg query failed: ${g}`));}),a.on("error",f=>{s(f);});})).match(/REG_(?:SZ|EXPAND_SZ)\s+(.+?)(?:\r?\n|$)/);return r?r[1].trim():void 0}catch{return}}},Zt=class extends at{userConfigFiles;constructor(){super(),this.userConfigFiles=[S.join(le.homedir(),".zshenv"),S.join(le.homedir(),".profile")];}getSourceFile(){let e=process.env.SHELL??"";return e.endsWith("/zsh")||e.endsWith("/zsh5")?this.userConfigFiles.find(t=>t.endsWith(".zshenv")):this.userConfigFiles.find(t=>t.endsWith(".profile"))}async setVariable(e,t){if(this.validateInput(e,t),this.isCI())throw new Error(`Cannot set environment variables in CI/CD environments.
|
|
183
183
|
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 h.readFile(e,"utf-8");}catch{}let o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`^export ${o}=.*$`,"gm");s.test(r)?r=r.replace(s,n):r=r.trimEnd()+`
|
|
184
184
|
`+n+`
|
|
185
|
-
`,await h.writeFile(e,r);}},
|
|
186
|
-
${y} Updating ${
|
|
187
|
-
`),await this.packageManager.executeUpdate(
|
|
188
|
-
${
|
|
185
|
+
`,await h.writeFile(e,r);}},Qt=class{static create(){let e=le.platform();switch(e){case "win32":return new Xt;case "darwin":case "linux":return new Zt;default:throw new Error(`Unsupported platform: ${e}`)}}},lt=class{manager;constructor(){this.manager=Qt.create();}async setKey(e,t){await this.manager.setVariable(e.toUpperCase(),t);}async getKey(e){return this.manager.getVariable(e.toUpperCase())}isCI(){return this.manager.isCIEnvironment()}getSourceFile(){return this.manager.getSourceFile()}};});var ct,Ar=m(()=>{ct=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=S__default.extname(e).toLowerCase();return this.extensionToLanguageMap.get(t)||null}};});function ri(){let i=le.platform();if(i==="darwin")return S.join(le.homedir(),"Library","Caches","constellation");if(i==="win32"){let e=process.env.LOCALAPPDATA||S.join(le.homedir(),"AppData","Local");return S.join(e,"constellation","cache")}else {let e=process.env.XDG_CACHE_HOME||S.join(le.homedir(),".cache");return S.join(e,"constellation")}}var oi,ii,si,Ie,en=m(()=>{oi=ri(),ii="update-state.json",si=1440*60*1e3,Ie=class{state=null;stateDir;stateFile;constructor(e){this.stateDir=e??oi,this.stateFile=S.join(this.stateDir,ii);}async load(){if(this.state)return this.state;try{let e=await A.readFile(this.stateFile,"utf-8");return this.state=JSON.parse(e),this.state}catch{return {lastCheckTimestamp:0}}}async save(e){try{await A.mkdir(this.stateDir,{recursive:!0}),await A.writeFile(this.stateFile,JSON.stringify(e,null,2)),this.state=e;}catch{}}async shouldCheck(){let e=await this.load();return Date.now()-e.lastCheckTimestamp>si}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 A.unlink(this.stateFile),this.state=null;}catch{}}};});var Te,tn=m(()=>{Te=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",s=>{r(s===0);}),o.on("error",()=>{r(false);});})}};});var ci,Re,nn=m(()=>{k();(({prompt:ci}=Tr)),Re=class{async promptForUpdate(e,t,n){console.log(""),console.log(c.cyan("\u2501".repeat(60))),console.log(`${U} ${c.bold("Update Available!")}`),console.log(""),console.log(` Current version: ${c.dim(e)}`),console.log(` Latest version: ${c.green.bold(t)}`),console.log(""),console.log(` ${c.dim(`Package manager: ${n}`)}`),console.log(c.cyan("\u2501".repeat(60))),console.log("");try{let{shouldUpdate:r}=await ci({type:"confirm",name:"shouldUpdate",message:"Would you like to update now?",initial:!0});return r}catch{return false}}};});async function rn(i){return new gt().check(i)}var pi,pt,gi,gt,jr=m(()=>{k();en();tn();nn();pi="https://registry.npmjs.org",pt="@constellationdev/cli",gi=5e3,gt=class{cache;packageManager;prompter;constructor(){this.cache=new Ie,this.packageManager=new Te,this.prompter=new Re;}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(),gi);try{let r=await fetch(`${pi}/${pt}/latest`,{signal:t.signal,headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Registry returned ${r.status}`);let s=(await r.json()).version;return {current:e,latest:s,hasUpdate:this.isNewerVersion(s,e)}}finally{clearTimeout(n);}}isNewerVersion(e,t){let n=s=>s.split("-")[0],r=n(e).split(".").map(Number),o=n(t).split(".").map(Number);for(let s=0;s<3;s++){let a=r[s]||0,l=o[s]||0;if(a>l)return true;if(a<l)return false}return false}async performUpdate(){return console.log(`
|
|
186
|
+
${y} Updating ${pt}...
|
|
187
|
+
`),await this.packageManager.executeUpdate(pt)?(console.log(`
|
|
188
|
+
${w} Update complete! Please re-run your command.
|
|
189
189
|
`),true):(console.log(`
|
|
190
|
-
${
|
|
191
|
-
`),false)}};});var
|
|
192
|
-
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
|
|
193
|
-
${i?.message??String(i)}`),process.exit(1);});
|
|
190
|
+
${C} Update failed. You can try updating manually:`),console.log(` ${this.packageManager.getUpdateCommandString(pt)}
|
|
191
|
+
`),false)}};});var Or=m(()=>{en();tn();nn();jr();});function ui(){return di.some(i=>!!process.env[i])}function fi(){return !!process.stdout.isTTY}function Lr(){return !ui()&&fi()}var di,Fr=m(()=>{di=["CI","GITHUB_ACTIONS","GITLAB_CI","JENKINS_URL","CIRCLECI","TRAVIS","BUILDKITE","DRONE"];});var $e,Dr=m(()=>{$e=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 s=o.split(" ");if(s.length<2)continue;let a=s[0];a==="A"?n.added.push(s[1]):a==="M"?n.modified.push(s[1]):a==="D"?n.deleted.push(s[1]):a.startsWith("R")&&s.length>=3&&n.renamed.push({from:s[1],to:s[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.
|
|
192
|
+
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 wi={};var Mr,sn,an,ke,Br=m(async()=>{Le();Pn();or();Rr();$r();Nr();Ar();zt();Or();ut();Fe();Fr();Dr();k();process.on("uncaughtException",i=>{i instanceof Error&&i.code==="ERR_USE_AFTER_CLOSE"&&process.exit(0),console.error(`${E} An unexpected error occurred during the index attempt:
|
|
193
|
+
${i?.message??String(i)}`),process.exit(1);});Mr=globalThis.__constellationVersion??(()=>{let i=S__default.dirname(fileURLToPath(import.meta.url)),e=S__default.join(i,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version})();if(Lr()){let i=process.argv[2];["auth","help","init","index"].includes(i)?mt(i):mt(),Ne.includes(i)||await rn(Mr)&&process.exit(0);}sn=process.cwd(),an=new lt,ke=new Command;ke.name("constellation").description("Connecting stars in your code into intelligent patterns").version(Mr);ke.command("init").description("Initialize a new constellation project configuration").option("--skip-mcp","Skip MCP server configuration for AI coding tools").option("--skip-ci","Skip CI/CD pipeline configuration").action(async i=>{try{let t={GitClient:new $e(sn)};await new be(t).run({skipMcp:i.skipMcp,skipCi:i.skipCi});}catch(e){console.error(`${E} Failed to initialize project: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});ke.command("auth").description("Configure authentication for the Constellation CLI").option("--manual","Use manual access key entry instead of browser-based authentication").action(async i=>{try{let e={Environment:an};await new fe(e).run(i.manual);}catch(e){console.error(`${E} Failed to configure authentication: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});ke.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 i=>{try{let e=await st.loadFromFile(S__default.join(sn,"constellation.json")),t=new $e(sn),n=new ot(e),r=new ct(e),o={GitClient:t,Config:e,LanguageRegistry:n,LanguageDetector:r,Environment:an},s=an.isCI(),a=i.full||!i.incremental&&s,l=i.dirty||!1;!i.full&&!i.incremental&&s&&console.log(`${y} CI environment detected \u2014 defaulting to full index. Use --incremental to override.`),await new we(o).run(a,l);}catch(e){!(e instanceof b)&&!(e instanceof N)&&console.error(`${E} Failed to run index command: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});ke.parse();});var Gr=/^>=\s*\d+\.\d+\.\d+$/;function gn(i,e=process.version){if(!Gr.test(i))return {compatible:true,current:e,required:i};let t=i.replace(/^>=\s*/,""),n=e.replace(/^v/,""),r=t.split(".").map(Number),o=n.split(".").map(Number),s=true;for(let a=0;a<3;a++){let l=r[a]||0,g=o[a]||0;if(g>l)break;if(g<l){s=false;break}}return {compatible:s,current:e,required:i}}ut();var Pi=dirname(fileURLToPath(import.meta.url)),bi=join(Pi,"..","package.json"),ln=JSON.parse(readFileSync(bi,"utf-8")),xi=process.argv[2];if(!Ne.includes(xi)&&ln.engines?.node){let i=gn(ln.engines.node);i.compatible||(console.error(`Error: Constellation CLI requires Node.js ${i.required} (current: ${i.current})`),console.error(" Please upgrade to the latest LTS version: https://nodejs.org"),process.exit(1));}globalThis.__constellationVersion=ln.version;await Br().then(()=>wi);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@constellationdev/cli",
|
|
3
|
-
"description": "
|
|
4
|
-
"version": "0.2.
|
|
3
|
+
"description": "Codebase Understanding for AI Coding Agents",
|
|
4
|
+
"version": "0.2.6",
|
|
5
5
|
"author": "ShiftinBits Inc",
|
|
6
6
|
"main": "dist/main.js",
|
|
7
7
|
"type": "module",
|