source: trip-planner-front/node_modules/postcss-custom-selectors/index.cjs.js@ 6c1585f

Last change on this file since 6c1585f was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 19.1 KB
Line 
1'use strict';
2
3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
5var parser = _interopDefault(require('postcss-selector-parser'));
6var fs = _interopDefault(require('fs'));
7var path = _interopDefault(require('path'));
8var postcss = _interopDefault(require('postcss'));
9
10function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11 try {
12 var info = gen[key](arg);
13 var value = info.value;
14 } catch (error) {
15 reject(error);
16 return;
17 }
18
19 if (info.done) {
20 resolve(value);
21 } else {
22 Promise.resolve(value).then(_next, _throw);
23 }
24}
25
26function _asyncToGenerator(fn) {
27 return function () {
28 var self = this,
29 args = arguments;
30 return new Promise(function (resolve, reject) {
31 var gen = fn.apply(self, args);
32
33 function _next(value) {
34 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
35 }
36
37 function _throw(err) {
38 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
39 }
40
41 _next(undefined);
42 });
43 };
44}
45
46function _defineProperty(obj, key, value) {
47 if (key in obj) {
48 Object.defineProperty(obj, key, {
49 value: value,
50 enumerable: true,
51 configurable: true,
52 writable: true
53 });
54 } else {
55 obj[key] = value;
56 }
57
58 return obj;
59}
60
61function _objectSpread(target) {
62 for (var i = 1; i < arguments.length; i++) {
63 var source = arguments[i] != null ? arguments[i] : {};
64 var ownKeys = Object.keys(source);
65
66 if (typeof Object.getOwnPropertySymbols === 'function') {
67 ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
68 return Object.getOwnPropertyDescriptor(source, sym).enumerable;
69 }));
70 }
71
72 ownKeys.forEach(function (key) {
73 _defineProperty(target, key, source[key]);
74 });
75 }
76
77 return target;
78}
79
80function _slicedToArray(arr, i) {
81 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
82}
83
84function _arrayWithHoles(arr) {
85 if (Array.isArray(arr)) return arr;
86}
87
88function _iterableToArrayLimit(arr, i) {
89 var _arr = [];
90 var _n = true;
91 var _d = false;
92 var _e = undefined;
93
94 try {
95 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
96 _arr.push(_s.value);
97
98 if (i && _arr.length === i) break;
99 }
100 } catch (err) {
101 _d = true;
102 _e = err;
103 } finally {
104 try {
105 if (!_n && _i["return"] != null) _i["return"]();
106 } finally {
107 if (_d) throw _e;
108 }
109 }
110
111 return _arr;
112}
113
114function _nonIterableRest() {
115 throw new TypeError("Invalid attempt to destructure non-iterable instance");
116}
117
118/* Return a Selectors AST from a Selectors String
119/* ========================================================================== */
120
121var getSelectorsAstFromSelectorsString = (selectorString => {
122 let selectorAST;
123 parser(selectors => {
124 selectorAST = selectors;
125 }).processSync(selectorString);
126 return selectorAST;
127});
128
129var getCustomSelectors = ((root, opts) => {
130 // initialize custom selectors
131 const customSelectors = {}; // for each custom selector atrule that is a child of the css root
132
133 root.nodes.slice().forEach(node => {
134 if (isCustomSelector(node)) {
135 // extract the name and selectors from the params of the custom selector
136 const _node$params$match = node.params.match(customSelectorParamsRegExp),
137 _node$params$match2 = _slicedToArray(_node$params$match, 3),
138 name = _node$params$match2[1],
139 selectors = _node$params$match2[2]; // write the parsed selectors to the custom selector
140
141
142 customSelectors[name] = getSelectorsAstFromSelectorsString(selectors); // conditionally remove the custom selector atrule
143
144 if (!Object(opts).preserve) {
145 node.remove();
146 }
147 }
148 });
149 return customSelectors;
150}); // match the custom selector name
151
152const customSelectorNameRegExp = /^custom-selector$/i; // match the custom selector params
153
154const customSelectorParamsRegExp = /^(:--[A-z][\w-]*)\s+([\W\w]+)\s*$/; // whether the atrule is a custom selector
155
156const isCustomSelector = node => node.type === 'atrule' && customSelectorNameRegExp.test(node.name) && customSelectorParamsRegExp.test(node.params);
157
158// return transformed selectors, replacing custom pseudo selectors with custom selectors
159function transformSelectorList(selectorList, customSelectors) {
160 let index = selectorList.nodes.length - 1;
161
162 while (index >= 0) {
163 const transformedSelectors = transformSelector(selectorList.nodes[index], customSelectors);
164
165 if (transformedSelectors.length) {
166 selectorList.nodes.splice(index, 1, ...transformedSelectors);
167 }
168
169 --index;
170 }
171
172 return selectorList;
173} // return custom pseudo selectors replaced with custom selectors
174
175function transformSelector(selector, customSelectors) {
176 const transpiledSelectors = [];
177
178 for (const index in selector.nodes) {
179 const _selector$nodes$index = selector.nodes[index],
180 value = _selector$nodes$index.value,
181 nodes = _selector$nodes$index.nodes;
182
183 if (value in customSelectors) {
184 var _iteratorNormalCompletion = true;
185 var _didIteratorError = false;
186 var _iteratorError = undefined;
187
188 try {
189 for (var _iterator = customSelectors[value].nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
190 const replacementSelector = _step.value;
191 const selectorClone = selector.clone();
192 selectorClone.nodes.splice(index, 1, ...replacementSelector.clone().nodes.map(node => {
193 // use spacing from the current usage
194 node.spaces = _objectSpread({}, selector.nodes[index].spaces);
195 return node;
196 }));
197 const retranspiledSelectors = transformSelector(selectorClone, customSelectors);
198 adjustNodesBySelectorEnds(selectorClone.nodes, Number(index));
199
200 if (retranspiledSelectors.length) {
201 transpiledSelectors.push(...retranspiledSelectors);
202 } else {
203 transpiledSelectors.push(selectorClone);
204 }
205 }
206 } catch (err) {
207 _didIteratorError = true;
208 _iteratorError = err;
209 } finally {
210 try {
211 if (!_iteratorNormalCompletion && _iterator.return != null) {
212 _iterator.return();
213 }
214 } finally {
215 if (_didIteratorError) {
216 throw _iteratorError;
217 }
218 }
219 }
220
221 return transpiledSelectors;
222 } else if (nodes && nodes.length) {
223 transformSelectorList(selector.nodes[index], customSelectors);
224 }
225 }
226
227 return transpiledSelectors;
228} // match selectors by difficult-to-separate ends
229
230
231const withoutSelectorStartMatch = /^(tag|universal)$/;
232const withoutSelectorEndMatch = /^(class|id|pseudo|tag|universal)$/;
233
234const isWithoutSelectorStart = node => withoutSelectorStartMatch.test(Object(node).type);
235
236const isWithoutSelectorEnd = node => withoutSelectorEndMatch.test(Object(node).type); // adjust nodes by selector ends (so that .class:--h1 becomes h1.class rather than .classh1)
237
238
239const adjustNodesBySelectorEnds = (nodes, index) => {
240 if (index && isWithoutSelectorStart(nodes[index]) && isWithoutSelectorEnd(nodes[index - 1])) {
241 let safeIndex = index - 1;
242
243 while (safeIndex && isWithoutSelectorEnd(nodes[safeIndex])) {
244 --safeIndex;
245 }
246
247 if (safeIndex < index) {
248 const node = nodes.splice(index, 1)[0];
249 nodes.splice(safeIndex, 0, node);
250 nodes[safeIndex].spaces.before = nodes[safeIndex + 1].spaces.before;
251 nodes[safeIndex + 1].spaces.before = '';
252
253 if (nodes[index]) {
254 nodes[index].spaces.after = nodes[safeIndex].spaces.after;
255 nodes[safeIndex].spaces.after = '';
256 }
257 }
258 }
259};
260
261var transformRules = ((root, customSelectors, opts) => {
262 root.walkRules(customPseudoRegExp, rule => {
263 const selector = parser(selectors => {
264 transformSelectorList(selectors, customSelectors, opts);
265 }).processSync(rule.selector);
266
267 if (opts.preserve) {
268 rule.cloneBefore({
269 selector
270 });
271 } else {
272 rule.selector = selector;
273 }
274 });
275});
276const customPseudoRegExp = /:--[A-z][\w-]*/;
277
278/* Import Custom Selectors from CSS AST
279/* ========================================================================== */
280
281function importCustomSelectorsFromCSSAST(root) {
282 return getCustomSelectors(root);
283}
284/* Import Custom Selectors from CSS File
285/* ========================================================================== */
286
287
288function importCustomSelectorsFromCSSFile(_x) {
289 return _importCustomSelectorsFromCSSFile.apply(this, arguments);
290}
291/* Import Custom Selectors from Object
292/* ========================================================================== */
293
294
295function _importCustomSelectorsFromCSSFile() {
296 _importCustomSelectorsFromCSSFile = _asyncToGenerator(function* (from) {
297 const css = yield readFile(path.resolve(from));
298 const root = postcss.parse(css, {
299 from: path.resolve(from)
300 });
301 return importCustomSelectorsFromCSSAST(root);
302 });
303 return _importCustomSelectorsFromCSSFile.apply(this, arguments);
304}
305
306function importCustomSelectorsFromObject(object) {
307 const customSelectors = Object.assign({}, Object(object).customSelectors || Object(object)['custom-selectors']);
308
309 for (const key in customSelectors) {
310 customSelectors[key] = getSelectorsAstFromSelectorsString(customSelectors[key]);
311 }
312
313 return customSelectors;
314}
315/* Import Custom Selectors from JSON file
316/* ========================================================================== */
317
318
319function importCustomSelectorsFromJSONFile(_x2) {
320 return _importCustomSelectorsFromJSONFile.apply(this, arguments);
321}
322/* Import Custom Selectors from JS file
323/* ========================================================================== */
324
325
326function _importCustomSelectorsFromJSONFile() {
327 _importCustomSelectorsFromJSONFile = _asyncToGenerator(function* (from) {
328 const object = yield readJSON(path.resolve(from));
329 return importCustomSelectorsFromObject(object);
330 });
331 return _importCustomSelectorsFromJSONFile.apply(this, arguments);
332}
333
334function importCustomSelectorsFromJSFile(_x3) {
335 return _importCustomSelectorsFromJSFile.apply(this, arguments);
336}
337/* Import Custom Selectors from Sources
338/* ========================================================================== */
339
340
341function _importCustomSelectorsFromJSFile() {
342 _importCustomSelectorsFromJSFile = _asyncToGenerator(function* (from) {
343 const object = yield Promise.resolve(require(path.resolve(from)));
344 return importCustomSelectorsFromObject(object);
345 });
346 return _importCustomSelectorsFromJSFile.apply(this, arguments);
347}
348
349function importCustomSelectorsFromSources(sources) {
350 return sources.map(source => {
351 if (source instanceof Promise) {
352 return source;
353 } else if (source instanceof Function) {
354 return source();
355 } // read the source as an object
356
357
358 const opts = source === Object(source) ? source : {
359 from: String(source)
360 }; // skip objects with custom selectors
361
362 if (Object(opts).customSelectors || Object(opts)['custom-selectors']) {
363 return opts;
364 } // source pathname
365
366
367 const from = String(opts.from || ''); // type of file being read from
368
369 const type = (opts.type || path.extname(from).slice(1)).toLowerCase();
370 return {
371 type,
372 from
373 };
374 }).reduce(
375 /*#__PURE__*/
376 function () {
377 var _ref = _asyncToGenerator(function* (customSelectors, source) {
378 const _ref2 = yield source,
379 type = _ref2.type,
380 from = _ref2.from;
381
382 if (type === 'ast') {
383 return Object.assign(customSelectors, importCustomSelectorsFromCSSAST(from));
384 }
385
386 if (type === 'css') {
387 return Object.assign(customSelectors, (yield importCustomSelectorsFromCSSFile(from)));
388 }
389
390 if (type === 'js') {
391 return Object.assign(customSelectors, (yield importCustomSelectorsFromJSFile(from)));
392 }
393
394 if (type === 'json') {
395 return Object.assign(customSelectors, (yield importCustomSelectorsFromJSONFile(from)));
396 }
397
398 return Object.assign(customSelectors, importCustomSelectorsFromObject((yield source)));
399 });
400
401 return function (_x4, _x5) {
402 return _ref.apply(this, arguments);
403 };
404 }(), {});
405}
406/* Helper utilities
407/* ========================================================================== */
408
409const readFile = from => new Promise((resolve, reject) => {
410 fs.readFile(from, 'utf8', (error, result) => {
411 if (error) {
412 reject(error);
413 } else {
414 resolve(result);
415 }
416 });
417});
418
419const readJSON =
420/*#__PURE__*/
421function () {
422 var _ref3 = _asyncToGenerator(function* (from) {
423 return JSON.parse((yield readFile(from)));
424 });
425
426 return function readJSON(_x6) {
427 return _ref3.apply(this, arguments);
428 };
429}();
430
431/* Import Custom Selectors from CSS File
432/* ========================================================================== */
433
434function exportCustomSelectorsToCssFile(_x, _x2) {
435 return _exportCustomSelectorsToCssFile.apply(this, arguments);
436}
437/* Import Custom Selectors from JSON file
438/* ========================================================================== */
439
440
441function _exportCustomSelectorsToCssFile() {
442 _exportCustomSelectorsToCssFile = _asyncToGenerator(function* (to, customSelectors) {
443 const cssContent = Object.keys(customSelectors).reduce((cssLines, name) => {
444 cssLines.push(`@custom-selector ${name} ${customSelectors[name]};`);
445 return cssLines;
446 }, []).join('\n');
447 const css = `${cssContent}\n`;
448 yield writeFile(to, css);
449 });
450 return _exportCustomSelectorsToCssFile.apply(this, arguments);
451}
452
453function exportCustomSelectorsToJsonFile(_x3, _x4) {
454 return _exportCustomSelectorsToJsonFile.apply(this, arguments);
455}
456/* Import Custom Selectors from Common JS file
457/* ========================================================================== */
458
459
460function _exportCustomSelectorsToJsonFile() {
461 _exportCustomSelectorsToJsonFile = _asyncToGenerator(function* (to, customSelectors) {
462 const jsonContent = JSON.stringify({
463 'custom-selectors': customSelectors
464 }, null, ' ');
465 const json = `${jsonContent}\n`;
466 yield writeFile(to, json);
467 });
468 return _exportCustomSelectorsToJsonFile.apply(this, arguments);
469}
470
471function exportCustomSelectorsToCjsFile(_x5, _x6) {
472 return _exportCustomSelectorsToCjsFile.apply(this, arguments);
473}
474/* Import Custom Selectors from Module JS file
475/* ========================================================================== */
476
477
478function _exportCustomSelectorsToCjsFile() {
479 _exportCustomSelectorsToCjsFile = _asyncToGenerator(function* (to, customSelectors) {
480 const jsContents = Object.keys(customSelectors).reduce((jsLines, name) => {
481 jsLines.push(`\t\t'${escapeForJS(name)}': '${escapeForJS(customSelectors[name])}'`);
482 return jsLines;
483 }, []).join(',\n');
484 const js = `module.exports = {\n\tcustomSelectors: {\n${jsContents}\n\t}\n};\n`;
485 yield writeFile(to, js);
486 });
487 return _exportCustomSelectorsToCjsFile.apply(this, arguments);
488}
489
490function exportCustomSelectorsToMjsFile(_x7, _x8) {
491 return _exportCustomSelectorsToMjsFile.apply(this, arguments);
492}
493/* Export Custom Selectors to Destinations
494/* ========================================================================== */
495
496
497function _exportCustomSelectorsToMjsFile() {
498 _exportCustomSelectorsToMjsFile = _asyncToGenerator(function* (to, customSelectors) {
499 const mjsContents = Object.keys(customSelectors).reduce((mjsLines, name) => {
500 mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customSelectors[name])}'`);
501 return mjsLines;
502 }, []).join(',\n');
503 const mjs = `export const customSelectors = {\n${mjsContents}\n};\n`;
504 yield writeFile(to, mjs);
505 });
506 return _exportCustomSelectorsToMjsFile.apply(this, arguments);
507}
508
509function exportCustomSelectorsToDestinations(customSelectors, destinations) {
510 return Promise.all(destinations.map(
511 /*#__PURE__*/
512 function () {
513 var _ref = _asyncToGenerator(function* (destination) {
514 if (destination instanceof Function) {
515 yield destination(defaultCustomSelectorsToJSON(customSelectors));
516 } else {
517 // read the destination as an object
518 const opts = destination === Object(destination) ? destination : {
519 to: String(destination)
520 }; // transformer for custom selectors into a JSON-compatible object
521
522 const toJSON = opts.toJSON || defaultCustomSelectorsToJSON;
523
524 if ('customSelectors' in opts) {
525 // write directly to an object as customSelectors
526 opts.customSelectors = toJSON(customSelectors);
527 } else if ('custom-selectors' in opts) {
528 // write directly to an object as custom-selectors
529 opts['custom-selectors'] = toJSON(customSelectors);
530 } else {
531 // destination pathname
532 const to = String(opts.to || ''); // type of file being written to
533
534 const type = (opts.type || path.extname(opts.to).slice(1)).toLowerCase(); // transformed custom selectors
535
536 const customSelectorsJSON = toJSON(customSelectors);
537
538 if (type === 'css') {
539 yield exportCustomSelectorsToCssFile(to, customSelectorsJSON);
540 }
541
542 if (type === 'js') {
543 yield exportCustomSelectorsToCjsFile(to, customSelectorsJSON);
544 }
545
546 if (type === 'json') {
547 yield exportCustomSelectorsToJsonFile(to, customSelectorsJSON);
548 }
549
550 if (type === 'mjs') {
551 yield exportCustomSelectorsToMjsFile(to, customSelectorsJSON);
552 }
553 }
554 }
555 });
556
557 return function (_x9) {
558 return _ref.apply(this, arguments);
559 };
560 }()));
561}
562/* Helper utilities
563/* ========================================================================== */
564
565const defaultCustomSelectorsToJSON = customSelectors => {
566 return Object.keys(customSelectors).reduce((customSelectorsJSON, key) => {
567 customSelectorsJSON[key] = String(customSelectors[key]);
568 return customSelectorsJSON;
569 }, {});
570};
571
572const writeFile = (to, text) => new Promise((resolve, reject) => {
573 fs.writeFile(to, text, error => {
574 if (error) {
575 reject(error);
576 } else {
577 resolve();
578 }
579 });
580});
581
582const escapeForJS = string => string.replace(/\\([\s\S])|(')/g, '\\$1$2').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
583
584var index = postcss.plugin('postcss-custom-selectors', opts => {
585 // whether to preserve custom selectors and rules using them
586 const preserve = Boolean(Object(opts).preserve); // sources to import custom selectors from
587
588 const importFrom = [].concat(Object(opts).importFrom || []); // destinations to export custom selectors to
589
590 const exportTo = [].concat(Object(opts).exportTo || []); // promise any custom selectors are imported
591
592 const customSelectorsPromise = importCustomSelectorsFromSources(importFrom);
593 return (
594 /*#__PURE__*/
595 function () {
596 var _ref = _asyncToGenerator(function* (root) {
597 const customProperties = Object.assign((yield customSelectorsPromise), getCustomSelectors(root, {
598 preserve
599 }));
600 yield exportCustomSelectorsToDestinations(customProperties, exportTo);
601 transformRules(root, customProperties, {
602 preserve
603 });
604 });
605
606 return function (_x) {
607 return _ref.apply(this, arguments);
608 };
609 }()
610 );
611});
612
613module.exports = index;
614//# sourceMappingURL=index.cjs.js.map
Note: See TracBrowser for help on using the repository browser.