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