|
| 1 | +type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[]; |
| 2 | +type JsonObject = { [key: string]: JsonValue }; |
| 3 | +type JsonPatchOp = { op: string; path: string; value?: JsonValue }; |
| 4 | +type JsonPatch = JsonPatchOp[]; |
| 5 | + |
| 6 | +function decodePointerToken(token: string): string { |
| 7 | + return token.replace(/~1/g, "/").replace(/~0/g, "~"); |
| 8 | +} |
| 9 | + |
| 10 | +function splitPointer(path: string): string[] { |
| 11 | + if (path === "") { |
| 12 | + throw new Error("Empty JSON Pointer path is not supported"); |
| 13 | + } |
| 14 | + if (!path.startsWith("/")) { |
| 15 | + throw new Error( |
| 16 | + `Only absolute JSON Pointer paths are supported, got: '${path}'` |
| 17 | + ); |
| 18 | + } |
| 19 | + const rawTokens = path.slice(1).split("/"); |
| 20 | + return rawTokens.filter((t) => t !== "").map(decodePointerToken); |
| 21 | +} |
| 22 | + |
| 23 | +function parseIndex(token: string, maxLen: number): number { |
| 24 | + const idx = parseInt(token, 10); |
| 25 | + if (isNaN(idx)) { |
| 26 | + throw new Error(`Array index must be an integer, got '${token}'`); |
| 27 | + } |
| 28 | + if (idx < 0 || idx >= maxLen) { |
| 29 | + throw new RangeError( |
| 30 | + `Array index ${idx} out of range (len=${maxLen})` |
| 31 | + ); |
| 32 | + } |
| 33 | + return idx; |
| 34 | +} |
| 35 | + |
| 36 | +function parseIndexForAdd(token: string, maxLen: number): number { |
| 37 | + const idx = parseInt(token, 10); |
| 38 | + if (isNaN(idx)) { |
| 39 | + throw new Error(`Array index must be an integer, got '${token}'`); |
| 40 | + } |
| 41 | + if (idx < 0 || idx > maxLen) { |
| 42 | + throw new RangeError( |
| 43 | + `Array index ${idx} out of range for add (len=${maxLen})` |
| 44 | + ); |
| 45 | + } |
| 46 | + return idx; |
| 47 | +} |
| 48 | + |
| 49 | +function traverseToParent(doc: JsonValue, path: string): [JsonValue, string] { |
| 50 | + const tokens = splitPointer(path); |
| 51 | + if (tokens.length === 0) { |
| 52 | + throw new Error( |
| 53 | + `Path '${path}' does not point to a child of the root` |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + let parent: JsonValue = doc; |
| 58 | + for (let i = 0; i < tokens.length - 1; i++) { |
| 59 | + const token = tokens[i]; |
| 60 | + if (Array.isArray(parent)) { |
| 61 | + const idx = parseIndex(token, parent.length); |
| 62 | + parent = parent[idx]; |
| 63 | + } else if (parent !== null && typeof parent === "object") { |
| 64 | + if (!(token in parent)) { |
| 65 | + throw new Error( |
| 66 | + `Path segment '${token}' not found while traversing '${path}'` |
| 67 | + ); |
| 68 | + } |
| 69 | + parent = (parent as JsonObject)[token]; |
| 70 | + } else { |
| 71 | + throw new TypeError( |
| 72 | + `Cannot traverse into non-container type at segment '${token}'` |
| 73 | + ); |
| 74 | + } |
| 75 | + } |
| 76 | + return [parent, tokens[tokens.length - 1]]; |
| 77 | +} |
| 78 | + |
| 79 | +function opAdd(doc: JsonValue, path: string, value: JsonValue): void { |
| 80 | + const [parent, token] = traverseToParent(doc, path); |
| 81 | + |
| 82 | + if (Array.isArray(parent)) { |
| 83 | + if (token === "-") { |
| 84 | + parent.push(value); |
| 85 | + return; |
| 86 | + } |
| 87 | + const idx = parseIndexForAdd(token, parent.length); |
| 88 | + parent.splice(idx, 0, value); |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + if (parent !== null && typeof parent === "object") { |
| 93 | + (parent as JsonObject)[token] = value; |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + throw new TypeError( |
| 98 | + `Cannot apply 'add' at '${path}': parent is not a container` |
| 99 | + ); |
| 100 | +} |
| 101 | + |
| 102 | +function opReplace(doc: JsonValue, path: string, value: JsonValue): void { |
| 103 | + const [parent, token] = traverseToParent(doc, path); |
| 104 | + |
| 105 | + if (Array.isArray(parent)) { |
| 106 | + const idx = parseIndex(token, parent.length); |
| 107 | + parent[idx] = value; |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + if (parent !== null && typeof parent === "object") { |
| 112 | + if (!(token in (parent as JsonObject))) { |
| 113 | + throw new Error( |
| 114 | + `Cannot 'replace' non-existent member '${token}' at '${path}'` |
| 115 | + ); |
| 116 | + } |
| 117 | + (parent as JsonObject)[token] = value; |
| 118 | + return; |
| 119 | + } |
| 120 | + |
| 121 | + throw new TypeError( |
| 122 | + `Cannot apply 'replace' at '${path}': parent is not a container` |
| 123 | + ); |
| 124 | +} |
| 125 | + |
| 126 | +function applyPatch(document: JsonValue, patch: JsonPatch): void { |
| 127 | + for (const op of patch) { |
| 128 | + const opType = op.op; |
| 129 | + const path = op.path; |
| 130 | + if (opType === undefined || path === undefined) { |
| 131 | + throw new Error(`Invalid JSON Patch operation: ${JSON.stringify(op)}`); |
| 132 | + } |
| 133 | + |
| 134 | + if (opType === "add") { |
| 135 | + opAdd(document, path, op.value as JsonValue); |
| 136 | + } else if (opType === "replace") { |
| 137 | + opReplace(document, path, op.value as JsonValue); |
| 138 | + } else { |
| 139 | + throw new Error( |
| 140 | + `Unsupported JSON Patch op: '${opType}' (only 'add' and 'replace' are allowed)` |
| 141 | + ); |
| 142 | + } |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +export function applyPatches( |
| 147 | + document: JsonObject, |
| 148 | + patchDocuments: JsonPatch[] |
| 149 | +): JsonObject { |
| 150 | + const result: JsonObject = JSON.parse(JSON.stringify(document)); |
| 151 | + for (const patch of patchDocuments) { |
| 152 | + applyPatch(result, patch); |
| 153 | + } |
| 154 | + return result; |
| 155 | +} |
0 commit comments