All files / src/providers/inertia InertiaProvider.ts

0% Statements 0/119
0% Branches 0/64
0% Functions 0/17
0% Lines 0/99

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                                                                                                                                                                                                                                                                                                                                                                                                                                                         
// src/providers/inertia/InertiaProvider.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../../cache/CacheManager';
import type { InertiaPage } from '../../types';
 
// ─── Inertia Page Indexer ─────────────────────────────────────────────────
 
export class InertiaIndexer {
  /**
   * Scans JS/TS/Vue/Svelte files under resources/js/Pages (or configured root)
   * and builds InertiaPage entries.
   */
  static async indexPages(workspaceRoot: string): Promise<InertiaPage[]> {
    const pages: InertiaPage[] = [];
    const pageRoots = [
      path.join(workspaceRoot, 'resources', 'js', 'Pages'),
      path.join(workspaceRoot, 'resources', 'js', 'pages'),
      path.join(workspaceRoot, 'resources', 'ts', 'Pages'),
    ];
 
    for (const pageRoot of pageRoots) {
      if (!fs.existsSync(pageRoot)) { continue; }
      InertiaIndexer.walkDir(pageRoot, pageRoot, pages);
    }
 
    return pages;
  }
 
  private static walkDir(dir: string, root: string, pages: InertiaPage[]): void {
    let entries: fs.Dirent[];
    try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
 
    for (const entry of entries) {
      const fullPath = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        InertiaIndexer.walkDir(fullPath, root, pages);
      } else if (entry.isFile()) {
        const ext = path.extname(entry.name).toLowerCase();
        if (!['.vue', '.jsx', '.tsx', '.svelte'].includes(ext)) { continue; }
 
        const rel = path.relative(root, fullPath);
        const pageName = rel.replace(/\\/g, '/').replace(/\.(vue|jsx|tsx|svelte)$/, '');
        let framework: InertiaPage['componentFramework'] = 'unknown';
        if (ext === '.vue') { framework = 'vue'; }
        else if (ext === '.jsx' || ext === '.tsx') { framework = 'react'; }
        else if (ext === '.svelte') { framework = 'svelte'; }
 
        // Extract props from defineProps or export default / interface Props
        const source = InertiaIndexer.safeRead(fullPath);
        const props = InertiaIndexer.extractProps(source, framework);
 
        pages.push({ name: pageName, filePath: fullPath, props, componentFramework: framework });
      }
    }
  }
 
  private static extractProps(source: string, framework: InertiaPage['componentFramework']): string[] {
    const props: string[] = [];
    if (framework === 'vue') {
      // defineProps({ key: Type }) or defineProps<{ key: Type }>()
      const m = /defineProps\s*(?:<[^>]+>)?\s*\(\s*\{([^}]+)\}/s.exec(source);
      if (m) {
        const propRe = /(\w+)\s*:/g; let pm: RegExpExecArray | null;
        while ((pm = propRe.exec(m[1])) !== null) { props.push(pm[1]); }
      }
    } else if (framework === 'react') {
      // interface Props { key: Type }  or  type Props = { key: Type }
      const m = /(?:interface|type)\s+Props\s*(?:=\s*)?\{([^}]+)\}/s.exec(source);
      if (m) {
        const propRe = /(\w+)\s*[?:]:/g; let pm: RegExpExecArray | null;
        while ((pm = propRe.exec(m[1])) !== null) { props.push(pm[1]); }
      }
    }
    return props;
  }
 
  private static safeRead(filePath: string): string {
    try { return fs.readFileSync(filePath, 'utf8'); } catch { return ''; }
  }
}
 
// ─── Inertia Completion Provider ──────────────────────────────────────────
 
