Skip to content

Commit

Permalink
🐛 Fix JsonPatch Formatter: Properly escape property name
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Gobinet committed Jul 30, 2024
1 parent bb534c1 commit 086c36b
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions packages/jsondiffpatch/src/formatters/jsonpatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ interface JSONFormatterContext extends BaseFormatterContext {
pushMoveOp: (to: number) => void;
currentPath: () => string;
toPath: (to: number) => string;
buildPath: (path: (string | number)[]) => string;
escapePath: (path: string | number) => string;
}

class JSONFormatter extends BaseFormatter<JSONFormatterContext, Op[]> {
Expand Down Expand Up @@ -89,14 +91,24 @@ class JSONFormatter extends BaseFormatter<JSONFormatterContext, Op[]> {
};

context.currentPath = function () {
return `/${this.path!.join('/')}`;
return `/${this.buildPath!(this.path!)}`;
};

context.toPath = function (toPath) {
const to = this.path!.slice();
to[to.length - 1] = toPath;
return `/${to.join('/')}`;
return `/${this.buildPath!(to)}`;
};

context.buildPath = function (path: (string | number)[]) {
return path.map((path) => this.escapePath!(path)).join('/')
}

context.escapePath = function (path: string | number) {
if (typeof path !== 'string') return path.toString();
if (path.indexOf('/') === -1 && path.indexOf('~') === -1) return path;
return path.replace(/~/g, '~0').replace(/\//g, '~1');
}
}

typeFormattterErrorFormatter(context: JSONFormatterContext, err: unknown) {
Expand Down

0 comments on commit 086c36b

Please sign in to comment.