@vielzeug/patchwork 0.0.0-stage → 26.11.13

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Helmuth Saatkamp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @vielzeug/patchwork
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ pnpm add @vielzeug/patchwork
9
+ npm install @vielzeug/patchwork
10
+ yarn add @vielzeug/patchwork
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```ts
16
+ import { apply, diff, tryApply } from '@vielzeug/patchwork';
17
+
18
+ const doc = { items: ['a'], title: 'Cart' };
19
+ const patch = diff(doc, { items: ['a', 'b'], title: 'Wagen' });
20
+ // [{ op: 'add', path: '/items/-', value: 'b' }, { op: 'replace', path: '/title', value: 'Wagen' }]
21
+
22
+ const next = apply(doc, patch); // doc untouched; untouched subtrees keep their identity
23
+
24
+ tryApply(doc, [{ op: 'test', path: '/title', value: 'Other' }]);
25
+ // { ok: false, error: { index: 0, path: '/title', reason: 'test', message: … } }
26
+ ```
27
+
28
+ Zero runtime dependencies. `apply` is copy-on-write, so memoized selectors recompute only
29
+ over the branches a patch actually touched; `tryApply` turns a failed `test` into data you
30
+ can log and reply to, which is what conflict handling in sync protocols needs.
31
+
32
+ ## Documentation
33
+
34
+ - [Overview](https://vielzeug.dev/patchwork/)
35
+ - [Usage Guide](https://vielzeug.dev/patchwork/usage)
36
+ - [API Reference](https://vielzeug.dev/patchwork/api)
37
+ - [Examples](https://vielzeug.dev/patchwork/examples)
38
+ - [Migration Guide](https://vielzeug.dev/patchwork/migration)
39
+
40
+ ## License
41
+
42
+ MIT © [Helmuth Saatkamp](https://github.com/helmuthdu): part of the [Vielzeug](https://github.com/helmuthdu/vielzeug) monorepo.
@@ -0,0 +1,2 @@
1
+ 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{};exports.PatchError=PatchError,exports.PatchPathError=PatchPathError,exports.PatchTestError=PatchTestError;
2
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","names":["message","options"],"sources":["../src/errors.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"],"mappings":"AACA,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,E"}
@@ -0,0 +1,11 @@
1
+ /** Base class for all patchwork errors. */
2
+ export declare class PatchError extends Error {
3
+ constructor(message: string, options?: ErrorOptions);
4
+ }
5
+ /** The document could not be patched because a pointer did not resolve. */
6
+ export declare class PatchPathError extends PatchError {
7
+ }
8
+ /** A `test` operation did not match the document. */
9
+ export declare class PatchTestError extends PatchError {
10
+ }
11
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,qBAAa,UAAW,SAAQ,KAAK;gBACvB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAKpD;AAED,2EAA2E;AAC3E,qBAAa,cAAe,SAAQ,UAAU;CAAG;AAEjD,qDAAqD;AACrD,qBAAa,cAAe,SAAQ,UAAU;CAAG"}
package/dist/errors.js ADDED
@@ -0,0 +1,9 @@
1
+ // src/errors.ts
2
+ var PatchError = class extends Error {
3
+ constructor(e, t) {
4
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
5
+ }
6
+ }, PatchPathError = class extends PatchError {}, PatchTestError = class extends PatchError {};
7
+ export { PatchError, PatchPathError, PatchTestError };
8
+
9
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":["message","options"],"sources":["../src/errors.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"],"mappings":";AACA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,GAAiB,GAAwB;EAGnD,AAFA,MAAMA,GAASC,CAAO,GACtB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,iBAAb,cAAoC,WAAW,CAAC,GAGnC,iBAAb,cAAoC,WAAW,CAAC"}
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./patch.cjs");exports.PatchError=e.PatchError,exports.PatchPathError=e.PatchPathError,exports.PatchTestError=e.PatchTestError,exports.apply=t.apply,exports.diff=t.diff,exports.formatPointer=t.formatPointer,exports.getIn=t.getIn,exports.parsePointer=t.parsePointer,exports.tryApply=t.tryApply;
@@ -0,0 +1,4 @@
1
+ export { PatchError, PatchPathError, PatchTestError } from './errors';
2
+ export { apply, diff, formatPointer, getIn, parsePointer, tryApply } from './patch';
3
+ export type { AddOperation, ApplyResult, CopyOperation, JsonObject, JsonPatch, JsonPointer, JsonValue, MoveOperation, PatchErrorInfo, PatchOperation, RemoveOperation, ReplaceOperation, TestOperation, } from './types';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACtE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACpF,YAAY,EACV,YAAY,EACZ,WAAW,EACX,aAAa,EACb,UAAU,EACV,SAAS,EACT,WAAW,EACX,SAAS,EACT,aAAa,EACb,cAAc,EACd,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,aAAa,GACd,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { PatchError as e, PatchPathError as t, PatchTestError as n } from "./errors.js";
2
+ import { apply as r, diff as i, formatPointer as a, getIn as o, parsePointer as s, tryApply as c } from "./patch.js";
3
+ export { e as PatchError, t as PatchPathError, n as PatchTestError, r as apply, i as diff, a as formatPointer, o as getIn, s as parsePointer, c as tryApply };
package/dist/patch.cjs ADDED
@@ -0,0 +1,2 @@
1
+ const e=require("./errors.cjs");function parsePointer(t){if(t===``)return[];if(!t.startsWith(`/`))throw new e.PatchPathError(`pointer "${t}" must start with "/"`);return t.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(t,n,r){let i=isArrayIndex(n);if(i<0||i>=t.length)throw new e.PatchPathError(`cannot ${r} at "/${n}": index out of bounds`);return i}function addIn(t,n,r){let[i=``,...a]=n;if(n.length===0)return r;if(Array.isArray(t)){if(i===`-`){if(a.length>0)throw new e.PatchPathError(`cannot add "/-": "-" must be the final token`);return[...t,r]}let n=isArrayIndex(i);if(n<0||n>t.length)throw new e.PatchPathError(`cannot add "/${i}": index out of bounds`);if(a.length>0){if(n===t.length)throw new e.PatchPathError(`cannot add "/${i}": index out of bounds`);return[...t.slice(0,n),addIn(t[n],a,r),...t.slice(n+1)]}return[...t.slice(0,n),r,...t.slice(n)]}if(isPlainObject(t)){if(a.length>0){if(!Object.hasOwn(t,i))throw new e.PatchPathError(`cannot add "/${i}": member does not exist`);return{...t,[i]:addIn(t[i],a,r)}}return Object.hasOwn(t,i)&&deepEqual(t[i],r)?t:{...t,[i]:r}}throw new e.PatchPathError(`cannot descend into a ${typeof t}`)}function replaceIn(t,n,r){let[i=``,...a]=n;if(n.length===0)return r;if(Array.isArray(t)){let e=descendArray(t,i,`replace`);return a.length===0?deepEqual(t[e],r)?t:[...t.slice(0,e),r,...t.slice(e+1)]:[...t.slice(0,e),replaceIn(t[e],a,r),...t.slice(e+1)]}if(isPlainObject(t)){if(!Object.hasOwn(t,i))throw new e.PatchPathError(`cannot replace "/${i}": member does not exist`);return a.length===0?deepEqual(t[i],r)?t:{...t,[i]:r}:{...t,[i]:replaceIn(t[i],a,r)}}throw new e.PatchPathError(`cannot descend into a ${typeof t}`)}function removeIn(t,n){let[r=``,...i]=n;if(n.length===0)return null;if(Array.isArray(t)){let e=descendArray(t,r,`remove`);return i.length===0?[...t.slice(0,e),...t.slice(e+1)]:[...t.slice(0,e),removeIn(t[e],i),...t.slice(e+1)]}if(isPlainObject(t)){if(!Object.hasOwn(t,r))throw new e.PatchPathError(`cannot remove "/${r}": member does not exist`);if(i.length===0){let e={...t};return delete e[r],e}return{...t,[r]:removeIn(t[r],i)}}throw new e.PatchPathError(`cannot descend into a ${typeof t}`)}function requireValue(t,n,r){let i=resolve(t,n);if(!i.exists)throw new e.PatchPathError(`pointer "${r}" does not resolve`);return i.value}function applyOperation(t,n){switch(n.op){case`add`:return addIn(t,parsePointer(n.path),structuredClone(n.value));case`remove`:return removeIn(t,parsePointer(n.path));case`replace`:return replaceIn(t,parsePointer(n.path),structuredClone(n.value));case`move`:{let e=requireValue(t,parsePointer(n.from),n.from);return addIn(removeIn(t,parsePointer(n.from)),parsePointer(n.path),e)}case`copy`:{let e=requireValue(t,parsePointer(n.from),n.from);return addIn(t,parsePointer(n.path),structuredClone(e))}case`test`:{let r=resolve(t,parsePointer(n.path));if(!r.exists||!deepEqual(r.value,n.value))throw new e.PatchTestError(`test failed at "${n.path}"`);return t}}}function apply(e,t){let n=e;for(let e of t)n=applyOperation(n,e);return n}function tryApply(t,n){let r=t;for(let t=0;t<n.length;t+=1){let i=n[t];try{r=applyOperation(r,i)}catch(n){let r=n instanceof e.PatchTestError?`test`:`path`,a=i.op===`move`||i.op===`copy`?i.from:i.path;return{error:{index:t,message:n.message,path:a,reason:r},ok:!1}}}return{doc:r,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.apply=apply,exports.diff=diff,exports.formatPointer=formatPointer,exports.getIn=getIn,exports.parsePointer=parsePointer,exports.tryApply=tryApply;
2
+ //# sourceMappingURL=patch.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patch.cjs","names":["PatchPathError","PatchTestError","require_errors","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/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":"A,gCAQA,SAAgB,aAAa,EAAgC,CAC3D,GAAIG,IAAY,GAAI,MAAO,CAAC,EAC5B,GAAI,CAACA,EAAQ,WAAW,GAAG,EAAG,MAAM,IAAIH,EAAAA,eAAe,YAAYG,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,OAAOC,EAAO,IAAK,GAAU,IAAID,EAAM,WAAW,IAAK,IAAI,CAAC,CAAC,WAAW,IAAK,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,CAC/F,CAEA,SAAS,cAAc,EAAmD,CACxE,OAAO,OAAOE,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAEA,SAAS,aAAa,EAAuB,CAC3C,GAAI,iBAAiB,KAAKF,CAAK,EAAG,CAChC,IAAMG,EAAQ,OAAOH,CAAK,EAC1B,OAAOG,WAAmCA,EAAQ,EACpD,CACA,MAAO,EACT,CAGA,SAAS,QAAQ,EAAgB,EAAmE,CAClG,IAAIC,EAAiCC,EACrC,IAAK,IAAML,KAASC,EAAQ,CAC1B,GAAI,MAAM,QAAQG,CAAO,EAAG,CAC1B,IAAMD,EAAQ,aAAaH,CAAK,EAChC,EAAUG,GAAS,GAAKA,EAAQC,EAAQ,OAASA,EAAQD,GAAS,IAAA,EACpE,MAAO,GAAI,cAAcC,CAAO,EAC9B,EAAU,OAAO,OAAOA,EAASJ,CAAK,EAAII,EAAQJ,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G,GAAKF,EAAY,IACtDC,EAAI,KAAK,CAAE,GAAI,SAAU,KAAM,GAAGL,EAAK,GAAGM,GAAI,CAAC,EAEjD,IAAK,IAAIA,EAAIF,EAAYE,EAAIJ,EAAG,OAASC,EAAQ,GAAK,EACpDE,EAAI,KAAK,CAAE,GAAI,MAAO,KAAM,GAAGL,EAAK,IAAK,MAAOE,EAAGI,EAAgB,CAAC,CAGxE,MACA,GAAI,cAAcL,CAAI,GAAK,cAAcC,CAAE,EAAG,CAC5C,IAAK,IAAMX,KAAO,OAAO,KAAKU,CAAI,EAC3B,OAAO,OAAOC,EAAIX,CAAG,GAAGc,EAAI,KAAK,CAAE,GAAI,SAAU,KAAM,GAAGL,IAAO,cAAc,CAACT,CAAG,CAAC,GAAI,CAAC,EAEhG,IAAK,IAAMA,KAAO,OAAO,KAAKW,CAAE,EAAG,CACjC,IAAMK,EAAY,GAAGP,IAAO,cAAc,CAACT,CAAG,CAAC,IACzCiB,EAAUN,EAAGX,GACd,OAAO,OAAOU,EAAMV,CAAG,EAG1B,SAASgB,EAAWN,EAAKV,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"}
@@ -0,0 +1,25 @@
1
+ import type { ApplyResult, JsonPatch, JsonPointer, JsonValue } from './types';
2
+ /** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */
3
+ export declare function parsePointer(pointer: JsonPointer): string[];
4
+ /** Escape and join reference tokens into a JSON Pointer. */
5
+ export declare function formatPointer(tokens: readonly string[]): JsonPointer;
6
+ /** Read the value a pointer targets; returns `undefined` when it does not resolve. */
7
+ export declare function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined;
8
+ /**
9
+ * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,
10
+ * so consumers can diff by reference afterwards. Throws {@link PatchPathError}
11
+ * when a pointer does not resolve and {@link PatchTestError} when a `test`
12
+ * operation does not match — use {@link tryApply} in protocol code where a
13
+ * rejection is an ordinary answer rather than an exception.
14
+ */
15
+ export declare function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T;
16
+ /** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */
17
+ export declare function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult;
18
+ /**
19
+ * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys
20
+ * diff field-by-field (the payload win sync protocols want); arrays trim
21
+ * their common suffix and emit ordered add/remove tails, so append-only
22
+ * lists stay small. The result applies cleanly via {@link apply}.
23
+ */
24
+ export declare function diff(from: JsonValue, to: JsonValue): JsonPatch;
25
+ //# sourceMappingURL=patch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patch.d.ts","sourceRoot":"","sources":["../src/patch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAc,SAAS,EAAE,WAAW,EAAE,SAAS,EAAkB,MAAM,SAAS,CAAC;AAM1G,mFAAmF;AACnF,wBAAgB,YAAY,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,EAAE,CAO3D;AAED,4DAA4D;AAC5D,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,WAAW,CAEpE;AA+BD,sFAAsF;AACtF,wBAAgB,KAAK,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,SAAS,CAEjF;AAgJD;;;;;;GAMG;AACH,wBAAgB,KAAK,CAAC,CAAC,SAAS,SAAS,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,GAAG,CAAC,CAItE;AAED,4GAA4G;AAC5G,wBAAgB,QAAQ,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,GAAG,WAAW,CAatE;AAgDD;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,GAAG,SAAS,CAI9D"}
package/dist/patch.js ADDED
@@ -0,0 +1,239 @@
1
+ import { PatchPathError as e, PatchTestError as t } from "./errors.js";
2
+ // 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", "~"));
7
+ }
8
+ function formatPointer(e) {
9
+ return e.map((e) => `/${e.replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
10
+ }
11
+ function isPlainObject(e) {
12
+ return typeof e == "object" && !!e && !Array.isArray(e);
13
+ }
14
+ function isArrayIndex(e) {
15
+ if (/^(0|[1-9]\d*)$/.test(e)) {
16
+ let t = Number(e);
17
+ return t <= 2 ** 53 - 1 ? t : -1;
18
+ }
19
+ return -1;
20
+ }
21
+ function resolve(e, t) {
22
+ let n = e;
23
+ for (let e of t) {
24
+ if (Array.isArray(n)) {
25
+ 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;
28
+ else return { exists: !1 };
29
+ if (n === void 0) return { exists: !1 };
30
+ }
31
+ return {
32
+ exists: !0,
33
+ value: n
34
+ };
35
+ }
36
+ function getIn(e, t) {
37
+ return resolve(e, parsePointer(t)).value;
38
+ }
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`);
51
+ return i;
52
+ }
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];
60
+ }
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`);
65
+ return [
66
+ ...t.slice(0, n),
67
+ addIn(t[n], a, r),
68
+ ...t.slice(n + 1)
69
+ ];
70
+ }
71
+ return [
72
+ ...t.slice(0, n),
73
+ r,
74
+ ...t.slice(n)
75
+ ];
76
+ }
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`);
80
+ return {
81
+ ...t,
82
+ [i]: addIn(t[i], a, r)
83
+ };
84
+ }
85
+ return Object.hasOwn(t, i) && deepEqual(t[i], r) ? t : {
86
+ ...t,
87
+ [i]: r
88
+ };
89
+ }
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)
101
+ ] : [
102
+ ...t.slice(0, e),
103
+ replaceIn(t[e], a, r),
104
+ ...t.slice(e + 1)
105
+ ];
106
+ }
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
112
+ } : {
113
+ ...t,
114
+ [i]: replaceIn(t[i], a, r)
115
+ };
116
+ }
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)
128
+ ];
129
+ }
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;
135
+ }
136
+ return {
137
+ ...t,
138
+ [r]: removeIn(t[r], i)
139
+ };
140
+ }
141
+ throw new e(`cannot descend into a ${typeof t}`);
142
+ }
143
+ function requireValue(t, n, r) {
144
+ let i = resolve(t, n);
145
+ if (!i.exists) throw new e(`pointer "${r}" does not resolve`);
146
+ return i.value;
147
+ }
148
+ function applyOperation(e, n) {
149
+ 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));
153
+ case "move": {
154
+ let t = requireValue(e, parsePointer(n.from), n.from);
155
+ return addIn(removeIn(e, parsePointer(n.from)), parsePointer(n.path), t);
156
+ }
157
+ case "copy": {
158
+ let t = requireValue(e, parsePointer(n.from), n.from);
159
+ return addIn(e, parsePointer(n.path), structuredClone(t));
160
+ }
161
+ 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;
165
+ }
166
+ }
167
+ }
168
+ function apply(e, t) {
169
+ let n = e;
170
+ for (let e of t) n = applyOperation(n, e);
171
+ return n;
172
+ }
173
+ function tryApply(e, n) {
174
+ let r = e;
175
+ for (let e = 0; e < n.length; e += 1) {
176
+ let i = n[e];
177
+ 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;
181
+ return {
182
+ error: {
183
+ index: e,
184
+ message: n.message,
185
+ path: a,
186
+ reason: r
187
+ },
188
+ ok: !1
189
+ };
190
+ }
191
+ }
192
+ return {
193
+ doc: r,
194
+ ok: !0
195
+ };
196
+ }
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({
205
+ op: "remove",
206
+ path: `${e}/${n}`
207
+ });
208
+ for (let t = a; t < n.length - i; t += 1) r.push({
209
+ op: "add",
210
+ path: `${e}/-`,
211
+ value: n[t]
212
+ });
213
+ } else if (isPlainObject(t) && isPlainObject(n)) {
214
+ for (let i of Object.keys(t)) Object.hasOwn(n, i) || r.push({
215
+ op: "remove",
216
+ path: `${e}${formatPointer([i])}`
217
+ });
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({
221
+ op: "add",
222
+ path: a,
223
+ value: o
224
+ });
225
+ }
226
+ } else r.push({
227
+ op: "replace",
228
+ path: e,
229
+ value: n
230
+ });
231
+ }
232
+ }
233
+ function diff(e, t) {
234
+ let n = [];
235
+ return diffNode("", e, t, n), n;
236
+ }
237
+ export { apply, diff, formatPointer, getIn, parsePointer, tryApply };
238
+
239
+ //# sourceMappingURL=patch.js.map
@@ -0,0 +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,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,CAAC,CAAC,KAAK,EAAE;AAC/F;AAEA,SAAS,cAAc,GAAmD;CACxE,OAAO,OAAOE,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAEA,SAAS,aAAa,GAAuB;CAC3C,IAAI,iBAAiB,KAAKF,CAAK,GAAG;EAChC,IAAMG,IAAQ,OAAOH,CAAK;EAC1B,OAAOG,mBAAmCA,IAAQ;CACpD;CACA,OAAO;AACT;AAGA,SAAS,QAAQ,GAAgB,GAAmE;CAClG,IAAIC,IAAiCC;CACrC,KAAK,IAAML,KAASC,GAAQ;EAC1B,IAAI,MAAM,QAAQG,CAAO,GAAG;GAC1B,IAAMD,IAAQ,aAAaH,CAAK;GAChC,IAAUG,KAAS,KAAKA,IAAQC,EAAQ,SAASA,EAAQD,KAAS,KAAA;EACpE,OAAO,IAAI,cAAcC,CAAO,GAC9B,IAAU,OAAO,OAAOA,GAASJ,CAAK,IAAII,EAAQJ,KAAS,KAAA;OA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,IAAIJ,EAAG,SAASC,GAAQ,KAAK,GACpD,EAAI,KAAK;IAAE,IAAI;IAAO,MAAM,GAAGH,EAAK;IAAK,OAAOE,EAAGI;GAAgB,CAAC;EAGxE,OACA,IAAI,cAAcL,CAAI,KAAK,cAAcC,CAAE,GAAG;GAC5C,KAAK,IAAMZ,KAAO,OAAO,KAAKW,CAAI,GAChC,AAAK,OAAO,OAAOC,GAAIZ,CAAG,KAAGe,EAAI,KAAK;IAAE,IAAI;IAAU,MAAM,GAAGL,IAAO,cAAc,CAACV,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"}
@@ -0,0 +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;
2
+ //# sourceMappingURL=patchwork.cjs.map
@@ -0,0 +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,UAA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E,EAAG,CAC5C,IAAK,IAAMX,KAAO,OAAO,KAAKU,CAAI,EAC3B,OAAO,OAAOC,EAAIX,CAAG,GAAGc,EAAI,KAAK,CAAE,GAAI,SAAU,KAAM,GAAGL,IAAO,cAAc,CAACT,CAAG,CAAC,GAAI,CAAC,EAEhG,IAAK,IAAMA,KAAO,OAAO,KAAKW,CAAE,EAAG,CACjC,IAAMK,EAAY,GAAGP,IAAO,cAAc,CAACT,CAAG,CAAC,IACzCiB,EAAUN,EAAGX,GACd,OAAO,OAAOU,EAAMV,CAAG,EAG1B,SAASgB,EAAWN,EAAKV,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"}
@@ -0,0 +1,2 @@
1
+ var Patchwork=(function(e){Object.defineProperty(e,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}return e.PatchError=PatchError,e.PatchPathError=PatchPathError,e.PatchTestError=PatchTestError,e.apply=apply,e.diff=diff,e.formatPointer=formatPointer,e.getIn=getIn,e.parsePointer=parsePointer,e.tryApply=tryApply,e})({});
2
+ //# sourceMappingURL=patchwork.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patchwork.iife.js","names":["exports","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,wFACA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACnD,MAAMC,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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GAAI,CAAC,EAEhG,IAAK,IAAMA,KAAO,OAAO,KAAKW,CAAE,EAAG,CACjC,IAAMK,EAAY,GAAGP,IAAO,cAAc,CAACT,CAAG,CAAC,IACzCiB,EAAUN,EAAGX,GACd,OAAO,OAAOU,EAAMV,CAAG,EAG1B,SAASgB,EAAWN,EAAKV,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"}
@@ -0,0 +1,244 @@
1
+ // src/errors.ts
2
+ var PatchError = class extends Error {
3
+ constructor(e, t) {
4
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
5
+ }
6
+ }, PatchPathError = class extends PatchError {}, PatchTestError = class extends PatchError {};
7
+ // src/patch.ts
8
+ function parsePointer(e) {
9
+ if (e === "") return [];
10
+ if (!e.startsWith("/")) throw new PatchPathError(`pointer "${e}" must start with "/"`);
11
+ return e.slice(1).split("/").map((e) => e.replaceAll("~1", "/").replaceAll("~0", "~"));
12
+ }
13
+ function formatPointer(e) {
14
+ return e.map((e) => `/${e.replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
15
+ }
16
+ function isPlainObject(e) {
17
+ return typeof e == "object" && !!e && !Array.isArray(e);
18
+ }
19
+ function isArrayIndex(e) {
20
+ if (/^(0|[1-9]\d*)$/.test(e)) {
21
+ let t = Number(e);
22
+ return t <= 2 ** 53 - 1 ? t : -1;
23
+ }
24
+ return -1;
25
+ }
26
+ function resolve(e, t) {
27
+ let n = e;
28
+ for (let e of t) {
29
+ if (Array.isArray(n)) {
30
+ let t = isArrayIndex(e);
31
+ n = t >= 0 && t < n.length ? n[t] : void 0;
32
+ } else if (isPlainObject(n)) n = Object.hasOwn(n, e) ? n[e] : void 0;
33
+ else return { exists: !1 };
34
+ if (n === void 0) return { exists: !1 };
35
+ }
36
+ return {
37
+ exists: !0,
38
+ value: n
39
+ };
40
+ }
41
+ function getIn(e, t) {
42
+ return resolve(e, parsePointer(t)).value;
43
+ }
44
+ function deepEqual(e, t) {
45
+ if (e === t) return !0;
46
+ if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => deepEqual(e, t[n]));
47
+ if (isPlainObject(e) && isPlainObject(t)) {
48
+ let n = Object.keys(e), r = Object.keys(t);
49
+ return n.length === r.length && n.every((n) => Object.hasOwn(t, n) && deepEqual(e[n], t[n]));
50
+ }
51
+ return !1;
52
+ }
53
+ function descendArray(e, t, n) {
54
+ let r = isArrayIndex(t);
55
+ if (r < 0 || r >= e.length) throw new PatchPathError(`cannot ${n} at "/${t}": index out of bounds`);
56
+ return r;
57
+ }
58
+ function addIn(e, t, n) {
59
+ let [r = "", ...i] = t;
60
+ if (t.length === 0) return n;
61
+ if (Array.isArray(e)) {
62
+ if (r === "-") {
63
+ if (i.length > 0) throw new PatchPathError("cannot add \"/-\": \"-\" must be the final token");
64
+ return [...e, n];
65
+ }
66
+ let t = isArrayIndex(r);
67
+ if (t < 0 || t > e.length) throw new PatchPathError(`cannot add "/${r}": index out of bounds`);
68
+ if (i.length > 0) {
69
+ if (t === e.length) throw new PatchPathError(`cannot add "/${r}": index out of bounds`);
70
+ return [
71
+ ...e.slice(0, t),
72
+ addIn(e[t], i, n),
73
+ ...e.slice(t + 1)
74
+ ];
75
+ }
76
+ return [
77
+ ...e.slice(0, t),
78
+ n,
79
+ ...e.slice(t)
80
+ ];
81
+ }
82
+ if (isPlainObject(e)) {
83
+ if (i.length > 0) {
84
+ if (!Object.hasOwn(e, r)) throw new PatchPathError(`cannot add "/${r}": member does not exist`);
85
+ return {
86
+ ...e,
87
+ [r]: addIn(e[r], i, n)
88
+ };
89
+ }
90
+ return Object.hasOwn(e, r) && deepEqual(e[r], n) ? e : {
91
+ ...e,
92
+ [r]: n
93
+ };
94
+ }
95
+ throw new PatchPathError(`cannot descend into a ${typeof e}`);
96
+ }
97
+ function replaceIn(e, t, n) {
98
+ let [r = "", ...i] = t;
99
+ if (t.length === 0) return n;
100
+ if (Array.isArray(e)) {
101
+ let t = descendArray(e, r, "replace");
102
+ return i.length === 0 ? deepEqual(e[t], n) ? e : [
103
+ ...e.slice(0, t),
104
+ n,
105
+ ...e.slice(t + 1)
106
+ ] : [
107
+ ...e.slice(0, t),
108
+ replaceIn(e[t], i, n),
109
+ ...e.slice(t + 1)
110
+ ];
111
+ }
112
+ if (isPlainObject(e)) {
113
+ if (!Object.hasOwn(e, r)) throw new PatchPathError(`cannot replace "/${r}": member does not exist`);
114
+ return i.length === 0 ? deepEqual(e[r], n) ? e : {
115
+ ...e,
116
+ [r]: n
117
+ } : {
118
+ ...e,
119
+ [r]: replaceIn(e[r], i, n)
120
+ };
121
+ }
122
+ throw new PatchPathError(`cannot descend into a ${typeof e}`);
123
+ }
124
+ function removeIn(e, t) {
125
+ let [n = "", ...r] = t;
126
+ if (t.length === 0) return null;
127
+ if (Array.isArray(e)) {
128
+ let t = descendArray(e, n, "remove");
129
+ return r.length === 0 ? [...e.slice(0, t), ...e.slice(t + 1)] : [
130
+ ...e.slice(0, t),
131
+ removeIn(e[t], r),
132
+ ...e.slice(t + 1)
133
+ ];
134
+ }
135
+ if (isPlainObject(e)) {
136
+ if (!Object.hasOwn(e, n)) throw new PatchPathError(`cannot remove "/${n}": member does not exist`);
137
+ if (r.length === 0) {
138
+ let t = { ...e };
139
+ return delete t[n], t;
140
+ }
141
+ return {
142
+ ...e,
143
+ [n]: removeIn(e[n], r)
144
+ };
145
+ }
146
+ throw new PatchPathError(`cannot descend into a ${typeof e}`);
147
+ }
148
+ function requireValue(e, t, n) {
149
+ let r = resolve(e, t);
150
+ if (!r.exists) throw new PatchPathError(`pointer "${n}" does not resolve`);
151
+ return r.value;
152
+ }
153
+ function applyOperation(e, t) {
154
+ switch (t.op) {
155
+ case "add": return addIn(e, parsePointer(t.path), structuredClone(t.value));
156
+ case "remove": return removeIn(e, parsePointer(t.path));
157
+ case "replace": return replaceIn(e, parsePointer(t.path), structuredClone(t.value));
158
+ case "move": {
159
+ let n = requireValue(e, parsePointer(t.from), t.from);
160
+ return addIn(removeIn(e, parsePointer(t.from)), parsePointer(t.path), n);
161
+ }
162
+ case "copy": {
163
+ let n = requireValue(e, parsePointer(t.from), t.from);
164
+ return addIn(e, parsePointer(t.path), structuredClone(n));
165
+ }
166
+ case "test": {
167
+ let n = resolve(e, parsePointer(t.path));
168
+ if (!n.exists || !deepEqual(n.value, t.value)) throw new PatchTestError(`test failed at "${t.path}"`);
169
+ return e;
170
+ }
171
+ }
172
+ }
173
+ function apply(e, t) {
174
+ let n = e;
175
+ for (let e of t) n = applyOperation(n, e);
176
+ return n;
177
+ }
178
+ function tryApply(e, t) {
179
+ let n = e;
180
+ for (let e = 0; e < t.length; e += 1) {
181
+ let r = t[e];
182
+ try {
183
+ n = applyOperation(n, r);
184
+ } catch (t) {
185
+ let n = t instanceof PatchTestError ? "test" : "path", i = r.op === "move" || r.op === "copy" ? r.from : r.path;
186
+ return {
187
+ error: {
188
+ index: e,
189
+ message: t.message,
190
+ path: i,
191
+ reason: n
192
+ },
193
+ ok: !1
194
+ };
195
+ }
196
+ }
197
+ return {
198
+ doc: n,
199
+ ok: !0
200
+ };
201
+ }
202
+ function diffNode(e, t, n, r) {
203
+ if (!deepEqual(t, n)) {
204
+ if (Array.isArray(t) && Array.isArray(n)) {
205
+ let i = 0;
206
+ for (; i < Math.min(t.length, n.length) && deepEqual(t[t.length - 1 - i], n[n.length - 1 - i]);) i += 1;
207
+ let a = Math.min(t.length, n.length) - i;
208
+ for (let i = 0; i < a; i += 1) diffNode(`${e}/${i}`, t[i], n[i], r);
209
+ for (let n = t.length - 1 - i; n >= a; --n) r.push({
210
+ op: "remove",
211
+ path: `${e}/${n}`
212
+ });
213
+ for (let t = a; t < n.length - i; t += 1) r.push({
214
+ op: "add",
215
+ path: `${e}/-`,
216
+ value: n[t]
217
+ });
218
+ } else if (isPlainObject(t) && isPlainObject(n)) {
219
+ for (let i of Object.keys(t)) Object.hasOwn(n, i) || r.push({
220
+ op: "remove",
221
+ path: `${e}${formatPointer([i])}`
222
+ });
223
+ for (let i of Object.keys(n)) {
224
+ let a = `${e}${formatPointer([i])}`, o = n[i];
225
+ Object.hasOwn(t, i) ? diffNode(a, t[i], o, r) : r.push({
226
+ op: "add",
227
+ path: a,
228
+ value: o
229
+ });
230
+ }
231
+ } else r.push({
232
+ op: "replace",
233
+ path: e,
234
+ value: n
235
+ });
236
+ }
237
+ }
238
+ function diff(e, t) {
239
+ let n = [];
240
+ return diffNode("", e, t, n), n;
241
+ }
242
+ export { PatchError, PatchPathError, PatchTestError, apply, diff, formatPointer, getIn, parsePointer, tryApply };
243
+
244
+ //# sourceMappingURL=patchwork.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patchwork.js","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":";AACA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,GAAiB,GAAwB;EAGnD,AAFA,MAAMA,GAASC,CAAO,GACtB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,iBAAb,cAAoC,WAAW,CAAC,GAGnC,iBAAb,cAAoC,WAAW,CAAC;;ACLhD,SAAgB,aAAa,GAAgC;CAC3D,IAAIC,MAAY,IAAI,OAAO,CAAC;CAC5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;IAAE,IAAI;IAAU,MAAM,GAAGL,IAAO,cAAc,CAACT,CAAG,CAAC;GAAI,CAAC;GAEhG,KAAK,IAAMA,KAAO,OAAO,KAAKW,CAAE,GAAG;IACjC,IAAMK,IAAY,GAAGP,IAAO,cAAc,CAACT,CAAG,CAAC,KACzCiB,IAAUN,EAAGX;IACnB,AAAK,OAAO,OAAOU,GAAMV,CAAG,IAG1B,SAASgB,GAAWN,EAAKV,IAAmBiB,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"}
@@ -0,0 +1,59 @@
1
+ /** A JSON value: the only shape patchwork reads and writes. */
2
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ /** An object value (the target of most patches). */
6
+ export type JsonObject = {
7
+ [key: string]: JsonValue;
8
+ };
9
+ /** RFC 6901 JSON Pointer, e.g. `/address/street` or `/items/0`. */
10
+ export type JsonPointer = string;
11
+ export type AddOperation = {
12
+ op: 'add';
13
+ path: JsonPointer;
14
+ value: JsonValue;
15
+ };
16
+ export type RemoveOperation = {
17
+ op: 'remove';
18
+ path: JsonPointer;
19
+ };
20
+ export type ReplaceOperation = {
21
+ op: 'replace';
22
+ path: JsonPointer;
23
+ value: JsonValue;
24
+ };
25
+ export type MoveOperation = {
26
+ op: 'move';
27
+ from: JsonPointer;
28
+ path: JsonPointer;
29
+ };
30
+ export type CopyOperation = {
31
+ op: 'copy';
32
+ from: JsonPointer;
33
+ path: JsonPointer;
34
+ };
35
+ export type TestOperation = {
36
+ op: 'test';
37
+ path: JsonPointer;
38
+ value: JsonValue;
39
+ };
40
+ /** One RFC 6902 operation. */
41
+ export type PatchOperation = AddOperation | CopyOperation | MoveOperation | RemoveOperation | ReplaceOperation | TestOperation;
42
+ /** An RFC 6902 JSON Patch: an ordered list of operations. */
43
+ export type JsonPatch = readonly PatchOperation[];
44
+ /** Result of {@link tryApply}. Never throws: a failed `test` is data, not an exception. */
45
+ export type ApplyResult = {
46
+ doc: JsonValue;
47
+ ok: true;
48
+ } | {
49
+ error: PatchErrorInfo;
50
+ ok: false;
51
+ };
52
+ /** A machine-readable description of why a patch was rejected. */
53
+ export type PatchErrorInfo = {
54
+ index: number;
55
+ message: string;
56
+ path: JsonPointer;
57
+ reason: 'path' | 'test';
58
+ };
59
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,MAAM,MAAM,SAAS,GAAG,IAAI,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEtG,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEtD,mEAAmE;AACnE,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC;AAEjC,MAAM,MAAM,YAAY,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,SAAS,CAAA;CAAE,CAAC;AAC9E,MAAM,MAAM,eAAe,GAAG;IAAE,EAAE,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC;AAClE,MAAM,MAAM,gBAAgB,GAAG;IAAE,EAAE,EAAE,SAAS,CAAC;IAAC,IAAI,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,SAAS,CAAA;CAAE,CAAC;AACtF,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC;AACjF,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC;AACjF,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,SAAS,CAAA;CAAE,CAAC;AAEhF,8BAA8B;AAC9B,MAAM,MAAM,cAAc,GACtB,YAAY,GACZ,aAAa,GACb,aAAa,GACb,eAAe,GACf,gBAAgB,GAChB,aAAa,CAAC;AAElB,6DAA6D;AAC7D,MAAM,MAAM,SAAS,GAAG,SAAS,cAAc,EAAE,CAAC;AAElD,2FAA2F;AAC3F,MAAM,MAAM,WAAW,GAAG;IAAE,GAAG,EAAE,SAAS,CAAC;IAAC,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,cAAc,CAAC;IAAC,EAAE,EAAE,KAAK,CAAA;CAAE,CAAC;AAE9F,kEAAkE;AAClE,MAAM,MAAM,cAAc,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,WAAW,CAAC;IAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@vielzeug/patchwork",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "26.11.13",
4
+ "description": "RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/helmuthdu/vielzeug",
8
+ "directory": "packages/patchwork"
9
+ },
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=22"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.js",
20
+ "types": "dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "import": "./dist/index.js",
24
+ "require": "./dist/index.cjs",
25
+ "types": "./dist/index.d.ts"
26
+ }
27
+ },
28
+ "sideEffects": false,
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "scripts": {
34
+ "build": "vite build && bun run --silent build:bundle && bun run --silent build:types",
35
+ "build:bundle": "vite build --config vite.bundle.config.ts",
36
+ "build:types": "tsc -p tsconfig.declarations.json",
37
+ "fix": "biome check --write src",
38
+ "lint": "biome ci src",
39
+ "prepublishOnly": "bun run --silent build",
40
+ "test": "vitest"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^26.6.6",
44
+ "typescript": "^6.0.3",
45
+ "vite": "^8.3.6",
46
+ "vitest": "^5.1.0"
47
+ }
48
+ }