import * as path from "path";
import * as fs from "fs/promises";
import { NodeEsBuild } from "./nodeEsBuild.mjs";
import { NodeWorker } from "./nodeWorker.mjs";
/**
 * Build the Lambda function
 * @param functionId
 * @returns
 */
async function buildLambda(functionId) {
    const artifactFile = await NodeEsBuild.getBuild(functionId);
    try {
        fs.access(artifactFile, fs.constants.F_OK);
    }
    catch (err) {
        throw new Error(`${functionId} function artifact file ${artifactFile} not found.`);
    }
    return {
        artifactFile: path.resolve(artifactFile),
    };
}
/**
 * Invoke the local handler
 * @param input
 * @returns
 */
async function invokeLocalHandler(input) {
    return await NodeWorker.runInWorker({
        artifactFile: input.artifactFile,
        fuctionRequest: input.fuctionRequest,
        environment: input.fuctionRequest.env,
    });
}
/**
 * Invoke a Lambda function locally
 * @param fuctionRequest
 * @returns
 */
async function invokeLambda(fuctionRequest) {
    // Build the Lambda function if needed
    const artifact = await buildLambda(fuctionRequest.functionId);
    // Invoke the Lambda function
    return await invokeLocalHandler({
        artifactFile: artifact.artifactFile,
        fuctionRequest: fuctionRequest,
    });
}
export const NodeHandler = {
    invokeLambda,
};
