Coder Social home page Coder Social logo

godaddy / eslint-plugin-i18n-json Goto Github PK

View Code? Open in Web Editor NEW
174.0 22.0 24.0 1.43 MB

Fully extendable eslint plugin for JSON i18n translation files.

Home Page: https://godaddy.github.io/2018/04/02/introducing-eslint-plugin-i18n-json/

License: MIT License

JavaScript 100.00%
eslint i18n json linter translations internationalization intl icu eslint-plugin translation eslint-rules

eslint-plugin-i18n-json's Introduction

eslint-plugin-i18n-json

Latest npm version Build Status

Fully extendable eslint plugin for JSON i18n translation files.

πŸŽ‰ Check out the introductory blog post!

Table of Contents

Features πŸš€

  • lint JSON translation files

    • rule: i18n-json/valid-json
    • configure a custom linter in case the default doesn't fit your needs.
  • validate syntax per message

    • rule: i18n-json/valid-message-syntax
    • default syntax check is for ICU Message Syntax
    • can support any message syntax through custom validators. Example
  • ensure translation files have identical keys

    • rule: i18n-json/identical-keys
    • supports different custom mappings and on the fly key structure generation
  • sort translation keys in ascending order through eslint auto-fix (case-sensitive)

    • rule: i18n-json/sorted-keys
    • can support a custom sort function to satisfy different sorting needs
  • ensure translation files have identical placeholders

    • rule: i18n-json/identical-placeholders
  • ability to ignore certain keys. Example: metadata keys, in progress translations, etc.

    • setting: i18n-json/ignore-keys Example
  • The plugin supports any level of nesting in the translation file. (escapes . in key names)

Note: Check out the Examples folder to see different use cases and project setups.

Requires

  • eslint >= 4.0.0
  • node >= 6.0.0

Examples

Check out the Examples folder to see different use cases.

Getting Started

Right out of the box you get the following through our recommended ruleset i18n-json/recommended:

  • i18n-json/valid-json
    • linting of each JSON translation file
    • default severity: error | 2
  • i18n-json/valid-message-syntax
    • default ICU Message syntax validation (using @formatjs/icu-messageformat-parser)
    • default severity: error | 2
  • i18n-json/sorted-keys
    • automatic case-sensitive ascending sort of all keys in the translation file.
    • Does a level order traversal of keys, and supports sorting nested objects

Let's say your translations project directory looks like the following, (project name: simple)

> tree simple -I node_modules

simple
β”œβ”€β”€ package.json
β”œβ”€β”€ readme.md
└── translations
    β”œβ”€β”€ en-US
    β”‚Β Β  └── index.json
    └── es-MX
        └── index.json

In this project directory, do the following:

  1. npm install --save-dev eslint-plugin-i18n-json

  2. Create a .eslintrc.js file in the root dir of your project. For this example: /simple/.eslintrc.js.

  3. paste in the following:

    module.exports = {
      extends: [
        'plugin:i18n-json/recommended',
      ],
    };
  4. add this npm script to your package.json file.

    • note:
      • without the --fix option, sorting the translation file won't work
      • the default eslint report formatter, stylish, doesn't handle lint messages of varying length well. Hence, we have also built a custom report formatter well suited for this plugin.
    {
      "scripts": {
        "lint": "eslint --fix --ext .json --format node_modules/eslint-plugin-i18n-json/formatter.js translations/"
      }
    }
    • Also, the following builtin formatters provided by eslint also work well: compact, unix, visualstudio, json. Learn more here
      • Example usage: eslint --fix --ext .json --format compact translations/
  5. npm run lint

  6. Profit! Relax knowing that each change to the translations project will go through strict checks by the eslint plugin.

    Example where we have invalid ICU message syntax.

