UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

81 lines (80 loc) 2.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpExtend = void 0; const AbstractOp_1 = require("./AbstractOp"); const json_pointer_1 = require("@jsonjoy.com/json-pointer"); const constants_1 = require("../constants"); const { isArray } = Array; /** * @category JSON Patch Extended */ class OpExtend extends AbstractOp_1.AbstractOp { constructor(path, props, deleteNull) { super(path); this.props = props; this.deleteNull = deleteNull; } op() { return 'extend'; } code() { return constants_1.OPCODE.extend; } apply(doc) { const ref = (0, json_pointer_1.find)(doc, this.path); if ((0, json_pointer_1.isArrayReference)(ref)) { if (ref.val !== undefined) { ref.obj[ref.key] = this.extend(ref.val); } } else if ((0, json_pointer_1.isObjectReference)(ref)) { ref.obj[ref.key] = this.extend(ref.val); } else { doc = this.extend(doc); } return { doc }; } extend(value) { if (isArray(value)) return value; if (typeof value !== 'object') return value; if (!value) return value; for (const [key, v] of Object.entries(this.props)) { if (key === '__proto__') throw new Error('NO_PROTO'); if (v === null && this.deleteNull) { delete value[key]; continue; } value[key] = v; } return value; } toJson(parent) { const op = { op: 'extend', path: (0, json_pointer_1.formatJsonPointer)(this.path), props: this.props, }; if (this.deleteNull) op.deleteNull = this.deleteNull; return op; } toCompact(parent, verbose) { const opcode = verbose ? 'extend' : constants_1.OPCODE.extend; return this.deleteNull ? [opcode, this.path, this.props, 1] : [opcode, this.path, this.props]; } encode(encoder, parent) { const { deleteNull } = this; encoder.encodeArrayHeader(deleteNull ? 4 : 3); encoder.writer.u8(constants_1.OPCODE.extend); encoder.encodeArray(this.path); encoder.encodeObject(this.props); if (deleteNull) encoder.writer.u8(1); } } exports.OpExtend = OpExtend;