All files / src/ide-json IdeJsonParser.ts

54.2% Statements 58/107
68.42% Branches 26/38
52.17% Functions 12/23
55.67% Lines 54/97

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 26634x 2x 2x 2x                                                                                                                                                                                                                         19x 19x 19x 19x   14x     14x 14x 14x 111x 111x 111x       14x 14x                 9x   9x   1x 2x   1x 1x 1x     1x       1x 2x 2x 2x       1x 2x 2x 2x       1x 1x 1x 1x 1x       1x 2x       2x 2x         1x 2x 3x 3x 3x             1x 1x 2x 4x     1x 3x         2x                                                                                                            
// src/ide-json/IdeJsonParser.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../cache/CacheManager';
import type {
  IdeJsonSchema,
  IdeJsonFunction,
  IdeJsonParameterType,
} from '../types';
 
// ─── Dynamic Provider Factory ─────────────────────────────────────────────
 
/**
 * Reads `ide.json` (or `ide-helper.json`) from the project root,
 * parses its schema, and dynamically registers VS Code completion
 * providers for any custom functions declared there.
 *
 * Schema example:
 * {
 *   "functions": [
 *     {
 *       "name": "my_route_helper",
 *       "parameters_patterns": [
 *         { "parameter": 0, "type": "route" }
 *       ]
 *     }
 *   ]
 * }
 */
export class IdeJsonParser implements vscode.Disposable {
  private readonly workspaceRoot: string;
  private readonly cache: CacheManager;
  private readonly registeredProviders: vscode.Disposable[] = [];
  private watcher: vscode.FileSystemWatcher | null = null;
 
  constructor(workspaceRoot: string, cache: CacheManager) {
    this.workspaceRoot = workspaceRoot;
    this.cache = cache;
  }
 
  async initialize(): Promise<void> {
    await this.loadAndRegister();
    this.watchIdeJson();
  }
 
  // ─── Load & Register ──────────────────────────────────────────────────
 
  private async loadAndRegister(): Promise<void> {
    const schema = this.readIdeJson();
    if (!schema) { return; }
 
    // Dispose previously registered dynamic providers before re-registering
    for (const p of this.registeredProviders) { p.dispose(); }
    this.registeredProviders.length = 0;
 
    for (const fn of schema.functions ?? []) {
      this.registerFunctionProvider(fn);
    }
 
    console.log(
      `[Maestro] ide.json: registered ${schema.functions?.length ?? 0} custom function providers`
    );
  }
 
  // ─── Dynamic Completion Provider ──────────────────────────────────────
 
  private registerFunctionProvider(fn: IdeJsonFunction): void {
    const cache = this.cache;
    const fnName = fn.name;
 
    // Build one provider per parameter pattern that needs completion
    for (const pattern of fn.parameters_patterns ?? []) {
      const paramIndex = pattern.parameter;
      const type = pattern.type;
 
      const provider = vscode.languages.registerCompletionItemProvider(
        [
          { language: 'php' },
          { language: 'blade' },
        ],
        {
          provideCompletionItems(
            document: vscode.TextDocument,
            position: vscode.Position
          ): vscode.CompletionItem[] {
            const lineText = document.lineAt(position).text;
            const textBefore = lineText.substring(0, position.character);
 
            // Detect: fnName(..., paramIndex-th param as string
            if (!IdeJsonParser.isInsideCustomFn(textBefore, fnName, paramIndex)) {
              return [];
            }
 
            return IdeJsonParser.buildItemsForType(type, cache);
          },
        },
        "'", '"' // trigger on quote characters
      );
 
      this.registeredProviders.push(provider);
    }
  }
 
  // ─── Context Detection ────────────────────────────────────────────────
 
