All files / src/inspections DiagnosticsProvider.ts

0% Statements 0/111
0% Branches 0/48
0% Functions 0/14
0% Lines 0/105

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
// src/inspections/DiagnosticsProvider.ts
import * as vscode from 'vscode';
import type { CacheManager } from '../cache/CacheManager';
 
const COLLECTION = vscode.languages.createDiagnosticCollection('laravel-maestro');
 
// ─── Known inspection patterns ────────────────────────────────────────────
 
// route('name') — first string arg
const ROUTE_CALL_RE = /\b(?:route|to_route)\s*\(\s*['"]([^'"]+)['"]/g;
// view('name'), @include('name'), @extends('name')
const VIEW_CALL_RE = /(?:\bview\s*\(\s*|@(?:include|includeIf|includeWhen|includeUnless|extends|component)\s*\(\s*)['"]([^'"]+)['"]/g;
// <x-component-name
const BLADE_COMPONENT_TAG_RE = /<x-([\w.-]+)/g;
// @include inside blade
// config('key') in non-config PHP
const CONFIG_CALL_RE = /\bconfig\s*\(\s*['"]([^'"]+)['"]/g;
// env('KEY') should not be used outside config files
const ENV_CALL_RE = /\benv\s*\(\s*['"]([^'"]+)['"]/g;
// Inertia::render('Page') or inertia('Page')
const INERTIA_CALL_RE = /(?:Inertia::render|inertia)\s*\(\s*['"]([^'"]+)['"]/g;
 
export class DiagnosticsProvider implements vscode.Disposable {
  private readonly cache: CacheManager;
  private readonly disposables: vscode.Disposable[] = [];
  private readonly debounceTimers = new Map<string, ReturnType<typeof setTimeout>>();
 
  constructor(cache: CacheManager) {
    this.cache = cache;
 
    // Validate on open and change
    this.disposables.push(
      vscode.workspace.onDidOpenTextDocument((doc) => this.validateDebounced(doc)),
      vscode.workspace.onDidChangeTextDocument((e) => this.validateDebounced(e.document)),
      vscode.workspace.onDidCloseTextDocument((doc) => COLLECTION.delete(doc.uri)),
    );
 
    // Validate all already-open documents
    for (const doc of vscode.workspace.textDocuments) {
      void this.validate(doc);
    }
  }
 
  private validateDebounced(doc: vscode.TextDocument): void {
    const key = doc.uri.toString();
    const existing = this.debounceTimers.get(key);
    if (existing) { clearTimeout(existing); }
    const timer = setTimeout(() => {
      this.debounceTimers.delete(key);
      void this.validate(doc);
    }, 500);
    this.debounceTimers.set(key, timer);
  }
 
  async validate(doc: vscode.TextDocument): Promise<void> {
    if (!['php', 'blade'].includes(doc.languageId)) { return; }
 
    const text = doc.getText();
    const diags: vscode.Diagnostic[] = [];
    const index = this.cache.getIndex();
 
    // ── 1. Unknown Route Names ─────────────────────────────────────────
    let m: RegExpExecArray | null;
    const routeRe = new RegExp(ROUTE_CALL_RE.source, 'g');
    while ((m = routeRe.exec(text)) !== null) {
      const routeName = m[1];
      if (routeName && !index.routes.has(routeName) && index.routes.size > 0) {
        const range = this.rangeOf(doc, m.index + m[0].indexOf(`'${routeName}'`), routeName.length + 2);
        diags.push(this.makeDiag(
          range,
          `Unknown route: '${routeName}'`,
          vscode.DiagnosticSeverity.Warning,
          'unknown-route'
        ));
      }
    }
 
    // ── 2. Unknown View Names ──────────────────────────────────────────
    const viewRe = new RegExp(VIEW_CALL_RE.source, 'g');
    while ((m = viewRe.exec(text)) !== null) {
      const viewName = m[1];
      if (viewName && !index.views.has(viewName) && index.views.size > 0 && !viewName.includes('*')) {
        const nameStart = m[0].lastIndexOf(`'${viewName}'`);
        const range = this.rangeOf(doc, m.index + nameStart, viewName.length + 2);
        diags.push(this.makeDiag(
          range,
          `Unknown view: '${viewName}'`,
          vscode.DiagnosticSeverity.Warning,
          'unknown-view',
          [{ title: `Create view '${viewName}'`, command: 'laravelMaestro.createBladeView', arguments: [viewName] }]
        ));
      }
    }
 
    // ── 3. Unknown Blade Components ────────────────────────────────────
    if (doc.languageId === 'blade' || doc.fileName.endsWith('.blade.php')) {
      const compRe = new RegExp(BLADE_COMPONENT_TAG_RE.source, 'g');
      while ((m = compRe.exec(text)) !== null) {
        const compName = m[1];
        if (compName && !index.bladeComponents.has(compName)) {
          const range = this.rangeOf(doc, m.index, m[0].length);
          diags.push(this.makeDiag(
            range,
            `Unknown Blade component: '<x-${compName}>'`,
            vscode.DiagnosticSeverity.Warning,
            'unknown-blade-component',
            [{ title: `Create component '${compName}'`, command: 'laravelMaestro.generateBladeComponent', arguments: [compName] }]
          ));
        }
      }
    }
 
    // ── 4. env() Outside Config Files ─────────────────────────────────
    const isConfigFile = doc.fileName.includes(`${require('path').sep}config${require('path').sep}`);
    if (!isConfigFile) {
      const envRe = new RegExp(ENV_CALL_RE.source, 'g');
      while ((m = envRe.exec(text)) !== null) {
        const range = this.rangeOf(doc, m.index, m[0].length);
        diags.push(this.makeDiag(
          range,
          `env() should not be called outside config files. Use config('key') instead.`,
          vscode.DiagnosticSeverity.Warning,
          'env-outside-config'
        ));
      }
    }
 
    // ── 5. Unknown Config Keys ─────────────────────────────────────────
    if (index.configs.size > 0) {
      const cfgRe = new RegExp(CONFIG_CALL_RE.source, 'g');
      while ((m = cfgRe.exec(text)) !== null) {
        const key = m[1];
        if (key && !index.configs.has(key) && !key.endsWith('.') && key.includes('.')) {
          const nameStart = m[0].lastIndexOf(`'${key}'`);
          const range = this.rangeOf(doc, m.index + nameStart, key.length + 2);
          diags.push(this.makeDiag(
            range,
            `Unknown config key: '${key}'`,
            vscode.DiagnosticSeverity.Hint,
            'unknown-config-key'
          ));
        }
      }
    }
 
    // ── 6. Unknown Inertia Pages ───────────────────────────────────────
    if (index.inertiaPages.size > 0) {
      const inertiaRe = new RegExp(INERTIA_CALL_RE.source, 'g');
      while ((m = inertiaRe.exec(text)) !== null) {
        const page = m[1];
        if (page && !index.inertiaPages.has(page)) {
          const nameStart = m[0].lastIndexOf(`'${page}'`);
          const range = this.rangeOf(doc, m.index + nameStart, page.length + 2);
          diags.push(this.makeDiag(
            range,
            `Unknown Inertia page: '${page}'`,
            vscode.DiagnosticSeverity.Warning,
            'unknown-inertia-page',
            [{ title: 'Create Inertia page', command: 'laravelMaestro.createInertiaPage', arguments: [page] }]
          ));
        }
      }
    }
 
    // ── 7. Translation Key Validation ─────────────────────────────────
    const translationCallRe = /(?:__|trans|@lang)\s*\(\s*['"]([^'"]+)['"]/g;
    while ((m = translationCallRe.exec(text)) !== null) {
      const key = m[1];
      const exists = Array.from(index.translations.values()).some(t => t.key === key);
      if (!exists && index.translations.size > 0 && key.includes('.')) {
        const nameStart = m[0].lastIndexOf(`'${key}'`);
        const range = this.rangeOf(doc, m.index + nameStart, key.length + 2);
        diags.push(this.makeDiag(
          range,
          `Unknown translation key: '${key}'`,
          vscode.DiagnosticSeverity.Hint,
          'unknown-translation-key'
        ));
      }
    }
 
    COLLECTION.set(doc.uri, diags);
  }
 
  // ─── Helpers ──────────────────────────────────────────────────────────
 
  private rangeOf(doc: vscode.TextDocument, offset: number, length: number): vscode.Range {
    const start = doc.positionAt(offset);
    const end = doc.positionAt(offset + length);
    return new vscode.Range(start, end);
  }
 
  private makeDiag(
    range: vscode.Range,
    message: string,
    severity: vscode.DiagnosticSeverity,
    code: string,
    actions?: Array<{ title: string; command: string; arguments?: unknown[] }>
  ): vscode.Diagnostic {
    const diag = new vscode.Diagnostic(range, message, severity);
    diag.source = 'Laravel Maestro';
    diag.code = code;
    if (actions) {
      // Store actions for use by the quick-fix code action provider
      (diag as DiagnosticWithActions).quickFixes = actions;
    }
    return diag;
  }
 
  /** Force re-validation of all open documents (call after re-index). */
  revalidateAll(): void {
    for (const doc of vscode.workspace.textDocuments) {
      void this.validate(doc);
    }
  }
 
  dispose(): void {
    COLLECTION.dispose();
    for (const d of this.disposables) { d.dispose(); }
    for (const t of this.debounceTimers.values()) { clearTimeout(t); }
  }
}
 
export interface DiagnosticWithActions extends vscode.Diagnostic {
  quickFixes?: Array<{ title: string; command: string; arguments?: unknown[] }>;
}
 
/** Code action provider that turns diagnostics into quick-fix actions. */
export class DiagnosticQuickFixProvider implements vscode.CodeActionProvider {
  static readonly providedCodeActionKinds = [vscode.CodeActionKind.QuickFix];
 
  provideCodeActions(
    _document: vscode.TextDocument,
    _range: vscode.Range,
    context: vscode.CodeActionContext
  ): vscode.CodeAction[] {
    const actions: vscode.CodeAction[] = [];
    for (const diag of context.diagnostics) {
      const d = diag as DiagnosticWithActions;
      if (!d.quickFixes) { continue; }
      for (const fix of d.quickFixes) {
        const action = new vscode.CodeAction(fix.title, vscode.CodeActionKind.QuickFix);
        action.command = { command: fix.command, title: fix.title, arguments: fix.arguments };
        action.diagnostics = [diag];
        actions.push(action);
      }
    }
    return actions;
  }
}