/**
 * Handler for fs_list messages.
 * Lists directory contents within a project with lazy loading.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject } from "../db/repositories/projects.js";
import { getSeq } from "../db/repositories/fs-state.js";
import { listDirectory, PathEscapeError } from "../services/filesystem.js";
import { capTreeDepth } from "./fs/limits.js";
import { logger } from "../utils/logger.js";
export async function handleFsList(message, send) {
    const msg = message;
    const { requestId, sessionId, payload } = msg;
    const { path: relativePath, depth: requestedDepth = 1 } = payload;
    const depth = capTreeDepth(requestedDepth);
    // Resolve project from sessionId (which is the projectId)
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "fs_list_response",
            requestId,
            sessionId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    try {
        const { children } = await listDirectory(project.path, relativePath, depth);
        const seq = getSeq(sessionId);
        send({
            type: "fs_list_response",
            requestId,
            sessionId,
            payload: {
                path: relativePath,
                children,
                seq,
            },
        });
    }
    catch (err) {
        if (err instanceof PathEscapeError) {
            send({
                type: "fs_list_response",
                requestId,
                sessionId,
                error: {
                    code: ErrorCode.OUTSIDE_PROJECT_ROOT,
                    message: "Path escapes project directory",
                },
            });
            return;
        }
        const errorMessage = err instanceof Error ? err.message : String(err);
        logger.error(`fs_list error: ${errorMessage}`);
        send({
            type: "fs_list_response",
            requestId,
            sessionId,
            error: {
                code: ErrorCode.UNKNOWN_ERROR,
                message: errorMessage,
            },
        });
    }
}
//# sourceMappingURL=fs-list.js.map