import MemoryBudgetError from "../../errors/MemoryBudgetError.js";
/** Immutable sync patch page with a deterministic resume cursor. */
export default class BoundedSyncPatchBatch {
    patches;
    cursor;
    constructor(fields) {
        const validFields = requireBatchFields(fields);
        this.patches = freezePatches(validFields.patches);
        this.cursor = normalizeCursor(validFields.cursor);
        Object.freeze(this);
    }
}
function requireBatchFields(fields) {
    if (fields !== null && typeof fields === 'object') {
        return fields;
    }
    throw new MemoryBudgetError('Bounded sync patch batch requires object fields', {
        code: 'E_BOUNDED_SYNC_BATCH_INVALID',
        context: { field: 'fields' },
    });
}
function freezePatches(values) {
    if (!Array.isArray(values)) {
        throw new MemoryBudgetError('Bounded sync patch batch requires a patch array', {
            code: 'E_BOUNDED_SYNC_BATCH_INVALID',
            context: { field: 'patches' },
        });
    }
    const patches = [];
    let index = 0;
    for (const value of values) {
        const descriptor = requirePatchDescriptor(value, `patches.${index}`);
        patches.push(Object.freeze({
            writerId: requireNonEmptyString(descriptor.writerId, 'writerId'),
            sha: requireNonEmptyString(descriptor.sha, 'sha'),
        }));
        index += 1;
    }
    return Object.freeze(patches);
}
function requirePatchDescriptor(value, field) {
    if (value !== null && typeof value === 'object') {
        return value;
    }
    throw new MemoryBudgetError('Bounded sync patch descriptors must be objects', {
        code: 'E_BOUNDED_SYNC_BATCH_INVALID',
        context: { field },
    });
}
function normalizeCursor(value) {
    if (value === null) {
        return null;
    }
    if (typeof value === 'string' && value.length > 0) {
        return value;
    }
    throw new MemoryBudgetError('Bounded sync patch batch cursor must be non-empty or null', {
        code: 'E_BOUNDED_SYNC_BATCH_INVALID',
        context: { field: 'cursor' },
    });
}
function requireNonEmptyString(value, field) {
    if (typeof value === 'string' && value.length > 0) {
        return value;
    }
    throw new MemoryBudgetError('Bounded sync patch descriptor fields must be non-empty', {
        code: 'E_BOUNDED_SYNC_BATCH_INVALID',
        context: { field },
    });
}
