Skip to content

Commit

Permalink
feat: rule no-unormalized-keys
Browse files Browse the repository at this point in the history
Fixes eslint#32
  • Loading branch information
bmeck committed Oct 7, 2024
1 parent cac8847 commit 73a61ad
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/rules/no-unnormalized-keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @fileoverview Rule to detect unnormalized keys in JSON.
* @author Bradley Meck Farias
*/

export default {
meta: {
type: "problem",

docs: {
description: "Disallow JSON keys that are not normalized",
},

messages: {
unnormalizedKey: "Unnormalized key found.",
},

schema: {
type: "array",
minItems: 0,
maxItems: 1,
items: {
enum: ["NFC", "NFD", "NFKC", "NFKD"],
},
},
},

create(context) {
const normalization = context.options.length
? s => s.normalize(context.options[0])
: s => s.normalize();
return {
Member(node) {
const key =
node.name.type === "String"
? node.name.value
: node.name.name;

if (normalization(key) !== key) {
context.report({
loc: node.name.loc,
messageId: "unnormalizedKey",
});
}
},
};
},
};
61 changes: 61 additions & 0 deletions tests/rules/no-unnormalized-keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @fileoverview Tests for no-empty-keys rule.
* @author Bradley Meck Farias
*/

//------------------------------------------------------------------------------
// Imports
//------------------------------------------------------------------------------

import rule from "../../src/rules/no-unnormalized-keys.js";
import json from "../../src/index.js";
import { RuleTester } from "eslint";

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester({
plugins: {
json,
},
language: "json/json",
});

const o = "\u1E9B\u0323";

ruleTester.run("no-unnormalized-keys", rule, {
valid: [
`{"${o}":"NFC"}`,
{
code: `{"${o}":"NFC"}`,
options: ["NFC"],
},
{
code: `{"${o.normalize("NFD")}":"NFD"}`,
options: ["NFD"],
},
{
code: `{"${o.normalize("NFKC")}":"NFKC"}`,
options: ["NFKC"],
},
{
code: `{"${o.normalize("NFKD")}":"NFKD"}`,
options: ["NFKD"],
},
],
invalid: [
{
code: `{"${o.normalize("NFD")}":"NFD"}`,
errors: [
{
messageId: "unnormalizedKey",
line: 1,
column: 2,
endLine: 1,
endColumn: 7,
},
],
},
],
});

0 comments on commit 73a61ad

Please sign in to comment.