Configuring your .eslintrc file

  • Simply update your .eslintrc.* with overrides for the individual rules.

  • Eslint severities: 2 = error, 1 = warning, 0 = off

  • Example of the module's default rule configuration:

    • see below for more information about how to further configure each rule. (some options may require switching to a .eslintrc.js file)
    // .eslintrc.json
    {
      "rules": {
          "i18n-json/valid-message-syntax": [2, {
            "syntax": "icu"
          }],
          "i18n-json/valid-json": 2,
          "i18n-json/sorted-keys": [2, {
            "order": "asc",
            "indentSpaces": 2,
          }],
          "i18n-json/identical-keys": 0
      }
    }
    // .eslintrc.js
    module.exports = {
      rules: {
        'i18n-json/valid-message-syntax': [2, {
          syntax: 'icu',
        }],
        'i18n-json/valid-json': 2,
        'i18n-json/sorted-keys': [2, {
          order: 'asc',
          indentSpaces: 2,
        }],
        'i18n-json/identical-keys': 0,
      },
    };

Rules

i18n-json/valid-json

  • linting of each JSON translation file

  • builtin linter uses json-lint

  • default severity: error | 2

  • options

    • linter: String (Optional)
      • Absolute path to a module which exports a JSON linting function.
        • Function(source: String)
        • This function will be passed the source of the current file being processed.
        • It should throw an Error, just like JSON.parse.
          // .eslintrc.js
          module.exports = {
            rules: {
              'i18n-json/valid-json': [2, {
                linter: path.resolve('path/to/custom-linter.js'),
              }],
            },
          };
          // custom-linter.js
          module.exports = (source) => {
            if (isBad(source)) {
              throw new SyntaxError('invalid syntax');
            }
          };

    Example output for Invalid JSON.

i18n-json/valid-message-syntax

  • default ICU Message syntax validation (using @formatjs/icu-messageformat-parser)

  • default severity: error | 2

  • options

    • syntax: String (Optional). Default value: icu.
      • Can be a built in validator: icu, non-empty-string.

        // .eslintrc.js
        module.exports = {
          rules: {
            'i18n-json/valid-message-syntax': [2, {
              syntax: 'non-empty-string',
            }],
          },
        };
      • Can be an absolute path to a module which exports a Syntax Validator Function.

        • Function(message: String, key: String)
        • This function will be invoked with each message and its corresponding key
        • It should throw an Error, just like JSON.parse on invalid syntax.
          // .eslintrc.js
          module.exports = {
            rules: {
              'i18n-json/valid-message-syntax': [2, {
                syntax: path.resolve('path/to/custom-syntax-validator.js'),
              }],
            },
          };
          // custom-syntax-validator.js example
          module.exports = (message, key) => {
            // each message should be in all caps.
            if (message !== message.toUpperCase()) {
              throw new SyntaxError('MESSAGE MUST BE IN ALL CAPS!');
            }
          };

    Output from the custom-message-syntax example where each message must have the word 'PIZZA' prepended to it.

i18n-json/identical-keys

  • compare each translation file's key structure with a reference translation file to ensure consistency

  • severity: 0 | off , this rule is OFF by default

  • Can turn this rule on by specifying options for it through your .eslintrc.* file.

  • options

    • filePath : String | Object (Required)

      • Can be an absolute path to the reference translation file.

        // .eslintrc.js
        module.exports = {
          rules: {
            'i18n-json/identical-keys': [2, {
              filePath: path.resolve('path/to/locale/en-US.json'),
            }],
          },
        };
      • Can be an Object which contains a Mapping for how to choose a reference translation file. (chosen by suffix match)

        // .eslintrc.js
        module.exports = {
          rules: {
            'i18n-json/identical-keys': [2, {
              filePath: {
                'login.json': path.resolve('./translations/en-US/login.json'),
                'search-results.json': path.resolve('./translations/en-US/search-results.json'),
                'todos.json': path.resolve('./translations/en-US/todos.json'),
              },
            }],
          },
        };
        • values in the path must be the absolute file path to the reference translation file.
        • the plugin will do a suffix match on the current file's path to determine which reference translation file to choose.
      • Can be an absolute path to an exported function which generates the reference key structure on the fly. The function will be passed the parsed JSON translations object and absolute path of the current file being processed.

        • Function(translations: Object, currentFileAbsolutePath: String) : Object
        // .eslintrc.js
        module.exports = {
          rules: {
            'i18n-json/identical-keys': [2, {
              filePath: path.resolve('path/to/key-structure-generator.js'),
            }],
          },
        };
        // key-structure-generator.js example
        module.exports = (translations, currentFileAbsolutePath) => {
          // identity key structure generator
          return translations;
        };

    Output from the slightly advanced identical keys example where some keys from the reference translation file (en-US) were not found during comparison.

