assert-token.js 1020 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. const ISSUE_LINK_PREFIX = 'https://github.com/sindresorhus/eslint-plugin-unicorn/issues/new?';
  3. function assertToken(token, {test, expected, ruleId}) {
  4. if (test?.(token)) {
  5. return;
  6. }
  7. expected = Array.isArray(expected) ? expected : [expected];
  8. expected = expected.map(expectedToken => typeof expectedToken === 'string' ? {value: expectedToken} : expectedToken);
  9. if (
  10. !test
  11. && expected.some(
  12. expectedToken =>
  13. Object.entries(expectedToken)
  14. .every(([key, value]) => token[key] === value),
  15. )
  16. ) {
  17. return;
  18. }
  19. const actual = `'${JSON.stringify({value: token.value, type: token.type})}'`;
  20. expected = expected.map(expectedToken => `'${JSON.stringify(expectedToken)}'`).join(' or ');
  21. const title = `\`${ruleId}\`: Unexpected token ${actual}`;
  22. const issueLink = `${ISSUE_LINK_PREFIX}title=${encodeURIComponent(title)}`;
  23. const message = `Expected token ${expected}, got ${actual}.\nPlease open an issue at ${issueLink}.`;
  24. throw new Error(message);
  25. }
  26. module.exports = assertToken;