Aucune description

parser.js 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = void 0;
  4. var _root = _interopRequireDefault(require("./selectors/root"));
  5. var _selector = _interopRequireDefault(require("./selectors/selector"));
  6. var _className = _interopRequireDefault(require("./selectors/className"));
  7. var _comment = _interopRequireDefault(require("./selectors/comment"));
  8. var _id = _interopRequireDefault(require("./selectors/id"));
  9. var _tag = _interopRequireDefault(require("./selectors/tag"));
  10. var _string = _interopRequireDefault(require("./selectors/string"));
  11. var _pseudo = _interopRequireDefault(require("./selectors/pseudo"));
  12. var _attribute = _interopRequireWildcard(require("./selectors/attribute"));
  13. var _universal = _interopRequireDefault(require("./selectors/universal"));
  14. var _combinator = _interopRequireDefault(require("./selectors/combinator"));
  15. var _nesting = _interopRequireDefault(require("./selectors/nesting"));
  16. var _sortAscending = _interopRequireDefault(require("./sortAscending"));
  17. var _tokenize = _interopRequireWildcard(require("./tokenize"));
  18. var tokens = _interopRequireWildcard(require("./tokenTypes"));
  19. var types = _interopRequireWildcard(require("./selectors/types"));
  20. var _util = require("./util");
  21. var _WHITESPACE_TOKENS, _Object$assign;
  22. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  23. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  24. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  25. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  26. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  27. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  28. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  29. function tokenStart(token) {
  30. return {
  31. line: token[_tokenize.FIELDS.START_LINE],
  32. column: token[_tokenize.FIELDS.START_COL]
  33. };
  34. }
  35. function tokenEnd(token) {
  36. return {
  37. line: token[_tokenize.FIELDS.END_LINE],
  38. column: token[_tokenize.FIELDS.END_COL]
  39. };
  40. }
  41. function getSource(startLine, startColumn, endLine, endColumn) {
  42. return {
  43. start: {
  44. line: startLine,
  45. column: startColumn
  46. },
  47. end: {
  48. line: endLine,
  49. column: endColumn
  50. }
  51. };
  52. }
  53. function getTokenSource(token) {
  54. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  55. }
  56. function getTokenSourceSpan(startToken, endToken) {
  57. if (!startToken) {
  58. return undefined;
  59. }
  60. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  61. }
  62. function unescapeProp(node, prop) {
  63. var value = node[prop];
  64. if (typeof value !== "string") {
  65. return;
  66. }
  67. if (value.indexOf("\\") !== -1) {
  68. (0, _util.ensureObject)(node, 'raws');
  69. node[prop] = (0, _util.unesc)(value);
  70. if (node.raws[prop] === undefined) {
  71. node.raws[prop] = value;
  72. }
  73. }
  74. return node;
  75. }
  76. function indexesOf(array, item) {
  77. var i = -1;
  78. var indexes = [];
  79. while ((i = array.indexOf(item, i + 1)) !== -1) {
  80. indexes.push(i);
  81. }
  82. return indexes;
  83. }
  84. function uniqs() {
  85. var list = Array.prototype.concat.apply([], arguments);
  86. return list.filter(function (item, i) {
  87. return i === list.indexOf(item);
  88. });
  89. }
  90. var Parser = /*#__PURE__*/function () {
  91. function Parser(rule, options) {
  92. if (options === void 0) {
  93. options = {};
  94. }
  95. this.rule = rule;
  96. this.options = Object.assign({
  97. lossy: false,
  98. safe: false
  99. }, options);
  100. this.position = 0;
  101. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  102. this.tokens = (0, _tokenize["default"])({
  103. css: this.css,
  104. error: this._errorGenerator(),
  105. safe: this.options.safe
  106. });
  107. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  108. this.root = new _root["default"]({
  109. source: rootSource
  110. });
  111. this.root.errorGenerator = this._errorGenerator();
  112. var selector = new _selector["default"]({
  113. source: {
  114. start: {
  115. line: 1,
  116. column: 1
  117. }
  118. }
  119. });
  120. this.root.append(selector);
  121. this.current = selector;
  122. this.loop();
  123. }
  124. var _proto = Parser.prototype;
  125. _proto._errorGenerator = function _errorGenerator() {
  126. var _this = this;
  127. return function (message, errorOptions) {
  128. if (typeof _this.rule === 'string') {
  129. return new Error(message);
  130. }
  131. return _this.rule.error(message, errorOptions);
  132. };
  133. };
  134. _proto.attribute = function attribute() {
  135. var attr = [];
  136. var startingToken = this.currToken;
  137. this.position++;
  138. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  139. attr.push(this.currToken);
  140. this.position++;
  141. }
  142. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  143. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  144. }
  145. var len = attr.length;
  146. var node = {
  147. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  148. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  149. };
  150. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  151. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  152. }
  153. var pos = 0;
  154. var spaceBefore = '';
  155. var commentBefore = '';
  156. var lastAdded = null;
  157. var spaceAfterMeaningfulToken = false;
  158. while (pos < len) {
  159. var token = attr[pos];
  160. var content = this.content(token);
  161. var next = attr[pos + 1];
  162. switch (token[_tokenize.FIELDS.TYPE]) {
  163. case tokens.space:
  164. // if (
  165. // len === 1 ||
  166. // pos === 0 && this.content(next) === '|'
  167. // ) {
  168. // return this.expected('attribute', token[TOKEN.START_POS], content);
  169. // }
  170. spaceAfterMeaningfulToken = true;
  171. if (this.options.lossy) {
  172. break;
  173. }
  174. if (lastAdded) {
  175. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  176. var prevContent = node.spaces[lastAdded].after || '';
  177. node.spaces[lastAdded].after = prevContent + content;
  178. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  179. if (existingComment) {
  180. node.raws.spaces[lastAdded].after = existingComment + content;
  181. }
  182. } else {
  183. spaceBefore = spaceBefore + content;
  184. commentBefore = commentBefore + content;
  185. }
  186. break;
  187. case tokens.asterisk:
  188. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  189. node.operator = content;
  190. lastAdded = 'operator';
  191. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  192. if (spaceBefore) {
  193. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  194. node.spaces.attribute.before = spaceBefore;
  195. spaceBefore = '';
  196. }
  197. if (commentBefore) {
  198. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  199. node.raws.spaces.attribute.before = spaceBefore;
  200. commentBefore = '';
  201. }
  202. node.namespace = (node.namespace || "") + content;
  203. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  204. if (rawValue) {
  205. node.raws.namespace += content;
  206. }
  207. lastAdded = 'namespace';
  208. }
  209. spaceAfterMeaningfulToken = false;
  210. break;
  211. case tokens.dollar:
  212. if (lastAdded === "value") {
  213. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  214. node.value += "$";
  215. if (oldRawValue) {
  216. node.raws.value = oldRawValue + "$";
  217. }
  218. break;
  219. }
  220. // Falls through
  221. case tokens.caret:
  222. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  223. node.operator = content;
  224. lastAdded = 'operator';
  225. }
  226. spaceAfterMeaningfulToken = false;
  227. break;
  228. case tokens.combinator:
  229. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  230. node.operator = content;
  231. lastAdded = 'operator';
  232. }
  233. if (content !== '|') {
  234. spaceAfterMeaningfulToken = false;
  235. break;
  236. }
  237. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  238. node.operator = content;
  239. lastAdded = 'operator';
  240. } else if (!node.namespace && !node.attribute) {
  241. node.namespace = true;
  242. }
  243. spaceAfterMeaningfulToken = false;
  244. break;
  245. case tokens.word:
  246. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  247. // this look-ahead probably fails with comment nodes involved.
  248. !node.operator && !node.namespace) {
  249. node.namespace = content;
  250. lastAdded = 'namespace';
  251. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  252. if (spaceBefore) {
  253. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  254. node.spaces.attribute.before = spaceBefore;
  255. spaceBefore = '';
  256. }
  257. if (commentBefore) {
  258. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  259. node.raws.spaces.attribute.before = commentBefore;
  260. commentBefore = '';
  261. }
  262. node.attribute = (node.attribute || "") + content;
  263. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  264. if (_rawValue) {
  265. node.raws.attribute += content;
  266. }
  267. lastAdded = 'attribute';
  268. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  269. var _unescaped = (0, _util.unesc)(content);
  270. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  271. var oldValue = node.value || '';
  272. node.value = oldValue + _unescaped;
  273. node.quoteMark = null;
  274. if (_unescaped !== content || _oldRawValue) {
  275. (0, _util.ensureObject)(node, 'raws');
  276. node.raws.value = (_oldRawValue || oldValue) + content;
  277. }
  278. lastAdded = 'value';
  279. } else {
  280. var insensitive = content === 'i' || content === "I";
  281. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  282. node.insensitive = insensitive;
  283. if (!insensitive || content === "I") {
  284. (0, _util.ensureObject)(node, 'raws');
  285. node.raws.insensitiveFlag = content;
  286. }
  287. lastAdded = 'insensitive';
  288. if (spaceBefore) {
  289. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  290. node.spaces.insensitive.before = spaceBefore;
  291. spaceBefore = '';
  292. }
  293. if (commentBefore) {
  294. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  295. node.raws.spaces.insensitive.before = commentBefore;
  296. commentBefore = '';
  297. }
  298. } else if (node.value || node.value === '') {
  299. lastAdded = 'value';
  300. node.value += content;
  301. if (node.raws.value) {
  302. node.raws.value += content;
  303. }
  304. }
  305. }
  306. spaceAfterMeaningfulToken = false;
  307. break;
  308. case tokens.str:
  309. if (!node.attribute || !node.operator) {
  310. return this.error("Expected an attribute followed by an operator preceding the string.", {
  311. index: token[_tokenize.FIELDS.START_POS]
  312. });
  313. }
  314. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  315. unescaped = _unescapeValue.unescaped,
  316. quoteMark = _unescapeValue.quoteMark;
  317. node.value = unescaped;
  318. node.quoteMark = quoteMark;
  319. lastAdded = 'value';
  320. (0, _util.ensureObject)(node, 'raws');
  321. node.raws.value = content;
  322. spaceAfterMeaningfulToken = false;
  323. break;
  324. case tokens.equals:
  325. if (!node.attribute) {
  326. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  327. }
  328. if (node.value) {
  329. return this.error('Unexpected "=" found; an operator was already defined.', {
  330. index: token[_tokenize.FIELDS.START_POS]
  331. });
  332. }
  333. node.operator = node.operator ? node.operator + content : content;
  334. lastAdded = 'operator';
  335. spaceAfterMeaningfulToken = false;
  336. break;
  337. case tokens.comment:
  338. if (lastAdded) {
  339. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  340. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  341. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  342. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  343. node.raws.spaces[lastAdded].after = rawLastComment + content;
  344. } else {
  345. var lastValue = node[lastAdded] || '';
  346. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  347. (0, _util.ensureObject)(node, 'raws');
  348. node.raws[lastAdded] = rawLastValue + content;
  349. }
  350. } else {
  351. commentBefore = commentBefore + content;
  352. }
  353. break;
  354. default:
  355. return this.error("Unexpected \"" + content + "\" found.", {
  356. index: token[_tokenize.FIELDS.START_POS]
  357. });
  358. }
  359. pos++;
  360. }
  361. unescapeProp(node, "attribute");
  362. unescapeProp(node, "namespace");
  363. this.newNode(new _attribute["default"](node));
  364. this.position++;
  365. }
  366. /**
  367. * return a node containing meaningless garbage up to (but not including) the specified token position.
  368. * if the token position is negative, all remaining tokens are consumed.
  369. *
  370. * This returns an array containing a single string node if all whitespace,
  371. * otherwise an array of comment nodes with space before and after.
  372. *
  373. * These tokens are not added to the current selector, the caller can add them or use them to amend
  374. * a previous node's space metadata.
  375. *
  376. * In lossy mode, this returns only comments.
  377. */;
  378. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  379. if (stopPosition < 0) {
  380. stopPosition = this.tokens.length;
  381. }
  382. var startPosition = this.position;
  383. var nodes = [];
  384. var space = "";
  385. var lastComment = undefined;
  386. do {
  387. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  388. if (!this.options.lossy) {
  389. space += this.content();
  390. }
  391. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  392. var spaces = {};
  393. if (space) {
  394. spaces.before = space;
  395. space = "";
  396. }
  397. lastComment = new _comment["default"]({
  398. value: this.content(),
  399. source: getTokenSource(this.currToken),
  400. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  401. spaces: spaces
  402. });
  403. nodes.push(lastComment);
  404. }
  405. } while (++this.position < stopPosition);
  406. if (space) {
  407. if (lastComment) {
  408. lastComment.spaces.after = space;
  409. } else if (!this.options.lossy) {
  410. var firstToken = this.tokens[startPosition];
  411. var lastToken = this.tokens[this.position - 1];
  412. nodes.push(new _string["default"]({
  413. value: '',
  414. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  415. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  416. spaces: {
  417. before: space,
  418. after: ''
  419. }
  420. }));
  421. }
  422. }
  423. return nodes;
  424. }
  425. /**
  426. *
  427. * @param {*} nodes
  428. */;
  429. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  430. var _this2 = this;
  431. if (requiredSpace === void 0) {
  432. requiredSpace = false;
  433. }
  434. var space = "";
  435. var rawSpace = "";
  436. nodes.forEach(function (n) {
  437. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  438. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  439. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  440. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  441. });
  442. if (rawSpace === space) {
  443. rawSpace = undefined;
  444. }
  445. var result = {
  446. space: space,
  447. rawSpace: rawSpace
  448. };
  449. return result;
  450. };
  451. _proto.isNamedCombinator = function isNamedCombinator(position) {
  452. if (position === void 0) {
  453. position = this.position;
  454. }
  455. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  456. };
  457. _proto.namedCombinator = function namedCombinator() {
  458. if (this.isNamedCombinator()) {
  459. var nameRaw = this.content(this.tokens[this.position + 1]);
  460. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  461. var raws = {};
  462. if (name !== nameRaw) {
  463. raws.value = "/" + nameRaw + "/";
  464. }
  465. var node = new _combinator["default"]({
  466. value: "/" + name + "/",
  467. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  468. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  469. raws: raws
  470. });
  471. this.position = this.position + 3;
  472. return node;
  473. } else {
  474. this.unexpected();
  475. }
  476. };
  477. _proto.combinator = function combinator() {
  478. var _this3 = this;
  479. if (this.content() === '|') {
  480. return this.namespace();
  481. }
  482. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  483. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  484. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  485. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  486. if (nodes.length > 0) {
  487. var last = this.current.last;
  488. if (last) {
  489. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  490. space = _this$convertWhitespa.space,
  491. rawSpace = _this$convertWhitespa.rawSpace;
  492. if (rawSpace !== undefined) {
  493. last.rawSpaceAfter += rawSpace;
  494. }
  495. last.spaces.after += space;
  496. } else {
  497. nodes.forEach(function (n) {
  498. return _this3.newNode(n);
  499. });
  500. }
  501. }
  502. return;
  503. }
  504. var firstToken = this.currToken;
  505. var spaceOrDescendantSelectorNodes = undefined;
  506. if (nextSigTokenPos > this.position) {
  507. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  508. }
  509. var node;
  510. if (this.isNamedCombinator()) {
  511. node = this.namedCombinator();
  512. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  513. node = new _combinator["default"]({
  514. value: this.content(),
  515. source: getTokenSource(this.currToken),
  516. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  517. });
  518. this.position++;
  519. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  520. // pass
  521. } else if (!spaceOrDescendantSelectorNodes) {
  522. this.unexpected();
  523. }
  524. if (node) {
  525. if (spaceOrDescendantSelectorNodes) {
  526. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  527. _space = _this$convertWhitespa2.space,
  528. _rawSpace = _this$convertWhitespa2.rawSpace;
  529. node.spaces.before = _space;
  530. node.rawSpaceBefore = _rawSpace;
  531. }
  532. } else {
  533. // descendant combinator
  534. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  535. _space2 = _this$convertWhitespa3.space,
  536. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  537. if (!_rawSpace2) {
  538. _rawSpace2 = _space2;
  539. }
  540. var spaces = {};
  541. var raws = {
  542. spaces: {}
  543. };
  544. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  545. spaces.before = _space2.slice(0, _space2.length - 1);
  546. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  547. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  548. spaces.after = _space2.slice(1);
  549. raws.spaces.after = _rawSpace2.slice(1);
  550. } else {
  551. raws.value = _rawSpace2;
  552. }
  553. node = new _combinator["default"]({
  554. value: ' ',
  555. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  556. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  557. spaces: spaces,
  558. raws: raws
  559. });
  560. }
  561. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  562. node.spaces.after = this.optionalSpace(this.content());
  563. this.position++;
  564. }
  565. return this.newNode(node);
  566. };
  567. _proto.comma = function comma() {
  568. if (this.position === this.tokens.length - 1) {
  569. this.root.trailingComma = true;
  570. this.position++;
  571. return;
  572. }
  573. this.current._inferEndPosition();
  574. var selector = new _selector["default"]({
  575. source: {
  576. start: tokenStart(this.tokens[this.position + 1])
  577. }
  578. });
  579. this.current.parent.append(selector);
  580. this.current = selector;
  581. this.position++;
  582. };
  583. _proto.comment = function comment() {
  584. var current = this.currToken;
  585. this.newNode(new _comment["default"]({
  586. value: this.content(),
  587. source: getTokenSource(current),
  588. sourceIndex: current[_tokenize.FIELDS.START_POS]
  589. }));
  590. this.position++;
  591. };
  592. _proto.error = function error(message, opts) {
  593. throw this.root.error(message, opts);
  594. };
  595. _proto.missingBackslash = function missingBackslash() {
  596. return this.error('Expected a backslash preceding the semicolon.', {
  597. index: this.currToken[_tokenize.FIELDS.START_POS]
  598. });
  599. };
  600. _proto.missingParenthesis = function missingParenthesis() {
  601. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  602. };
  603. _proto.missingSquareBracket = function missingSquareBracket() {
  604. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  605. };
  606. _proto.unexpected = function unexpected() {
  607. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  608. };
  609. _proto.namespace = function namespace() {
  610. var before = this.prevToken && this.content(this.prevToken) || true;
  611. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  612. this.position++;
  613. return this.word(before);
  614. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  615. this.position++;
  616. return this.universal(before);
  617. }
  618. };
  619. _proto.nesting = function nesting() {
  620. if (this.nextToken) {
  621. var nextContent = this.content(this.nextToken);
  622. if (nextContent === "|") {
  623. this.position++;
  624. return;
  625. }
  626. }
  627. var current = this.currToken;
  628. this.newNode(new _nesting["default"]({
  629. value: this.content(),
  630. source: getTokenSource(current),
  631. sourceIndex: current[_tokenize.FIELDS.START_POS]
  632. }));
  633. this.position++;
  634. };
  635. _proto.parentheses = function parentheses() {
  636. var last = this.current.last;
  637. var unbalanced = 1;
  638. this.position++;
  639. if (last && last.type === types.PSEUDO) {
  640. var selector = new _selector["default"]({
  641. source: {
  642. start: tokenStart(this.tokens[this.position - 1])
  643. }
  644. });
  645. var cache = this.current;
  646. last.append(selector);
  647. this.current = selector;
  648. while (this.position < this.tokens.length && unbalanced) {
  649. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  650. unbalanced++;
  651. }
  652. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  653. unbalanced--;
  654. }
  655. if (unbalanced) {
  656. this.parse();
  657. } else {
  658. this.current.source.end = tokenEnd(this.currToken);
  659. this.current.parent.source.end = tokenEnd(this.currToken);
  660. this.position++;
  661. }
  662. }
  663. this.current = cache;
  664. } else {
  665. // I think this case should be an error. It's used to implement a basic parse of media queries
  666. // but I don't think it's a good idea.
  667. var parenStart = this.currToken;
  668. var parenValue = "(";
  669. var parenEnd;
  670. while (this.position < this.tokens.length && unbalanced) {
  671. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  672. unbalanced++;
  673. }
  674. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  675. unbalanced--;
  676. }
  677. parenEnd = this.currToken;
  678. parenValue += this.parseParenthesisToken(this.currToken);
  679. this.position++;
  680. }
  681. if (last) {
  682. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  683. } else {
  684. this.newNode(new _string["default"]({
  685. value: parenValue,
  686. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  687. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  688. }));
  689. }
  690. }
  691. if (unbalanced) {
  692. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  693. }
  694. };
  695. _proto.pseudo = function pseudo() {
  696. var _this4 = this;
  697. var pseudoStr = '';
  698. var startingToken = this.currToken;
  699. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  700. pseudoStr += this.content();
  701. this.position++;
  702. }
  703. if (!this.currToken) {
  704. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  705. }
  706. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  707. this.splitWord(false, function (first, length) {
  708. pseudoStr += first;
  709. _this4.newNode(new _pseudo["default"]({
  710. value: pseudoStr,
  711. source: getTokenSourceSpan(startingToken, _this4.currToken),
  712. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  713. }));
  714. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  715. _this4.error('Misplaced parenthesis.', {
  716. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  717. });
  718. }
  719. });
  720. } else {
  721. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  722. }
  723. };
  724. _proto.space = function space() {
  725. var content = this.content();
  726. // Handle space before and after the selector
  727. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  728. return node.type === 'comment';
  729. })) {
  730. this.spaces = this.optionalSpace(content);
  731. this.position++;
  732. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  733. this.current.last.spaces.after = this.optionalSpace(content);
  734. this.position++;
  735. } else {
  736. this.combinator();
  737. }
  738. };
  739. _proto.string = function string() {
  740. var current = this.currToken;
  741. this.newNode(new _string["default"]({
  742. value: this.content(),
  743. source: getTokenSource(current),
  744. sourceIndex: current[_tokenize.FIELDS.START_POS]
  745. }));
  746. this.position++;
  747. };
  748. _proto.universal = function universal(namespace) {
  749. var nextToken = this.nextToken;
  750. if (nextToken && this.content(nextToken) === '|') {
  751. this.position++;
  752. return this.namespace();
  753. }
  754. var current = this.currToken;
  755. this.newNode(new _universal["default"]({
  756. value: this.content(),
  757. source: getTokenSource(current),
  758. sourceIndex: current[_tokenize.FIELDS.START_POS]
  759. }), namespace);
  760. this.position++;
  761. };
  762. _proto.splitWord = function splitWord(namespace, firstCallback) {
  763. var _this5 = this;
  764. var nextToken = this.nextToken;
  765. var word = this.content();
  766. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  767. this.position++;
  768. var current = this.content();
  769. word += current;
  770. if (current.lastIndexOf('\\') === current.length - 1) {
  771. var next = this.nextToken;
  772. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  773. word += this.requiredSpace(this.content(next));
  774. this.position++;
  775. }
  776. }
  777. nextToken = this.nextToken;
  778. }
  779. var hasClass = indexesOf(word, '.').filter(function (i) {
  780. // Allow escaped dot within class name
  781. var escapedDot = word[i - 1] === '\\';
  782. // Allow decimal numbers percent in @keyframes
  783. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  784. return !escapedDot && !isKeyframesPercent;
  785. });
  786. var hasId = indexesOf(word, '#').filter(function (i) {
  787. return word[i - 1] !== '\\';
  788. });
  789. // Eliminate Sass interpolations from the list of id indexes
  790. var interpolations = indexesOf(word, '#{');
  791. if (interpolations.length) {
  792. hasId = hasId.filter(function (hashIndex) {
  793. return !~interpolations.indexOf(hashIndex);
  794. });
  795. }
  796. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  797. indices.forEach(function (ind, i) {
  798. var index = indices[i + 1] || word.length;
  799. var value = word.slice(ind, index);
  800. if (i === 0 && firstCallback) {
  801. return firstCallback.call(_this5, value, indices.length);
  802. }
  803. var node;
  804. var current = _this5.currToken;
  805. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  806. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  807. if (~hasClass.indexOf(ind)) {
  808. var classNameOpts = {
  809. value: value.slice(1),
  810. source: source,
  811. sourceIndex: sourceIndex
  812. };
  813. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  814. } else if (~hasId.indexOf(ind)) {
  815. var idOpts = {
  816. value: value.slice(1),
  817. source: source,
  818. sourceIndex: sourceIndex
  819. };
  820. node = new _id["default"](unescapeProp(idOpts, "value"));
  821. } else {
  822. var tagOpts = {
  823. value: value,
  824. source: source,
  825. sourceIndex: sourceIndex
  826. };
  827. unescapeProp(tagOpts, "value");
  828. node = new _tag["default"](tagOpts);
  829. }
  830. _this5.newNode(node, namespace);
  831. // Ensure that the namespace is used only once
  832. namespace = null;
  833. });
  834. this.position++;
  835. };
  836. _proto.word = function word(namespace) {
  837. var nextToken = this.nextToken;
  838. if (nextToken && this.content(nextToken) === '|') {
  839. this.position++;
  840. return this.namespace();
  841. }
  842. return this.splitWord(namespace);
  843. };
  844. _proto.loop = function loop() {
  845. while (this.position < this.tokens.length) {
  846. this.parse(true);
  847. }
  848. this.current._inferEndPosition();
  849. return this.root;
  850. };
  851. _proto.parse = function parse(throwOnParenthesis) {
  852. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  853. case tokens.space:
  854. this.space();
  855. break;
  856. case tokens.comment:
  857. this.comment();
  858. break;
  859. case tokens.openParenthesis:
  860. this.parentheses();
  861. break;
  862. case tokens.closeParenthesis:
  863. if (throwOnParenthesis) {
  864. this.missingParenthesis();
  865. }
  866. break;
  867. case tokens.openSquare:
  868. this.attribute();
  869. break;
  870. case tokens.dollar:
  871. case tokens.caret:
  872. case tokens.equals:
  873. case tokens.word:
  874. this.word();
  875. break;
  876. case tokens.colon:
  877. this.pseudo();
  878. break;
  879. case tokens.comma:
  880. this.comma();
  881. break;
  882. case tokens.asterisk:
  883. this.universal();
  884. break;
  885. case tokens.ampersand:
  886. this.nesting();
  887. break;
  888. case tokens.slash:
  889. case tokens.combinator:
  890. this.combinator();
  891. break;
  892. case tokens.str:
  893. this.string();
  894. break;
  895. // These cases throw; no break needed.
  896. case tokens.closeSquare:
  897. this.missingSquareBracket();
  898. case tokens.semicolon:
  899. this.missingBackslash();
  900. default:
  901. this.unexpected();
  902. }
  903. }
  904. /**
  905. * Helpers
  906. */;
  907. _proto.expected = function expected(description, index, found) {
  908. if (Array.isArray(description)) {
  909. var last = description.pop();
  910. description = description.join(', ') + " or " + last;
  911. }
  912. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  913. if (!found) {
  914. return this.error("Expected " + an + " " + description + ".", {
  915. index: index
  916. });
  917. }
  918. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  919. index: index
  920. });
  921. };
  922. _proto.requiredSpace = function requiredSpace(space) {
  923. return this.options.lossy ? ' ' : space;
  924. };
  925. _proto.optionalSpace = function optionalSpace(space) {
  926. return this.options.lossy ? '' : space;
  927. };
  928. _proto.lossySpace = function lossySpace(space, required) {
  929. if (this.options.lossy) {
  930. return required ? ' ' : '';
  931. } else {
  932. return space;
  933. }
  934. };
  935. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  936. var content = this.content(token);
  937. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  938. return this.requiredSpace(content);
  939. } else {
  940. return content;
  941. }
  942. };
  943. _proto.newNode = function newNode(node, namespace) {
  944. if (namespace) {
  945. if (/^ +$/.test(namespace)) {
  946. if (!this.options.lossy) {
  947. this.spaces = (this.spaces || '') + namespace;
  948. }
  949. namespace = true;
  950. }
  951. node.namespace = namespace;
  952. unescapeProp(node, "namespace");
  953. }
  954. if (this.spaces) {
  955. node.spaces.before = this.spaces;
  956. this.spaces = '';
  957. }
  958. return this.current.append(node);
  959. };
  960. _proto.content = function content(token) {
  961. if (token === void 0) {
  962. token = this.currToken;
  963. }
  964. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  965. };
  966. /**
  967. * returns the index of the next non-whitespace, non-comment token.
  968. * returns -1 if no meaningful token is found.
  969. */
  970. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  971. if (startPosition === void 0) {
  972. startPosition = this.position + 1;
  973. }
  974. var searchPosition = startPosition;
  975. while (searchPosition < this.tokens.length) {
  976. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  977. searchPosition++;
  978. continue;
  979. } else {
  980. return searchPosition;
  981. }
  982. }
  983. return -1;
  984. };
  985. _createClass(Parser, [{
  986. key: "currToken",
  987. get: function get() {
  988. return this.tokens[this.position];
  989. }
  990. }, {
  991. key: "nextToken",
  992. get: function get() {
  993. return this.tokens[this.position + 1];
  994. }
  995. }, {
  996. key: "prevToken",
  997. get: function get() {
  998. return this.tokens[this.position - 1];
  999. }
  1000. }]);
  1001. return Parser;
  1002. }();
  1003. exports["default"] = Parser;
  1004. module.exports = exports.default;