MCPcopy Create free account
hub / github.com/Effect-TS/effect / applyOperation

Function applyOperation

packages/effect/src/JsonPatch.ts:318–356  ·  view source on GitHub ↗
(doc: Schema.Json, op: JsonPatchOperation)

Source from the content-addressed store, hash-verified

316}
317
318function applyOperation(doc: Schema.Json, op: JsonPatchOperation): Schema.Json {
319 if (op.path === "") {
320 if (op.op === "remove") throw new Error("Unsupported operation at the root")
321 return op.value
322 }
323
324 const resolved = resolveParent(doc, op.path)
325 if (resolved === null) {
326 throw new Error(`Cannot ${op.op} at "${op.path}" (parent not found or not a container).`)
327 }
328
329 const { lastToken, parent, stack } = resolved
330
331 if (Array.isArray(parent)) {
332 if (lastToken === "-" && op.op !== "add") {
333 throw new Error(`"-" is not valid for ${op.op} at "${op.path}".`)
334 }
335 const index = lastToken === "-" ? parent.length : toIndex(lastToken)
336 const maxIndex = op.op === "add" ? parent.length : parent.length - 1
337 if (index > maxIndex) throw new Error(`Array index out of bounds at "${op.path}".`)
338 const updated = parent.slice()
339 if (op.op === "add") updated.splice(index, 0, op.value)
340 else if (op.op === "remove") updated.splice(index, 1)
341 else updated[index] = op.value
342 return rebuildFromStack(stack, updated)
343 }
344
345 if (isJsonObject(parent)) {
346 if (op.op !== "add" && !Object.hasOwn(parent, lastToken)) {
347 throw new Error(`Property "${lastToken}" does not exist at "${op.path}".`)
348 }
349 const updated = { ...parent }
350 if (op.op === "remove") delete updated[lastToken]
351 else InternalRecord.assignProperty(updated, lastToken, op.value)
352 return rebuildFromStack(stack, updated)
353 }
354
355 throw new Error(`Cannot ${op.op} at "${op.path}" (parent not found or not a container).`)
356}
357
358type StackEntry = { readonly container: unknown; readonly token: number | string }
359

Callers 1

applyFunction · 0.85

Calls 4

resolveParentFunction · 0.85
toIndexFunction · 0.85
rebuildFromStackFunction · 0.85
isJsonObjectFunction · 0.70

Tested by

no test coverage detected