  static isInsideCustomFn(
    textBefore: string,
    fnName: string,
    paramIndex: number
  ): boolean {
    // Check if we're inside the function call at the right argument position
    const escaped = fnName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const pattern = new RegExp(`\\b${escaped}\\s*\\(`);
    const fnMatch = pattern.exec(textBefore);
    if (!fnMatch) { return false; }
 
    const afterParen = textBefore.slice(fnMatch.index + fnMatch[0].length);
 
    // Count commas to determine argument position (simplified, handles nesting)
    let depth = 0;
    let commas = 0;
    for (const ch of afterParen) {
      if (ch === '(' || ch === '[') { depth++; }
      if (ch === ')' || ch === ']') { depth--; }
      if (ch === ',' && depth === 0) { commas++; }
    }
 
    // Are we in a string at the right position?
    const endsWithOpenString = /['"][^'"]*$/.test(afterParen);
    return endsWithOpenString && commas === paramIndex;
  }
 
  // ─── Item Builder ─────────────────────────────────────────────────────
 
  static buildItemsForType(
    type: IdeJsonParameterType,
    cache: CacheManager
  ): vscode.CompletionItem[] {
    const index = cache.getIndex();
 
    switch (type) {
      case 'route':
        return Array.from(index.routes.values())
          .filter((r) => r.name)
          .map((r) => {
            const item = new vscode.CompletionItem(r.name, vscode.CompletionItemKind.Value);
            item.detail = `[${r.methods.join('|')}] /${r.uri}`;
            item.documentation = new vscode.MarkdownString(
              `**Route (ide.json):** \`${r.name}\`\n\nAction: \`${r.action}\``
            );
            return item;
          });
 
      case 'view':
        return Array.from(index.views.keys()).map((viewName) => {
          const item = new vscode.CompletionItem(viewName, vscode.CompletionItemKind.File);
          item.detail = 'Blade view';
          return item;
        });
 
      case 'config':
        return Array.from(index.configs.values()).map((cfg) => {
          const item = new vscode.CompletionItem(cfg.key, vscode.CompletionItemKind.Variable);
          item.detail = String(cfg.value).slice(0, 60);
          return item;
        });
 
      case 'translation':
        return Array.from(index.translations.values()).map((t) => {
          const item = new vscode.CompletionItem(t.key, vscode.CompletionItemKind.Text);
          item.detail = t.value.slice(0, 80);
          item.documentation = new vscode.MarkdownString(`\`${t.locale}\`: ${t.value}`);
          return item;
        });
 
      case 'model':
        return Array.from(index.models.values()).map((m) => {
          const item = new vscode.CompletionItem(
            m.namespace ? `${m.namespace}\\${m.className}` : m.className,
            vscode.CompletionItemKind.Class
          );
          item.detail = `Model — ${m.tableName}`;
          return item;
        });
 
      case 'column':
        // Return all columns across all tables
        return Array.from(index.dbSchema.entries()).flatMap(([table, cols]) =>
          cols.map((col) => {
            const item = new vscode.CompletionItem(`${table}.${col.name}`, vscode.CompletionItemKind.Field);
            item.detail = col.type;
            return item;
          })
        );
 
      case 'middleware':
        // Extract middleware from routes (deduplicated)
        {
          const middlewareSet = new Set<string>();
          for (const r of index.routes.values()) {
            for (const m of r.middleware) {
              middlewareSet.add(m);
            }
          }
          return Array.from(middlewareSet).map((mw) => {
            return new vscode.CompletionItem(mw, vscode.CompletionItemKind.Keyword);
          });
        }
 
      default:
        return [];
    }
  }
 
  // ─── ide.json Reader ──────────────────────────────────────────────────
 
  private readIdeJson(): IdeJsonSchema | null {
    const candidates = [
      path.join(this.workspaceRoot, 'ide.json'),
      path.join(this.workspaceRoot, 'ide-helper.json'),
      path.join(this.workspaceRoot, '.ide.json'),
    ];
 
    for (const candidate of candidates) {
      if (fs.existsSync(candidate)) {
        try {
          const raw = fs.readFileSync(candidate, 'utf8');
          const parsed = JSON.parse(raw) as IdeJsonSchema;
          return parsed;
        } catch (err) {
          vscode.window.showWarningMessage(
            `[Laravel Maestro] Failed to parse ${path.basename(candidate)}: ${String(err)}`
          );
          return null;
        }
      }
    }
 
    return null;
  }
 
  // ─── File Watcher ─────────────────────────────────────────────────────
 
  private watchIdeJson(): void {
    this.watcher = vscode.workspace.createFileSystemWatcher(
      new vscode.RelativePattern(this.workspaceRoot, '{ide.json,.ide.json,ide-helper.json}')
    );
 
    this.watcher.onDidChange(() => void this.loadAndRegister());
    this.watcher.onDidCreate(() => void this.loadAndRegister());
    this.watcher.onDidDelete(() => {
      // Clean up all dynamic providers on deletion
      for (const p of this.registeredProviders) { p.dispose(); }
      this.registeredProviders.length = 0;
    });
  }
 
  // ─── Lifecycle ────────────────────────────────────────────────────────
 
  dispose(): void {
    this.watcher?.dispose();
    for (const p of this.registeredProviders) { p.dispose(); }
  }
}