/**
 * Zod schemas for validating postMessage responses from the iframe.
 *
 * Every response crossing the iframe boundary is validated at runtime to
 * prevent a compromised or buggy iframe from injecting arbitrary data.
 */
import { z } from 'zod';
// -- Helpers --
// Accept both 0x-prefixed and unprefixed hex strings from WASM
const hexString = z.string().regex(/^(0x)?[0-9a-fA-F]*$/);
const publicKeyPoint = z.object({ x: z.string(), y: z.string() });
/**
 * serde-wasm-bindgen serializes Rust HashMap/BTreeMap as a JS Map, but Zod's
 * z.record() expects a plain object. Walk the data and convert any Map instances
 * to plain objects before Zod validation.
 */
export function convertMapsToObjects(value) {
    if (value instanceof Map) {
        const obj = {};
        value.forEach((v, k) => { obj[String(k)] = convertMapsToObjects(v); });
        return obj;
    }
    if (Array.isArray(value)) {
        return value.map(convertMapsToObjects);
    }
    if (typeof value === 'object' && value !== null) {
        const out = {};
        for (const [k, v] of Object.entries(value)) {
            out[k] = convertMapsToObjects(v);
        }
        return out;
    }
    return value;
}
export function parseResponse(schema, data, opName) {
    const normalized = convertMapsToObjects(data);
    const result = schema.safeParse(normalized);
    if (!result.success) {
        const issues = result.error.issues
            .map((i) => `${i.path.join('.')}: ${i.message}`)
            .join('; ');
        throw new Error(`Invalid response from iframe for "${opName}": ${issues}`);
    }
    return result.data;
}
// -- Stored Session --
export const StoredSessionSchema = z.object({
    token: z.string(),
    expirySecs: z.number(),
    walletAddress: z.string(),
    vaultExists: z.boolean(),
    chainRegistrations: z.record(z.string()).optional(),
});
// -- Key Status --
export const KeyStatusSchema = z.enum(['none', 'locked', 'ready']);
// -- Public Keys --
export const PublicKeysSchema = z.object({
    mpk: z.string(),
    privacyAddress: z.string(),
    viewingPublicKey: publicKeyPoint,
    nullifyingPublicKey: publicKeyPoint,
    accountId: z.string(),
    accountSalt: z.string(),
    authPkX: z.string(),
    authPkY: z.string(),
});
// -- Authentication --
// BIP-39 mnemonic: 12 or 24 lowercase words separated by single spaces
const mnemonicString = z.string().regex(/^[a-z]+( [a-z]+){11}(( [a-z]+){12})?$/, 'Invalid mnemonic format (expected 12 or 24 lowercase words)');
export const AuthenticateResultSchema = z.object({
    status: z.enum(['authenticated', 'credentialRequired', 'mnemonicGenerated']),
    privacyAddress: z.string().optional(),
    mpk: z.string().optional(),
    mnemonic: mnemonicString.optional(),
    isNewUser: z.boolean().optional(),
    chainRegistrations: z.record(z.string()).optional(),
    action: z.enum(['setup', 'unlock']).optional(),
    unlockType: z.enum(['pin', 'password']).optional(),
});
// -- Deposit Crypto --
export const ShieldCommitmentResultSchema = z.object({
    commitment: hexString,
    randomIn: hexString,
    npk: hexString,
});
export const DepositCiphertextResultSchema = z.object({
    viewingKey: hexString,
    teeWrapKey: hexString,
    receiverWrapKey: hexString,
    ct0: hexString,
    ct1: hexString,
    ct2: hexString,
});
// -- Simple Result Types --
export const NullifiersResultSchema = z.array(hexString);
export const HexResultSchema = hexString;
// -- Transfer / Withdraw Crypto --
export const EcdhKeysResultSchema = z.object({
    viewingKey: hexString,
    teeWrapKey: hexString,
    receiverWrapKey: hexString,
    blindingScalar: hexString,
    ephTxEncKey: hexString,
});
export const TransferCiphertextResultSchema = z.object({
    ct0: hexString,
    ct1: hexString,
    ct2: hexString,
    ct3: hexString,
});
export const SpendingSignatureResultSchema = z.object({
    authPkX: hexString,
    authPkY: hexString,
    sigR8X: hexString,
    sigR8Y: hexString,
    sigS: hexString,
});
// -- Digest --
export const DigestResultSchema = z.object({
    digestHi: hexString,
    digestLo: hexString,
});
// -- Auth Crypto --
export const ViewAuthSignatureResultSchema = z.object({
    signature: z.string(),
    viewingPublicKey: publicKeyPoint,
});
export const RegistrationDataSchema = z.object({
    authPkX: hexString,
    authPkY: hexString,
});
//# sourceMappingURL=schemas.js.map