import { clone as deepClone } from '@jsonjoy.com/util/lib/json-clone/clone';
import { findByPointer } from '@jsonjoy.com/json-pointer/lib/findByPointer/v6';
function applyOp(doc, operation) {
    switch (operation.op) {
        case 'add': {
            const [obj, key] = findByPointer(operation.path, doc);
            switch (typeof key) {
                case 'number': {
                    if (key > obj.length)
                        throw new Error('INVALID_INDEX');
                    if (key === obj.length)
                        obj.push(operation.value);
                    else
                        obj.splice(key, 0, operation.value);
                    break;
                }
                case 'string': {
                    obj[key] = operation.value;
                    break;
                }
                default: {
                    doc = operation.value;
                    break;
                }
            }
        }
    }
    return { doc };
}
export function applyPatch(doc, patch, options) {
    if (!options.mutate)
        doc = deepClone(doc);
    const res = [];
    for (let i = 0; i < patch.length; i++) {
        const operation = patch[i];
        const operationResult = applyOp(doc, operation);
        res.push(operationResult);
        doc = operationResult.doc;
    }
    return { doc, res };
}
//# sourceMappingURL=v2.js.map