export class InertiaCompletionProvider implements vscode.CompletionItemProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideCompletionItems(
    document: vscode.TextDocument,
    position: vscode.Position
  ): vscode.CompletionItem[] {
    const lineText = document.lineAt(position).text;
    const textBefore = lineText.substring(0, position.character);
    const index = this.cache.getIndex();
 
    // Inertia::render('Page', [...])  or  inertia('Page')
    if (!/(?:Inertia::render|->inertia|inertia)\s*\(\s*['"][^'"]*$/.test(textBefore)) {
      return [];
    }
 
    return Array.from(index.inertiaPages.values()).map((page) => {
      const item = new vscode.CompletionItem(page.name, vscode.CompletionItemKind.File);
      item.detail = `Inertia ${page.componentFramework} page`;
      const md = new vscode.MarkdownString();
      md.appendMarkdown(`**Inertia Page:** \`${page.name}\`\n\n`);
      md.appendMarkdown(`**Framework:** ${page.componentFramework}\n\n`);
      if (page.props.length > 0) {
        md.appendMarkdown(`**Props:** ${page.props.map(p => `\`${p}\``).join(', ')}\n`);
      }
      item.documentation = md;
      item.sortText = `0_${page.name}`;
      return item;
    });
  }
}
 
// ─── Inertia Hover Provider ────────────────────────────────────────────────
 
export class InertiaHoverProvider implements vscode.HoverProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover | undefined {
    const wordRange = document.getWordRangeAtPosition(position, /['"][^'"]+['"]/);
    if (!wordRange) { return undefined; }
 
    const name = document.getText(wordRange).replace(/['"]/g, '');
    const index = this.cache.getIndex();
    const page = index.inertiaPages.get(name);
    if (!page) { return undefined; }
 
    const md = new vscode.MarkdownString();
    md.isTrusted = true;
    md.appendMarkdown(`### 🔀 Inertia Page: \`${page.name}\`\n\n`);
    md.appendMarkdown(`**File:** \`${page.filePath}\`\n\n`);
    md.appendMarkdown(`**Framework:** ${page.componentFramework}\n`);
    if (page.props.length > 0) {
      md.appendMarkdown(`\n**Props:** ${page.props.map(p => `\`${p}\``).join(', ')}\n`);
    }
    return new vscode.Hover(md, wordRange);
  }
}
 
// ─── Inertia Definition Provider ──────────────────────────────────────────
 
export class InertiaDefinitionProvider implements vscode.DefinitionProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideDefinition(document: vscode.TextDocument, position: vscode.Position): vscode.Location | undefined {
    const wordRange = document.getWordRangeAtPosition(position, /['"][^'"]+['"]/);
    if (!wordRange) { return undefined; }
 
    const name = document.getText(wordRange).replace(/['"]/g, '');
    const index = this.cache.getIndex();
    const page = index.inertiaPages.get(name);
    if (!page || !fs.existsSync(page.filePath)) { return undefined; }
 
    return new vscode.Location(vscode.Uri.file(page.filePath), new vscode.Position(0, 0));
  }
}
 
// ─── Create Inertia Page Generator ────────────────────────────────────────
 
export class InertiaPageGenerator {
  constructor(_cache: CacheManager, private readonly workspaceRoot: string) {}
 
  async generate(): Promise<void> {
    const name = await vscode.window.showInputBox({
      prompt: 'Inertia page name (e.g. Users/Index)',
      placeHolder: 'Users/Index',
      validateInput: (v) => v.trim() ? null : 'Name is required',
    });
    if (!name) { return; }
 
    const framework = await vscode.window.showQuickPick(
      ['Vue (SFC)', 'React (TSX)', 'Svelte'],
      { placeHolder: 'Component framework' }
    );
    if (!framework) { return; }
 
    const ext = framework.includes('Vue') ? '.vue' : framework.includes('React') ? '.tsx' : '.svelte';
    const filePath = path.join(this.workspaceRoot, 'resources', 'js', 'Pages', ...name.split('/')) + ext;
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); }
 
    const content = framework.includes('Vue')
      ? `<script setup lang="ts">
const props = defineProps({})
</script>
 
<template>
  <div>
    <h1>${(name.split('/').pop() ?? name)}</h1>
  </div>
</template>
`
      : framework.includes('React')
      ? `import React from 'react';
 
export default function ${(name.split('/').pop() ?? name)}() {
  return <div><h1>${(name.split('/').pop() ?? name)}</h1></div>;
}
`
      : `<script lang="ts">
  export let data = {};
</script>
 
<h1>${(name.split('/').pop() ?? name)}</h1>
`;
 
    const uri = vscode.Uri.file(filePath);
    const edit = new vscode.WorkspaceEdit();
    edit.createFile(uri, { overwrite: false });
    edit.insert(uri, new vscode.Position(0,0), content);
    await vscode.workspace.applyEdit(edit);
    const doc = await vscode.workspace.openTextDocument(uri);
    await vscode.window.showTextDocument(doc);
    vscode.window.showInformationMessage('[Maestro] Created Inertia page: ' + name);
  }
}