i18n-json/sorted-keys

  • automatic case-sensitive ascending sort of all keys in the translation file

  • if turned on, the this rule by will sort keys in an ascending order by default.

  • default severity: error | 2

  • options

    • sortFunctionPath: String (Optional). Absolute path to a module which exports a custom sort function. The function should return the desired order of translation keys. The rule will do a level order traversal of the translations and call this custom sort at each level of the object, hence supporting nested objects. This option takes precedence over the order option.
      • NOTE: eslint does additional verification passes on your files after a "fix" is applied (in our case, once the sorted keys are written back to your JSON file). Ensure your sort function won't switch the ordering once the keys are already sorted. For example, if your sort function looks like Object.keys(translations).reverse(), then on the initial pass your keys would be sorted correctly, but in the next pass the order of keys would again be reversed. This would lead to a loop where eslint cannot verify the fix is working correctly. Eslint will not apply the intended sorting fixes in this scenarios.
      • Function(translations: Object) : Array
      // .eslintrc.js
      module.exports = {
        rules: {
          'i18n-json/sorted-keys': [2, {
            sortFunctionPath: path.resolve('path/to/custom-sort.js'),
          }],
        },
      };
      // custom-sort.js example
      // Ascending sort
      module.exports = (translations) => {
        return Object.keys(translations).sort((keyA, keyB) => {
          if (keyA == keyB) {
            return 0;
          } else if (keyA < keyB) {
            return -1;
          } else {
            return 1;
          }
        })
      };
    • order: String (Optional). Possible values: asc|desc. Default value: asc. Case-sensitive sort order of translation keys. The rule does a level order traversal of object keys. Supports nested objects. Note: if you supply a custom sort function through sortFunctionPath, then this option will be ignored.
    • indentSpaces : Number (Optional). Default value: 2. The number of spaces to indent the emitted sorted translations with. (Will be passed to JSON.stringify when generating fixed output). In the case --fix is not supplied to eslint, and the i18n-json/sorted-keys rule is not switched off, it will emit an error (or warning) if it detects an invalid sort order for translation keys.

i18n-json/identical-placeholders

  • compare each translation's placeholders with the reference file to ensure consistency
  • severity: 0 | off , this rule is OFF by default
  • Can turn this rule on by specifying options for it through your .eslintrc.* file.
  • options
    • filePath : String (Required)

      • Can be an absolute path to the reference translation file.
        // .eslintrc.js
        module.exports = {
          rules: {
            'i18n-json/identical-placeholders': [2, {
              filePath: path.resolve('path/to/locale/en-US.json'),
            }],
          },
        };

Settings

i18n-json/ignore-keys

  • list of key paths (case sensitive) to ignore when checking syntax and doing key structure comparisons. Example
  • this setting is used by the following rules: i18n-json/identical-keys, i18n-json/valid-syntax and i18n-json/identical-placeholders.
  • if the key path points to an object, the nested paths are also ignored.
    • e.g. if the key a was added to the ignore-keys list, then a.b will also be ignored.
      {
        "a": {
          "b": "translation"
        }
      }
  • example usage: metadata keys with values not corresponding to the syntax specified or work-in-progress translation keys which should not be used in comparisons.

Example setting configuration:

