From 138b1019f1fb2d58c0ee8a1f8f92c31573f36953 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20B=C3=B6hm?= Date: Thu, 1 Oct 2020 11:06:16 -0700 Subject: [PATCH] feat(stringify): Escape unsafe characters --- src/stringify.spec.ts | 22 ++++++++++++++++++++++ src/stringify.ts | 14 ++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 src/stringify.spec.ts diff --git a/src/stringify.spec.ts b/src/stringify.spec.ts new file mode 100644 index 00000000..37a9a7d6 --- /dev/null +++ b/src/stringify.spec.ts @@ -0,0 +1,22 @@ +import { readFileSync } from "fs"; +import { parse, stringify } from "."; +import { tests } from "./__fixtures__/tests"; + +describe("Stringify & re-parse", () => { + describe("Own tests", () => { + for (const [selector, expected, message] of tests) { + test(`${message} (${selector})`, () => { + expect(parse(stringify(expected))).toStrictEqual(expected); + }); + } + }); + + it("Collected Selectors (qwery, sizzle, nwmatcher)", () => { + const out = JSON.parse( + readFileSync(`${__dirname}/__fixtures__/out.json`, "utf8") + ); + for (const s of Object.keys(out)) { + expect(parse(s)).toStrictEqual(out[s]); + } + }); +}); diff --git a/src/stringify.ts b/src/stringify.ts index b38c038f..a4a9d873 100644 --- a/src/stringify.ts +++ b/src/stringify.ts @@ -10,6 +10,14 @@ const actionTypes: { [key: string]: string } = { hyphen: "|", }; +const charsToEscape = new Set([ + ...Object.values(actionTypes).filter(Boolean), + ":", + "[", + "]", + " ", +]); + export default function stringify(token: Selector[][]): string { return token.map(stringifySubselector).join(", "); } @@ -73,6 +81,8 @@ function stringifyToken(token: Selector): string { } function escapeName(str: string): string { - // TODO - return str; + return str + .split("") + .map((c) => (charsToEscape.has(c) ? `\\${c}` : c)) + .join(""); }