unplugin-tailwindcss-mangle 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,155 +3,22 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var unplugin$1 = require('unplugin');
6
- var micromatch = require('micromatch');
7
- var fs = require('fs');
8
- var path = require('path');
6
+ var index = require('./index-2edd594b.js');
9
7
  var parse5 = require('parse5');
10
- var core = require('@babel/core');
11
- var postcss = require('postcss');
12
- var parser = require('postcss-selector-parser');
8
+ var index$1 = require('./index-c8e1bdc5.js');
9
+ var path = require('path');
10
+ var fs = require('fs');
13
11
  var tailwindcssPatch = require('tailwindcss-patch');
12
+ require('@babel/types');
13
+ require('@babel/core');
14
+ require('micromatch');
15
+ require('postcss');
16
+ require('postcss-selector-parser');
14
17
 
15
18
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
16
19
 
17
- var micromatch__default = /*#__PURE__*/_interopDefault(micromatch);
18
- var fs__default = /*#__PURE__*/_interopDefault(fs);
19
20
  var path__default = /*#__PURE__*/_interopDefault(path);
20
- var postcss__default = /*#__PURE__*/_interopDefault(postcss);
21
- var parser__default = /*#__PURE__*/_interopDefault(parser);
22
-
23
- const pluginName = 'unplugin-tailwindcss-mangle';
24
-
25
- const { isMatch } = micromatch__default["default"];
26
- const isMangleClass = (className) => {
27
- return /[-:]/.test(className);
28
- };
29
- function groupBy(arr, cb) {
30
- if (!Array.isArray(arr)) {
31
- throw new Error('expected an array for first argument');
32
- }
33
- if (typeof cb !== 'function') {
34
- throw new Error('expected a function for second argument');
35
- }
36
- const result = {};
37
- for (let i = 0; i < arr.length; i++) {
38
- const item = arr[i];
39
- const bucketCategory = cb(item);
40
- const bucket = result[bucketCategory];
41
- if (!Array.isArray(bucket)) {
42
- result[bucketCategory] = [item];
43
- }
44
- else {
45
- result[bucketCategory].push(item);
46
- }
47
- }
48
- return result;
49
- }
50
- function getGroupedEntries(entries, options = {
51
- cssMatcher(file) {
52
- return /\.css$/.test(file);
53
- },
54
- htmlMatcher(file) {
55
- return /\.html?$/.test(file);
56
- },
57
- jsMatcher(file) {
58
- return /\.[cm]?js$/.test(file);
59
- }
60
- }) {
61
- const { cssMatcher, htmlMatcher, jsMatcher } = options;
62
- const groupedEntries = groupBy(entries, ([file]) => {
63
- if (cssMatcher(file)) {
64
- return 'css';
65
- }
66
- else if (htmlMatcher(file)) {
67
- return 'html';
68
- }
69
- else if (jsMatcher(file)) {
70
- return 'js';
71
- }
72
- else {
73
- return 'other';
74
- }
75
- });
76
- if (!groupedEntries.css) {
77
- groupedEntries.css = [];
78
- }
79
- if (!groupedEntries.html) {
80
- groupedEntries.html = [];
81
- }
82
- if (!groupedEntries.js) {
83
- groupedEntries.js = [];
84
- }
85
- if (!groupedEntries.other) {
86
- groupedEntries.other = [];
87
- }
88
- return groupedEntries;
89
- }
90
- const acceptChars = 'abcdefghijklmnopqrstuvwxyz'.split('');
91
- function stripEscapeSequence(words) {
92
- return words.replace(/\\/g, '');
93
- }
94
- function isRegexp(value) {
95
- return Object.prototype.toString.call(value) === '[object RegExp]';
96
- }
97
- function regExpTest(arr = [], str) {
98
- if (Array.isArray(arr)) {
99
- for (let i = 0; i < arr.length; i++) {
100
- const item = arr[i];
101
- if (typeof item === 'string') {
102
- if (item === str) {
103
- return true;
104
- }
105
- }
106
- else if (isRegexp(item)) {
107
- item.lastIndex = 0;
108
- if (item.test(str)) {
109
- return true;
110
- }
111
- }
112
- }
113
- return false;
114
- }
115
- throw new TypeError("paramater 'arr' should be a Array of Regexp | String !");
116
- }
117
- function escapeStringRegexp(str) {
118
- if (typeof str !== 'string') {
119
- throw new TypeError('Expected a string');
120
- }
121
- return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
122
- }
123
- function createGlobMatcher(pattern, fallbackValue = false) {
124
- if (typeof pattern === 'undefined') {
125
- return function (file) {
126
- return fallbackValue;
127
- };
128
- }
129
- return function (file) {
130
- return isMatch(file, pattern);
131
- };
132
- }
133
- function getCacheDir(basedir = process.cwd()) {
134
- return path__default["default"].resolve(basedir, 'node_modules/.cache', pluginName);
135
- }
136
- function mkCacheDirectory(cwd = process.cwd()) {
137
- const cacheDirectory = getCacheDir(cwd);
138
- const exists = fs__default["default"].existsSync(cacheDirectory);
139
- if (!exists) {
140
- fs__default["default"].mkdirSync(cacheDirectory, {
141
- recursive: true
142
- });
143
- }
144
- return cacheDirectory;
145
- }
146
- function cacheDump(filename, data, basedir) {
147
- try {
148
- const dir = mkCacheDirectory(basedir);
149
- fs__default["default"].writeFileSync(path__default["default"].resolve(dir, filename), JSON.stringify(Array.from(data), null, 2), 'utf-8');
150
- }
151
- catch (error) {
152
- console.log(error);
153
- }
154
- }
21
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
155
22
 
