"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTypedCookie = exports.createTypedCookie = void 0;
const server_runtime_1 = require("@remix-run/server-runtime");
function createTypedCookie({ cookie, schema, }) {
    if (schema._def.typeName === "ZodObject") {
        let flashSchema = {};
        for (let key in schema.shape) {
            flashSchema[flash(key)] = schema.shape[key].optional();
        }
    }
    return {
        isTyped: true,
        get name() {
            return cookie.name;
        },
        get isSigned() {
            return cookie.isSigned;
        },
        get expires() {
            return cookie.expires;
        },
        async parse(cookieHeader, options) {
            if (!cookieHeader)
                return null;
            let value = await cookie.parse(cookieHeader, options);
            return await parseSchemaWithFlashKeys(schema, value);
        },
        async serialize(value, options) {
            let parsedValue = await parseSchemaWithFlashKeys(schema, value);
            return cookie.serialize(parsedValue, options);
        },
    };
}
exports.createTypedCookie = createTypedCookie;
/**
 * Returns true if an object is a Remix Utils Typed Cookie container.
 *
 * @see https://github.com/sergiodxa/remix-utils#typed-cookies
 */
function isTypedCookie(value) {
    return ((0, server_runtime_1.isCookie)(value) &&
        value.isTyped === true);
}
exports.isTypedCookie = isTypedCookie;
function flash(name) {
    return `__flash_${name}__`;
}
function parseSchemaWithFlashKeys(schema, value) {
    // if the Schema is not a ZodObject, we use it directly
    if (schema._def.typeName !== "ZodObject") {
        return schema.nullable().parseAsync(value);
    }
    // but if it's a ZodObject, we need to add support for flash keys, so we
    // get the shape of the schema, create a flash key for each key, and then we
    // extend the original schema with the flash schema and parse the value
    let objectSchema = schema;
    let flashSchema = {};
    for (let key in objectSchema.shape) {
        flashSchema[flash(key)] = objectSchema.shape[key].optional();
    }
    return objectSchema.extend(flashSchema).parseAsync(value);
}
