
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7cd02ddd-a091-588e-b7a7-320e5c8201e8")}catch(e){}}();
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { createGitProcessEnv } from "../core/git-process-env.js";
const execFileAsync = promisify(execFile);
const CACHE_TTL_MS = 10_000;
const DEFAULT_LIMIT = 20;
const MAX_LIMIT = 100;
const fileIndexCache = new Map();
function normalizeLines(stdout) {
    const seen = new Set();
    const files = [];
    for (const rawLine of stdout.split(/\r?\n/g)) {
        const line = rawLine.trim();
        if (!line || seen.has(line)) {
            continue;
        }
        seen.add(line);
        files.push(line);
    }
    return files;
}
function getCachedFileIndex(cwd) {
    const cached = fileIndexCache.get(cwd);
    if (!cached) {
        return null;
    }
    if (cached.expiresAt <= Date.now()) {
        fileIndexCache.delete(cwd);
        return null;
    }
    return cached.files;
}
function getCachedChangedPaths(cwd) {
    const cached = fileIndexCache.get(cwd);
    if (!cached) {
        return null;
    }
    if (cached.expiresAt <= Date.now()) {
        fileIndexCache.delete(cwd);
        return null;
    }
    return cached.changedPaths;
}
function parsePorcelainChangedPaths(stdout) {
    const changed = new Set();
    for (const rawLine of stdout.split(/\r?\n/g)) {
        const line = rawLine.trimEnd();
        if (!line || line.length < 4) {
            continue;
        }
        const payload = line.slice(3).trim();
        if (!payload) {
            continue;
        }
        const renamedParts = payload.split(" -> ");
        const path = renamedParts[renamedParts.length - 1]?.trim();
        if (!path) {
            continue;
        }
        changed.add(path);
    }
    return changed;
}
async function loadFileIndex(cwd) {
    const cached = getCachedFileIndex(cwd);
    const cachedChangedPaths = getCachedChangedPaths(cwd);
    if (cached && cachedChangedPaths) {
        return {
            files: cached,
            changedPaths: cachedChangedPaths,
        };
    }
    try {
        const [filesResult, statusResult] = await Promise.all([
            execFileAsync("git", ["ls-files", "--cached", "--others", "--exclude-standard"], {
                cwd,
                maxBuffer: 8 * 1024 * 1024,
                env: createGitProcessEnv(),
            }),
            execFileAsync("git", ["status", "--porcelain=v1", "--untracked-files=all"], {
                cwd,
                maxBuffer: 8 * 1024 * 1024,
                env: createGitProcessEnv(),
            }).catch(() => ({ stdout: "" })),
        ]);
        const files = normalizeLines(filesResult.stdout);
        const changedPaths = parsePorcelainChangedPaths(statusResult.stdout);
        fileIndexCache.set(cwd, {
            expiresAt: Date.now() + CACHE_TTL_MS,
            files,
            changedPaths,
        });
        return { files, changedPaths };
    }
    catch {
        return {
            files: [],
            changedPaths: new Set(),
        };
    }
}
function getMatchScore(path, queryLower) {
    const pathLower = path.toLowerCase();
    const name = path.slice(path.lastIndexOf("/") + 1);
    const nameLower = name.toLowerCase();
    if (nameLower.startsWith(queryLower)) {
        return 0;
    }
    if (pathLower.startsWith(queryLower)) {
        return 1;
    }
    if (nameLower.includes(queryLower)) {
        return 2;
    }
    if (pathLower.includes(queryLower)) {
        return 3;
    }
    return null;
}
function normalizeLimit(limit) {
    if (!Number.isFinite(limit)) {
        return DEFAULT_LIMIT;
    }
    const rounded = Math.floor(limit ?? DEFAULT_LIMIT);
    return Math.max(1, Math.min(MAX_LIMIT, rounded));
}
export async function searchWorkspaceFiles(cwd, query, limit) {
    const trimmedQuery = query.trim();
    const normalizedLimit = normalizeLimit(limit);
    const { files, changedPaths } = await loadFileIndex(cwd);
    if (files.length === 0) {
        return [];
    }
    if (!trimmedQuery) {
        const sorted = [...files].sort((left, right) => {
            const leftChanged = changedPaths.has(left);
            const rightChanged = changedPaths.has(right);
            if (leftChanged !== rightChanged) {
                return leftChanged ? -1 : 1;
            }
            return left.localeCompare(right);
        });
        return sorted.slice(0, normalizedLimit).map((path) => ({
            path,
            name: path.slice(path.lastIndexOf("/") + 1) || path,
            changed: changedPaths.has(path),
        }));
    }
    const queryLower = trimmedQuery.toLowerCase();
    const ranked = files
        .map((path) => {
        const score = getMatchScore(path, queryLower);
        if (score == null) {
            return null;
        }
        return { path, score, changed: changedPaths.has(path) };
    })
        .filter((entry) => entry !== null)
        .sort((left, right) => {
        if (left.changed !== right.changed) {
            return left.changed ? -1 : 1;
        }
        if (left.score !== right.score) {
            return left.score - right.score;
        }
        if (left.path.length !== right.path.length) {
            return left.path.length - right.path.length;
        }
        return left.path.localeCompare(right.path);
    });
    return ranked.slice(0, normalizedLimit).map((entry) => ({
        path: entry.path,
        name: entry.path.slice(entry.path.lastIndexOf("/") + 1) || entry.path,
        changed: entry.changed,
    }));
}
//# sourceMappingURL=search-workspace-files.js.map
//# debugId=7cd02ddd-a091-588e-b7a7-320e5c8201e8
