meta-parser.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. /* exported metaParser */
  3. const metaParser = (() => {
  4. require(['/vendor/usercss-meta/usercss-meta.min']); /* global usercssMeta */
  5. const {createParser, ParseError} = usercssMeta;
  6. const PREPROCESSORS = new Set(['default', 'uso', 'stylus', 'less']);
  7. const options = {
  8. validateKey: {
  9. preprocessor: state => {
  10. if (!PREPROCESSORS.has(state.value)) {
  11. throw new ParseError({
  12. code: 'unknownPreprocessor',
  13. args: [state.value],
  14. index: state.valueIndex,
  15. });
  16. }
  17. },
  18. },
  19. validateVar: {
  20. select: state => {
  21. if (state.varResult.options.every(o => o.name !== state.value)) {
  22. throw new ParseError({
  23. code: 'invalidSelectValueMismatch',
  24. index: state.valueIndex,
  25. });
  26. }
  27. },
  28. color: state => {
  29. require(['/js/color/color-converter']); /* global colorConverter */
  30. const color = colorConverter.parse(state.value);
  31. if (!color) {
  32. throw new ParseError({
  33. code: 'invalidColor',
  34. args: [state.value],
  35. index: state.valueIndex,
  36. });
  37. }
  38. state.value = colorConverter.format(color);
  39. },
  40. },
  41. };
  42. const parser = createParser(options);
  43. const looseParser = createParser(Object.assign({}, options, {
  44. allowErrors: true,
  45. unknownKey: 'throw',
  46. }));
  47. return {
  48. lint: looseParser.parse,
  49. parse: parser.parse,
  50. nullifyInvalidVars(vars) {
  51. for (const va of Object.values(vars)) {
  52. if (va.value !== null) {
  53. try {
  54. parser.validateVar(va);
  55. } catch (err) {
  56. va.value = null;
  57. }
  58. }
  59. }
  60. return vars;
  61. },
  62. };
  63. })();