// .eslintrc.js
{
  settings: {
    /*
      None of the key paths listed below
      will be checked for valid i18n syntax
      nor be used in the identical-keys rule comparison.
      (if the key path points to an object, the nested paths are also ignored)
    */
    'i18n-json/ignore-keys': [
      'translationMetadata',
      'login.form.inProgressTranslationKey',
      'some-key'
    ],
  },
}

Disclaimer

  • None of the translations in the examples provided reflect actual GoDaddy translations. They were just created using Google Translate for example's sake πŸ˜‰.

Special Thanks πŸ‘

License πŸ“‹

MIT

eslint-plugin-i18n-json's People

Contributors

dhaldar-godaddy avatar maccuaa avatar mayank23 avatar mjethva-godaddy avatar nainterceptor avatar pauldcomanici avatar pnevares avatar tvarsis avatar xxsnakerxx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eslint-plugin-i18n-json's Issues

underscore dependency high vulnerability

Hi,

We've came across a bump issue in our project regarding the use of underscore dependency in eslint-plugin-i18n-json. As suggested here do you plan to update 'underscore to versions 1.12.1 or 1.13.0-2 or later ?

Best regards,

Pix dev-team

image

Using plugin with different folder structure

Hi, how to use this plugin in project with folder structure like this:

translations/
---alerts/
------en/
--------translation.json
------de/
--------translation.json
---common/
------en/
--------translation.json
------de/
--------translation.json

Failing recommended config with valid translations?

Hello,

I have just found out about this plugin and decided to test it on a working project. For the sake of example, I will simplify my translation files down to the following file locales/translation.json.

{
  "too_long": "Max {{ limit }} characters allowed!"
}

Then in .eslintrc.json I added this line to the extends array.

"extends": [
    "config-1",
    "plugin:i18n-json/recommended"
]

And added this script to package.json.

"scripts": {
    "lint-i18n": "eslint --fix --ext .json --format node_modules/eslint-plugin-i18n-json/formatter.js locales/"
}

Let's execute yarn lint-i18n now...

βœ–  ERROR  (i18n-json/valid-message-syntax)

  - Expected
  + Received

    Object {
  -   "too_long": "ValidMessage<String>",
  +   "too_long": "String('Max {{ limit }} characters allowed') ===> Expected '0', [1-9] or [^ tnr,.+={}#] but '{' found.",
    }

> βœ– 1 ERROR
> ⚠ 0 WARNINGS

How do I make this test pass? Whenever this translation is used, it gets injected the limit variable. Thanks for any advice!

Validation fails for `icu` syntax

Having a json file with:

{
  "INVALID_CHAR_BACK_SLASH": "Backslash (\u005C) is not allowed",
  "INVALID_CHAR_CURLY_BRACES": "Curly braces ('{}') are not allowed"
}

Having .eslint config:

{
  "extends": [
    "plugin:i18n-json/recommended"
  ],
  "rules": {
    "i18n-json/identical-keys": 0, // we have only one file
    "i18n-json/sorted-keys": 2,
    "i18n-json/valid-json": 2,
    "i18n-json/valid-message-syntax": [
      2,
      {
        "syntax": "icu"
      }
    ]
  },
  "settings": {
    "i18n-json/ignore-keys": [ // add in this array string keys that have empty value
    ]
  }
}

Running script for validation returns:

  0:0  error  
- Expected
+ Received

  Object {
-   "INVALID_CHAR_BACK_SLASH": "ValidMessage<String>",
-   "INVALID_CHAR_CURLY_BRACES": "ValidMessage<String>",
+   "INVALID_CHAR_BACK_SLASH": "String('Backslash (\\) is not allowed') ===> Expected '#', '', 'u', '{', '}', '{', [^{}0-x1Fx7f tnr], end of input or whitespace but '' found.",
+   "INVALID_CHAR_CURLY_BRACES": "String('Curly braces ('{}') are not allowed') ===> Expected '0', [1-9] or [^ tnr,.+={}#] but '}' found.",
  }  i18n-json/valid-message-syntax

