devcontext
Version:
DevContext is a cutting-edge Model Context Protocol (MCP) server designed to provide developers with continuous, project-centric context awareness.
190 lines • 170 kB
JavaScript
#!/usr/bin/env node
"use strict";
var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);import rn from"dotenv";var H,te,Qe,Jr,U,Ke,Qr,B=ae(()=>{rn.config();H=process.env.TURSO_DATABASE_URL,te=process.env.TURSO_AUTH_TOKEN,Qe=process.env.LOG_LEVEL||"INFO",Jr=process.env.DB_LOGGING_ENABLED==="true",U=parseInt(process.env.DEFAULT_TOKEN_BUDGET||"4000",10),Ke=parseFloat(process.env.CONTEXT_DECAY_RATE||"0.95"),Qr=parseInt(process.env.MAX_CACHE_SIZE||"1000",10)});function Ce(){return process.env.MCP_MODE==="true"||process.env.MCP_MODE===!0||global.MCP_MODE===!0}var ve,Ze,c,M=ae(()=>{B();ve={DEBUG:0,INFO:1,WARN:2,ERROR:3};Ze=Ce(),c=(e,t,n=null)=>{if(Ce()||Ze||process.env.MCP_MODE==="true")return;let r=e.toUpperCase();if(!ve.hasOwnProperty(r)||ve[r]<ve[Qe])return;let s=`[${new Date().toISOString()}] [${r}]: ${t}`;if(n){let a=typeof n=="string"?n:JSON.stringify(n);s+=` - ${a}`}Ce()||Ze||process.env.MCP_MODE==="true"||(r==="DEBUG"||r==="INFO"?console.log(s):console.error(s))}});import{createClient as on}from"@libsql/client";async function sn(){let e=process.env.MCP_MODE==="true";try{let t=!1;try{let r=await C(`
SELECT name FROM sqlite_master
WHERE type='table' AND name='project_patterns'
`);t=r&&r.rows&&r.rows.length>0}catch(r){e||c("warn",`Error checking table existence: ${r.message}`);return}if(!t){e||c("info","project_patterns table doesn't exist yet, skipping migration");return}let n=!1;try{let r=await C(`
PRAGMA table_info(project_patterns)
`);if(r&&r.rows){for(let o of r.rows)if(o&&o.name==="language"){n=!0;break}}}catch(r){e||c("warn",`Error checking column existence: ${r.message}`);return}if(n){e||c("debug","Language column already exists in project_patterns table");return}e||c("info","Adding language column to project_patterns table");try{await C("ALTER TABLE project_patterns ADD COLUMN language TEXT"),e||c("info","Successfully added language column to project_patterns table")}catch(r){if(r.message&&r.message.includes("duplicate column"))e||c("info","Language column already exists, skipping");else{e||c("warn",`Error adding language column: ${r.message}`);return}}try{await C("CREATE INDEX IF NOT EXISTS idx_project_patterns_language ON project_patterns(language)"),e||c("info","Created index for language column")}catch(r){e||c("warn",`Error creating index: ${r.message}`)}}catch(t){e||c("warn",`Migration warning: ${t.message}`)}}var J,Q,xe,C,be,N=ae(()=>{B();M();J=null,Q=()=>{let e=process.env.MCP_MODE==="true";if(J)return J;if(!H){let t="TURSO_DATABASE_URL is not defined in environment variables";throw e?new Error:new Error(t)}if(!te){let t="TURSO_AUTH_TOKEN is not defined in environment variables";throw e?new Error:new Error(t)}return J=on({url:H,authToken:te}),e||c("info","Database client created",{url:H.substring(0,20)+"..."}),J},xe=async(e=null)=>{let t=process.env.MCP_MODE==="true";try{let r=0;for(;r<3;)try{return await(e||Q()).execute("SELECT 1"),!0}catch(o){if(r++,r>=3){if(t)return!1;throw new Error(`Database connection test failed: ${o.message}`)}let s=Math.pow(2,r)*100;await new Promise(a=>setTimeout(a,s)),e||(J=null)}return!0}catch(n){if(t)return!1;throw new Error(`Database connection test failed: ${n.message}`)}},C=async(e,t=[])=>{let n=process.env.MCP_MODE==="true";try{n||c("debug","DB - EXECUTING QUERY",{sql:e.substring(0,150)+(e.length>150?"...":""),args:t.length>0?JSON.stringify(t.slice(0,3))+(t.length>3?"...":""):"[]"});let r=3,o=0,s;for(;o<r;)try{s=await Q().execute({sql:e,args:t});break}catch(a){o++;let l=a.message?.includes("connection")||a.message?.includes("timeout")||a.message?.includes("closed");if(o>=r||!l)throw a;let i=Math.pow(2,o)*100;await new Promise(u=>setTimeout(u,i)),J=null}return n||c("debug","DB - QUERY RESULT",{rowCount:s.rows?.length||0,rowsPreview:s.rows?.length>0?JSON.stringify(s.rows[0]).substring(0,100)+"...":"No rows",affectedRows:s.rowsAffected||0}),s}catch(r){throw n||c("error","DB - QUERY ERROR",{message:r.message,query:e.substring(0,150),args:t.length>0?JSON.stringify(t.slice(0,3)):"[]"}),n?new Error:new Error(`Query execution failed: ${r.message}
Query: ${e}`)}};be=async()=>{let e=process.env.MCP_MODE==="true";try{let t=Q(),n=!0;try{await sn()}catch(o){e||c("warn",`Migration warning: ${o.message}`)}let r=[`CREATE TABLE IF NOT EXISTS code_entities (
entity_id TEXT PRIMARY KEY, -- UUID
file_path TEXT, -- Full path for file entities, or path to file containing the entity
entity_type TEXT NOT NULL, -- e.g., 'file', 'function', 'class', 'method', 'variable', 'interface', 'comment_block'
name TEXT, -- Name of the function, class, variable etc.
start_line INTEGER,
end_line INTEGER,
content_hash TEXT, -- Hash of the raw content to detect changes
raw_content TEXT,
summary TEXT, -- AI or rule-based summary
language TEXT, -- Programming language
parent_entity_id TEXT, -- For hierarchical structure (e.g., function inside a class, class inside a file)
last_modified_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- For recency
importance_score REAL DEFAULT 1.0, -- For prioritization, can decay
custom_metadata TEXT, -- JSON blob for other properties
FOREIGN KEY (parent_entity_id) REFERENCES code_entities(entity_id) ON DELETE CASCADE
)`,"CREATE INDEX IF NOT EXISTS idx_code_entities_file_path ON code_entities(file_path)","CREATE INDEX IF NOT EXISTS idx_code_entities_type ON code_entities(entity_type)","CREATE INDEX IF NOT EXISTS idx_code_entities_name ON code_entities(name)","CREATE INDEX IF NOT EXISTS idx_code_entities_last_accessed ON code_entities(last_accessed_at DESC)","CREATE INDEX IF NOT EXISTS idx_code_entities_importance ON code_entities(importance_score DESC)",`CREATE TABLE IF NOT EXISTS entity_keywords (
keyword_id INTEGER PRIMARY KEY AUTOINCREMENT,
entity_id TEXT NOT NULL,
keyword TEXT NOT NULL,
term_frequency REAL,
weight REAL DEFAULT 1.0,
keyword_type TEXT, -- e.g., 'identifier', 'comment', 'string_literal', 'n_gram_2', 'n_gram_3'
FOREIGN KEY (entity_id) REFERENCES code_entities(entity_id) ON DELETE CASCADE
)`,"CREATE INDEX IF NOT EXISTS idx_entity_keywords_keyword ON entity_keywords(keyword)","CREATE INDEX IF NOT EXISTS idx_entity_keywords_entity ON entity_keywords(entity_id)","CREATE UNIQUE INDEX IF NOT EXISTS idx_entity_keywords_entity_keyword_type ON entity_keywords(entity_id, keyword, keyword_type)",`CREATE VIRTUAL TABLE IF NOT EXISTS code_entities_fts USING fts5(
entity_id UNINDEXED,
name,
searchable_content
)`,`CREATE TRIGGER IF NOT EXISTS code_entities_ai AFTER INSERT ON code_entities BEGIN
INSERT INTO code_entities_fts (entity_id, name, searchable_content)
VALUES (new.entity_id, new.name, new.raw_content || ' ' || COALESCE(new.summary, ''));
END`,`CREATE TRIGGER IF NOT EXISTS code_entities_ad AFTER DELETE ON code_entities BEGIN
DELETE FROM code_entities_fts WHERE entity_id = old.entity_id;
END`,`CREATE TRIGGER IF NOT EXISTS code_entities_au AFTER UPDATE ON code_entities BEGIN
UPDATE code_entities_fts SET
name = new.name,
searchable_content = new.raw_content || ' ' || COALESCE(new.summary, '')
WHERE entity_id = old.entity_id;
END`,`CREATE TABLE IF NOT EXISTS code_relationships (
relationship_id TEXT PRIMARY KEY, -- UUID
source_entity_id TEXT NOT NULL,
target_entity_id TEXT NOT NULL,
relationship_type TEXT NOT NULL,
weight REAL DEFAULT 1.0,
metadata TEXT, -- JSON blob
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (source_entity_id) REFERENCES code_entities(entity_id) ON DELETE CASCADE,
FOREIGN KEY (target_entity_id) REFERENCES code_entities(entity_id) ON DELETE CASCADE
)`,"CREATE INDEX IF NOT EXISTS idx_code_relationships_source ON code_relationships(source_entity_id, relationship_type)","CREATE INDEX IF NOT EXISTS idx_code_relationships_target ON code_relationships(target_entity_id, relationship_type)","CREATE UNIQUE INDEX IF NOT EXISTS idx_code_relationships_unique ON code_relationships(source_entity_id, target_entity_id, relationship_type)",`CREATE TABLE IF NOT EXISTS conversation_history (
message_id TEXT PRIMARY KEY, -- UUID
conversation_id TEXT NOT NULL,
role TEXT NOT NULL, -- 'user', 'assistant', 'system'
content TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
related_context_entity_ids TEXT, -- JSON array of entity_ids
summary TEXT,
user_intent TEXT,
topic_segment_id TEXT, -- Reference to topic segment
semantic_markers TEXT, -- JSON array of semantic markers found in message
sentiment_indicators TEXT -- JSON structure for sentiment analysis
)`,"CREATE INDEX IF NOT EXISTS idx_conversation_history_conversation_ts ON conversation_history(conversation_id, timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_conversation_history_topic ON conversation_history(topic_segment_id)",`CREATE TABLE IF NOT EXISTS conversation_topics (
topic_id TEXT PRIMARY KEY, -- UUID
conversation_id TEXT NOT NULL,
topic_name TEXT NOT NULL,
description TEXT,
start_message_id TEXT NOT NULL,
end_message_id TEXT, -- NULL if ongoing
start_timestamp TIMESTAMP NOT NULL,
end_timestamp TIMESTAMP, -- NULL if ongoing
primary_entities TEXT, -- JSON array of entity_ids
keywords TEXT, -- JSON array of keywords
summary TEXT,
parent_topic_id TEXT, -- For hierarchical topic structure
FOREIGN KEY (start_message_id) REFERENCES conversation_history(message_id) ON DELETE CASCADE,
FOREIGN KEY (parent_topic_id) REFERENCES conversation_topics(topic_id) ON DELETE SET NULL
)`,"CREATE INDEX IF NOT EXISTS idx_conversation_topics_conversation ON conversation_topics(conversation_id)","CREATE INDEX IF NOT EXISTS idx_conversation_topics_timestamps ON conversation_topics(start_timestamp, end_timestamp)",`CREATE TABLE IF NOT EXISTS conversation_purposes (
purpose_id TEXT PRIMARY KEY, -- UUID
conversation_id TEXT NOT NULL,
purpose_type TEXT NOT NULL, -- 'debugging', 'feature_planning', 'code_review', etc.
confidence REAL DEFAULT 0.0, -- Confidence score (0.0 to 1.0)
start_timestamp TEXT NOT NULL, -- ISO timestamp
end_timestamp TEXT, -- ISO timestamp, NULL if still active
metadata TEXT -- Additional metadata in JSON format
)`,"CREATE INDEX IF NOT EXISTS idx_conversation_purposes_conversation ON conversation_purposes(conversation_id)","CREATE INDEX IF NOT EXISTS idx_conversation_purposes_type ON conversation_purposes(purpose_type, confidence DESC)",`CREATE TABLE IF NOT EXISTS timeline_events (
event_id TEXT PRIMARY KEY, -- UUID
event_type TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
data TEXT, -- JSON blob
associated_entity_ids TEXT, -- JSON array of code_entity_ids
conversation_id TEXT -- If related to a specific conversation
)`,"CREATE INDEX IF NOT EXISTS idx_timeline_events_ts ON timeline_events(timestamp DESC)","CREATE INDEX IF NOT EXISTS idx_timeline_events_type ON timeline_events(event_type)",`CREATE TABLE IF NOT EXISTS context_snapshots (
snapshot_id TEXT PRIMARY KEY, -- UUID
name TEXT,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
timeline_event_id TEXT,
snapshot_data TEXT NOT NULL, -- JSON blob
FOREIGN KEY (timeline_event_id) REFERENCES timeline_events(event_id) ON DELETE SET NULL
)`,"CREATE INDEX IF NOT EXISTS idx_context_snapshots_name ON context_snapshots(name)",`CREATE TABLE IF NOT EXISTS focus_areas (
focus_id TEXT PRIMARY KEY, -- UUID
focus_type TEXT NOT NULL,
identifier TEXT,
description TEXT,
related_entity_ids TEXT, -- JSON array of code_entity_ids
keywords TEXT, -- JSON array of defining keywords
last_activated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT FALSE
)`,"CREATE INDEX IF NOT EXISTS idx_focus_areas_active ON focus_areas(is_active, last_activated_at DESC)",`CREATE TABLE IF NOT EXISTS project_patterns (
pattern_id TEXT PRIMARY KEY, -- UUID
pattern_type TEXT NOT NULL,
name TEXT,
description TEXT,
representation TEXT NOT NULL, -- JSON or textual
detection_rules TEXT,
frequency INTEGER DEFAULT 0,
last_detected_at TIMESTAMP,
utility_score REAL DEFAULT 0.0,
confidence_score REAL DEFAULT 0.5, -- confidence in pattern validity
reinforcement_count INTEGER DEFAULT 1, -- times pattern was reinforced
is_global BOOLEAN DEFAULT FALSE, -- indicates if promoted to global status
session_origin_id TEXT, -- originating session if any
language TEXT, -- NEW COLUMN: programming language the pattern applies to
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`,"CREATE INDEX IF NOT EXISTS idx_project_patterns_type ON project_patterns(pattern_type)","CREATE INDEX IF NOT EXISTS idx_project_patterns_global ON project_patterns(is_global, confidence_score DESC)","CREATE INDEX IF NOT EXISTS idx_project_patterns_utility ON project_patterns(utility_score DESC)",`CREATE TABLE IF NOT EXISTS pattern_observations (
observation_id TEXT PRIMARY KEY, -- UUID
pattern_id TEXT NOT NULL,
conversation_id TEXT,
context_entities TEXT, -- JSON array of entity_ids
observation_type TEXT NOT NULL, -- 'usage', 'confirmation', 'rejection'
observation_data TEXT, -- JSON with details
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (pattern_id) REFERENCES project_patterns(pattern_id) ON DELETE CASCADE
)`,"CREATE INDEX IF NOT EXISTS idx_pattern_observations_pattern ON pattern_observations(pattern_id)","CREATE INDEX IF NOT EXISTS idx_pattern_observations_type_ts ON pattern_observations(observation_type, timestamp DESC)",`CREATE TABLE IF NOT EXISTS system_logs (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
level TEXT NOT NULL, -- 'INFO', 'WARN', 'ERROR', 'DEBUG'
message TEXT NOT NULL,
data TEXT -- Optional JSON blob
)`,"CREATE INDEX IF NOT EXISTS idx_system_logs_timestamp_level ON system_logs(timestamp DESC, level)",`CREATE TABLE IF NOT EXISTS knowledge_items (
item_id TEXT PRIMARY KEY, -- UUID
item_type TEXT NOT NULL, -- Type of knowledge item (concept, code_pattern, domain_term, etc.)
name TEXT NOT NULL, -- Display name of the knowledge item
content TEXT, -- JSON or raw content depending on type
metadata TEXT, -- Additional metadata as JSON
confidence_score REAL DEFAULT 0.5, -- Confidence score
created_at TEXT NOT NULL, -- Creation timestamp
updated_at TEXT NOT NULL, -- Last update timestamp
conversation_id TEXT -- Source conversation ID
)`,"CREATE INDEX IF NOT EXISTS idx_knowledge_items_type ON knowledge_items(item_type)","CREATE INDEX IF NOT EXISTS idx_knowledge_items_conversation ON knowledge_items(conversation_id)","CREATE INDEX IF NOT EXISTS idx_knowledge_items_confidence ON knowledge_items(confidence_score DESC)",`CREATE TABLE IF NOT EXISTS context_states (
state_id TEXT PRIMARY KEY, -- UUID
milestone_id TEXT,
conversation_id TEXT,
topic_id TEXT,
state_type TEXT NOT NULL, -- Type of context state
state_data TEXT, -- JSON data representing the state
created_at TEXT NOT NULL, -- Creation timestamp
metadata TEXT -- Additional metadata as JSON
)`,"CREATE INDEX IF NOT EXISTS idx_context_states_milestone ON context_states(milestone_id)","CREATE INDEX IF NOT EXISTS idx_context_states_conversation ON context_states(conversation_id)"];for(let o of r)try{await t.execute(o)}catch(s){e||(c("error",`Error executing schema statement: ${s.message}`),c("error",`Failed statement: ${o.substring(0,100)}...`)),n=!1}return n}catch(t){if(e)return!1;throw new Error(`Database schema initialization failed: ${t.message}`)}}});import{v4 as gn}from"uuid";async function Ie(e,t,n,r=1,o={}){if(!e||!t||!n)throw new Error("Source entity ID, target entity ID, and relationship type are required");let s=gn(),a=JSON.stringify(o);try{await C(`
INSERT INTO code_relationships (
relationship_id, source_entity_id, target_entity_id, relationship_type, weight, metadata
) VALUES (?, ?, ?, ?, ?, ?)
`,[s,e,t,n,r,a])}catch(l){if(l.message&&l.message.includes("UNIQUE constraint failed"))await C(`
UPDATE code_relationships
SET weight = ?, metadata = ?
WHERE source_entity_id = ? AND target_entity_id = ? AND relationship_type = ?
`,[r,a,e,t,n]);else throw console.error(`Error adding relationship between ${e} and ${t}:`,l),l}}async function ce(e,t="outgoing",n=[]){if(!e)throw new Error("Entity ID is required");if(!["outgoing","incoming","both"].includes(t))throw new Error("Direction must be 'outgoing', 'incoming', or 'both'");let r=`
SELECT
relationship_id,
source_entity_id,
target_entity_id,
relationship_type,
weight,
metadata
FROM code_relationships
WHERE
`,o=[];if(t==="outgoing"?(r+="source_entity_id = ?",o.push(e)):t==="incoming"?(r+="target_entity_id = ?",o.push(e)):(r+="(source_entity_id = ? OR target_entity_id = ?)",o.push(e,e)),n.length>0){let s=n.map(()=>"?").join(", ");r+=` AND relationship_type IN (${s})`,o.push(...n)}try{return(await C(r,o)).map(a=>({...a,metadata:a.metadata?JSON.parse(a.metadata):{}}))}catch(s){throw console.error(`Error getting relationships for entity ${e}:`,s),s}}var W=ae(()=>{N()});B();N();M();import{McpServer as jr}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Wr}from"@modelcontextprotocol/sdk/server/stdio.js";N();import"zod";import{v4 as Yn}from"uuid";N();import{v4 as Pe}from"uuid";function I(e,t="plaintext"){let n=e.toLowerCase();switch(t){case"javascript":case"typescript":case"jsx":case"tsx":return Ye(n);case"python":return Ve(n);case"java":case"csharp":case"c#":return mn(n);case"ruby":return et(n);case"go":return fn(n);case"plaintext":default:return O(n)}}function Re(e,t){if(!e)return[];let n=[];switch(t.toLowerCase()){case"javascript":case"typescript":case"jsx":case"tsx":an(e,n);break;case"python":cn(e,n);break;case"csharp":case"c#":ln(e,n);break}return n}function an(e,t){let n=/\.\s*then\s*\(\s*(?:function\s*\([^)]*\)|[^=>(]*=>\s*[^)]*)\s*\)(?:\s*\.(?:then|catch|finally)\s*\([^)]*\))+/g,r;for(;(r=n.exec(e))!==null;)t.push({idiom:r[0],type:"js_promise_chain",location:{start:r.index,end:r.index+r[0].length}});let o=/\basync\s+(?:function\s*[a-zA-Z0-9_$]*\s*\([^)]*\)|(?:[a-zA-Z0-9_$]+\s*=>)|(?:\([^)]*\)\s*=>))(?:(?:.|\n)*?\bawait\b(?:.|\n)*?)/g;for(;(r=o.exec(e))!==null;)t.push({idiom:r[0],type:"js_async_await",location:{start:r.index,end:r.index+r[0].length}});let s=/(?:\.|\()(?:[a-zA-Z0-9_$]+)?\s*\(\s*(?:\([^)]*\)|[a-zA-Z0-9_$]+)\s*=>\s*(?:{[^}]*}|[^);,]*)/g;for(;(r=s.exec(e))!==null;)t.some(l=>l.type==="js_promise_chain"&&r.index>=l.location.start&&r.index+r[0].length<=l.location.end)||t.push({idiom:r[0],type:"js_arrow_callback",location:{start:r.index,end:r.index+r[0].length}})}function cn(e,t){let n=/\[\s*[^\[\]]*\s+for\s+[^\[\]]+\s+in\s+[^\[\]]+(?:\s+if\s+[^\[\]]+)?\s*\]/g,r;for(;(r=n.exec(e))!==null;)t.push({idiom:r[0],type:"python_list_comprehension",location:{start:r.index,end:r.index+r[0].length}});let o=/\{\s*[^{}]*\s*:\s*[^{}]*\s+for\s+[^{}]+\s+in\s+[^{}]+(?:\s+if\s+[^{}]+)?\s*\}/g;for(;(r=o.exec(e))!==null;)t.push({idiom:r[0],type:"python_dict_comprehension",location:{start:r.index,end:r.index+r[0].length}});let s=/lambda\s+[^:]+:[^,\n)]+/g;for(;(r=s.exec(e))!==null;)t.push({idiom:r[0],type:"python_lambda",location:{start:r.index,end:r.index+r[0].length}});let a=/\(\s*[^()]*\s+for\s+[^()]+\s+in\s+[^()]+(?:\s+if\s+[^()]+)?\s*\)/g;for(;(r=a.exec(e))!==null;)t.push({idiom:r[0],type:"python_generator_expression",location:{start:r.index,end:r.index+r[0].length}})}function ln(e,t){let n=/\.\s*(?:Where|Select|OrderBy|OrderByDescending|GroupBy|Join|Skip|Take|First|FirstOrDefault|Any|All|Count)\s*\(\s*[^)]*\)(?:\s*\.\s*(?:Where|Select|OrderBy|OrderByDescending|GroupBy|Join|Skip|Take|First|FirstOrDefault|Any|All|Count)\s*\(\s*[^)]*\))*/g,r;for(;(r=n.exec(e))!==null;)t.push({idiom:r[0],type:"csharp_linq_method",location:{start:r.index,end:r.index+r[0].length}});let o=/from\s+\w+\s+in\s+[^{]+(?:where\s+[^{]+)?(?:orderby\s+[^{]+)?(?:select\s+[^{;]+)?(?:group\s+[^{;]+by\s+[^{;]+)?/g;for(;(r=o.exec(e))!==null;)t.push({idiom:r[0],type:"csharp_linq_query",location:{start:r.index,end:r.index+r[0].length}});let s=/\basync\s+[^(]*\([^)]*\)(?:\s*<[^>]*>)?\s*(?:=>)?\s*{(?:(?:.|\n)*?\bawait\b(?:.|\n)*?)}/g;for(;(r=s.exec(e))!==null;)t.push({idiom:r[0],type:"csharp_async_await",location:{start:r.index,end:r.index+r[0].length}});let a=/(?:\([^)]*\)|\w+)\s*=>\s*(?:{[^}]*}|[^;]+)/g;for(;(r=a.exec(e))!==null;)t.some(i=>(i.type==="csharp_linq_method"||i.type==="csharp_linq_query")&&r.index>=i.location.start&&r.index+r[0].length<=i.location.end)||t.push({idiom:r[0],type:"csharp_lambda",location:{start:r.index,end:r.index+r[0].length}})}function L(e,t=10,n="plaintext"){let r=dn(n),o={};for(let a of e)o[a]||(o[a]=0),o[a]++;let s=[];for(let[a,l]of Object.entries(o)){if(r.has(a)&&a.length<6&&!/[_\-$#@]/.test(a))continue;let i=l;un(a,n)&&(i*=2),a.length>6&&(i*=1.5),/[_$]/.test(a)&&(i*=1.2),a.length<3&&!/[_\-$#@]/.test(a)&&(i*=.5),i=pn(a,i,n),s.push({keyword:a,score:i})}return s.sort((a,l)=>l.score-a.score).slice(0,t)}function un(e,t){return!!(/[a-z][A-Z]/.test(e)||/^[A-Z][a-z]/.test(e)||e.includes("_")&&e.length>4||/^(on|handle|process|get|set|is|has|should|with)/i.test(e)||/[a-z][0-9]/.test(e)||(t==="javascript"||t==="typescript")&&(/\$/.test(e)||/^use[A-Z]/.test(e))||t==="python"&&(/^__.*__$/.test(e)||/^self\./.test(e)))}function pn(e,t,n){switch(n){case"javascript":case"typescript":case"jsx":case"tsx":/^(use|component|props|state|render|effect|memo|callback)/.test(e)&&(t*=1.5),/^(on[A-Z]|handle[A-Z])/.test(e)&&(t*=1.3);break;case"python":/^(def|class|self|super|__init__|__main__)/.test(e)&&(t*=1.3),/^@/.test(e)&&(t*=1.4);break;case"java":case"csharp":case"c#":/^(public|private|protected|static|final|override|virtual|abstract)/.test(e)&&(t*=1.2),/^(class|interface|enum|record|struct)/.test(e)&&(t*=1.3);break;case"ruby":/^(attr_|def|class|module|require|include|extend)/.test(e)&&(t*=1.3),/^:/.test(e)&&(t*=1.2);break;case"go":/^(func|struct|interface|type|go|chan|defer|goroutine)/.test(e)&&(t*=1.3);break}return t}function dn(e){let t=new Set(["a","an","the","and","or","but","if","then","else","when","at","from","by","for","with","about","against","between","into","through","during","before","after","above","below","to","is","am","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","would","should","could","ought","i","you","he","she","it","we","they","their","this","that","these","those","of","in","as","on","not","no","its","his","her"]),n=new Set(["function","class","if","else","for","while","do","switch","case","break","continue","return","try","catch","finally","throw","throws","public","private","protected","static","final","abstract","interface","extends","implements","import","export","package","namespace","var","let","const","new","this","super","null","undefined","true","false"]),r=new Set([...t,...n]);switch(e){case"javascript":case"typescript":case"jsx":case"tsx":["typeof","instanceof","async","await","yield","void","delete","module","require","console","log","window","document","event","prototype","constructor","string","number","boolean","object","array"].forEach(o=>r.add(o));break;case"python":["def","lambda","from","as","import","with","is","in","not","and","or","global","nonlocal","pass","yield","assert","del","raise","except","print","exec","eval","None","True","False","range","len","self"].forEach(o=>r.add(o));break;case"java":["void","boolean","byte","char","short","int","long","float","double","instanceof","strictfp","synchronized","transient","volatile","native","package","throws","throw","exception","assert","enum"].forEach(o=>r.add(o));break;case"csharp":case"c#":["using","namespace","where","select","from","group","into","orderby","join","equals","out","ref","in","value","is","as","void","int","string","bool","decimal","object","char","byte","sbyte","uint","long","ulong","short","ushort","double","float","dynamic","delegate","event","async","await","partial","virtual","override","sealed","base"].forEach(o=>r.add(o));break;case"ruby":["def","end","module","require","include","extend","attr","attr_reader","attr_writer","attr_accessor","lambda","proc","yield","self","nil","true","false","unless","until","begin","rescue","ensure","alias"].forEach(o=>r.add(o));break;case"go":["func","type","struct","interface","map","chan","go","select","package","import","const","var","iota","make","new","append","len","cap","nil","true","false","int","int8","int16","int32","int64","uint","uint8","uint16","uint32","uint64","float32","float64","string","byte","rune","defer","panic","recover"].forEach(o=>r.add(o));break}return r}function O(e){return e.replace(/([a-z0-9])[-_]([a-z0-9])/g,"$1$2").replace(/[.,;:(){}[\]<>?!]/g," $& ").replace(/\u0001/g,"_").split(/\s+/).filter(r=>r.length>0)}function Ye(e){let t=[],n={},r=0,s=e.replace(/\/\*[\s\S]*?\*\//g,S=>{let b=`__COMMENT_BLOCK_${r++}__`;return n[b]=S,b}).replace(/\/\/[^\n]*/g,S=>{let b=`__COMMENT_LINE_${r++}__`;return n[b]=S,b}),a={},l=0,h=s.replace(/(?<![a-zA-Z0-9_\)\]\}])\/(?:\\\/|[^\/\n])+\/[gimuy]*/g,S=>{let b=`__REGEX_${l++}__`;return a[b]=S,b}).replace(/`(?:\\`|\\\\|[^`])*`/g,S=>{let b=`__TEMPLATE_${l++}__`;a[b]=S;let x=[],v=S.match(/\${([^}]*)}/g);return v&&(v.forEach(R=>{x.push(R.slice(2,-1))}),x.forEach(R=>{let A=Ye(R);t.push(...A)})),b}).replace(/'(?:\\'|\\\\|[^'])*'|"(?:\\"|\\\\|[^"])*"/g,S=>{let b=`__STRING_${l++}__`;return a[b]=S,b}).replace(/<([A-Z][a-zA-Z0-9]*|[a-z][a-z0-9]*)((?:\s+[a-zA-Z0-9_]+(?:=(?:"|'|\{).*?(?:"|'|\}))?)*)\s*(?:\/)?>/g,(S,b,x)=>{let v=`__JSX_TAG_${l++}__`;if(a[v]=S,t.push(b),x){let R=x.match(/[a-zA-Z0-9_]+(?==)/g);R&&t.push(...R)}return v}).replace(/<\/([A-Z][a-zA-Z0-9]*|[a-z][a-z0-9]*)>/g,(S,b)=>{let x=`__JSX_CLOSING_${l++}__`;return a[x]=S,t.push(b),x}).replace(/@([a-zA-Z][a-zA-Z0-9_]*)(?:\((?:[^)(]*|\([^)(]*\))*\))?/g,(S,b)=>{let x=`__DECORATOR_${l++}__`;a[x]=S,t.push(b);let v=S.match(/\((.*)\)/);if(v&&v[1]){let R=O(v[1]);t.push(...R)}return x}).replace(/=>/g,S=>(t.push("arrow_function")," => ")).replace(/\?\./g,S=>(t.push("optional_chaining")," ?. ")).replace(/\?\?/g,S=>(t.push("nullish_coalescing")," ?? ")).replace(/import\s+(?:{[^}]*}|\*\s+as\s+[a-zA-Z][a-zA-Z0-9_]*|[a-zA-Z][a-zA-Z0-9_]*)\s+from\s+['"][^'"]*['"]/g,S=>{t.push("import");let b=S.match(/from\s+['"]([^'"]*)['"]/);b&&b[1]&&t.push(b[1]);let x=S.match(/import\s+({[^}]*}|\*\s+as\s+[a-zA-Z][a-zA-Z0-9_]*|[a-zA-Z][a-zA-Z0-9_]*)/);if(x&&x[1]){let v=x[1];if(v.startsWith("{")){let R=v.replace(/[{}]/g,"").split(",").map(A=>A.trim()).filter(A=>A.length>0);t.push(...R)}else if(v.includes("* as")){let R=v.match(/\*\s+as\s+([a-zA-Z][a-zA-Z0-9_]*)/);R&&R[1]&&t.push(R[1])}else t.push(v.trim())}return" "}),f=O(h),p=[];for(let S of f){if(S.startsWith("__")&&S.endsWith("__")){p.push(S);continue}if(["=>","?.","??"].includes(S)){p.push(S);continue}let b=S.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(" ");p.push(S),b.length>1&&p.push(...b)}let E=[];for(let S of p)if(a[S]){if(S.startsWith("__REGEX_")?E.push("regex_literal"):S.startsWith("__JSX_")?E.push("jsx_element"):S.startsWith("__DECORATOR_")?E.push("decorator"):E.push(S),S.startsWith("__STRING_")||S.startsWith("__TEMPLATE_")){let x=a[S].replace(/^[`'"](.*)[`'"]$/s,"$1"),v=O(x);E.push(...v)}}else if(n[S]){E.push("code_comment");let x=n[S].replace(/^\/\*|\*\/$/g,"").replace(/^\/\//g,"").split(/\s+/).filter(v=>/^[a-z0-9_]{3,}$/i.test(v)).map(v=>v.toLowerCase());E.push(...x)}else E.push(S);return[...new Set(E)]}function Ve(e){let t=[],n={},r=0,s=e.replace(/(?:'''[\s\S]*?'''|"""[\s\S]*?""")/g,h=>{let f=`__PYCOMMENT_BLOCK_${r++}__`;return n[f]=h,f}).replace(/#[^\n]*/g,h=>{let f=`__PYCOMMENT_LINE_${r++}__`;return n[f]=h,f}),a={},l=0,y=s.replace(/(?:f|fr|rf)(?:'''[\s\S]*?'''|"""[\s\S]*?"""|'(?:\\'|\\\\|[^'])*'|"(?:\\"|\\\\|[^"])*")/g,h=>{let f=`__PYFSTRING_${l++}__`;a[f]=h;let p=[],E=h.match(/(?<!\\){([^{}]*)}/g);return E&&(E.forEach(S=>{p.push(S.slice(1,-1))}),p.forEach(S=>{let b=Ve(S);t.push(...b)})),f}).replace(/(?:r|b|rb|br)?(?:'''[\s\S]*?'''|"""[\s\S]*?"""|'(?:\\'|\\\\|[^'])*'|"(?:\\"|\\\\|[^"])*")/g,h=>{let f=`__PYSTRING_${l++}__`;return a[f]=h,f}).replace(/@([a-zA-Z][a-zA-Z0-9_.]*)(?:\((?:[^)(]*|\([^)(]*\))*\))?/g,(h,f)=>{let p=`__PYDECORATOR_${l++}__`;a[p]=h,t.push(f);let E=h.match(/\((.*)\)/);if(E&&E[1]){let S=O(E[1]);t.push(...S)}return p}).replace(/:=/g,h=>(t.push("walrus_operator")," := ")).replace(/\[.*:.*\]/g,h=>(t.push("slice_operation"),h.slice(1,-1).split(":").forEach(E=>{if(E.trim()){let S=O(E.trim());t.push(...S)}}),h)),_=y.split(`
`),g=0;for(let h of _){if(h.trim()==="")continue;let f=h.match(/^(\s*)/),p=f?f[1].length:0;if(p!==g){if(p>g)t.push("indent");else{let S=Math.floor((g-p)/4);for(let b=0;b<S;b++)t.push("dedent")}g=p}let E=h.trim();if(E){let S=["def","class","lambda","return","yield","from","import","as","with","try","except","finally","raise","assert","if","elif","else","while","for","in","continue","break","pass","global","nonlocal","del","is","not","and","or","async","await","comprehension","self"];for(let x of S)E.includes(x)&&new RegExp(`\\b${x}\\b`,"g").test(E)&&t.push(x);let b=O(E);t.push(...b)}}(y.includes("append(")||y.includes(".extend("))&&t.push("list_operation"),(y.includes(".get(")||y.includes(".items()")||y.includes(".keys()")||y.includes(".values()"))&&t.push("dict_operation");let w=[];for(let h of t){if(h.startsWith("__")&&h.endsWith("__")){w.push(h);continue}if(h.includes("_")){let f=h.split("_").filter(p=>p.length>0);w.push(h),w.push(...f)}else w.push(h)}let T=[];for(let h of w)if(a[h]){if(h.startsWith("__PYFSTRING_")?T.push("f_string"):h.startsWith("__PYSTRING_")?T.push("string_literal"):h.startsWith("__PYDECORATOR_")?T.push("decorator"):T.push(h),h.startsWith("__PYSTRING_")||h.startsWith("__PYFSTRING_")){let p=a[h];if(p.startsWith("f")||p.startsWith("r")||p.startsWith("fr")||p.startsWith("rf")||p.startsWith("b")||p.startsWith("rb")||p.startsWith("br")){let S=/^[a-z]+/.exec(p)[0].length;p=p.substring(S)}p=p.replace(/^['"]|['"]$/g,""),p=p.replace(/^'''|'''$/g,""),p=p.replace(/^"""|"""$/g,""),p=p.replace(/{[^{}]*}/g," ");let E=O(p);T.push(...E)}}else if(n[h]){T.push("code_comment");let p=n[h].replace(/^#{1}/,"").replace(/^'''|'''$/g,"").replace(/^"""|"""$/g,"").split(/\s+/).filter(E=>/^[a-z0-9_]{3,}$/i.test(E)).map(E=>E.toLowerCase());T.push(...p)}else T.push(h);return[...new Set(T)]}function mn(e){let t=[],n={},r=0,s=e.replace(/\/\*[\s\S]*?\*\//g,f=>{let p=`__JAVA_COMMENT_BLOCK_${r++}__`;return n[p]=f,p}).replace(/\/\/[^\n]*/g,f=>{let p=`__JAVA_COMMENT_LINE_${r++}__`;return n[p]=f,p}),a={},l=0,y=s.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g,f=>{let p=`__JAVASTRING_${l++}__`;return a[p]=f,p}).replace(/@([a-zA-Z][a-zA-Z0-9_.]*)(?:\s*\((?:[^)(]*|\([^)(]*\))*\))?/g,(f,p)=>{let E=`__ANNOTATION_${l++}__`;a[E]=f,t.push("annotation"),t.push(p.toLowerCase());let S=f.match(/\((.*)\)/);if(S&&S[1]){let x=S[1].split(",");for(let v of x){let R=v.split("=");R.length===2&&t.push(R[0].trim());let A=O(v);t.push(...A)}}return E}).replace(/<([^<>]*(?:<[^<>]*(?:<[^<>]*>)*[^<>]*>)*[^<>]*)>/g,f=>{let p=`__GENERIC_${l++}__`;a[p]=f,t.push("generic_type");let S=f.slice(1,-1).split(/,(?![^<>]*>)/);for(let b of S){let x=O(b.trim());t.push(...x)}return p}).replace(/(?:\(.*?\)|[a-zA-Z_][a-zA-Z0-9_]*)\s*(?:->|=>)\s*(?:{[\s\S]*?}|[^;]*)/g,f=>{let p=`__LAMBDA_${l++}__`;a[p]=f,t.push("lambda_expression");let E=O(f);return t.push(...E),p}),_=["public","private","protected","internal","static","final","abstract","override","virtual","readonly","const","sealed","partial","async","volatile","transient","synchronized","unsafe","extern"],g=y;for(let f of _){let p=new RegExp(`\\b${f}\\b`,"gi");g=g.replace(p,E=>(t.push(E.toLowerCase()),t.push("access_modifier"),E))}if(g=g.replace(/\b(?:package|namespace)\s+([a-zA-Z_][a-zA-Z0-9_.]*)/g,(f,p)=>{t.push("package_declaration");let E=p.split(".");return t.push(p),t.push(...E),f}),g=g.replace(/\b(?:import|using)\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.]*(?:\.\*)?)/g,(f,p)=>{t.push("import_statement");let E=p.split(".");return t.push(p),E.length>0&&E[E.length-1]==="*"&&(E.pop(),t.push("wildcard_import")),t.push(...E),f}),/\bfrom\b.*\bin\b.*\bselect\b/i.test(g)){t.push("linq_expression");let f=["from","in","select","where","group","by","into","orderby","join","let","on","equals"];for(let p of f)new RegExp(`\\b${p}\\b`,"gi").test(g)&&t.push(`linq_${p}`)}let w=O(g);t.push(...w);let T=[];for(let f of t){if(f.startsWith("__")&&f.endsWith("__")){T.push(f);continue}if(f.includes(".")){let p=f.split(".");T.push(f),T.push(...p);continue}if(T.push(f),/[a-z][A-Z]/.test(f)){let p=f.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(" ");p.length>1&&T.push(...p)}}let h=[];for(let f of T)if(a[f]){if(f.startsWith("__JAVASTRING_")?h.push("string_literal"):f.startsWith("__ANNOTATION_")?h.push("annotation"):f.startsWith("__GENERIC_")?h.push("generic"):f.startsWith("__LAMBDA_")?h.push("lambda"):h.push(f),f.startsWith("__JAVASTRING_")){let E=a[f].replace(/^"|"$/g,"").replace(/^'|'$/g,"");if(E.trim().length>0){let S=O(E);h.push(...S)}}}else if(n[f]){h.push("code_comment");let E=n[f].replace(/^\/\*|\*\/$/g,"").replace(/^\/\//g,"").split(/\s+/).filter(S=>/^[a-z0-9_]{3,}$/i.test(S)).map(S=>S.toLowerCase());h.push(...E)}else h.push(f);return[...new Set(h)]}function et(e){let t=[],n={},r=0,s=e.replace(/=begin[\s\S]*?=end/g,p=>{let E=`__RUBY_COMMENT_BLOCK_${r++}__`;return n[E]=p,E}).replace(/#[^\n]*/g,p=>{let E=`__RUBY_COMMENT_LINE_${r++}__`;return n[E]=p,E}),a={},l=0,_=s.replace(/"(?:[^"\\]|\\.|#\{[^}]*\})*"/g,p=>{let E=`__RUBY_INTERPOLATED_STRING_${l++}__`;a[E]=p;let S=[],b=p.match(/#\{([^}]*)\}/g);return b&&(b.forEach(x=>{S.push(x.slice(2,-1))}),S.forEach(x=>{let v=et(x);t.push(...v)})),E}).replace(/('(?:[^'\\]|\\.)*'|%[qQ]?\{(?:[^\\}]|\\.)*\}|%[qQ]?\((?:[^\\)]|\\.)*\)|%[qQ]?\[(?:[^\\]]|\\.)*\]|%[qQ]?<(?:[^\\>]|\\.)*>|<<-?(['"]?)(\w+)\1[\s\S]*?\2)/g,p=>{let E=`__RUBY_STRING_${l++}__`;return a[E]=p,E}).replace(/\/(?:[^\/\\]|\\.)*\/[iomxneus]*/g,p=>{let E=`__RUBY_REGEXP_${l++}__`;return a[E]=p,t.push("regexp"),E}).replace(/:(?:@?[a-zA-Z_][a-zA-Z0-9_]*(?:[?!]|=(?!=))?|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)/g,p=>{let E=`__RUBY_SYMBOL_${l++}__`;a[E]=p;let S=p.substring(1);return t.push("symbol"),t.push(`symbol_${S}`),(S.endsWith("?")||S.endsWith("!"))&&t.push(`symbol_${S.slice(0,-1)}`),E});_=_.replace(/\bdo\s*(?:\|[^|]*\|)?[\s\S]*?\bend\b/g,p=>{let E=`__RUBY_BLOCK_DO_${l++}__`;a[E]=p,t.push("block_do_end");let S=p.match(/\|\s*([^|]*)\s*\|/);S&&S[1]&&S[1].split(",").forEach(R=>{t.push(R.trim())});let b=p.replace(/\bdo\s*(?:\|[^|]*\|)?/,"").replace(/\bend\b$/,""),x=O(b);return t.push(...x),E}),_=_.replace(/\{(?:\s*\|[^|]*\|\s*)?[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/g,p=>{if(/^\{\s*:/.test(p)||/^\{\s*['"]/.test(p))return p;let E=`__RUBY_BLOCK_BRACE_${l++}__`;a[E]=p,t.push("block_brace");let S=p.match(/\|\s*([^|]*)\s*\|/);S&&S[1]&&S[1].split(",").forEach(R=>{t.push(R.trim())});let b=p.slice(1,-1);S&&(b=b.replace(/\|\s*[^|]*\s*\|/,""));let x=O(b);return t.push(...x),E});let g=_.replace(/\.\.(\.)?/g,p=>(t.push(p===".."?"range_operator_inclusive":"range_operator_exclusive")," "+p+" "));g=g.replace(/\bdef\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_]*[?!=]?)/g,(p,E)=>(t.push("method_definition"),t.push(E),(E.endsWith("?")||E.endsWith("!")||E.endsWith("="))&&t.push(E.slice(0,-1)),p)),g=g.replace(/\b(?:class|module)\s+([A-Z][a-zA-Z0-9_]*(?:::[A-Z][a-zA-Z0-9_]*)*)/g,(p,E)=>{if(t.push(p.startsWith("class")?"class_definition":"module_definition"),t.push(E),E.includes("::")){let S=E.split("::");t.push(...S)}return p});let w=O(g),T=["if","unless","else","elsif","end","begin","rescue","ensure","while","until","for","break","next","redo","retry","return","super","self","nil","true","false","and","or","not","yield"];for(let p of T)new RegExp(`\\b${p}\\b`,"g").test(g)&&t.push(p);t.push(...w);let h=[];for(let p of t){if(p.startsWith("__RUBY_")){h.push(p);continue}h.push(p),(p.endsWith("?")||p.endsWith("!"))&&h.push(p.slice(0,-1)),p.endsWith("=")&&!["==","!=",">=","<=","=>"].includes(p)&&h.push(p.slice(0,-1))}let f=[];for(let p of h)if(a[p])if(p.startsWith("__RUBY_STRING_")||p.startsWith("__RUBY_INTERPOLATED_STRING_")){f.push("string_literal");let S=a[p];if(S.startsWith("'")&&S.endsWith("'")||S.startsWith('"')&&S.endsWith('"')?S=S.slice(1,-1):(S.startsWith("%q")||S.startsWith("%Q"))&&(S=S.slice(3,-1)),S=S.replace(/#\{[^}]*\}/g," "),S.trim()){let b=O(S);f.push(...b)}}else p.startsWith("__RUBY_SYMBOL_")?f.push("symbol"):p.startsWith("__RUBY_BLOCK_")?f.push("block"):p.startsWith("__RUBY_REGEXP_")?f.push("regexp"):f.push(p);else if(n[p]){f.push("code_comment");let S=n[p].replace(/^#/,"").replace(/^=begin\s*|\s*=end$/g,"").split(/\s+/).filter(b=>/^[a-z0-9_]{3,}$/i.test(b)).map(b=>b.toLowerCase());f.push(...S)}else f.push(p);return[...new Set(f)]}function fn(e){let t=[],n={},r=0,s=e.replace(/\/\*[\s\S]*?\*\//g,v=>{let R=`__GO_COMMENT_BLOCK_${r++}__`;return n[R]=v,R}).replace(/\/\/[^\n]*/g,v=>{let R=`__GO_COMMENT_LINE_${r++}__`;return n[R]=v,R}),a={},l=0,f=s.replace(/`[^`]*`/g,v=>{let R=`__GO_RAW_STRING_${l++}__`;return a[R]=v,R}).replace(/"(?:[^"\\]|\\.)*"/g,v=>{let R=`__GO_STRING_${l++}__`;return a[R]=v,R}).replace(/'(?:[^'\\]|\\.)*'/g,v=>{let R=`__GO_RUNE_${l++}__`;return a[R]=v,R}).replace(/`(?:[a-zA-Z0-9_]+:"[^"]*")+`/g,v=>{let R=`__GO_STRUCT_TAG_${l++}__`;a[R]=v,t.push("struct_tag");let A=v.slice(1,-1).split(" ");for(let k of A){if(!k.trim())continue;let[D,se]=k.split(":");if(D&&se){t.push(`tag_${D}`);let ie=se.replace(/^"|"$/g,"");if(ie)if(ie.includes(",")){let nn=ie.split(",");t.push(...nn)}else t.push(ie)}}return R}).replace(/<-/g,v=>(t.push("channel_operation")," <- ")).replace(/\bgo\s+(?:func\b|[a-zA-Z_][a-zA-Z0-9_]*\s*\()/g,v=>{t.push("goroutine");let R=v.match(/go\s+([a-zA-Z_][a-zA-Z0-9_]*)/);return R&&R[1]&&t.push(R[1]),v}).replace(/\bselect\s*{[\s\S]*?}/g,v=>{t.push("select_statement");let R=v.match(/case\s+[^:]+:/g);if(R)for(let A of R){let k=A.slice(4,-1).trim(),D=O(k);t.push(...D)}return v}).replace(/\bdefer\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g,v=>{t.push("defer");let R=v.match(/defer\s+([a-zA-Z_][a-zA-Z0-9_]*)/);return R&&R[1]&&t.push(R[1]),v}).replace(/\btype\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+(?:struct|interface)\s*{[\s\S]*?}/g,(v,R)=>{if(t.push("type_declaration"),t.push(R),v.includes("struct")){t.push("struct_type");let A=v.match(/([a-zA-Z_][a-zA-Z0-9_]*)\s+([a-zA-Z_][a-zA-Z0-9_.*[\]]*)/g);if(A)for(let k of A){let D=k.trim().split(/\s+/);D.length>=2&&(t.push(D[0]),t.push(D[1]))}}else if(v.includes("interface")){t.push("interface_type");let A=v.match(/([a-zA-Z_][a-zA-Z0-9_]*)\s*\([\s\S]*?\)(?:\s*\([\s\S]*?\))?\s*[,{]/g);if(A)for(let k of A){let D=k.match(/([a-zA-Z_][a-zA-Z0-9_]*)/);D&&D[1]&&t.push(D[1])}}return v}),p=["make","new","len","cap","append","copy","delete","close","complex","real","imag","panic","recover"];for(let v of p){let R=new RegExp(`\\b${v}\\s*\\(`,"g");f=f.replace(R,A=>(t.push(`builtin_${v}`),A))}let E=["package","import","func","return","var","const","type","struct","interface","map","chan","go","select","case","default","defer","if","else","switch","for","range","continue","break","fallthrough","goto","nil","iota","true","false"];for(let v of E)new RegExp(`\\b${v}\\b`,"g").test(f)&&t.push(v);let S=O(f);t.push(...S);let b=[];for(let v of t){if(v.startsWith("__GO_")){b.push(v);continue}if(b.push(v),/[a-z][A-Z]/.test(v)){let R=v.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(" ");R.length>1&&b.push(...R)}}let x=[];for(let v of b)if(a[v])if(v.startsWith("__GO_STRING_")){x.push("string_literal");let A=a[v].slice(1,-1);if(A.trim().length>0){let k=O(A);x.push(...k)}}else if(v.startsWith("__GO_RAW_STRING_")){x.push("raw_string_literal");let A=a[v].slice(1,-1);if(A.includes(`
`)){let k=A.split(`
`);for(let D of k)if(D.trim()){let se=O(D.trim());x.push(...se)}}else if(A.trim()){let k=O(A);x.push(...k)}}else v.startsWith("__GO_STRUCT_TAG_")?x.push("struct_tag"):v.startsWith("__GO_RUNE_")?x.push("rune_literal"):x.push(v);else if(n[v]){x.push("code_comment");let A=n[v].replace(/^\/\*|\*\/$/g,"").replace(/^\/\//g,"").split(/\s+/).filter(k=>/^[a-z0-9_]{3,}$/i.test(k)).map(k=>k.toLowerCase());x.push(...A)}else x.push(v);return[...new Set(x)]}function Ae(e){if(typeof e!="string")return"";let t=e.toLowerCase();if(t.length<=2)return t;if(t.endsWith("ing")){let n=t.slice(0,-3);return n.length>2?n:t}if(t.endsWith("ed")){let n=t.slice(0,-2);return n.length>2?n:t}return t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t.endsWith("es")||t.endsWith("ly")||t.endsWith("er")?t.slice(0,-2):t}N();import{v4 as rt}from"uuid";import hn from"crypto";import it from"path";import"acorn";W();N();import*as tt from"acorn";async function Oe(e,t){if(!e||e.trim()==="")return console.warn("Empty code content provided to buildAST"),null;let n=t.toLowerCase();if(["javascript","typescript","js","ts","jsx","tsx"].includes(n))try{return tt.parse(e,{ecmaVersion:"latest",sourceType:"module",locations:!0,ranges:!0,allowAwaitOutsideFunction:!0,allowImportExportEverywhere:!0,allowReserved:!0,allowReturnOutsideFunction:!1,allowSuperOutsideMethod:!1})}catch(r){return console.error(`Error parsing ${n} code:`,r.message),{error:!0,message:r.message,location:r.loc,type:"AST_PARSE_ERROR"}}else return console.log(`AST generation is not yet supported for ${n}`),null}M();function yn(e){return hn.createHash("sha256").update(e).digest("hex")}function _n(e){return it.basename(e)}function En(e,t){if(t)return t.toLowerCase();let n=it.extname(e).toLowerCase();return{".js":"javascript",".jsx":"javascript",".ts":"typescript",".tsx":"typescript",".py":"python",".rb":"ruby",".java":"java",".go":"go",".rs":"rust",".php":"php",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".swift":"swift",".kt":"kotlin",".html":"html",".css":"css",".scss":"scss",".json":"json",".md":"markdown",".xml":"xml",".yaml":"yaml",".yml":"yaml"}[n]||"unknown"}function ot(e,t){return e.substring(0,t).split(`
`).length}function st(e,t){let n=[],r={function:{python:/def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*:/g,ruby:/def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(\([^)]*\))?\s*(do|\n)/g,java:/(public|private|protected|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;])/g,go:/func\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?:\([^)]*\))?\s*\{/g,php:/function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*\{/g,default:/function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*\{/g},class:{python:/class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(\([^)]*\))?\s*:/g,ruby:/class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*((<|::)\s*[A-Za-z0-9_:]*)?/g,java:/class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(extends\s+[A-Za-z0-9_]+)?\s*(implements\s+[A-Za-z0-9_,\s]+)?\s*\{/g,go:/type\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+struct\s*\{/g,php:/class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(extends\s+[A-Za-z0-9_]+)?\s*(implements\s+[A-Za-z0-9_,\s]+)?\s*\{/g,default:/class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(extends\s+[A-Za-z0-9_]+)?\s*\{/g},variable:{python:/(^|\s)([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(?!==)/g,ruby:/(^|\s)([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(?!=)/g,java:/(private|protected|public|static|\s) +[\w\<\>\[\]]+\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*[^;]+;/g,go:/var\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+[\w\[\]]+(\s*=\s*[^;]+)?/g,php:/(\$[a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(?!=)/g,default:/(const|let|var)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*[^;]+;/g}},o=r.function[t]||r.function.default,s;for(;(s=o.exec(e))!==null;){let l=s[1]||s[2],i=s.index,u=ot(e,i),m=u+10;n.push({type:"function",name:l,start_position:i,start_line:u,end_line:m,raw_content:e.substring(i,i+s[0].length+100)})}let a=r.class[t]||r.class.default;for(;(s=a.exec(e))!==null;){let l=s[1],i=s.index,u=ot(e,i),m=u+20;n.push({type:"class",name:l,start_position:i,start_line:u,end_line:m,raw_content:e.substring(i,i+s[0].length+500)})}return n}function wn(e,t){let n=[],r=[],o=new Map,s=new WeakSet;function a(i,u,m,y,_,g,w,T=null,h={}){let f={type:i,name:u,start_position:m,end_position:y,start_line:_,end_line:g,raw_content:w,custom_metadata:h};return n.push(f),T&&r.push({source:T,target:f,type:"contains"}),f}function l(i,u=null,m=null,y=null){if(!i||typeof i!="object"||s.has(i)||(s.add(i),!i.loc))return;let _=i.loc?.start?.line,g=i.loc?.end?.line,w=i.start,T=i.end,h=t.substring(w,T),f=null;switch(i.type){case"FunctionDeclaration":{let p=i.id?.name||"anonymous",E=i.params?.map(S=>S.type==="Identifier"?S.name:"param");f=a("function",p,w,T,_,g,h,m,{ast_node_type:i.type,params:E||[],is_async:i.async||!1,is_generator:i.generator||!1}),o.set(i,f),i.body&&l(i.body,i,f,p);break}case"FunctionExpression":case"ArrowFunctionExpression":{let p="anonymous",E="function_expression";u&&u.type==="VariableDeclarator"&&u.id?(p=u.id.name,E="function"):u&&u.type==="AssignmentExpression"&&u.left?u.left.type==="Identifier"?(p=u.left.name,E="function"):u.left.type==="MemberExpression"&&u.left.property&&(p=u.left.property.name,E="method"):u&&u.type==="Property"&&u.key?(p=u.key.name||u.key.value||"anonymous",E="method"):u&&u.type==="MethodDefinition"&&u.key&&(p=u.key.name||"anonymous",E="method");let S=i.params?.map(b=>b.type==="Identifier"?b.name:"param");f=a(E,p,w,T,_,g,h,m,{ast_node_type:i.type,params:S||[],is_async:i.async||!1,is_generator:i.generator||!1,is_arrow:i.type==="ArrowFunctionExpression"}),o.set(i,f),i.body&&l(i.body,i,f,p);break}case"ClassDeclaration":{let p=i.id?.name||"anonymous";f=a("class",p,w,T,_,g,h,m,{ast_node_type:i.type}),o.set(i,f),i.superClass&&i.superClass.type==="Identifier"&&r.push({source:f,target:{name:i.superClass.name,type:"class"},type:"extends"}),i.body&&l(i.body,i,f,p);break}case"ClassExpression":{let p=i.id?.name||"anonymous";u&&u.type==="VariableDeclarator"&&u.id&&(p=u.id.name),f=a("class",p,w,T,_,g,h,m,{ast_node_type:i.type}),o.set(i,f),i.superClass&&i.superClass.type==="Identifier"&&r.push({source:f,target:{name:i.superClass.name,type:"class"},type:"extends"}),i.body&&l(i.body,i,f,p);break}case"MethodDefinition":{let p=i.key?.name||i.key?.value||"anonymous",E=i.kind||"method";f=a(E==="constructor"?"constructor":"method",p,w,T,_,g,h,m,{ast_node_type:i.type,kind:E,is_static:!!i.static,is_async:i.value?.async||!1,is_generator:i.value?.generator||!1}),o.set(i,f),i.value&&l(i.value,i,f,p);break}case"VariableDeclaration":{i.declarations.forEach(p=>{l(p,i,m,y)});break}case"VariableDeclarator":{if(i.id&&i.id.type==="Identifier"){let p=i.id.name,E=!1,S="variable";i.init?["FunctionExpression","ArrowFunctionExpression","ClassExpression","ObjectExpression","NewExpression"].includes(i.init.type)?(E=!0,i.init.type==="ObjectExpression"&&(S="object")):i.init.type==="Literal"&&typeof i.init.value=="object"?(E=!0,S="object"):m&&m.type!=="variable"&&(E=!0):E=!0,E&&(f=a(S,p,w,T,_,g,h,m,{ast_node_type:i.type,variable_kind:u?.kind||"var"}),o.set(i,f))}i.init&&l(i.init,i,m||f,y);break}case"ImportDeclaration":{let p=i.source.value,E=i.specifiers.map(S=>S.type==="ImportDefaultSpecifier"?{type:"default",name:S.local.name}:S.type==="ImportNamespaceSpecifier"?{type:"namespace",name:S.local.name}:{type:"named",name:S.local.name,imported:S.imported?.name||S.local.name});f=a("import",p,w,T,_,g,h,m,{ast_node_type:i.type,specifiers:E}),o.set(i,f),E.forEach(S=>{r.push({source:f,target:{name:S.name,type:"imported"},type:"imports",metadata:{source_module:p,import_type:S.type,original_name:S.imported}})});break}case"ExportNamedDeclaration":{let p="named_export";i.declaration?i.declaration.type==="FunctionDeclaration"||i.declaration.type==="ClassDeclaration"?p=i.declaration.id?.name||"anonymous":i.declaration.type==="VariableDeclaration"&&i.declaration.declarations.length>0&&(p=i.declaration.declarations[0].id?.name||"anonymous"):i.specifiers&&i.specifiers.length>0&&(p=i.specifiers.map(E=>E.exported?.name||E.local?.name||"anonymous").join(",")),f=a("export",p,w,T,_,g,h,m,{ast_node_type:i.type,source:i.source?.value}),o.set(i,f),i.declaration&&l(i.declaration,i,m,y),i.specifiers&&i.specifiers.forEach(E=>{E.local&&E.exported&&r.push({source:f,target:{name:E.local.name,type:"exported"},type:"exports",metadata:{exported_as:E.exported.name,source_module:i.source?.value}})});break}case"ExportDefaultDeclaration":{let p="default";i.declaration&&(i.declaration.type==="FunctionDeclaration"||i.declaration.type==="ClassDeclaration"?p=i.declaration.id?.name||"default":i.declaration.type==="Identifier"&&(p=i.declaration.name)),f=a("export",p,w,T,_,g,h,m,{ast_node_type:i.type,is_default:!0}),o.set(i,f),i.declaration&&l(i.declaration,i,m,y),r.push({source:f,target:{name:p,type:"exported"},type:"exports",metadata:{is_default:!0}});break}case"InterfaceDeclaration":{let p=i.id?.name||"anonymous";f=a("interface",p,w,T,_,g,h,m,{ast_node_type:i.type}),o.set(i,f),i.extends&&i.extends.forEach(E=>{E.expression&&E.expression.type==="Identifier"&&r.push({source:f,target:{name:E.expression.name,type:"interface"},type:"extends"})}),i.body&&l(i.body,i,f,p);break}case"TypeAliasDeclaration":{let p=i.id?.name||"anonymous";f=a("type_alias",p,w,T,_,g,h,m,{ast_node_type:i.type}),o.set(i,f),i.typeAnnotation&&l(i.typeAnnotation,i,f,p);break}case"EnumDeclaration":{let p=i.id?.name||"anonymous";f=a("enum",p,w,T,_,g,h,m,{ast_node_type:i.t