parse.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var fs = require('fs');
  2. var ParsingError = require('./parsing-error');
  3. var Defaults = {
  4. SYNTAX: 'css',
  5. NEED_INFO: false,
  6. CSS_RULE: 'stylesheet',
  7. JS_RULE: 'program'
  8. };
  9. /**
  10. * @param {String} css
  11. * @param {Object} options
  12. * @return {Object} AST
  13. */
  14. function parse(css, options) {
  15. if (!css || typeof css !== 'string')
  16. throw new Error('Please, pass a string to parse');
  17. var syntax = options && options.syntax || Defaults.SYNTAX;
  18. var needInfo = options && options.needInfo || Defaults.NEED_INFO;
  19. var rule = options && options.rule ||
  20. (syntax === 'js' ? Defaults.JS_RULE : Defaults.CSS_RULE);
  21. if (!fs.existsSync(__dirname + '/' + syntax))
  22. return console.error('Syntax "' + syntax + '" is not supported yet, sorry');
  23. var getTokens = require('./' + syntax + '/tokenizer');
  24. var mark = require('./' + syntax + '/mark');
  25. var parse = require('./' + syntax + '/parse');
  26. var tokens = getTokens(css);
  27. mark(tokens);
  28. try {
  29. return parse(tokens, rule, needInfo);
  30. } catch (e) {
  31. throw new ParsingError(e, css);
  32. }
  33. }
  34. module.exports = parse;