βœ– 1 problem (1 error, 0 warnings)

Other info:

High Severity Dependency

This library has a high severity dependency (underscore 1.6.0).

└─┬ [email protected]
  └─┬ [email protected]
    └─┬ [email protected]
      └── [email protected]

I did some digging. nomnom has been deprecated and jsonlint has been abandoned for a long time (there are 409 forks). An open PR has resolved this issue.

The code of jsonlint is actually pretty simple. You could probably include it yourself internally so you don't have an insecure dependency out of your control which has long since been abandoned.

Prettier rules gives Unexpected token

Hello,

I've installed this plugin for a React Native project, and everything is working so far, but one error by translation file remains, and I don't know what is wrong.

eslint --fix --format node_modules/eslint-plugin-i18n-json/formatter.js --ext .json src/locales

is reporting me

src/locales/de/translation.json

βœ–  ERROR  (prettier/prettier)
  Parsing error: Unexpected token

src/locales/en/translation.json

βœ–  ERROR  (prettier/prettier)
  Parsing error: Unexpected token

src/locales/es/translation.json

βœ–  ERROR  (prettier/prettier)
  Parsing error: Unexpected token

src/locales/fr/translation.json

βœ–  ERROR  (prettier/prettier)
  Parsing error: Unexpected token

> βœ– 4 ERRORS
> ⚠ 0 WARNINGS
error Command failed with exit code 1.

I've checked file format, line ending, invisible characters, error still appears.

Here is my .eslintrc.js config file :

