@vielzeug/patchwork 26.11.13 → 26.11.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/patch.js CHANGED
@@ -1,16 +1,14 @@
1
- import { PatchPathError as e, PatchTestError as t } from "./errors.js";
1
+ import { deepEqual as e, isPlainObject as t } from "./_equality.js";
2
+ import { PatchPathError as n, PatchTestError as r } from "./errors.js";
2
3
  // src/patch.ts
3
- function parsePointer(t) {
4
- if (t === "") return [];
5
- if (!t.startsWith("/")) throw new e(`pointer "${t}" must start with "/"`);
6
- return t.slice(1).split("/").map((e) => e.replaceAll("~1", "/").replaceAll("~0", "~"));
4
+ function parsePointer(e) {
5
+ if (e === "") return [];
6
+ if (!e.startsWith("/")) throw new n(`pointer "${e}" must start with "/"`);
7
+ return e.slice(1).split("/").map((e) => e.replaceAll("~1", "/").replaceAll("~0", "~"));
7
8
  }
8
9
  function formatPointer(e) {
9
10
  return e.map((e) => `/${e.replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
10
11
  }
11
- function isPlainObject(e) {
12
- return typeof e == "object" && !!e && !Array.isArray(e);
13
- }
14
12
  function isArrayIndex(e) {
15
13
  if (/^(0|[1-9]\d*)$/.test(e)) {
16
14
  let t = Number(e);
@@ -18,150 +16,151 @@ function isArrayIndex(e) {
18
16
  }
19
17
  return -1;
20
18
  }
21
- function resolve(e, t) {
22
- let n = e;
23
- for (let e of t) {
24
- if (Array.isArray(n)) {
19
+ function resolve(e, n) {
20
+ let r = e;
21
+ for (let e of n) {
22
+ if (Array.isArray(r)) {
25
23
  let t = isArrayIndex(e);
26
- n = t >= 0 && t < n.length ? n[t] : void 0;
27
- } else if (isPlainObject(n)) n = Object.hasOwn(n, e) ? n[e] : void 0;
24
+ r = t >= 0 && t < r.length ? r[t] : void 0;
25
+ } else if (t(r)) r = Object.hasOwn(r, e) ? r[e] : void 0;
28
26
  else return { exists: !1 };
29
- if (n === void 0) return { exists: !1 };
27
+ if (r === void 0) return { exists: !1 };
30
28
  }
31
29
  return {
32
30
  exists: !0,
33
- value: n
31
+ value: r
34
32
  };
35
33
  }
36
34
  function getIn(e, t) {
37
35
  return resolve(e, parsePointer(t)).value;
38
36
  }
39
- function deepEqual(e, t) {
40
- if (e === t) return !0;
41
- if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => deepEqual(e, t[n]));
42
- if (isPlainObject(e) && isPlainObject(t)) {
43
- let n = Object.keys(e), r = Object.keys(t);
44
- return n.length === r.length && n.every((n) => Object.hasOwn(t, n) && deepEqual(e[n], t[n]));
45
- }
46
- return !1;
47
- }
48
- function descendArray(t, n, r) {
49
- let i = isArrayIndex(n);
50
- if (i < 0 || i >= t.length) throw new e(`cannot ${r} at "/${n}": index out of bounds`);
37
+ function descendArray(e, t, r) {
38
+ let i = isArrayIndex(t);
39
+ if (i < 0 || i >= e.length) throw new n(`cannot ${r} at "/${t}": index out of bounds`);
51
40
  return i;
52
41
  }
53
- function addIn(t, n, r) {
54
- let [i = "", ...a] = n;
55
- if (n.length === 0) return r;
56
- if (Array.isArray(t)) {
57
- if (i === "-") {
58
- if (a.length > 0) throw new e("cannot add \"/-\": \"-\" must be the final token");
59
- return [...t, r];
42
+ function addIn(r, i, a) {
43
+ let [o = "", ...s] = i;
44
+ if (i.length === 0) return a;
45
+ if (Array.isArray(r)) {
46
+ if (o === "-") {
47
+ if (s.length > 0) throw new n("cannot add \"/-\": \"-\" must be the final token");
48
+ return [...r, a];
60
49
  }
61
- let n = isArrayIndex(i);
62
- if (n < 0 || n > t.length) throw new e(`cannot add "/${i}": index out of bounds`);
63
- if (a.length > 0) {
64
- if (n === t.length) throw new e(`cannot add "/${i}": index out of bounds`);
50
+ let e = isArrayIndex(o);
51
+ if (e < 0 || e > r.length) throw new n(`cannot add "/${o}": index out of bounds`);
52
+ if (s.length > 0) {
53
+ if (e === r.length) throw new n(`cannot add "/${o}": index out of bounds`);
65
54
  return [
66
- ...t.slice(0, n),
67
- addIn(t[n], a, r),
68
- ...t.slice(n + 1)
55
+ ...r.slice(0, e),
56
+ addIn(r[e], s, a),
57
+ ...r.slice(e + 1)
69
58
  ];
70
59
  }
71
60
  return [
72
- ...t.slice(0, n),
73
- r,
74
- ...t.slice(n)
61
+ ...r.slice(0, e),
62
+ a,
63
+ ...r.slice(e)
75
64
  ];
76
65
  }
77
- if (isPlainObject(t)) {
78
- if (a.length > 0) {
79
- if (!Object.hasOwn(t, i)) throw new e(`cannot add "/${i}": member does not exist`);
66
+ if (t(r)) {
67
+ if (s.length > 0) {
68
+ if (!Object.hasOwn(r, o)) throw new n(`cannot add "/${o}": member does not exist`);
80
69
  return {
81
- ...t,
82
- [i]: addIn(t[i], a, r)
70
+ ...r,
71
+ [o]: addIn(r[o], s, a)
83
72
  };
84
73
  }
85
- return Object.hasOwn(t, i) && deepEqual(t[i], r) ? t : {
86
- ...t,
87
- [i]: r
74
+ return Object.hasOwn(r, o) && e(r[o], a) ? r : {
75
+ ...r,
76
+ [o]: a
88
77
  };
89
78
  }
90
- throw new e(`cannot descend into a ${typeof t}`);
91
- }
92
- function replaceIn(t, n, r) {
93
- let [i = "", ...a] = n;
94
- if (n.length === 0) return r;
95
- if (Array.isArray(t)) {
96
- let e = descendArray(t, i, "replace");
97
- return a.length === 0 ? deepEqual(t[e], r) ? t : [
98
- ...t.slice(0, e),
99
- r,
100
- ...t.slice(e + 1)
79
+ throw new n(`cannot descend into a ${typeof r}`);
80
+ }
81
+ function replaceIn(r, i, a) {
82
+ let [o = "", ...s] = i;
83
+ if (i.length === 0) return a;
84
+ if (Array.isArray(r)) {
85
+ let t = descendArray(r, o, "replace");
86
+ return s.length === 0 ? e(r[t], a) ? r : [
87
+ ...r.slice(0, t),
88
+ a,
89
+ ...r.slice(t + 1)
101
90
  ] : [
102
- ...t.slice(0, e),
103
- replaceIn(t[e], a, r),
104
- ...t.slice(e + 1)
91
+ ...r.slice(0, t),
92
+ replaceIn(r[t], s, a),
93
+ ...r.slice(t + 1)
105
94
  ];
106
95
  }
107
- if (isPlainObject(t)) {
108
- if (!Object.hasOwn(t, i)) throw new e(`cannot replace "/${i}": member does not exist`);
109
- return a.length === 0 ? deepEqual(t[i], r) ? t : {
110
- ...t,
111
- [i]: r
96
+ if (t(r)) {
97
+ if (!Object.hasOwn(r, o)) throw new n(`cannot replace "/${o}": member does not exist`);
98
+ return s.length === 0 ? e(r[o], a) ? r : {
99
+ ...r,
100
+ [o]: a
112
101
  } : {
113
- ...t,
114
- [i]: replaceIn(t[i], a, r)
102
+ ...r,
103
+ [o]: replaceIn(r[o], s, a)
115
104
  };
116
105
  }
117
- throw new e(`cannot descend into a ${typeof t}`);
118
- }
119
- function removeIn(t, n) {
120
- let [r = "", ...i] = n;
121
- if (n.length === 0) return null;
122
- if (Array.isArray(t)) {
123
- let e = descendArray(t, r, "remove");
124
- return i.length === 0 ? [...t.slice(0, e), ...t.slice(e + 1)] : [
125
- ...t.slice(0, e),
126
- removeIn(t[e], i),
127
- ...t.slice(e + 1)
106
+ throw new n(`cannot descend into a ${typeof r}`);
107
+ }
108
+ function removeIn(e, r) {
109
+ let [i = "", ...a] = r;
110
+ if (r.length === 0) return null;
111
+ if (Array.isArray(e)) {
112
+ let t = descendArray(e, i, "remove");
113
+ return a.length === 0 ? [...e.slice(0, t), ...e.slice(t + 1)] : [
114
+ ...e.slice(0, t),
115
+ removeIn(e[t], a),
116
+ ...e.slice(t + 1)
128
117
  ];
129
118
  }
130
- if (isPlainObject(t)) {
131
- if (!Object.hasOwn(t, r)) throw new e(`cannot remove "/${r}": member does not exist`);
132
- if (i.length === 0) {
133
- let e = { ...t };
134
- return delete e[r], e;
119
+ if (t(e)) {
120
+ if (!Object.hasOwn(e, i)) throw new n(`cannot remove "/${i}": member does not exist`);
121
+ if (a.length === 0) {
122
+ let t = { ...e };
123
+ return delete t[i], t;
135
124
  }
136
125
  return {
137
- ...t,
138
- [r]: removeIn(t[r], i)
126
+ ...e,
127
+ [i]: removeIn(e[i], a)
139
128
  };
140
129
  }
141
- throw new e(`cannot descend into a ${typeof t}`);
130
+ throw new n(`cannot descend into a ${typeof e}`);
142
131
  }
143
- function requireValue(t, n, r) {
144
- let i = resolve(t, n);
145
- if (!i.exists) throw new e(`pointer "${r}" does not resolve`);
132
+ function requireValue(e, t, r) {
133
+ let i = resolve(e, t);
134
+ if (!i.exists) throw new n(`pointer "${r}" does not resolve`, { pointer: r });
146
135
  return i.value;
147
136
  }
148
- function applyOperation(e, n) {
137
+ function at(e, t) {
138
+ try {
139
+ return t();
140
+ } catch (t) {
141
+ throw t instanceof n && t.pointer === void 0 ? new n(t.message, {
142
+ cause: t,
143
+ pointer: e
144
+ }) : t;
145
+ }
146
+ }
147
+ function applyOperation(t, n) {
149
148
  switch (n.op) {
150
- case "add": return addIn(e, parsePointer(n.path), structuredClone(n.value));
151
- case "remove": return removeIn(e, parsePointer(n.path));
152
- case "replace": return replaceIn(e, parsePointer(n.path), structuredClone(n.value));
149
+ case "add": return at(n.path, () => addIn(t, parsePointer(n.path), structuredClone(n.value)));
150
+ case "remove": return at(n.path, () => removeIn(t, parsePointer(n.path)));
151
+ case "replace": return at(n.path, () => replaceIn(t, parsePointer(n.path), structuredClone(n.value)));
153
152
  case "move": {
154
- let t = requireValue(e, parsePointer(n.from), n.from);
155
- return addIn(removeIn(e, parsePointer(n.from)), parsePointer(n.path), t);
153
+ let e = at(n.from, () => requireValue(t, parsePointer(n.from), n.from)), r = at(n.from, () => removeIn(t, parsePointer(n.from)));
154
+ return at(n.path, () => addIn(r, parsePointer(n.path), e));
156
155
  }
157
156
  case "copy": {
158
- let t = requireValue(e, parsePointer(n.from), n.from);
159
- return addIn(e, parsePointer(n.path), structuredClone(t));
157
+ let e = at(n.from, () => requireValue(t, parsePointer(n.from), n.from));
158
+ return at(n.path, () => addIn(t, parsePointer(n.path), structuredClone(e)));
160
159
  }
161
160
  case "test": {
162
- let r = resolve(e, parsePointer(n.path));
163
- if (!r.exists || !deepEqual(r.value, n.value)) throw new t(`test failed at "${n.path}"`);
164
- return e;
161
+ let i = resolve(t, parsePointer(n.path));
162
+ if (!i.exists || !e(i.value, n.value)) throw new r(`test failed at "${n.path}"`);
163
+ return t;
165
164
  }
166
165
  }
167
166
  }
@@ -170,63 +169,66 @@ function apply(e, t) {
170
169
  for (let e of t) n = applyOperation(n, e);
171
170
  return n;
172
171
  }
173
- function tryApply(e, n) {
174
- let r = e;
175
- for (let e = 0; e < n.length; e += 1) {
176
- let i = n[e];
172
+ function tryApply(e, t) {
173
+ let i = e;
174
+ for (let e = 0; e < t.length; e += 1) {
175
+ let a = t[e];
177
176
  try {
178
- r = applyOperation(r, i);
179
- } catch (n) {
180
- let r = n instanceof t ? "test" : "path", a = i.op === "move" || i.op === "copy" ? i.from : i.path;
177
+ i = applyOperation(i, a);
178
+ } catch (t) {
179
+ let i = t instanceof r ? "test" : "path", o = t instanceof n ? t.pointer ?? a.path : a.path;
181
180
  return {
182
181
  error: {
183
182
  index: e,
184
- message: n.message,
185
- path: a,
186
- reason: r
183
+ message: t.message,
184
+ path: o,
185
+ reason: i
187
186
  },
188
187
  ok: !1
189
188
  };
190
189
  }
191
190
  }
192
191
  return {
193
- doc: r,
192
+ doc: i,
194
193
  ok: !0
195
194
  };
196
195
  }
197
- function diffNode(e, t, n, r) {
198
- if (!deepEqual(t, n)) {
199
- if (Array.isArray(t) && Array.isArray(n)) {
200
- let i = 0;
201
- for (; i < Math.min(t.length, n.length) && deepEqual(t[t.length - 1 - i], n[n.length - 1 - i]);) i += 1;
202
- let a = Math.min(t.length, n.length) - i;
203
- for (let i = 0; i < a; i += 1) diffNode(`${e}/${i}`, t[i], n[i], r);
204
- for (let n = t.length - 1 - i; n >= a; --n) r.push({
196
+ function diffNode(n, r, i, a) {
197
+ if (!e(r, i)) {
198
+ if (Array.isArray(r) && Array.isArray(i)) {
199
+ let t = Math.min(r.length, i.length), o = 0;
200
+ for (; o < t && e(r[o], i[o]);) o += 1;
201
+ let s = 0;
202
+ for (; s < t - o && e(r[r.length - 1 - s], i[i.length - 1 - s]);) s += 1;
203
+ let c = r.length - s, l = i.length - s, u = Math.min(c, l) - o;
204
+ for (let e = o; e < o + u; e += 1) diffNode(`${n}/${e}`, r[e], i[e], a);
205
+ for (let e = c - 1; e >= o + u; --e) a.push({
205
206
  op: "remove",
206
- path: `${e}/${n}`
207
+ path: `${n}/${e}`
207
208
  });
208
- for (let t = a; t < n.length - i; t += 1) r.push({
209
+ let d = s === 0;
210
+ for (let e = o + u; e < l; e += 1) a.push({
209
211
  op: "add",
210
- path: `${e}/-`,
211
- value: n[t]
212
+ path: d ? `${n}/-` : `${n}/${e}`,
213
+ value: i[e]
212
214
  });
213
- } else if (isPlainObject(t) && isPlainObject(n)) {
214
- for (let i of Object.keys(t)) Object.hasOwn(n, i) || r.push({
215
+ } else if (t(r) && t(i)) {
216
+ for (let e of Object.keys(r)) Object.hasOwn(i, e) || a.push({
215
217
  op: "remove",
216
- path: `${e}${formatPointer([i])}`
218
+ path: `${n}${formatPointer([e])}`
217
219
  });
218
- for (let i of Object.keys(n)) {
219
- let a = `${e}${formatPointer([i])}`, o = n[i];
220
- Object.hasOwn(t, i) ? diffNode(a, t[i], o, r) : r.push({
220
+ for (let e of Object.keys(i)) {
221
+ let t = `${n}${formatPointer([e])}`, o = i[e];
222
+ Object.hasOwn(r, e) ? diffNode(t, r[e], o, a) : a.push({
221
223
  op: "add",
222
- path: a,
224
+ path: t,
223
225
  value: o
224
226
  });
225
227
  }
226
- } else r.push({
228
+ } else a.push({
227
229
  op: "replace",
228
- path: e,
229
- value: n
230
+ path: n,
231
+ value: i
230
232
  });
231
233
  }
232
234
  }
package/dist/patch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"patch.js","names":["pointer","PatchPathError","token","tokens","value","index","current","doc","a","b","item","aKeys","bKeys","key","action","rest","next","found","operation","PatchTestError","patch","error","reason","path","from","to","common","headLength","ops","i","childPath","toValue"],"sources":["../src/patch.ts"],"sourcesContent":["import { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Structural equality (JSON domain: no NaN/undefined/prototype concerns)\n// ---------------------------------------------------------------------------\n\nfunction deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`);\n return found.value as JsonValue;\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return addIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'remove':\n return removeIn(doc, parsePointer(operation.path));\n case 'replace':\n return replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'move': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(removeIn(doc, parsePointer(operation.from)), parsePointer(operation.path), value);\n }\n case 'copy': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(doc, parsePointer(operation.path), structuredClone(value));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = operation.op === 'move' || operation.op === 'copy' ? operation.from : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Trim the common suffix, then walk positionally: equal entries skip,\n // changed entries recurse, surplus tails add or remove in apply-safe order.\n let common = 0;\n while (\n common < Math.min(from.length, to.length) &&\n deepEqual(from[from.length - 1 - common] as JsonValue, to[to.length - 1 - common] as JsonValue)\n ) {\n common += 1;\n }\n const headLength = Math.min(from.length, to.length) - common;\n for (let i = 0; i < headLength; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = from.length - 1 - common; i >= headLength; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n for (let i = headLength; i < to.length - common; i += 1) {\n ops.push({ op: 'add', path: `${path}/-`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays trim\n * their common suffix and emit ordered add/remove tails, so append-only\n * lists stay small. The result applies cleanly via {@link apply}.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":";;AAQA,SAAgB,aAAa,GAAgC;CAC3D,IAAIA,MAAY,IAAI,OAAO,CAAC;CAC5B,IAAI,CAACA,EAAQ,WAAW,GAAG,GAAG,MAAM,IAAIC,EAA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AACV,CAAG,CAAC;GAAI,CAAC;GAEhG,KAAK,IAAMA,KAAO,OAAO,KAAKY,CAAE,GAAG;IACjC,IAAMK,IAAY,GAAGP,IAAO,cAAc,CAACV,CAAG,CAAC,KACzCkB,IAAUN,EAAGZ;IACnB,AAAK,OAAO,OAAOW,GAAMX,CAAG,IAG1B,SAASiB,GAAWN,EAAKX,IAAmBkB,GAASH,CAAG,IAFxDA,EAAI,KAAK;KAAE,IAAI;KAAO,MAAME;KAAW,OAAOC;IAAQ,CAAC;GAI3D;EAEF,OACA,EAAI,KAAK;GAAE,IAAI;GAAW;GAAM,OAAON;EAAG,CAAC;CAhB3C;AAiBF;AAQA,SAAgB,KAAK,GAAiB,GAA0B;CAC9D,IAAMG,IAAwB,CAAC;CAE/B,OADA,SAAS,IAAIJ,GAAMC,GAAIG,CAAG,GACnBA;AACT"}
1
+ {"version":3,"file":"patch.js","names":["pointer","PatchPathError","token","tokens","index","current","doc","isPlainObject","action","rest","value","deepEqual","next","found","run","error","operation","removed","PatchTestError","patch","reason","path","from","to","shared","head","tail","fromMiddle","toMiddle","overlap","i","ops","appends","key","childPath","toValue"],"sources":["../src/patch.ts"],"sourcesContent":["import { deepEqual, isPlainObject } from './_equality';\nimport { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`, { pointer });\n return found.value as JsonValue;\n}\n\n/** Attributes path failures thrown inside `run` to `pointer` (the caller's full pointer). */\nfunction at<T>(pointer: JsonPointer, run: () => T): T {\n try {\n return run();\n } catch (error) {\n if (error instanceof PatchPathError && error.pointer === undefined) {\n throw new PatchPathError(error.message, { cause: error, pointer });\n }\n throw error;\n }\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'remove':\n return at(operation.path, () => removeIn(doc, parsePointer(operation.path)));\n case 'replace':\n return at(operation.path, () => replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'move': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n const removed = at(operation.from, () => removeIn(doc, parsePointer(operation.from)));\n return at(operation.path, () => addIn(removed, parsePointer(operation.path), value));\n }\n case 'copy': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(value)));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = error instanceof PatchPathError ? (error.pointer ?? operation.path) : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Align on the common prefix and (non-overlapping) common suffix, recurse positionally\n // through the middle, then let surplus removals fall off the middle's tail (descending)\n // and surplus inserts land in ascending index order. True appends keep the `-` token.\n const shared = Math.min(from.length, to.length);\n let head = 0;\n while (head < shared && deepEqual(from[head] as JsonValue, to[head] as JsonValue)) head += 1;\n let tail = 0;\n while (\n tail < shared - head &&\n deepEqual(from[from.length - 1 - tail] as JsonValue, to[to.length - 1 - tail] as JsonValue)\n ) {\n tail += 1;\n }\n const fromMiddle = from.length - tail; // exclusive end of from's middle\n const toMiddle = to.length - tail; // exclusive end of to's middle\n const overlap = Math.min(fromMiddle, toMiddle) - head;\n for (let i = head; i < head + overlap; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = fromMiddle - 1; i >= head + overlap; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n const appends = tail === 0; // surplus only ever lands at the end when no tail is shared\n for (let i = head + overlap; i < toMiddle; i += 1) {\n ops.push({ op: 'add', path: appends ? `${path}/-` : `${path}/${i}`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays align\n * on their common prefix and suffix and emit ordered removals and indexed\n * inserts around a positionally diffed middle, so appends, prepends, and\n * middle inserts each stay one operation. Not minimal-edit: a reorder\n * diffs positionally. The result always round-trips:\n * `apply(from, diff(from, to))` deep-equals `to`.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":";;;AASA,SAAgB,aAAa,GAAgC;CAC3D,IAAIA,MAAY,IAAI,OAAO,CAAC;CAC5B,IAAI,CAACA,EAAQ,WAAW,GAAG,GAAG,MAAM,IAAIC,EAAe,YAAYD,EAAQ,sBAAsB;CACjG,OAAOA,EACJ,MAAM,CAAC,CAAC,CACR,MAAM,GAAG,CAAC,CACV,KAAK,MAAUE,EAAM,WAAW,MAAM,GAAG,CAAC,CAAC,WAAW,MAAM,GAAG,CAAC;AACrE;AAGA,SAAgB,cAAc,GAAwC;CACpE,OAAOC,EAAO,KAAK,MAAU,IAAID,EAAM,WAAW,KAAK,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI,GAAG,C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,CAAG,IAG1B,SAASC,GAAWZ,EAAKW,IAAmBE,GAASJ,CAAG,IAFxDA,EAAI,KAAK;KAAE,IAAI;KAAO,MAAMG;KAAW,OAAOC;IAAQ,CAAC;GAI3D;EAEF,OACA,EAAI,KAAK;GAAE,IAAI;GAAW;GAAM,OAAOZ;EAAG,CAAC;CAhB3C;AAiBF;AAWA,SAAgB,KAAK,GAAiB,GAA0B;CAC9D,IAAMQ,IAAwB,CAAC;CAE/B,OADA,SAAS,IAAIT,GAAMC,GAAIQ,CAAG,GACnBA;AACT"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var PatchError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},PatchPathError=class extends PatchError{},PatchTestError=class extends PatchError{};function parsePointer(e){if(e===``)return[];if(!e.startsWith(`/`))throw new PatchPathError(`pointer "${e}" must start with "/"`);return e.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`))}function formatPointer(e){return e.map(e=>`/${e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`).join(``)}function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isArrayIndex(e){if(/^(0|[1-9]\d*)$/.test(e)){let t=Number(e);return t<=2**53-1?t:-1}return-1}function resolve(e,t){let n=e;for(let e of t){if(Array.isArray(n)){let t=isArrayIndex(e);n=t>=0&&t<n.length?n[t]:void 0}else if(isPlainObject(n))n=Object.hasOwn(n,e)?n[e]:void 0;else return{exists:!1};if(n===void 0)return{exists:!1}}return{exists:!0,value:n}}function getIn(e,t){return resolve(e,parsePointer(t)).value}function deepEqual(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>deepEqual(e,t[n]));if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&deepEqual(e[n],t[n]))}return!1}function descendArray(e,t,n){let r=isArrayIndex(t);if(r<0||r>=e.length)throw new PatchPathError(`cannot ${n} at "/${t}": index out of bounds`);return r}function addIn(e,t,n){let[r=``,...i]=t;if(t.length===0)return n;if(Array.isArray(e)){if(r===`-`){if(i.length>0)throw new PatchPathError(`cannot add "/-": "-" must be the final token`);return[...e,n]}let t=isArrayIndex(r);if(t<0||t>e.length)throw new PatchPathError(`cannot add "/${r}": index out of bounds`);if(i.length>0){if(t===e.length)throw new PatchPathError(`cannot add "/${r}": index out of bounds`);return[...e.slice(0,t),addIn(e[t],i,n),...e.slice(t+1)]}return[...e.slice(0,t),n,...e.slice(t)]}if(isPlainObject(e)){if(i.length>0){if(!Object.hasOwn(e,r))throw new PatchPathError(`cannot add "/${r}": member does not exist`);return{...e,[r]:addIn(e[r],i,n)}}return Object.hasOwn(e,r)&&deepEqual(e[r],n)?e:{...e,[r]:n}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function replaceIn(e,t,n){let[r=``,...i]=t;if(t.length===0)return n;if(Array.isArray(e)){let t=descendArray(e,r,`replace`);return i.length===0?deepEqual(e[t],n)?e:[...e.slice(0,t),n,...e.slice(t+1)]:[...e.slice(0,t),replaceIn(e[t],i,n),...e.slice(t+1)]}if(isPlainObject(e)){if(!Object.hasOwn(e,r))throw new PatchPathError(`cannot replace "/${r}": member does not exist`);return i.length===0?deepEqual(e[r],n)?e:{...e,[r]:n}:{...e,[r]:replaceIn(e[r],i,n)}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function removeIn(e,t){let[n=``,...r]=t;if(t.length===0)return null;if(Array.isArray(e)){let t=descendArray(e,n,`remove`);return r.length===0?[...e.slice(0,t),...e.slice(t+1)]:[...e.slice(0,t),removeIn(e[t],r),...e.slice(t+1)]}if(isPlainObject(e)){if(!Object.hasOwn(e,n))throw new PatchPathError(`cannot remove "/${n}": member does not exist`);if(r.length===0){let t={...e};return delete t[n],t}return{...e,[n]:removeIn(e[n],r)}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function requireValue(e,t,n){let r=resolve(e,t);if(!r.exists)throw new PatchPathError(`pointer "${n}" does not resolve`);return r.value}function applyOperation(e,t){switch(t.op){case`add`:return addIn(e,parsePointer(t.path),structuredClone(t.value));case`remove`:return removeIn(e,parsePointer(t.path));case`replace`:return replaceIn(e,parsePointer(t.path),structuredClone(t.value));case`move`:{let n=requireValue(e,parsePointer(t.from),t.from);return addIn(removeIn(e,parsePointer(t.from)),parsePointer(t.path),n)}case`copy`:{let n=requireValue(e,parsePointer(t.from),t.from);return addIn(e,parsePointer(t.path),structuredClone(n))}case`test`:{let n=resolve(e,parsePointer(t.path));if(!n.exists||!deepEqual(n.value,t.value))throw new PatchTestError(`test failed at "${t.path}"`);return e}}}function apply(e,t){let n=e;for(let e of t)n=applyOperation(n,e);return n}function tryApply(e,t){let n=e;for(let e=0;e<t.length;e+=1){let r=t[e];try{n=applyOperation(n,r)}catch(t){let n=t instanceof PatchTestError?`test`:`path`,i=r.op===`move`||r.op===`copy`?r.from:r.path;return{error:{index:e,message:t.message,path:i,reason:n},ok:!1}}}return{doc:n,ok:!0}}function diffNode(e,t,n,r){if(!deepEqual(t,n)){if(Array.isArray(t)&&Array.isArray(n)){let i=0;for(;i<Math.min(t.length,n.length)&&deepEqual(t[t.length-1-i],n[n.length-1-i]);)i+=1;let a=Math.min(t.length,n.length)-i;for(let i=0;i<a;i+=1)diffNode(`${e}/${i}`,t[i],n[i],r);for(let n=t.length-1-i;n>=a;--n)r.push({op:`remove`,path:`${e}/${n}`});for(let t=a;t<n.length-i;t+=1)r.push({op:`add`,path:`${e}/-`,value:n[t]})}else if(isPlainObject(t)&&isPlainObject(n)){for(let i of Object.keys(t))Object.hasOwn(n,i)||r.push({op:`remove`,path:`${e}${formatPointer([i])}`});for(let i of Object.keys(n)){let a=`${e}${formatPointer([i])}`,o=n[i];Object.hasOwn(t,i)?diffNode(a,t[i],o,r):r.push({op:`add`,path:a,value:o})}}else r.push({op:`replace`,path:e,value:n})}}function diff(e,t){let n=[];return diffNode(``,e,t,n),n}exports.PatchError=PatchError,exports.PatchPathError=PatchPathError,exports.PatchTestError=PatchTestError,exports.apply=apply,exports.diff=diff,exports.formatPointer=formatPointer,exports.getIn=getIn,exports.parsePointer=parsePointer,exports.tryApply=tryApply;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var PatchError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},PatchPathError=class extends PatchError{pointer;constructor(e,t){super(e,t),this.pointer=t?.pointer}},PatchTestError=class extends PatchError{};function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function deepEqual(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>deepEqual(e,t[n]));if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&deepEqual(e[n],t[n]))}return!1}function parsePointer(e){if(e===``)return[];if(!e.startsWith(`/`))throw new PatchPathError(`pointer "${e}" must start with "/"`);return e.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`))}function formatPointer(e){return e.map(e=>`/${e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`).join(``)}function isArrayIndex(e){if(/^(0|[1-9]\d*)$/.test(e)){let t=Number(e);return t<=2**53-1?t:-1}return-1}function resolve(e,t){let n=e;for(let e of t){if(Array.isArray(n)){let t=isArrayIndex(e);n=t>=0&&t<n.length?n[t]:void 0}else if(isPlainObject(n))n=Object.hasOwn(n,e)?n[e]:void 0;else return{exists:!1};if(n===void 0)return{exists:!1}}return{exists:!0,value:n}}function getIn(e,t){return resolve(e,parsePointer(t)).value}function descendArray(e,t,n){let r=isArrayIndex(t);if(r<0||r>=e.length)throw new PatchPathError(`cannot ${n} at "/${t}": index out of bounds`);return r}function addIn(e,t,n){let[r=``,...i]=t;if(t.length===0)return n;if(Array.isArray(e)){if(r===`-`){if(i.length>0)throw new PatchPathError(`cannot add "/-": "-" must be the final token`);return[...e,n]}let t=isArrayIndex(r);if(t<0||t>e.length)throw new PatchPathError(`cannot add "/${r}": index out of bounds`);if(i.length>0){if(t===e.length)throw new PatchPathError(`cannot add "/${r}": index out of bounds`);return[...e.slice(0,t),addIn(e[t],i,n),...e.slice(t+1)]}return[...e.slice(0,t),n,...e.slice(t)]}if(isPlainObject(e)){if(i.length>0){if(!Object.hasOwn(e,r))throw new PatchPathError(`cannot add "/${r}": member does not exist`);return{...e,[r]:addIn(e[r],i,n)}}return Object.hasOwn(e,r)&&deepEqual(e[r],n)?e:{...e,[r]:n}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function replaceIn(e,t,n){let[r=``,...i]=t;if(t.length===0)return n;if(Array.isArray(e)){let t=descendArray(e,r,`replace`);return i.length===0?deepEqual(e[t],n)?e:[...e.slice(0,t),n,...e.slice(t+1)]:[...e.slice(0,t),replaceIn(e[t],i,n),...e.slice(t+1)]}if(isPlainObject(e)){if(!Object.hasOwn(e,r))throw new PatchPathError(`cannot replace "/${r}": member does not exist`);return i.length===0?deepEqual(e[r],n)?e:{...e,[r]:n}:{...e,[r]:replaceIn(e[r],i,n)}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function removeIn(e,t){let[n=``,...r]=t;if(t.length===0)return null;if(Array.isArray(e)){let t=descendArray(e,n,`remove`);return r.length===0?[...e.slice(0,t),...e.slice(t+1)]:[...e.slice(0,t),removeIn(e[t],r),...e.slice(t+1)]}if(isPlainObject(e)){if(!Object.hasOwn(e,n))throw new PatchPathError(`cannot remove "/${n}": member does not exist`);if(r.length===0){let t={...e};return delete t[n],t}return{...e,[n]:removeIn(e[n],r)}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function requireValue(e,t,n){let r=resolve(e,t);if(!r.exists)throw new PatchPathError(`pointer "${n}" does not resolve`,{pointer:n});return r.value}function at(e,t){try{return t()}catch(t){throw t instanceof PatchPathError&&t.pointer===void 0?new PatchPathError(t.message,{cause:t,pointer:e}):t}}function applyOperation(e,t){switch(t.op){case`add`:return at(t.path,()=>addIn(e,parsePointer(t.path),structuredClone(t.value)));case`remove`:return at(t.path,()=>removeIn(e,parsePointer(t.path)));case`replace`:return at(t.path,()=>replaceIn(e,parsePointer(t.path),structuredClone(t.value)));case`move`:{let n=at(t.from,()=>requireValue(e,parsePointer(t.from),t.from)),r=at(t.from,()=>removeIn(e,parsePointer(t.from)));return at(t.path,()=>addIn(r,parsePointer(t.path),n))}case`copy`:{let n=at(t.from,()=>requireValue(e,parsePointer(t.from),t.from));return at(t.path,()=>addIn(e,parsePointer(t.path),structuredClone(n)))}case`test`:{let n=resolve(e,parsePointer(t.path));if(!n.exists||!deepEqual(n.value,t.value))throw new PatchTestError(`test failed at "${t.path}"`);return e}}}function apply(e,t){let n=e;for(let e of t)n=applyOperation(n,e);return n}function tryApply(e,t){let n=e;for(let e=0;e<t.length;e+=1){let r=t[e];try{n=applyOperation(n,r)}catch(t){let n=t instanceof PatchTestError?`test`:`path`,i=t instanceof PatchPathError?t.pointer??r.path:r.path;return{error:{index:e,message:t.message,path:i,reason:n},ok:!1}}}return{doc:n,ok:!0}}function diffNode(e,t,n,r){if(!deepEqual(t,n)){if(Array.isArray(t)&&Array.isArray(n)){let i=Math.min(t.length,n.length),a=0;for(;a<i&&deepEqual(t[a],n[a]);)a+=1;let o=0;for(;o<i-a&&deepEqual(t[t.length-1-o],n[n.length-1-o]);)o+=1;let s=t.length-o,c=n.length-o,l=Math.min(s,c)-a;for(let i=a;i<a+l;i+=1)diffNode(`${e}/${i}`,t[i],n[i],r);for(let t=s-1;t>=a+l;--t)r.push({op:`remove`,path:`${e}/${t}`});let u=o===0;for(let t=a+l;t<c;t+=1)r.push({op:`add`,path:u?`${e}/-`:`${e}/${t}`,value:n[t]})}else if(isPlainObject(t)&&isPlainObject(n)){for(let i of Object.keys(t))Object.hasOwn(n,i)||r.push({op:`remove`,path:`${e}${formatPointer([i])}`});for(let i of Object.keys(n)){let a=`${e}${formatPointer([i])}`,o=n[i];Object.hasOwn(t,i)?diffNode(a,t[i],o,r):r.push({op:`add`,path:a,value:o})}}else r.push({op:`replace`,path:e,value:n})}}function diff(e,t){let n=[];return diffNode(``,e,t,n),n}exports.PatchError=PatchError,exports.PatchPathError=PatchPathError,exports.PatchTestError=PatchTestError,exports.apply=apply,exports.diff=diff,exports.formatPointer=formatPointer,exports.getIn=getIn,exports.parsePointer=parsePointer,exports.tryApply=tryApply;
2
2
  //# sourceMappingURL=patchwork.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"patchwork.cjs","names":["message","options","pointer","token","tokens","value","index","current","doc","a","b","item","aKeys","bKeys","key","action","rest","next","found","operation","patch","error","reason","path","from","to","common","headLength","ops","i","childPath","toValue"],"sources":["../src/errors.ts","../src/patch.ts"],"sourcesContent":["/** Base class for all patchwork errors. */\nexport class PatchError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** The document could not be patched because a pointer did not resolve. */\nexport class PatchPathError extends PatchError {}\n\n/** A `test` operation did not match the document. */\nexport class PatchTestError extends PatchError {}\n","import { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Structural equality (JSON domain: no NaN/undefined/prototype concerns)\n// ---------------------------------------------------------------------------\n\nfunction deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`);\n return found.value as JsonValue;\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return addIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'remove':\n return removeIn(doc, parsePointer(operation.path));\n case 'replace':\n return replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'move': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(removeIn(doc, parsePointer(operation.from)), parsePointer(operation.path), value);\n }\n case 'copy': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(doc, parsePointer(operation.path), structuredClone(value));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = operation.op === 'move' || operation.op === 'copy' ? operation.from : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Trim the common suffix, then walk positionally: equal entries skip,\n // changed entries recurse, surplus tails add or remove in apply-safe order.\n let common = 0;\n while (\n common < Math.min(from.length, to.length) &&\n deepEqual(from[from.length - 1 - common] as JsonValue, to[to.length - 1 - common] as JsonValue)\n ) {\n common += 1;\n }\n const headLength = Math.min(from.length, to.length) - common;\n for (let i = 0; i < headLength; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = from.length - 1 - common; i >= headLength; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n for (let i = headLength; i < to.length - common; i += 1) {\n ops.push({ op: 'add', path: `${path}/-`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays trim\n * their common suffix and emit ordered add/remove tails, so append-only\n * lists stay small. The result applies cleanly via {@link apply}.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":"A,mEACA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACnD,MAAMA,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,eAAb,cAAoC,UAAW,CAAC,EAGnC,eAAb,cAAoC,UAAW,CAAC,ECLhD,SAAgB,aAAa,EAAgC,CAC3D,GAAIC,IAAY,GAAI,MAAO,CAAC,EAC5B,GAAI,CAACA,EAAQ,WAAW,GAAG,EAAG,MAAM,IAAI,eAAe,YAAYA,EAAQ,sBAAsB,EACjG,OAAOA,EACJ,MAAM,CAAC,CAAC,CACR,MAAM,GAAG,CAAC,CACV,IAAK,GAAUC,EAAM,WAAW,KAAM,GAAG,CAAC,CAAC,WAAW,KAAM,GAAG,CAAC,CACrE,CAGA,SAAgB,cAAc,EAAwC,CACpE,O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,GAAmBiB,EAASH,CAAG,EAFxDA,EAAI,KAAK,CAAE,GAAI,MAAO,KAAME,EAAW,MAAOC,CAAQ,CAAC,CAI3D,CAEF,MACAH,EAAI,KAAK,CAAE,GAAI,UAAW,OAAM,MAAOH,CAAG,CAAC,CAhB3C,CAiBF,CAQA,SAAgB,KAAK,EAAiB,EAA0B,CAC9D,IAAMG,EAAwB,CAAC,EAE/B,OADA,SAAS,GAAIJ,EAAMC,EAAIG,CAAG,EACnBA,CACT,C"}
1
+ {"version":3,"file":"patchwork.cjs","names":["message","options","value","a","b","item","index","aKeys","bKeys","key","pointer","token","tokens","current","doc","action","rest","next","found","run","error","operation","removed","patch","reason","path","from","to","shared","head","tail","fromMiddle","toMiddle","overlap","ops","i","appends","childPath","toValue"],"sources":["../src/errors.ts","../src/_equality.ts","../src/patch.ts"],"sourcesContent":["import type { JsonPointer } from './types';\n\n/** Base class for all patchwork errors. */\nexport class PatchError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * The document could not be patched because a pointer did not resolve. `pointer` names the\n * offending pointer when the library can attribute one (the failing `path` of a `move` is\n * not its `from`).\n */\nexport class PatchPathError extends PatchError {\n readonly pointer: JsonPointer | undefined;\n\n constructor(message: string, options?: ErrorOptions & { pointer?: JsonPointer }) {\n super(message, options);\n this.pointer = options?.pointer;\n }\n}\n\n/** A `test` operation did not match the document. */\nexport class PatchTestError extends PatchError {}\n","/**\n * Internal JSON-domain helpers shared by the patch engine and the merge module.\n * Never re-exported from the package barrel.\n */\nimport type { JsonObject, JsonValue } from './types';\n\nexport function isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Structural equality over the JSON domain: no NaN/undefined/prototype concerns. */\nexport function deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n","import { deepEqual, isPlainObject } from './_equality';\nimport { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`, { pointer });\n return found.value as JsonValue;\n}\n\n/** Attributes path failures thrown inside `run` to `pointer` (the caller's full pointer). */\nfunction at<T>(pointer: JsonPointer, run: () => T): T {\n try {\n return run();\n } catch (error) {\n if (error instanceof PatchPathError && error.pointer === undefined) {\n throw new PatchPathError(error.message, { cause: error, pointer });\n }\n throw error;\n }\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'remove':\n return at(operation.path, () => removeIn(doc, parsePointer(operation.path)));\n case 'replace':\n return at(operation.path, () => replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'move': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n const removed = at(operation.from, () => removeIn(doc, parsePointer(operation.from)));\n return at(operation.path, () => addIn(removed, parsePointer(operation.path), value));\n }\n case 'copy': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(value)));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = error instanceof PatchPathError ? (error.pointer ?? operation.path) : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Align on the common prefix and (non-overlapping) common suffix, recurse positionally\n // through the middle, then let surplus removals fall off the middle's tail (descending)\n // and surplus inserts land in ascending index order. True appends keep the `-` token.\n const shared = Math.min(from.length, to.length);\n let head = 0;\n while (head < shared && deepEqual(from[head] as JsonValue, to[head] as JsonValue)) head += 1;\n let tail = 0;\n while (\n tail < shared - head &&\n deepEqual(from[from.length - 1 - tail] as JsonValue, to[to.length - 1 - tail] as JsonValue)\n ) {\n tail += 1;\n }\n const fromMiddle = from.length - tail; // exclusive end of from's middle\n const toMiddle = to.length - tail; // exclusive end of to's middle\n const overlap = Math.min(fromMiddle, toMiddle) - head;\n for (let i = head; i < head + overlap; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = fromMiddle - 1; i >= head + overlap; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n const appends = tail === 0; // surplus only ever lands at the end when no tail is shared\n for (let i = head + overlap; i < toMiddle; i += 1) {\n ops.push({ op: 'add', path: appends ? `${path}/-` : `${path}/${i}`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays align\n * on their common prefix and suffix and emit ordered removals and indexed\n * inserts around a positionally diffed middle, so appends, prepends, and\n * middle inserts each stay one operation. Not minimal-edit: a reorder\n * diffs positionally. The result always round-trips:\n * `apply(from, diff(from, to))` deep-equals `to`.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":"A,mEAGA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACnD,MAAMA,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,eAAb,cAAoC,UAAW,CAC7C,QAEA,YAAY,EAAiB,EAAoD,CAC/E,MAAMD,EAASC,CAAO,EACtB,KAAK,QAAUA,GAAS,OAC1B,CACF,EAGa,eAAb,cAAoC,UAAW,CAAC,ECpBhD,SAAgB,cAAc,EAAmD,CAC/E,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAGA,SAAgB,UAAU,EAAc,EAAuB,CAC7D,GAAIC,IAAMC,EAAG,MAAO,GACpB,GAAI,MAAM,QAAQD,CAAC,GAAK,MAAM,QAAQC,CAAC,EACrC,OAAOD,EAAE,SAAWC,EAAE,QAAUD,EAAE,OAAO,EAAM,IAAU,UAAUE,EAAMD,EAAEE,EAAmB,CAAC,EAEjG,GAAI,cAAcH,CAAC,GAAK,cAAcC,CAAC,EAAG,CACxC,IAAMG,EAAQ,OAAO,KAAKJ,CAAC,EACrBK,EAAQ,OAAO,KAAKJ,CAAC,EAC3B,OACEG,EAAM,SAAWC,EAAM,QACvBD,EAAM,MAAO,GAAQ,OAAO,OAAOH,EAAGK,CAAG,GAAK,UAAUN,EAAEM,GAAmBL,EAAEK,EAAiB,CAAC,CAErG,CACA,MAAO,EACT,CChBA,SAAg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