156
23
  ({
157
24
  HTML: parse5.html.NS.HTML,
@@ -268,107 +135,6 @@ function htmlHandler(rawSource, options) {
268
135
  return parse5.serialize(fragment);
269
136
  }
270
137
 
271
- const validateFilterRE = /[\w\u00A0-\uFFFF-_:%-?]/;
272
- function isValidSelector(selector = '') {
273
- return validateFilterRE.test(selector);
274
- }
275
- const splitCode = (code) => code.split(/[\s"]+/).filter(isValidSelector);
276
-
277
- function makeRegex(str) {
278
- return new RegExp('(?<=^|[\\s"])' + escapeStringRegexp(str), 'g');
279
- }
280
- function handleValue(str, node, options) {
281
- const set = options.runtimeSet;
282
- const clsGen = options.classGenerator;
283
- const arr = splitCode(str);
284
- let rawStr = str;
285
- for (let i = 0; i < arr.length; i++) {
286
- const v = arr[i];
287
- if (set.has(v)) {
288
- let ignoreFlag = false;
289
- if (Array.isArray(node.leadingComments)) {
290
- ignoreFlag = node.leadingComments.findIndex((x) => x.value.includes('tw-mangle') && x.value.includes('ignore')) > -1;
291
- }
292
- if (!ignoreFlag) {
293
- rawStr = rawStr.replace(makeRegex(v), clsGen.generateClassName(v).name);
294
- }
295
- }
296
- }
297
- return rawStr;
298
- }
299
- function jsHandler(rawSource, options) {
300
- const result = core.transformSync(rawSource, {
301
- babelrc: false,
302
- ast: true,
303
- plugins: [
304
- () => {
305
- return {
306
- visitor: {
307
- StringLiteral: {
308
- enter(p) {
309
- const n = p.node;
310
- n.value = handleValue(n.value, n, options);
311
- }
312
- },
313
- TemplateElement: {
314
- enter(p) {
315
- const n = p.node;
316
- n.value.raw = handleValue(n.value.raw, n, options);
317
- }
318
- }
319
- }
320
- };
321
- }
322
- ],
323
- sourceMaps: false,
324
- configFile: false
325
- });
326
- return result;
327
- }
328
-
329
- const postcssPlugin = 'postcss-mangle-tailwindcss-plugin';
330
- const postcssMangleTailwindcssPlugin = (options) => {
331
- let newClassMap = {};
332
- if (options) {
333
- if (options.newClassMap) {
334
- newClassMap = options.newClassMap;
335
- }
336
- }
337
- return {
338
- postcssPlugin,
339
- Rule(rule, helper) {
340
- rule.selector = parser__default["default"]((selectors) => {
341
- selectors.walkClasses((s) => {
342
- if (s.value) {
343
- const hit = newClassMap[s.value];
344
- if (hit) {
345
- if (s.parent) {
346
- const idx = s.parent.nodes.indexOf(s);
347
- if (idx > -1) {
348
- const nextNode = s.parent.nodes[idx + 1];
349
- if (nextNode && nextNode.type === 'attribute' && nextNode.attribute.indexOf('data-v-') > -1) {
350
- return;
351
- }
352
- }
353
- }
354
- s.value = hit.name;
355
- }
356
- }
357
- });
358
- }).processSync(rule.selector);
359
- }
360
- };
361
- };
362
- postcssMangleTailwindcssPlugin.postcss = true;
363
-
364
- function cssHandler(rawSource, options) {
365
- return postcss__default["default"]([
366
- postcssMangleTailwindcssPlugin({
367
- newClassMap: options.classGenerator.newClassMap
368
- })
369
- ]).process(rawSource).css;
370
- }
371
-
372
138
  class ClassGenerator {
373
139
  newClassMap;
374
140
  newClassSize;
@@ -384,31 +150,31 @@ class ClassGenerator {
384
150
  }
385
151
  defaultClassGenerate() {
386
152
  const chars = [];
387
- let rest = (this.newClassSize - (this.newClassSize % acceptChars.length)) / acceptChars.length;
153
+ let rest = (this.newClassSize - (this.newClassSize % index.acceptChars.length)) / index.acceptChars.length;
388
154
  if (rest > 0) {
389
155
  while (true) {
390
156
  rest -= 1;
391
- const m = rest % acceptChars.length;
392
- const c = acceptChars[m];
157
+ const m = rest % index.acceptChars.length;
158
+ const c = index.acceptChars[m];
393
159
  chars.push(c);
394
160
  rest -= m;
395
161
  if (rest === 0) {
396
162
  break;
397
163
  }
398
- rest /= acceptChars.length;
164
+ rest /= index.acceptChars.length;
399
165
  }
400
166
  }
401
- const prefixIndex = this.newClassSize % acceptChars.length;
402
- const newClassName = `${this.classPrefix}${acceptChars[prefixIndex]}${chars.join('')}`;
167
+ const prefixIndex = this.newClassSize % index.acceptChars.length;
168
+ const newClassName = `${this.classPrefix}${index.acceptChars[prefixIndex]}${chars.join('')}`;
403
169
  return newClassName;
404
170
  }
405
171
  ignoreClassName(className) {
406
- return regExpTest(this.opts.ignoreClass, className);
172
+ return index.regExpTest(this.opts.ignoreClass, className);
407
173
  }
408
174
  includeFilePath(filePath) {
409
175
  const { include } = this.opts;
410
176
  if (Array.isArray(include)) {
411
- return regExpTest(include, filePath);
177
+ return index.regExpTest(include, filePath);
412
178
  }
413
179
  else {
414
180
  return true;
@@ -417,7 +183,7 @@ class ClassGenerator {
417
183
  excludeFilePath(filePath) {
418
184
  const { exclude } = this.opts;
419
185
  if (Array.isArray(exclude)) {
420
- return regExpTest(exclude, filePath);
186
+ return index.regExpTest(exclude, filePath);
421
187
  }
422
188
  else {
423
189
  return false;
@@ -427,7 +193,7 @@ class ClassGenerator {
427
193
  return this.includeFilePath(filePath) && !this.excludeFilePath(filePath);
428
194
  }
429
195
  transformCssClass(className) {
430
- const key = stripEscapeSequence(className);
196
+ const key = index.stripEscapeSequence(className);
431
197
  const cn = this.newClassMap[key];
432
198
  if (cn)
433
199
  return cn.name;
@@ -435,7 +201,7 @@ class ClassGenerator {
435
201
  }
436
202
  generateClassName(original) {
437
203
  const opts = this.opts;
438
- original = stripEscapeSequence(original);
204
+ original = index.stripEscapeSequence(original);
439
205
  const cn = this.newClassMap[original];
440
206
  if (cn)
441
207
  return cn;
@@ -446,7 +212,7 @@ class ClassGenerator {
446
212
  if (!newClassName) {
447
213
  newClassName = this.defaultClassGenerate();
448
214
  }
449
- if (opts.reserveClassName && regExpTest(opts.reserveClassName, newClassName)) {
215
+ if (opts.reserveClassName && index.regExpTest(opts.reserveClassName, newClassName)) {
450
216
  if (opts.log) {
451
217
  console.log(`The class name has been reserved. ${newClassName}`);
452
218
  }
@@ -467,12 +233,13 @@ class ClassGenerator {
467
233
  }
468
234
 
469
235
  function getOptions(options = {}) {
470
- const includeMatcher = createGlobMatcher(options.include, true);
471
- const excludeMatcher = createGlobMatcher(options.exclude, false);
236
+ const includeMatcher = index.createGlobMatcher(options.include, true);
237
+ const excludeMatcher = index.createGlobMatcher(options.exclude, false);
472
238
  function isInclude(file) {
473
239
  return includeMatcher(file) && !excludeMatcher(file);
474
240
  }
475
241
  let classSet;
242
+ const twPatcher = new tailwindcssPatch.TailwindcssPatcher();
476
243
  const classSetOutputOptions = {
477
244
  filename: 'classSet.json',
478
245
  type: 'partial'
@@ -488,18 +255,18 @@ function getOptions(options = {}) {
488
255
  }
489
256
  const classGenerator = new ClassGenerator(options.classGenerator);
490
257
  function getCachedClassSet() {
491
- const set = tailwindcssPatch.getClassCacheSet();
258
+ const set = twPatcher.getClassSet();
492
259
  const isOutput = set.size && options.classSetOutput;
493
260
  if (isOutput && classSetOutputOptions.type === 'all') {
494
- cacheDump(classSetOutputOptions.filename, set, classSetOutputOptions.dir);
261
+ index.cacheDump(classSetOutputOptions.filename, set, classSetOutputOptions.dir);
495
262
  }
496
263
  set.forEach((c) => {
497
- if (!isMangleClass(c)) {
264
+ if (!index.isMangleClass(c)) {
498
265
  set.delete(c);
499
266
  }
500
267
  });
501
268
  if (isOutput && classSetOutputOptions.type === 'partial') {
502
- cacheDump(classSetOutputOptions.filename, set, classSetOutputOptions.dir);
269
+ index.cacheDump(classSetOutputOptions.filename, set, classSetOutputOptions.dir);
503
270
  }
504
271
  classSet = set;
505
272
  return classSet;
@@ -511,7 +278,8 @@ function getOptions(options = {}) {
511
278
  excludeMatcher,
512
279
  isInclude,
513
280
  classSetOutputOptions,
514
- classMapOutputOptions
281
+ classMapOutputOptions,
282
+ twPatcher
515
283
  };
516
284
  }
517
285
 
@@ -519,7 +287,7 @@ const outputCachedMap = new Map();
519
287
  const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
520
288
  const { classGenerator, getCachedClassSet, isInclude, classMapOutputOptions } = getOptions(options);
521
289
  return {
522
- name: pluginName,
290
+ name: index.pluginName,
523
291
  enforce: 'post',
524
292
  vite: {
525
293
  generateBundle: {
@@ -528,7 +296,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
528
296
  if (!runtimeSet.size) {
529
297
  return;
530
298
  }
531
- const groupedEntries = getGroupedEntries(Object.entries(bundle));
299
+ const groupedEntries = index.getGroupedEntries(Object.entries(bundle));
532
300
  if (Array.isArray(groupedEntries.html) && groupedEntries.html.length) {
533
301
  for (let i = 0; i < groupedEntries.html.length; i++) {
534
302
  const [file, asset] = groupedEntries.html[i];
@@ -544,7 +312,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
544
312
  for (let i = 0; i < groupedEntries.js.length; i++) {
545
313
  const [file, chunk] = groupedEntries.js[i];
546
314
  if (isInclude(file)) {
547
- const code = jsHandler(chunk.code, {
315
+ const code = index.jsHandler(chunk.code, {
548
316
  runtimeSet,
549
317
  classGenerator
550
318
  }).code;
@@ -558,7 +326,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
558
326
  for (let i = 0; i < groupedEntries.css.length; i++) {
559
327
  const [file, css] = groupedEntries.css[i];
560
328
  if (isInclude(file)) {
561
- css.source = cssHandler(css.source.toString(), {
329
+ css.source = index$1.cssHandler(css.source.toString(), {
562
330
  classGenerator,
563
331
  runtimeSet
564
332
  });
@@ -569,7 +337,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
569
337
  }
570
338
  },
571
339
  webpack(compiler) {
572
- const Compilation = compiler.webpack.Compilation;
340
+ const { NormalModule, Compilation } = compiler.webpack;
573
341
  const { ConcatSource } = compiler.webpack.sources;
574
342
  function getAssetPath(outputPath, file, abs = true) {
575
343
  const fn = abs ? path__default["default"].resolve : path__default["default"].relative;
@@ -587,13 +355,28 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
587
355
  console.log(error);
588
356
  }
589
357
  }
590
- compiler.hooks.compilation.tap(pluginName, (compilation) => {
358
+ const twmCssloader = path__default["default"].resolve(__dirname, 'twm-css.js');
359
+ compiler.hooks.compilation.tap(index.pluginName, (compilation) => {
360
+ NormalModule.getCompilationHooks(compilation).loader.tap(index.pluginName, (loaderContext, module) => {
361
+ const idx = module.loaders.findIndex((x) => x.loader.includes('css-loader'));
362
+ if (idx > -1) {
363
+ module.loaders.splice(idx + 1, 0, {
364
+ loader: twmCssloader,
365
+ options: {
366
+ classGenerator,
367
+ getCachedClassSet
368
+ },
369
+ ident: null,
370
+ type: null
371
+ });
372
+ }
373
+ });
591
374
  compilation.hooks.processAssets.tap({
592
- name: pluginName,
375
+ name: index.pluginName,
593
376
  stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE
594
377
  }, (assets) => {
595
378
  const runtimeSet = getCachedClassSet();
596
- const groupedEntries = getGroupedEntries(Object.entries(assets));
379
+ const groupedEntries = index.getGroupedEntries(Object.entries(assets));
597
380
  if (!runtimeSet.size) {
598
381
  const css = new Map();
599
382
  const html = new Map();
@@ -633,7 +416,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
633
416
  for (let i = 0; i < groupedEntries.js.length; i++) {
634
417
  const [file, chunk] = groupedEntries.js[i];
635
418
  if (isInclude(file)) {
636
- const code = jsHandler(chunk.source().toString(), {
419
+ const code = index.jsHandler(chunk.source().toString(), {
637
420
  runtimeSet,
638
421
  classGenerator
639
422
  }).code;
@@ -648,7 +431,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
648
431
  for (let i = 0; i < groupedEntries.css.length; i++) {
649
432
  const [file, css] = groupedEntries.css[i];
650
433
  if (isInclude(file)) {
651
- const newCss = cssHandler(css.source().toString(), {
434
+ const newCss = index$1.cssHandler(css.source().toString(), {
652
435
  classGenerator,
653
436
  runtimeSet
654
437
  });
@@ -674,7 +457,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
674
457
  js.forEach((chunk, file) => {
675
458
  if (isInclude(file)) {
676
459
  const rawCode = chunk.source().toString();
677
- const code = jsHandler(rawCode, {
460
+ const code = index.jsHandler(rawCode, {
678
461
  runtimeSet,
679
462
  classGenerator
680
463
  }).code;
@@ -688,7 +471,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
688
471
  if (css.size) {
689
472
  css.forEach((style, file) => {
690
473
  if (isInclude(file)) {
691
- const newCss = cssHandler(style.source().toString(), {
474
+ const newCss = index$1.cssHandler(style.source().toString(), {
692
475
  classGenerator,
693
476
  runtimeSet
694
477
  });
@@ -704,7 +487,7 @@ const unplugin = unplugin$1.createUnplugin((options = {}, meta) => {
704
487
  writeBundle() {
705
488
  const entries = Object.entries(classGenerator.newClassMap);
706
489
  if (entries.length && classMapOutputOptions) {
707
- cacheDump(classMapOutputOptions.filename, entries.map((x) => {
490
+ index.cacheDump(classMapOutputOptions.filename, entries.map((x) => {
708
491
  return [x[0], x[1].name];
709
492
  }), classMapOutputOptions.dir);
710
493
  }