Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix JsonPatch Formatter: Properly escape property name #372

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,13 +91,23 @@ 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');
};
}

Expand Down
6 changes: 6 additions & 0 deletions packages/jsondiffpatch/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,12 @@ describe('DiffPatcher', () => {
});
expectFormat(before, after, diff);
});

it('should escape the property name', () => {
expectFormat({ 'tree/item': 1 }, { 'tree/item': 2 }, [
replaceOp('/tree~1item', 2),
]);
});
});

describe('html', () => {
Expand Down
Loading