source: trip-planner-front/node_modules/postcss-custom-properties/index.esm.mjs@ 8d391a1

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

initial commit

  • Property mode set to 100644
File size: 18.0 KB
Line 
1import postcss from 'postcss';
2import valueParser from 'postcss-values-parser';
3import fs from 'fs';
4import path from 'path';
5
6function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
7 try {
8 var info = gen[key](arg);
9 var value = info.value;
10 } catch (error) {
11 reject(error);
12 return;
13 }
14
15 if (info.done) {
16 resolve(value);
17 } else {
18 Promise.resolve(value).then(_next, _throw);
19 }
20}
21
22function _asyncToGenerator(fn) {
23 return function () {
24 var self = this,
25 args = arguments;
26 return new Promise(function (resolve, reject) {
27 var gen = fn.apply(self, args);
28
29 function _next(value) {
30 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31 }
32
33 function _throw(err) {
34 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
35 }
36
37 _next(undefined);
38 });
39 };
40}
41
42function parse(string) {
43 return valueParser(string).parse();
44}
45
46function isBlockIgnored(ruleOrDeclaration) {
47 var rule = ruleOrDeclaration.selector ? ruleOrDeclaration : ruleOrDeclaration.parent;
48 return /(!\s*)?postcss-custom-properties:\s*off\b/i.test(rule.toString());
49}
50
51function isRuleIgnored(rule) {
52 var previous = rule.prev();
53 return Boolean(isBlockIgnored(rule) || previous && previous.type === 'comment' && /(!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i.test(previous.text));
54}
55
56function getCustomPropertiesFromRoot(root, opts) {
57 // initialize custom selectors
58 const customPropertiesFromHtmlElement = {};
59 const customPropertiesFromRootPseudo = {}; // for each html or :root rule
60
61 root.nodes.slice().forEach(rule => {
62 const customPropertiesObject = isHtmlRule(rule) ? customPropertiesFromHtmlElement : isRootRule(rule) ? customPropertiesFromRootPseudo : null; // for each custom property
63
64 if (customPropertiesObject) {
65 rule.nodes.slice().forEach(decl => {
66 if (isCustomDecl(decl) && !isBlockIgnored(decl)) {
67 const prop = decl.prop; // write the parsed value to the custom property
68
69 customPropertiesObject[prop] = parse(decl.value).nodes; // conditionally remove the custom property declaration
70
71 if (!opts.preserve) {
72 decl.remove();
73 }
74 }
75 }); // conditionally remove the empty html or :root rule
76
77 if (!opts.preserve && isEmptyParent(rule) && !isBlockIgnored(rule)) {
78 rule.remove();
79 }
80 }
81 }); // return all custom properties, preferring :root properties over html properties
82
83 return Object.assign({}, customPropertiesFromHtmlElement, customPropertiesFromRootPseudo);
84} // match html and :root rules
85
86const htmlSelectorRegExp = /^html$/i;
87const rootSelectorRegExp = /^:root$/i;
88const customPropertyRegExp = /^--[A-z][\w-]*$/; // whether the node is an html or :root rule
89
90const isHtmlRule = node => node.type === 'rule' && htmlSelectorRegExp.test(node.selector) && Object(node.nodes).length;
91
92const isRootRule = node => node.type === 'rule' && rootSelectorRegExp.test(node.selector) && Object(node.nodes).length; // whether the node is an custom property
93
94
95const isCustomDecl = node => node.type === 'decl' && customPropertyRegExp.test(node.prop); // whether the node is a parent without children
96
97
98const isEmptyParent = node => Object(node.nodes).length === 0;
99
100/* Get Custom Properties from CSS File
101/* ========================================================================== */
102
103function getCustomPropertiesFromCSSFile(_x) {
104 return _getCustomPropertiesFromCSSFile.apply(this, arguments);
105}
106/* Get Custom Properties from Object
107/* ========================================================================== */
108
109
110function _getCustomPropertiesFromCSSFile() {
111 _getCustomPropertiesFromCSSFile = _asyncToGenerator(function* (from) {
112 const css = yield readFile(from);
113 const root = postcss.parse(css, {
114 from
115 });
116 return getCustomPropertiesFromRoot(root, {
117 preserve: true
118 });
119 });
120 return _getCustomPropertiesFromCSSFile.apply(this, arguments);
121}
122
123function getCustomPropertiesFromObject(object) {
124 const customProperties = Object.assign({}, Object(object).customProperties, Object(object)['custom-properties']);
125
126 for (const key in customProperties) {
127 customProperties[key] = parse(String(customProperties[key])).nodes;
128 }
129
130 return customProperties;
131}
132/* Get Custom Properties from JSON file
133/* ========================================================================== */
134
135
136function getCustomPropertiesFromJSONFile(_x2) {
137 return _getCustomPropertiesFromJSONFile.apply(this, arguments);
138}
139/* Get Custom Properties from JS file
140/* ========================================================================== */
141
142
143function _getCustomPropertiesFromJSONFile() {
144 _getCustomPropertiesFromJSONFile = _asyncToGenerator(function* (from) {
145 const object = yield readJSON(from);
146 return getCustomPropertiesFromObject(object);
147 });
148 return _getCustomPropertiesFromJSONFile.apply(this, arguments);
149}
150
151function getCustomPropertiesFromJSFile(_x3) {
152 return _getCustomPropertiesFromJSFile.apply(this, arguments);
153}
154/* Get Custom Properties from Imports
155/* ========================================================================== */
156
157
158function _getCustomPropertiesFromJSFile() {
159 _getCustomPropertiesFromJSFile = _asyncToGenerator(function* (from) {
160 const object = yield import(from);
161 return getCustomPropertiesFromObject(object);
162 });
163 return _getCustomPropertiesFromJSFile.apply(this, arguments);
164}
165
166function getCustomPropertiesFromImports(sources) {
167 return sources.map(source => {
168 if (source instanceof Promise) {
169 return source;
170 } else if (source instanceof Function) {
171 return source();
172 } // read the source as an object
173
174
175 const opts = source === Object(source) ? source : {
176 from: String(source)
177 }; // skip objects with Custom Properties
178
179 if (opts.customProperties || opts['custom-properties']) {
180 return opts;
181 } // source pathname
182
183
184 const from = path.resolve(String(opts.from || '')); // type of file being read from
185
186 const type = (opts.type || path.extname(from).slice(1)).toLowerCase();
187 return {
188 type,
189 from
190 };
191 }).reduce(
192 /*#__PURE__*/
193 function () {
194 var _ref = _asyncToGenerator(function* (customProperties, source) {
195 const _ref2 = yield source,
196 type = _ref2.type,
197 from = _ref2.from;
198
199 if (type === 'css') {
200 return Object.assign((yield customProperties), (yield getCustomPropertiesFromCSSFile(from)));
201 }
202
203 if (type === 'js') {
204 return Object.assign((yield customProperties), (yield getCustomPropertiesFromJSFile(from)));
205 }
206
207 if (type === 'json') {
208 return Object.assign((yield customProperties), (yield getCustomPropertiesFromJSONFile(from)));
209 }
210
211 return Object.assign((yield customProperties), (yield getCustomPropertiesFromObject((yield source))));
212 });
213
214 return function (_x4, _x5) {
215 return _ref.apply(this, arguments);
216 };
217 }(), {});
218}
219/* Helper utilities
220/* ========================================================================== */
221
222const readFile = from => new Promise((resolve, reject) => {
223 fs.readFile(from, 'utf8', (error, result) => {
224 if (error) {
225 reject(error);
226 } else {
227 resolve(result);
228 }
229 });
230});
231
232const readJSON =
233/*#__PURE__*/
234function () {
235 var _ref3 = _asyncToGenerator(function* (from) {
236 return JSON.parse((yield readFile(from)));
237 });
238
239 return function readJSON(_x6) {
240 return _ref3.apply(this, arguments);
241 };
242}();
243
244function transformValueAST(root, customProperties) {
245 if (root.nodes && root.nodes.length) {
246 root.nodes.slice().forEach(child => {
247 if (isVarFunction(child)) {
248 // eslint-disable-next-line no-unused-vars
249 const _child$nodes$slice = child.nodes.slice(1, -1),
250 propertyNode = _child$nodes$slice[0],
251 comma = _child$nodes$slice[1],
252 fallbacks = _child$nodes$slice.slice(2);
253
254 const name = propertyNode.value;
255
256 if (name in Object(customProperties)) {
257 // conditionally replace a known custom property
258 const nodes = asClonedArrayWithBeforeSpacing(customProperties[name], child.raws.before);
259 child.replaceWith(...nodes);
260 retransformValueAST({
261 nodes
262 }, customProperties, name);
263 } else if (fallbacks.length) {
264 // conditionally replace a custom property with a fallback
265 const index = root.nodes.indexOf(child);
266
267 if (index !== -1) {
268 root.nodes.splice(index, 1, ...asClonedArrayWithBeforeSpacing(fallbacks, child.raws.before));
269 }
270
271 transformValueAST(root, customProperties);
272 }
273 } else {
274 transformValueAST(child, customProperties);
275 }
276 });
277 }
278
279 return root;
280} // retransform the current ast without a custom property (to prevent recursion)
281
282function retransformValueAST(root, customProperties, withoutProperty) {
283 const nextCustomProperties = Object.assign({}, customProperties);
284 delete nextCustomProperties[withoutProperty];
285 return transformValueAST(root, nextCustomProperties);
286} // match var() functions
287
288
289const varRegExp = /^var$/i; // whether the node is a var() function
290
291const isVarFunction = node => node.type === 'func' && varRegExp.test(node.value) && Object(node.nodes).length > 0; // return an array with its nodes cloned, preserving the raw
292
293
294const asClonedArrayWithBeforeSpacing = (array, beforeSpacing) => {
295 const clonedArray = asClonedArray(array, null);
296
297 if (clonedArray[0]) {
298 clonedArray[0].raws.before = beforeSpacing;
299 }
300
301 return clonedArray;
302}; // return an array with its nodes cloned
303
304
305const asClonedArray = (array, parent) => array.map(node => asClonedNode(node, parent)); // return a cloned node
306
307
308const asClonedNode = (node, parent) => {
309 const cloneNode = new node.constructor(node);
310
311 for (const key in node) {
312 if (key === 'parent') {
313 cloneNode.parent = parent;
314 } else if (Object(node[key]).constructor === Array) {
315 cloneNode[key] = asClonedArray(node.nodes, cloneNode);
316 } else if (Object(node[key]).constructor === Object) {
317 cloneNode[key] = Object.assign({}, node[key]);
318 }
319 }
320
321 return cloneNode;
322};
323
324var transformProperties = ((root, customProperties, opts) => {
325 // walk decls that can be transformed
326 root.walkDecls(decl => {
327 if (isTransformableDecl(decl) && !isRuleIgnored(decl)) {
328 const originalValue = decl.value;
329 const valueAST = parse(originalValue);
330 const value = String(transformValueAST(valueAST, customProperties)); // conditionally transform values that have changed
331
332 if (value !== originalValue) {
333 if (opts.preserve) {
334 decl.cloneBefore({
335 value
336 });
337 } else {
338 decl.value = value;
339 }
340 }
341 }
342 });
343}); // match custom properties
344
345const customPropertyRegExp$1 = /^--[A-z][\w-]*$/; // match custom property inclusions
346
347const customPropertiesRegExp = /(^|[^\w-])var\([\W\w]+\)/; // whether the declaration should be potentially transformed
348
349const isTransformableDecl = decl => !customPropertyRegExp$1.test(decl.prop) && customPropertiesRegExp.test(decl.value);
350
351/* Write Custom Properties to CSS File
352/* ========================================================================== */
353
354function writeCustomPropertiesToCssFile(_x, _x2) {
355 return _writeCustomPropertiesToCssFile.apply(this, arguments);
356}
357/* Write Custom Properties to JSON file
358/* ========================================================================== */
359
360
361function _writeCustomPropertiesToCssFile() {
362 _writeCustomPropertiesToCssFile = _asyncToGenerator(function* (to, customProperties) {
363 const cssContent = Object.keys(customProperties).reduce((cssLines, name) => {
364 cssLines.push(`\t${name}: ${customProperties[name]};`);
365 return cssLines;
366 }, []).join('\n');
367 const css = `:root {\n${cssContent}\n}\n`;
368 yield writeFile(to, css);
369 });
370 return _writeCustomPropertiesToCssFile.apply(this, arguments);
371}
372
373function writeCustomPropertiesToJsonFile(_x3, _x4) {
374 return _writeCustomPropertiesToJsonFile.apply(this, arguments);
375}
376/* Write Custom Properties to Common JS file
377/* ========================================================================== */
378
379
380function _writeCustomPropertiesToJsonFile() {
381 _writeCustomPropertiesToJsonFile = _asyncToGenerator(function* (to, customProperties) {
382 const jsonContent = JSON.stringify({
383 'custom-properties': customProperties
384 }, null, ' ');
385 const json = `${jsonContent}\n`;
386 yield writeFile(to, json);
387 });
388 return _writeCustomPropertiesToJsonFile.apply(this, arguments);
389}
390
391function writeCustomPropertiesToCjsFile(_x5, _x6) {
392 return _writeCustomPropertiesToCjsFile.apply(this, arguments);
393}
394/* Write Custom Properties to Module JS file
395/* ========================================================================== */
396
397
398function _writeCustomPropertiesToCjsFile() {
399 _writeCustomPropertiesToCjsFile = _asyncToGenerator(function* (to, customProperties) {
400 const jsContents = Object.keys(customProperties).reduce((jsLines, name) => {
401 jsLines.push(`\t\t'${escapeForJS(name)}': '${escapeForJS(customProperties[name])}'`);
402 return jsLines;
403 }, []).join(',\n');
404 const js = `module.exports = {\n\tcustomProperties: {\n${jsContents}\n\t}\n};\n`;
405 yield writeFile(to, js);
406 });
407 return _writeCustomPropertiesToCjsFile.apply(this, arguments);
408}
409
410function writeCustomPropertiesToMjsFile(_x7, _x8) {
411 return _writeCustomPropertiesToMjsFile.apply(this, arguments);
412}
413/* Write Custom Properties to Exports
414/* ========================================================================== */
415
416
417function _writeCustomPropertiesToMjsFile() {
418 _writeCustomPropertiesToMjsFile = _asyncToGenerator(function* (to, customProperties) {
419 const mjsContents = Object.keys(customProperties).reduce((mjsLines, name) => {
420 mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customProperties[name])}'`);
421 return mjsLines;
422 }, []).join(',\n');
423 const mjs = `export const customProperties = {\n${mjsContents}\n};\n`;
424 yield writeFile(to, mjs);
425 });
426 return _writeCustomPropertiesToMjsFile.apply(this, arguments);
427}
428
429function writeCustomPropertiesToExports(customProperties, destinations) {
430 return Promise.all(destinations.map(
431 /*#__PURE__*/
432 function () {
433 var _ref = _asyncToGenerator(function* (destination) {
434 if (destination instanceof Function) {
435 yield destination(defaultCustomPropertiesToJSON(customProperties));
436 } else {
437 // read the destination as an object
438 const opts = destination === Object(destination) ? destination : {
439 to: String(destination)
440 }; // transformer for Custom Properties into a JSON-compatible object
441
442 const toJSON = opts.toJSON || defaultCustomPropertiesToJSON;
443
444 if ('customProperties' in opts) {
445 // write directly to an object as customProperties
446 opts.customProperties = toJSON(customProperties);
447 } else if ('custom-properties' in opts) {
448 // write directly to an object as custom-properties
449 opts['custom-properties'] = toJSON(customProperties);
450 } else {
451 // destination pathname
452 const to = String(opts.to || ''); // type of file being written to
453
454 const type = (opts.type || path.extname(opts.to).slice(1)).toLowerCase(); // transformed Custom Properties
455
456 const customPropertiesJSON = toJSON(customProperties);
457
458 if (type === 'css') {
459 yield writeCustomPropertiesToCssFile(to, customPropertiesJSON);
460 }
461
462 if (type === 'js') {
463 yield writeCustomPropertiesToCjsFile(to, customPropertiesJSON);
464 }
465
466 if (type === 'json') {
467 yield writeCustomPropertiesToJsonFile(to, customPropertiesJSON);
468 }
469
470 if (type === 'mjs') {
471 yield writeCustomPropertiesToMjsFile(to, customPropertiesJSON);
472 }
473 }
474 }
475 });
476
477 return function (_x9) {
478 return _ref.apply(this, arguments);
479 };
480 }()));
481}
482/* Helper utilities
483/* ========================================================================== */
484
485const defaultCustomPropertiesToJSON = customProperties => {
486 return Object.keys(customProperties).reduce((customPropertiesJSON, key) => {
487 customPropertiesJSON[key] = String(customProperties[key]);
488 return customPropertiesJSON;
489 }, {});
490};
491
492const writeFile = (to, text) => new Promise((resolve, reject) => {
493 fs.writeFile(to, text, error => {
494 if (error) {
495 reject(error);
496 } else {
497 resolve();
498 }
499 });
500});
501
502const escapeForJS = string => string.replace(/\\([\s\S])|(')/g, '\\$1$2').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
503
504var index = postcss.plugin('postcss-custom-properties', opts => {
505 // whether to preserve custom selectors and rules using them
506 const preserve = 'preserve' in Object(opts) ? Boolean(opts.preserve) : true; // sources to import custom selectors from
507
508 const importFrom = [].concat(Object(opts).importFrom || []); // destinations to export custom selectors to
509
510 const exportTo = [].concat(Object(opts).exportTo || []); // promise any custom selectors are imported
511
512 const customPropertiesPromise = getCustomPropertiesFromImports(importFrom); // synchronous transform
513
514 const syncTransform = root => {
515 const customProperties = getCustomPropertiesFromRoot(root, {
516 preserve
517 });
518 transformProperties(root, customProperties, {
519 preserve
520 });
521 }; // asynchronous transform
522
523
524 const asyncTransform =
525 /*#__PURE__*/
526 function () {
527 var _ref = _asyncToGenerator(function* (root) {
528 const customProperties = Object.assign({}, (yield customPropertiesPromise), getCustomPropertiesFromRoot(root, {
529 preserve
530 }));
531 yield writeCustomPropertiesToExports(customProperties, exportTo);
532 transformProperties(root, customProperties, {
533 preserve
534 });
535 });
536
537 return function asyncTransform(_x) {
538 return _ref.apply(this, arguments);
539 };
540 }(); // whether to return synchronous function if no asynchronous operations are requested
541
542
543 const canReturnSyncFunction = importFrom.length === 0 && exportTo.length === 0;
544 return canReturnSyncFunction ? syncTransform : asyncTransform;
545});
546
547export default index;
548//# sourceMappingURL=index.esm.mjs.map
Note: See TracBrowser for help on using the repository browser.