"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBrowserbaseSession = createBrowserbaseSession;
const sdk_1 = __importDefault(require("@browserbasehq/sdk"));
const sdkErrors_js_1 = require("../types/public/sdkErrors.js");
const timeoutConfig_js_1 = require("../timeoutConfig.js");
async function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
    const bb = new sdk_1.default({ apiKey });
    const sessionCreateTimeoutMs = (0, timeoutConfig_js_1.getEnvTimeoutMs)("BROWSERBASE_SESSION_CREATE_MAX_MS");
    // Resume an existing session if provided
    if (resumeSessionId) {
        const retrievePromise = bb.sessions.retrieve(resumeSessionId);
        const existing = (sessionCreateTimeoutMs
            ? await (0, timeoutConfig_js_1.withTimeout)(retrievePromise, sessionCreateTimeoutMs, "Browserbase session retrieve")
            : await retrievePromise);
        if (!existing?.id) {
            throw new sdkErrors_js_1.BrowserbaseSessionNotFoundError();
        }
        const ws = existing.connectUrl;
        if (!ws) {
            throw new sdkErrors_js_1.StagehandInitError(`Browserbase session resume missing connectUrl for ${resumeSessionId}`);
        }
        return { ws, sessionId: resumeSessionId, bb };
    }
    // Create a new session with optional overrides and a default viewport
    const { projectId: overrideProjectId, browserSettings, userMetadata, ...rest } = params ?? {};
    // satisfies check ensures our BrowserbaseSessionCreateParamsSchema stays in sync with SDK
    const createPayload = {
        projectId: overrideProjectId ?? projectId,
        ...rest,
        browserSettings: {
            ...(browserSettings ?? {}),
            viewport: browserSettings?.viewport ?? { width: 1288, height: 711 },
        },
        userMetadata: {
            ...(userMetadata ?? {}),
            stagehand: "true",
        },
    };
    const createPromise = bb.sessions.create(createPayload);
    const created = (sessionCreateTimeoutMs
        ? await (0, timeoutConfig_js_1.withTimeout)(createPromise, sessionCreateTimeoutMs, "Browserbase session create")
        : await createPromise);
    if (!created?.connectUrl || !created?.id) {
        throw new sdkErrors_js_1.StagehandInitError("Browserbase session creation returned an unexpected shape.");
    }
    return { ws: created.connectUrl, sessionId: created.id, bb };
}
//# sourceMappingURL=browserbase.js.map