module.exports = {
  env: {
    node: true,
    es6: true,
    jest: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
    'plugin:i18n-json/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2018,
    project: './tsconfig.json',
    sourceType: 'module',
  },
  plugins: ['react', 'react-hooks', '@typescript-eslint', 'prettier'],
  rules: {
    indent: [
      'error',
      2,
      {
        SwitchCase: 1,
        ignoredNodes: ['CallExpression > ObjectExpression, ConditionalExpression'],
      },
    ],
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single', { avoidEscape: true }],
    semi: ['error', 'never'],
    'no-empty-function': 'off',
    '@typescript-eslint/no-empty-function': 'off',
    '@typescript-eslint/no-unsafe-assignment': 'off',
    '@typescript-eslint/restrict-template-expressions': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unsafe-return': 'off',
    '@typescript-eslint/no-unsafe-member-access': 'off',
    '@typescript-eslint/no-unsafe-call': 'off',
    '@typescript-eslint/restrict-plus-operands': 'off',
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/no-floating-promises': 'warn',
    '@typescript-eslint/no-var-requires': 'warn',
    '@typescript-eslint/no-implied-eval': 'warn',
    '@typescript-eslint/ban-types': 'warn',
    '@typescript-eslint/unbound-method': 'warn',
    '@typescript-eslint/require-await': 'warn',
    'prefer-rest-params': 'warn',
    'no-prototype-builtins': 'off',
    'react/display-name': 'off',
    'react/prop-types': 'off',
    'prettier/prettier': 'error',
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
}

and my .prettierrc.js file :

module.exports = {
  jsxBracketSameLine: true,
  singleQuote: true,
  trailingComma: 'all',
  printWidth: 120,
  semi: false,
  arrowParens: 'always',
}

unique-keys rule

Please consider adding a rule that warns/disallows a key to be used more than once in the JSON.

sorting fails with some numbers as a keys

Sorting fails with an error when using numbers, for example "01" and "20" at the same time
const translations = {
"a": {
"20": "k",
"01": "k",
"b": "k",
"c": "k"
}
}

i18n-json/identical-keys suffix matching with similarly named files causes issues

When multiple files with the same suffix matching another language file are included in the filePaths there is an issue matching the correct file to check.

I updated the example/multiple-files-per-locale on my fork to demonstrate this with a simple example using search-results.json and another file z-search-results.json.

When running npm run lint in that example it outputs the following errors, despite all keys matching in each file:

Screen Shot 2022-03-29 at 3 39 46 PM

I tracked this down to be an issue with the code here https://github.com/godaddy/eslint-plugin-i18n-json/blob/master/src/identical-keys.js#L10-L13 and was able to solve this use case by replacing that with
const match = sourceFilePath.substr(sourceFilePath.lastIndexOf('/') + 1);

Check for identical values

Is it at all feasible to create a rule that checks for duplicate/identical (or similar) values rather than keys? I'm not all too familiar with eslint plugin development, but I recently learned about the Levenshtein Distance and I thought it'd be a great addition to lint our i18n language files with.

Expected space or tab after '/*' in comment spaced-comment

Versions

node -v: v10.16.3
npm -v: 6.9.0

Eslint version from package.json

    "eslint": "6.7.1",
    "eslint-loader": "3.0.2",
    "eslint-plugin-cypress": "2.7.0",
    "eslint-plugin-i18n-json": "2.4.3",
    "eslint-plugin-import": "2.18.2",
    "eslint-plugin-react": "7.16.0",
    "eslint-plugin-react-hooks": "2.3.0",
    "eslint-plugin-require-jsdoc-except": "1.3.0",

File used

File name:

en-us.json

Content:

{
  "TEST": "test"
}

Rules

.eslintrc file contains:

{
  "extends": [
    "plugin:i18n-json/recommended"
  ],
  "rules": {
    "i18n-json/identical-keys": 0, // we have only one file
    "i18n-json/sorted-keys": 2,
    "i18n-json/valid-json": 2,
    "i18n-json/valid-message-syntax": [
      2,
      {
        "syntax": "icu"
      }
    ]
  },
  "settings": {
    "i18n-json/ignore-keys": [ // add in this array string keys that have empty value
    ]
  }
}

Script

In package.json I execute script:

"lint-locale": "eslint --ext .json ./src/modules/l10n/strings",

Note: Inside ./src/modules/l10n/strings I have .eslintrc file.

Issue

When running linting script I get:

src/modules/l10n/strings/en-us.json
  1:1  error  Expected space or tab after '/*' in comment  spaced-comment
  3:4  error  Expected space or tab after '/*' in comment  spaced-comment

Note: Reverting back to v2.4.2 I do not get any error.

Comment validation support

In our translation files, we require translator notes to add proper context for translators. Example:

{
  //@note: Button text to buy an item
  β€œBUY_ME”: β€œBuy me”
}

I’d like the comment to be required for each string. Is this something that this plugin could handle? Or is there a way to provide this functionality be extending this plugin?

processor fail when json file contain '**'

Use Case:
i want to use that plugin for linting and auto-fix my json config file

Example Input:

{
  "command": {
    "publish": {
      "conventionalCommits": true,
      "ignoreChanges": [
        "**/__fixtures__/**",
        "**/__mocks__/**",
        "**/__tests__/**",
        "yarn.lock",
        "CHANGELOG.md"
      ],
      "message": "chore(release): publish"
    }
  },
  "npmClient": "yarn",
  "packages": ["packages/*"],
  "version": "independent"
}

Result:

  6:12  error  Parsing error: '{' expected

Root case:
My Json file contain '*/' which make that plugin consider end of comment

Work around:
Manually escape */

{
"command": {
"publish": {
"conventionalCommits": true,
"ignoreChanges": [
"*/fixtures/**",
"
*/mocks/",
"**/tests/
",
"yarn.lock",
"CHANGELOG.md"
],
"message": "chore(release): publish"
}
},
"npmClient": "yarn",
"packages": ["packages/*"],
"version": "independent"
}

Preprocessor breakes other tools

The preprocessor transforms the JSON in a big comment block, making it hard to have other tools with this plugin.

Any plans on fixing that?

Upgrade deprecated intl-messageformat-parser to v6

Problem
When installing eslint-plugin-i18n-json with jspm, the following warning is displayed
warn (jspm) Deprecation warning for npm:[email protected]: backwards incompatible, please upgrade to 6.0 instead
This causes jspm being stuck for a while with the following message
... Finalizing https://registry.npmjs.org/@formatjs/intl-numberformat/-/intl-numberformat-5.7.1.tgz#sha512-wVkzeqIAxfibB7zekX4xJbHrVfqy6zik2xd4f0zhD4UAn/JfxSin4nFfY35VNr7R0ZtvPqrKBnbddEpyXRF+Zw==

Solution
intl-messageformat-parser should be bumped up to it's latest version, v6. There shouldn't be breaking changes, as looking into CHANGELOG, for v6 there were only bugfixes (see), later one version bumps and another bugfix.

i18n-json/valid-message-syntax: Add possibility to allow Arrays

Currently it is hardcoded that Arrays can't be a valid translation. However, based on the setup, there are some legitimate usages of Arrays and this is blocking it for no reason.

} else if (Array.isArray(value)) {
invalidMessages.push({
value: ARRAY,
key,
path,
error: new TypeError('An Array cannot be a translation value.')
});
} else {

The problem is, that we can't bypass this check with a custom validator which would allow Arrays for some specific keys

a vulnerability CVE-2021-23358 is introduced in eslint-plugin-i18n-json

Hi, a vulnerability CVE-2021-23358 is introduced in eslint-plugin-i18n-json via:
● [email protected] βž” [email protected] βž” [email protected] βž” [email protected]

However, jsonlint is a legacy package, which has not been maintained for about 3 years.
Is it possible to migrate jsonlint to other package or remove it to remediate this vulnerability?

I noticed a migration record in other js repo for jsonlint:

● in cfn-include, version 1.0.0 βž” 1.0.1, remove jsonlint via commit
● in gavel, version 2.1.2 βž” 2.1.3, migrate jsonlint to json-parse-helpfulerror via commit

Thanks.

identical-keys rule displays error whenever structure changes

I am using the identical-keys rule however every time I add or remove a key from an i18n file I get an error. The only way to clear the error is to restart the webpack-dev-server which I guess causes the eslint-plugin-i18n-json plugin to rescan all the files and then it's happy again.

It's not a major issue, but it is annoying to have to restart the dev server every single time.

ERROR in ./src/i18n/locales/en/resource.json
Module build failed (from ./node_modules/eslint-loader/index.js):
Module failed because of a eslint error.

/Users/maccuaa/Projects/sbp/ui/src/i18n/locales/en/resource.json
  0:0  error
- Expected
+ Received

@@ -336,2 +336,3 @@
        "username": "Message<String>",
+       "x": "Message<String>",
      },  i18n-json/identical-keys

βœ– 1 problem (1 error, 0 warnings)βœ– 1 problem (1 error, 0 warnings)

My Eslint configuration is:

rules: {
    'i18n-json/valid-json': 2,
    'i18n-json/valid-message-syntax': [
      2,
      {
        syntax: 'non-empty-string'
      }
    ],
    'i18n-json/sorted-keys': 2,
    'i18n-json/identical-keys': [
      2,
      {
        filePath: {
          'resource.json': path.resolve('src/i18n/locales/en/resource.json'),
     .
     .
     .

`--fix` flag is not recognized

In running the tool against a locale file, the --fix is not recognized.

/app # npx eslint --fix config/locales/en.json 

/app/config/locales/en.json
  0:0  error  Keys should be sorted, please use --fix  i18n-json/sorted-keys

βœ– 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

Note that this command is run with the --fix option.

Ignore keys

Some translation services require metadata included in language files as a property. It would be great to be able to whitelist properties so that they don't get linted.

For example, right now I'm getting a Array [] ===> TypeError: An Array cannot be a translation value. because the metadata includes an array.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.