parser.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  23. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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); 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 && // this look-ahead probably fails with comment nodes involved.
  247. !node.operator && !node.namespace) {
  248. node.namespace = content;
  249. lastAdded = 'namespace';
  250. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  251. if (spaceBefore) {
  252. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  253. node.spaces.attribute.before = spaceBefore;
  254. spaceBefore = '';
  255. }
  256. if (commentBefore) {
  257. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  258. node.raws.spaces.attribute.before = commentBefore;
  259. commentBefore = '';
  260. }
  261. node.attribute = (node.attribute || "") + content;
  262. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  263. if (_rawValue) {
  264. node.raws.attribute += content;
  265. }
  266. lastAdded = 'attribute';
  267. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  268. var _unescaped = (0, _util.unesc)(content);
  269. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  270. var oldValue = node.value || '';
  271. node.value = oldValue + _unescaped;
  272. node.quoteMark = null;
  273. if (_unescaped !== content || _oldRawValue) {
  274. (0, _util.ensureObject)(node, 'raws');
  275. node.raws.value = (_oldRawValue || oldValue) + content;
  276. }
  277. lastAdded = 'value';
  278. } else {
  279. var insensitive = content === 'i' || content === "I";
  280. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  281. node.insensitive = insensitive;
  282. if (!insensitive || content === "I") {
  283. (0, _util.ensureObject)(node, 'raws');
  284. node.raws.insensitiveFlag = content;
  285. }
  286. lastAdded = 'insensitive';
  287. if (spaceBefore) {
  288. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  289. node.spaces.insensitive.before = spaceBefore;
  290. spaceBefore = '';
  291. }
  292. if (commentBefore) {
  293. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  294. node.raws.spaces.insensitive.before = commentBefore;
  295. commentBefore = '';
  296. }
  297. } else if (node.value || node.value === '') {
  298. lastAdded = 'value';
  299. node.value += content;
  300. if (node.raws.value) {
  301. node.raws.value += content;
  302. }
  303. }
  304. }
  305. spaceAfterMeaningfulToken = false;
  306. break;
  307. case tokens.str:
  308. if (!node.attribute || !node.operator) {
  309. return this.error("Expected an attribute followed by an operator preceding the string.", {
  310. index: token[_tokenize.FIELDS.START_POS]
  311. });
  312. }
  313. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  314. unescaped = _unescapeValue.unescaped,
  315. quoteMark = _unescapeValue.quoteMark;
  316. node.value = unescaped;
  317. node.quoteMark = quoteMark;
  318. lastAdded = 'value';
  319. (0, _util.ensureObject)(node, 'raws');
  320. node.raws.value = content;
  321. spaceAfterMeaningfulToken = false;
  322. break;
  323. case tokens.equals:
  324. if (!node.attribute) {
  325. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  326. }
  327. if (node.value) {
  328. return this.error('Unexpected "=" found; an operator was already defined.', {
  329. index: token[_tokenize.FIELDS.START_POS]
  330. });
  331. }
  332. node.operator = node.operator ? node.operator + content : content;
  333. lastAdded = 'operator';
  334. spaceAfterMeaningfulToken = false;
  335. break;
  336. case tokens.comment:
  337. if (lastAdded) {
  338. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  339. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  340. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  341. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  342. node.raws.spaces[lastAdded].after = rawLastComment + content;
  343. } else {
  344. var lastValue = node[lastAdded] || '';
  345. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  346. (0, _util.ensureObject)(node, 'raws');
  347. node.raws[lastAdded] = rawLastValue + content;
  348. }
  349. } else {
  350. commentBefore = commentBefore + content;
  351. }
  352. break;
  353. default:
  354. return this.error("Unexpected \"" + content + "\" found.", {
  355. index: token[_tokenize.FIELDS.START_POS]
  356. });
  357. }
  358. pos++;
  359. }
  360. unescapeProp(node, "attribute");
  361. unescapeProp(node, "namespace");
  362. this.newNode(new _attribute["default"](node));
  363. this.position++;
  364. }
  365. /**
  366. * return a node containing meaningless garbage up to (but not including) the specified token position.
  367. * if the token position is negative, all remaining tokens are consumed.
  368. *
  369. * This returns an array containing a single string node if all whitespace,
  370. * otherwise an array of comment nodes with space before and after.
  371. *
  372. * These tokens are not added to the current selector, the caller can add them or use them to amend
  373. * a previous node's space metadata.
  374. *
  375. * In lossy mode, this returns only comments.
  376. */
  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. ;
  430. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  431. var _this2 = this;
  432. if (requiredSpace === void 0) {
  433. requiredSpace = false;
  434. }
  435. var space = "";
  436. var rawSpace = "";
  437. nodes.forEach(function (n) {
  438. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  439. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  440. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  441. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  442. });
  443. if (rawSpace === space) {
  444. rawSpace = undefined;
  445. }
  446. var result = {
  447. space: space,
  448. rawSpace: rawSpace
  449. };
  450. return result;
  451. };
  452. _proto.isNamedCombinator = function isNamedCombinator(position) {
  453. if (position === void 0) {
  454. position = this.position;
  455. }
  456. 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;
  457. };
  458. _proto.namedCombinator = function namedCombinator() {
  459. if (this.isNamedCombinator()) {
  460. var nameRaw = this.content(this.tokens[this.position + 1]);
  461. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  462. var raws = {};
  463. if (name !== nameRaw) {
  464. raws.value = "/" + nameRaw + "/";
  465. }
  466. var node = new _combinator["default"]({
  467. value: "/" + name + "/",
  468. 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]),
  469. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  470. raws: raws
  471. });
  472. this.position = this.position + 3;
  473. return node;
  474. } else {
  475. this.unexpected();
  476. }
  477. };
  478. _proto.combinator = function combinator() {
  479. var _this3 = this;
  480. if (this.content() === '|') {
  481. return this.namespace();
  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]]) {// pass
  520. } else if (!spaceOrDescendantSelectorNodes) {
  521. this.unexpected();
  522. }
  523. if (node) {
  524. if (spaceOrDescendantSelectorNodes) {
  525. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  526. _space = _this$convertWhitespa2.space,
  527. _rawSpace = _this$convertWhitespa2.rawSpace;
  528. node.spaces.before = _space;
  529. node.rawSpaceBefore = _rawSpace;
  530. }
  531. } else {
  532. // descendant combinator
  533. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  534. _space2 = _this$convertWhitespa3.space,
  535. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  536. if (!_rawSpace2) {
  537. _rawSpace2 = _space2;
  538. }
  539. var spaces = {};
  540. var raws = {
  541. spaces: {}
  542. };
  543. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  544. spaces.before = _space2.slice(0, _space2.length - 1);
  545. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  546. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  547. spaces.after = _space2.slice(1);
  548. raws.spaces.after = _rawSpace2.slice(1);
  549. } else {
  550. raws.value = _rawSpace2;
  551. }
  552. node = new _combinator["default"]({
  553. value: ' ',
  554. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  555. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  556. spaces: spaces,
  557. raws: raws
  558. });
  559. }
  560. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  561. node.spaces.after = this.optionalSpace(this.content());
  562. this.position++;
  563. }
  564. return this.newNode(node);
  565. };
  566. _proto.comma = function comma() {
  567. if (this.position === this.tokens.length - 1) {
  568. this.root.trailingComma = true;
  569. this.position++;
  570. return;
  571. }
  572. this.current._inferEndPosition();
  573. var selector = new _selector["default"]({
  574. source: {
  575. start: tokenStart(this.tokens[this.position + 1])
  576. }
  577. });
  578. this.current.parent.append(selector);
  579. this.current = selector;
  580. this.position++;
  581. };
  582. _proto.comment = function comment() {
  583. var current = this.currToken;
  584. this.newNode(new _comment["default"]({
  585. value: this.content(),
  586. source: getTokenSource(current),
  587. sourceIndex: current[_tokenize.FIELDS.START_POS]
  588. }));
  589. this.position++;
  590. };
  591. _proto.error = function error(message, opts) {
  592. throw this.root.error(message, opts);
  593. };
  594. _proto.missingBackslash = function missingBackslash() {
  595. return this.error('Expected a backslash preceding the semicolon.', {
  596. index: this.currToken[_tokenize.FIELDS.START_POS]
  597. });
  598. };
  599. _proto.missingParenthesis = function missingParenthesis() {
  600. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  601. };
  602. _proto.missingSquareBracket = function missingSquareBracket() {
  603. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  604. };
  605. _proto.unexpected = function unexpected() {
  606. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  607. };
  608. _proto.namespace = function namespace() {
  609. var before = this.prevToken && this.content(this.prevToken) || true;
  610. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  611. this.position++;
  612. return this.word(before);
  613. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  614. this.position++;
  615. return this.universal(before);
  616. }
  617. };
  618. _proto.nesting = function nesting() {
  619. if (this.nextToken) {
  620. var nextContent = this.content(this.nextToken);
  621. if (nextContent === "|") {
  622. this.position++;
  623. return;
  624. }
  625. }
  626. var current = this.currToken;
  627. this.newNode(new _nesting["default"]({
  628. value: this.content(),
  629. source: getTokenSource(current),
  630. sourceIndex: current[_tokenize.FIELDS.START_POS]
  631. }));
  632. this.position++;
  633. };
  634. _proto.parentheses = function parentheses() {
  635. var last = this.current.last;
  636. var unbalanced = 1;
  637. this.position++;
  638. if (last && last.type === types.PSEUDO) {
  639. var selector = new _selector["default"]({
  640. source: {
  641. start: tokenStart(this.tokens[this.position - 1])
  642. }
  643. });
  644. var cache = this.current;
  645. last.append(selector);
  646. this.current = selector;
  647. while (this.position < this.tokens.length && unbalanced) {
  648. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  649. unbalanced++;
  650. }
  651. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  652. unbalanced--;
  653. }
  654. if (unbalanced) {
  655. this.parse();
  656. } else {
  657. this.current.source.end = tokenEnd(this.currToken);
  658. this.current.parent.source.end = tokenEnd(this.currToken);
  659. this.position++;
  660. }
  661. }
  662. this.current = cache;
  663. } else {
  664. // I think this case should be an error. It's used to implement a basic parse of media queries
  665. // but I don't think it's a good idea.
  666. var parenStart = this.currToken;
  667. var parenValue = "(";
  668. var parenEnd;
  669. while (this.position < this.tokens.length && unbalanced) {
  670. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  671. unbalanced++;
  672. }
  673. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  674. unbalanced--;
  675. }
  676. parenEnd = this.currToken;
  677. parenValue += this.parseParenthesisToken(this.currToken);
  678. this.position++;
  679. }
  680. if (last) {
  681. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  682. } else {
  683. this.newNode(new _string["default"]({
  684. value: parenValue,
  685. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  686. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  687. }));
  688. }
  689. }
  690. if (unbalanced) {
  691. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  692. }
  693. };
  694. _proto.pseudo = function pseudo() {
  695. var _this4 = this;
  696. var pseudoStr = '';
  697. var startingToken = this.currToken;
  698. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  699. pseudoStr += this.content();
  700. this.position++;
  701. }
  702. if (!this.currToken) {
  703. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  704. }
  705. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  706. this.splitWord(false, function (first, length) {
  707. pseudoStr += first;
  708. _this4.newNode(new _pseudo["default"]({
  709. value: pseudoStr,
  710. source: getTokenSourceSpan(startingToken, _this4.currToken),
  711. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  712. }));
  713. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  714. _this4.error('Misplaced parenthesis.', {
  715. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  716. });
  717. }
  718. });
  719. } else {
  720. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  721. }
  722. };
  723. _proto.space = function space() {
  724. var content = this.content(); // Handle space before and after the selector
  725. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  726. return node.type === 'comment';
  727. })) {
  728. this.spaces = this.optionalSpace(content);
  729. this.position++;
  730. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  731. this.current.last.spaces.after = this.optionalSpace(content);
  732. this.position++;
  733. } else {
  734. this.combinator();
  735. }
  736. };
  737. _proto.string = function string() {
  738. var current = this.currToken;
  739. this.newNode(new _string["default"]({
  740. value: this.content(),
  741. source: getTokenSource(current),
  742. sourceIndex: current[_tokenize.FIELDS.START_POS]
  743. }));
  744. this.position++;
  745. };
  746. _proto.universal = function universal(namespace) {
  747. var nextToken = this.nextToken;
  748. if (nextToken && this.content(nextToken) === '|') {
  749. this.position++;
  750. return this.namespace();
  751. }
  752. var current = this.currToken;
  753. this.newNode(new _universal["default"]({
  754. value: this.content(),
  755. source: getTokenSource(current),
  756. sourceIndex: current[_tokenize.FIELDS.START_POS]
  757. }), namespace);
  758. this.position++;
  759. };
  760. _proto.splitWord = function splitWord(namespace, firstCallback) {
  761. var _this5 = this;
  762. var nextToken = this.nextToken;
  763. var word = this.content();
  764. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  765. this.position++;
  766. var current = this.content();
  767. word += current;
  768. if (current.lastIndexOf('\\') === current.length - 1) {
  769. var next = this.nextToken;
  770. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  771. word += this.requiredSpace(this.content(next));
  772. this.position++;
  773. }
  774. }
  775. nextToken = this.nextToken;
  776. }
  777. var hasClass = indexesOf(word, '.').filter(function (i) {
  778. // Allow escaped dot within class name
  779. var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes
  780. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  781. return !escapedDot && !isKeyframesPercent;
  782. });
  783. var hasId = indexesOf(word, '#').filter(function (i) {
  784. return word[i - 1] !== '\\';
  785. }); // Eliminate Sass interpolations from the list of id indexes
  786. var interpolations = indexesOf(word, '#{');
  787. if (interpolations.length) {
  788. hasId = hasId.filter(function (hashIndex) {
  789. return !~interpolations.indexOf(hashIndex);
  790. });
  791. }
  792. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  793. indices.forEach(function (ind, i) {
  794. var index = indices[i + 1] || word.length;
  795. var value = word.slice(ind, index);
  796. if (i === 0 && firstCallback) {
  797. return firstCallback.call(_this5, value, indices.length);
  798. }
  799. var node;
  800. var current = _this5.currToken;
  801. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  802. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  803. if (~hasClass.indexOf(ind)) {
  804. var classNameOpts = {
  805. value: value.slice(1),
  806. source: source,
  807. sourceIndex: sourceIndex
  808. };
  809. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  810. } else if (~hasId.indexOf(ind)) {
  811. var idOpts = {
  812. value: value.slice(1),
  813. source: source,
  814. sourceIndex: sourceIndex
  815. };
  816. node = new _id["default"](unescapeProp(idOpts, "value"));
  817. } else {
  818. var tagOpts = {
  819. value: value,
  820. source: source,
  821. sourceIndex: sourceIndex
  822. };
  823. unescapeProp(tagOpts, "value");
  824. node = new _tag["default"](tagOpts);
  825. }
  826. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  827. namespace = null;
  828. });
  829. this.position++;
  830. };
  831. _proto.word = function word(namespace) {
  832. var nextToken = this.nextToken;
  833. if (nextToken && this.content(nextToken) === '|') {
  834. this.position++;
  835. return this.namespace();
  836. }
  837. return this.splitWord(namespace);
  838. };
  839. _proto.loop = function loop() {
  840. while (this.position < this.tokens.length) {
  841. this.parse(true);
  842. }
  843. this.current._inferEndPosition();
  844. return this.root;
  845. };
  846. _proto.parse = function parse(throwOnParenthesis) {
  847. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  848. case tokens.space:
  849. this.space();
  850. break;
  851. case tokens.comment:
  852. this.comment();
  853. break;
  854. case tokens.openParenthesis:
  855. this.parentheses();
  856. break;
  857. case tokens.closeParenthesis:
  858. if (throwOnParenthesis) {
  859. this.missingParenthesis();
  860. }
  861. break;
  862. case tokens.openSquare:
  863. this.attribute();
  864. break;
  865. case tokens.dollar:
  866. case tokens.caret:
  867. case tokens.equals:
  868. case tokens.word:
  869. this.word();
  870. break;
  871. case tokens.colon:
  872. this.pseudo();
  873. break;
  874. case tokens.comma:
  875. this.comma();
  876. break;
  877. case tokens.asterisk:
  878. this.universal();
  879. break;
  880. case tokens.ampersand:
  881. this.nesting();
  882. break;
  883. case tokens.slash:
  884. case tokens.combinator:
  885. this.combinator();
  886. break;
  887. case tokens.str:
  888. this.string();
  889. break;
  890. // These cases throw; no break needed.
  891. case tokens.closeSquare:
  892. this.missingSquareBracket();
  893. case tokens.semicolon:
  894. this.missingBackslash();
  895. default:
  896. this.unexpected();
  897. }
  898. }
  899. /**
  900. * Helpers
  901. */
  902. ;
  903. _proto.expected = function expected(description, index, found) {
  904. if (Array.isArray(description)) {
  905. var last = description.pop();
  906. description = description.join(', ') + " or " + last;
  907. }
  908. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  909. if (!found) {
  910. return this.error("Expected " + an + " " + description + ".", {
  911. index: index
  912. });
  913. }
  914. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  915. index: index
  916. });
  917. };
  918. _proto.requiredSpace = function requiredSpace(space) {
  919. return this.options.lossy ? ' ' : space;
  920. };
  921. _proto.optionalSpace = function optionalSpace(space) {
  922. return this.options.lossy ? '' : space;
  923. };
  924. _proto.lossySpace = function lossySpace(space, required) {
  925. if (this.options.lossy) {
  926. return required ? ' ' : '';
  927. } else {
  928. return space;
  929. }
  930. };
  931. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  932. var content = this.content(token);
  933. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  934. return this.requiredSpace(content);
  935. } else {
  936. return content;
  937. }
  938. };
  939. _proto.newNode = function newNode(node, namespace) {
  940. if (namespace) {
  941. if (/^ +$/.test(namespace)) {
  942. if (!this.options.lossy) {
  943. this.spaces = (this.spaces || '') + namespace;
  944. }
  945. namespace = true;
  946. }
  947. node.namespace = namespace;
  948. unescapeProp(node, "namespace");
  949. }
  950. if (this.spaces) {
  951. node.spaces.before = this.spaces;
  952. this.spaces = '';
  953. }
  954. return this.current.append(node);
  955. };
  956. _proto.content = function content(token) {
  957. if (token === void 0) {
  958. token = this.currToken;
  959. }
  960. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  961. };
  962. /**
  963. * returns the index of the next non-whitespace, non-comment token.
  964. * returns -1 if no meaningful token is found.
  965. */
  966. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  967. if (startPosition === void 0) {
  968. startPosition = this.position + 1;
  969. }
  970. var searchPosition = startPosition;
  971. while (searchPosition < this.tokens.length) {
  972. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  973. searchPosition++;
  974. continue;
  975. } else {
  976. return searchPosition;
  977. }
  978. }
  979. return -1;
  980. };
  981. _createClass(Parser, [{
  982. key: "currToken",
  983. get: function get() {
  984. return this.tokens[this.position];
  985. }
  986. }, {
  987. key: "nextToken",
  988. get: function get() {
  989. return this.tokens[this.position + 1];
  990. }
  991. }, {
  992. key: "prevToken",
  993. get: function get() {
  994. return this.tokens[this.position - 1];
  995. }
  996. }]);
  997. return Parser;
  998. }();
  999. exports["default"] = Parser;
  1000. module.exports = exports.default;