@cnguu/vite-plugin-uni-cdn 1.0.0

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.mjs ADDED
@@ -0,0 +1,1226 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createFilter, normalizePath } from 'vite';
4
+
5
+ const ANSI_BACKGROUND_OFFSET = 10;
6
+
7
+ const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
8
+
9
+ const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
10
+
11
+ const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
12
+
13
+ const styles$1 = {
14
+ modifier: {
15
+ reset: [0, 0],
16
+ // 21 isn't widely supported and 22 does the same thing
17
+ bold: [1, 22],
18
+ dim: [2, 22],
19
+ italic: [3, 23],
20
+ underline: [4, 24],
21
+ overline: [53, 55],
22
+ inverse: [7, 27],
23
+ hidden: [8, 28],
24
+ strikethrough: [9, 29],
25
+ },
26
+ color: {
27
+ black: [30, 39],
28
+ red: [31, 39],
29
+ green: [32, 39],
30
+ yellow: [33, 39],
31
+ blue: [34, 39],
32
+ magenta: [35, 39],
33
+ cyan: [36, 39],
34
+ white: [37, 39],
35
+
36
+ // Bright color
37
+ blackBright: [90, 39],
38
+ gray: [90, 39], // Alias of `blackBright`
39
+ grey: [90, 39], // Alias of `blackBright`
40
+ redBright: [91, 39],
41
+ greenBright: [92, 39],
42
+ yellowBright: [93, 39],
43
+ blueBright: [94, 39],
44
+ magentaBright: [95, 39],
45
+ cyanBright: [96, 39],
46
+ whiteBright: [97, 39],
47
+ },
48
+ bgColor: {
49
+ bgBlack: [40, 49],
50
+ bgRed: [41, 49],
51
+ bgGreen: [42, 49],
52
+ bgYellow: [43, 49],
53
+ bgBlue: [44, 49],
54
+ bgMagenta: [45, 49],
55
+ bgCyan: [46, 49],
56
+ bgWhite: [47, 49],
57
+
58
+ // Bright color
59
+ bgBlackBright: [100, 49],
60
+ bgGray: [100, 49], // Alias of `bgBlackBright`
61
+ bgGrey: [100, 49], // Alias of `bgBlackBright`
62
+ bgRedBright: [101, 49],
63
+ bgGreenBright: [102, 49],
64
+ bgYellowBright: [103, 49],
65
+ bgBlueBright: [104, 49],
66
+ bgMagentaBright: [105, 49],
67
+ bgCyanBright: [106, 49],
68
+ bgWhiteBright: [107, 49],
69
+ },
70
+ };
71
+
72
+ Object.keys(styles$1.modifier);
73
+ const foregroundColorNames = Object.keys(styles$1.color);
74
+ const backgroundColorNames = Object.keys(styles$1.bgColor);
75
+ [...foregroundColorNames, ...backgroundColorNames];
76
+
77
+ function assembleStyles() {
78
+ const codes = new Map();
79
+
80
+ for (const [groupName, group] of Object.entries(styles$1)) {
81
+ for (const [styleName, style] of Object.entries(group)) {
82
+ styles$1[styleName] = {
83
+ open: `\u001B[${style[0]}m`,
84
+ close: `\u001B[${style[1]}m`,
85
+ };
86
+
87
+ group[styleName] = styles$1[styleName];
88
+
89
+ codes.set(style[0], style[1]);
90
+ }
91
+
92
+ Object.defineProperty(styles$1, groupName, {
93
+ value: group,
94
+ enumerable: false,
95
+ });
96
+ }
97
+
98
+ Object.defineProperty(styles$1, 'codes', {
99
+ value: codes,
100
+ enumerable: false,
101
+ });
102
+
103
+ styles$1.color.close = '\u001B[39m';
104
+ styles$1.bgColor.close = '\u001B[49m';
105
+
106
+ styles$1.color.ansi = wrapAnsi16();
107
+ styles$1.color.ansi256 = wrapAnsi256();
108
+ styles$1.color.ansi16m = wrapAnsi16m();
109
+ styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
110
+ styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
111
+ styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
112
+
113
+ // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
114
+ Object.defineProperties(styles$1, {
115
+ rgbToAnsi256: {
116
+ value(red, green, blue) {
117
+ // We use the extended greyscale palette here, with the exception of
118
+ // black and white. normal palette only has 4 greyscale shades.
119
+ if (red === green && green === blue) {
120
+ if (red < 8) {
121
+ return 16;
122
+ }
123
+
124
+ if (red > 248) {
125
+ return 231;
126
+ }
127
+
128
+ return Math.round(((red - 8) / 247) * 24) + 232;
129
+ }
130
+
131
+ return 16
132
+ + (36 * Math.round(red / 255 * 5))
133
+ + (6 * Math.round(green / 255 * 5))
134
+ + Math.round(blue / 255 * 5);
135
+ },
136
+ enumerable: false,
137
+ },
138
+ hexToRgb: {
139
+ value(hex) {
140
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
141
+ if (!matches) {
142
+ return [0, 0, 0];
143
+ }
144
+
145
+ let [colorString] = matches;
146
+
147
+ if (colorString.length === 3) {
148
+ colorString = [...colorString].map(character => character + character).join('');
149
+ }
150
+
151
+ const integer = Number.parseInt(colorString, 16);
152
+
153
+ return [
154
+ /* eslint-disable no-bitwise */
155
+ (integer >> 16) & 0xFF,
156
+ (integer >> 8) & 0xFF,
157
+ integer & 0xFF,
158
+ /* eslint-enable no-bitwise */
159
+ ];
160
+ },
161
+ enumerable: false,
162
+ },
163
+ hexToAnsi256: {
164
+ value: hex => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
165
+ enumerable: false,
166
+ },
167
+ ansi256ToAnsi: {
168
+ value(code) {
169
+ if (code < 8) {
170
+ return 30 + code;
171
+ }
172
+
173
+ if (code < 16) {
174
+ return 90 + (code - 8);
175
+ }
176
+
177
+ let red;
178
+ let green;
179
+ let blue;
180
+
181
+ if (code >= 232) {
182
+ red = (((code - 232) * 10) + 8) / 255;
183
+ green = red;
184
+ blue = red;
185
+ } else {
186
+ code -= 16;
187
+
188
+ const remainder = code % 36;
189
+
190
+ red = Math.floor(code / 36) / 5;
191
+ green = Math.floor(remainder / 6) / 5;
192
+ blue = (remainder % 6) / 5;
193
+ }
194
+
195
+ const value = Math.max(red, green, blue) * 2;
196
+
197
+ if (value === 0) {
198
+ return 30;
199
+ }
200
+
201
+ // eslint-disable-next-line no-bitwise
202
+ let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
203
+
204
+ if (value === 2) {
205
+ result += 60;
206
+ }
207
+
208
+ return result;
209
+ },
210
+ enumerable: false,
211
+ },
212
+ rgbToAnsi: {
213
+ value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
214
+ enumerable: false,
215
+ },
216
+ hexToAnsi: {
217
+ value: hex => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
218
+ enumerable: false,
219
+ },
220
+ });
221
+
222
+ return styles$1;
223
+ }
224
+
225
+ const ansiStyles = assembleStyles();
226
+
227
+ /* eslint-env browser */
228
+
229
+ const level = (() => {
230
+ if (!('navigator' in globalThis)) {
231
+ return 0;
232
+ }
233
+
234
+ if (globalThis.navigator.userAgentData) {
235
+ const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
236
+ if (brand && brand.version > 93) {
237
+ return 3;
238
+ }
239
+ }
240
+
241
+ if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
242
+ return 1;
243
+ }
244
+
245
+ return 0;
246
+ })();
247
+
248
+ const colorSupport = level !== 0 && {
249
+ level};
250
+
251
+ const supportsColor = {
252
+ stdout: colorSupport,
253
+ stderr: colorSupport,
254
+ };
255
+
256
+ // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
257
+ function stringReplaceAll(string, substring, replacer) {
258
+ let index = string.indexOf(substring);
259
+ if (index === -1) {
260
+ return string;
261
+ }
262
+
263
+ const substringLength = substring.length;
264
+ let endIndex = 0;
265
+ let returnValue = '';
266
+ do {
267
+ returnValue += string.slice(endIndex, index) + substring + replacer;
268
+ endIndex = index + substringLength;
269
+ index = string.indexOf(substring, endIndex);
270
+ } while (index !== -1);
271
+
272
+ returnValue += string.slice(endIndex);
273
+ return returnValue;
274
+ }
275
+
276
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
277
+ let endIndex = 0;
278
+ let returnValue = '';
279
+ do {
280
+ const gotCR = string[index - 1] === '\r';
281
+ returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
282
+ endIndex = index + 1;
283
+ index = string.indexOf('\n', endIndex);
284
+ } while (index !== -1);
285
+
286
+ returnValue += string.slice(endIndex);
287
+ return returnValue;
288
+ }
289
+
290
+ const {stdout: stdoutColor, stderr: stderrColor} = supportsColor;
291
+
292
+ const GENERATOR = Symbol('GENERATOR');
293
+ const STYLER = Symbol('STYLER');
294
+ const IS_EMPTY = Symbol('IS_EMPTY');
295
+
296
+ // `supportsColor.level` → `ansiStyles.color[name]` mapping
297
+ const levelMapping = [
298
+ 'ansi',
299
+ 'ansi',
300
+ 'ansi256',
301
+ 'ansi16m',
302
+ ];
303
+
304
+ const styles = Object.create(null);
305
+
306
+ const applyOptions = (object, options = {}) => {
307
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
308
+ throw new Error('The `level` option should be an integer from 0 to 3');
309
+ }
310
+
311
+ // Detect level if not set manually
312
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
313
+ object.level = options.level === undefined ? colorLevel : options.level;
314
+ };
315
+
316
+ const chalkFactory = options => {
317
+ const chalk = (...strings) => strings.join(' ');
318
+ applyOptions(chalk, options);
319
+
320
+ Object.setPrototypeOf(chalk, createChalk.prototype);
321
+
322
+ return chalk;
323
+ };
324
+
325
+ function createChalk(options) {
326
+ return chalkFactory(options);
327
+ }
328
+
329
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
330
+
331
+ for (const [styleName, style] of Object.entries(ansiStyles)) {
332
+ styles[styleName] = {
333
+ get() {
334
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
335
+ Object.defineProperty(this, styleName, {value: builder});
336
+ return builder;
337
+ },
338
+ };
339
+ }
340
+
341
+ styles.visible = {
342
+ get() {
343
+ const builder = createBuilder(this, this[STYLER], true);
344
+ Object.defineProperty(this, 'visible', {value: builder});
345
+ return builder;
346
+ },
347
+ };
348
+
349
+ const getModelAnsi = (model, level, type, ...arguments_) => {
350
+ if (model === 'rgb') {
351
+ if (level === 'ansi16m') {
352
+ return ansiStyles[type].ansi16m(...arguments_);
353
+ }
354
+
355
+ if (level === 'ansi256') {
356
+ return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
357
+ }
358
+
359
+ return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
360
+ }
361
+
362
+ if (model === 'hex') {
363
+ return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
364
+ }
365
+
366
+ return ansiStyles[type][model](...arguments_);
367
+ };
368
+
369
+ const usedModels = ['rgb', 'hex', 'ansi256'];
370
+
371
+ for (const model of usedModels) {
372
+ styles[model] = {
373
+ get() {
374
+ const {level} = this;
375
+ return function (...arguments_) {
376
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
377
+ return createBuilder(this, styler, this[IS_EMPTY]);
378
+ };
379
+ },
380
+ };
381
+
382
+ const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
383
+ styles[bgModel] = {
384
+ get() {
385
+ const {level} = this;
386
+ return function (...arguments_) {
387
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
388
+ return createBuilder(this, styler, this[IS_EMPTY]);
389
+ };
390
+ },
391
+ };
392
+ }
393
+
394
+ const proto = Object.defineProperties(() => {}, {
395
+ ...styles,
396
+ level: {
397
+ enumerable: true,
398
+ get() {
399
+ return this[GENERATOR].level;
400
+ },
401
+ set(level) {
402
+ this[GENERATOR].level = level;
403
+ },
404
+ },
405
+ });
406
+
407
+ const createStyler = (open, close, parent) => {
408
+ let openAll;
409
+ let closeAll;
410
+ if (parent === undefined) {
411
+ openAll = open;
412
+ closeAll = close;
413
+ } else {
414
+ openAll = parent.openAll + open;
415
+ closeAll = close + parent.closeAll;
416
+ }
417
+
418
+ return {
419
+ open,
420
+ close,
421
+ openAll,
422
+ closeAll,
423
+ parent,
424
+ };
425
+ };
426
+
427
+ const createBuilder = (self, _styler, _isEmpty) => {
428
+ // Single argument is hot path, implicit coercion is faster than anything
429
+ // eslint-disable-next-line no-implicit-coercion
430
+ const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
431
+
432
+ // We alter the prototype because we must return a function, but there is
433
+ // no way to create a function with a different prototype
434
+ Object.setPrototypeOf(builder, proto);
435
+
436
+ builder[GENERATOR] = self;
437
+ builder[STYLER] = _styler;
438
+ builder[IS_EMPTY] = _isEmpty;
439
+
440
+ return builder;
441
+ };
442
+
443
+ const applyStyle = (self, string) => {
444
+ if (self.level <= 0 || !string) {
445
+ return self[IS_EMPTY] ? '' : string;
446
+ }
447
+
448
+ let styler = self[STYLER];
449
+
450
+ if (styler === undefined) {
451
+ return string;
452
+ }
453
+
454
+ const {openAll, closeAll} = styler;
455
+ if (string.includes('\u001B')) {
456
+ while (styler !== undefined) {
457
+ // Replace any instances already present with a re-opening code
458
+ // otherwise only the part of the string until said closing code
459
+ // will be colored, and the rest will simply be 'plain'.
460
+ string = stringReplaceAll(string, styler.close, styler.open);
461
+
462
+ styler = styler.parent;
463
+ }
464
+ }
465
+
466
+ // We can move both next actions out of loop, because remaining actions in loop won't have
467
+ // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
468
+ // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
469
+ const lfIndex = string.indexOf('\n');
470
+ if (lfIndex !== -1) {
471
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
472
+ }
473
+
474
+ return openAll + string + closeAll;
475
+ };
476
+
477
+ Object.defineProperties(createChalk.prototype, styles);
478
+
479
+ const chalk = createChalk();
480
+ createChalk({level: stderrColor ? stderrColor.level : 0});
481
+
482
+ const LogLevels = {
483
+ fatal: 0,
484
+ error: 0,
485
+ warn: 1,
486
+ log: 2,
487
+ info: 3,
488
+ success: 3,
489
+ fail: 3,
490
+ debug: 4,
491
+ trace: 5,
492
+ verbose: Number.POSITIVE_INFINITY
493
+ };
494
+ const LogTypes = {
495
+ // Silent
496
+ silent: {
497
+ level: -1
498
+ },
499
+ // Level 0
500
+ fatal: {
501
+ level: LogLevels.fatal
502
+ },
503
+ error: {
504
+ level: LogLevels.error
505
+ },
506
+ // Level 1
507
+ warn: {
508
+ level: LogLevels.warn
509
+ },
510
+ // Level 2
511
+ log: {
512
+ level: LogLevels.log
513
+ },
514
+ // Level 3
515
+ info: {
516
+ level: LogLevels.info
517
+ },
518
+ success: {
519
+ level: LogLevels.success
520
+ },
521
+ fail: {
522
+ level: LogLevels.fail
523
+ },
524
+ ready: {
525
+ level: LogLevels.info
526
+ },
527
+ start: {
528
+ level: LogLevels.info
529
+ },
530
+ box: {
531
+ level: LogLevels.info
532
+ },
533
+ // Level 4
534
+ debug: {
535
+ level: LogLevels.debug
536
+ },
537
+ // Level 5
538
+ trace: {
539
+ level: LogLevels.trace
540
+ },
541
+ // Verbose
542
+ verbose: {
543
+ level: LogLevels.verbose
544
+ }
545
+ };
546
+
547
+ function isPlainObject$1(value) {
548
+ if (value === null || typeof value !== "object") {
549
+ return false;
550
+ }
551
+ const prototype = Object.getPrototypeOf(value);
552
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
553
+ return false;
554
+ }
555
+ if (Symbol.iterator in value) {
556
+ return false;
557
+ }
558
+ if (Symbol.toStringTag in value) {
559
+ return Object.prototype.toString.call(value) === "[object Module]";
560
+ }
561
+ return true;
562
+ }
563
+
564
+ function _defu(baseObject, defaults, namespace = ".", merger) {
565
+ if (!isPlainObject$1(defaults)) {
566
+ return _defu(baseObject, {}, namespace);
567
+ }
568
+ const object = Object.assign({}, defaults);
569
+ for (const key in baseObject) {
570
+ if (key === "__proto__" || key === "constructor") {
571
+ continue;
572
+ }
573
+ const value = baseObject[key];
574
+ if (value === null || value === void 0) {
575
+ continue;
576
+ }
577
+ if (Array.isArray(value) && Array.isArray(object[key])) {
578
+ object[key] = [...value, ...object[key]];
579
+ } else if (isPlainObject$1(value) && isPlainObject$1(object[key])) {
580
+ object[key] = _defu(
581
+ value,
582
+ object[key],
583
+ (namespace ? `${namespace}.` : "") + key.toString());
584
+ } else {
585
+ object[key] = value;
586
+ }
587
+ }
588
+ return object;
589
+ }
590
+ function createDefu(merger) {
591
+ return (...arguments_) => (
592
+ // eslint-disable-next-line unicorn/no-array-reduce
593
+ arguments_.reduce((p, c) => _defu(p, c, ""), {})
594
+ );
595
+ }
596
+ const defu = createDefu();
597
+
598
+ function isPlainObject(obj) {
599
+ return Object.prototype.toString.call(obj) === "[object Object]";
600
+ }
601
+ function isLogObj(arg) {
602
+ if (!isPlainObject(arg)) {
603
+ return false;
604
+ }
605
+ if (!arg.message && !arg.args) {
606
+ return false;
607
+ }
608
+ if (arg.stack) {
609
+ return false;
610
+ }
611
+ return true;
612
+ }
613
+
614
+ let paused = false;
615
+ const queue = [];
616
+ class Consola {
617
+ options;
618
+ _lastLog;
619
+ _mockFn;
620
+ /**
621
+ * Creates an instance of Consola with specified options or defaults.
622
+ *
623
+ * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
624
+ */
625
+ constructor(options = {}) {
626
+ const types = options.types || LogTypes;
627
+ this.options = defu(
628
+ {
629
+ ...options,
630
+ defaults: { ...options.defaults },
631
+ level: _normalizeLogLevel(options.level, types),
632
+ reporters: [...options.reporters || []]
633
+ },
634
+ {
635
+ types: LogTypes,
636
+ throttle: 1e3,
637
+ throttleMin: 5,
638
+ formatOptions: {
639
+ date: true,
640
+ colors: false,
641
+ compact: true
642
+ }
643
+ }
644
+ );
645
+ for (const type in types) {
646
+ const defaults = {
647
+ type,
648
+ ...this.options.defaults,
649
+ ...types[type]
650
+ };
651
+ this[type] = this._wrapLogFn(defaults);
652
+ this[type].raw = this._wrapLogFn(
653
+ defaults,
654
+ true
655
+ );
656
+ }
657
+ if (this.options.mockFn) {
658
+ this.mockTypes();
659
+ }
660
+ this._lastLog = {};
661
+ }
662
+ /**
663
+ * Gets the current log level of the Consola instance.
664
+ *
665
+ * @returns {number} The current log level.
666
+ */
667
+ get level() {
668
+ return this.options.level;
669
+ }
670
+ /**
671
+ * Sets the minimum log level that will be output by the instance.
672
+ *
673
+ * @param {number} level - The new log level to set.
674
+ */
675
+ set level(level) {
676
+ this.options.level = _normalizeLogLevel(
677
+ level,
678
+ this.options.types,
679
+ this.options.level
680
+ );
681
+ }
682
+ /**
683
+ * Displays a prompt to the user and returns the response.
684
+ * Throw an error if `prompt` is not supported by the current configuration.
685
+ *
686
+ * @template T
687
+ * @param {string} message - The message to display in the prompt.
688
+ * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
689
+ * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
690
+ */
691
+ prompt(message, opts) {
692
+ if (!this.options.prompt) {
693
+ throw new Error("prompt is not supported!");
694
+ }
695
+ return this.options.prompt(message, opts);
696
+ }
697
+ /**
698
+ * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
699
+ *
700
+ * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
701
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
702
+ */
703
+ create(options) {
704
+ const instance = new Consola({
705
+ ...this.options,
706
+ ...options
707
+ });
708
+ if (this._mockFn) {
709
+ instance.mockTypes(this._mockFn);
710
+ }
711
+ return instance;
712
+ }
713
+ /**
714
+ * Creates a new Consola instance with the specified default log object properties.
715
+ *
716
+ * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
717
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
718
+ */
719
+ withDefaults(defaults) {
720
+ return this.create({
721
+ ...this.options,
722
+ defaults: {
723
+ ...this.options.defaults,
724
+ ...defaults
725
+ }
726
+ });
727
+ }
728
+ /**
729
+ * Creates a new Consola instance with a specified tag, which will be included in every log.
730
+ *
731
+ * @param {string} tag - The tag to include in each log of the new instance.
732
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
733
+ */
734
+ withTag(tag) {
735
+ return this.withDefaults({
736
+ tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
737
+ });
738
+ }
739
+ /**
740
+ * Adds a custom reporter to the Consola instance.
741
+ * Reporters will be called for each log message, depending on their implementation and log level.
742
+ *
743
+ * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
744
+ * @returns {Consola} The current Consola instance.
745
+ */
746
+ addReporter(reporter) {
747
+ this.options.reporters.push(reporter);
748
+ return this;
749
+ }
750
+ /**
751
+ * Removes a custom reporter from the Consola instance.
752
+ * If no reporter is specified, all reporters will be removed.
753
+ *
754
+ * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
755
+ * @returns {Consola} The current Consola instance.
756
+ */
757
+ removeReporter(reporter) {
758
+ if (reporter) {
759
+ const i = this.options.reporters.indexOf(reporter);
760
+ if (i !== -1) {
761
+ return this.options.reporters.splice(i, 1);
762
+ }
763
+ } else {
764
+ this.options.reporters.splice(0);
765
+ }
766
+ return this;
767
+ }
768
+ /**
769
+ * Replaces all reporters of the Consola instance with the specified array of reporters.
770
+ *
771
+ * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
772
+ * @returns {Consola} The current Consola instance.
773
+ */
774
+ setReporters(reporters) {
775
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
776
+ return this;
777
+ }
778
+ wrapAll() {
779
+ this.wrapConsole();
780
+ this.wrapStd();
781
+ }
782
+ restoreAll() {
783
+ this.restoreConsole();
784
+ this.restoreStd();
785
+ }
786
+ /**
787
+ * Overrides console methods with Consola logging methods for consistent logging.
788
+ */
789
+ wrapConsole() {
790
+ for (const type in this.options.types) {
791
+ if (!console["__" + type]) {
792
+ console["__" + type] = console[type];
793
+ }
794
+ console[type] = this[type].raw;
795
+ }
796
+ }
797
+ /**
798
+ * Restores the original console methods, removing Consola overrides.
799
+ */
800
+ restoreConsole() {
801
+ for (const type in this.options.types) {
802
+ if (console["__" + type]) {
803
+ console[type] = console["__" + type];
804
+ delete console["__" + type];
805
+ }
806
+ }
807
+ }
808
+ /**
809
+ * Overrides standard output and error streams to redirect them through Consola.
810
+ */
811
+ wrapStd() {
812
+ this._wrapStream(this.options.stdout, "log");
813
+ this._wrapStream(this.options.stderr, "log");
814
+ }
815
+ _wrapStream(stream, type) {
816
+ if (!stream) {
817
+ return;
818
+ }
819
+ if (!stream.__write) {
820
+ stream.__write = stream.write;
821
+ }
822
+ stream.write = (data) => {
823
+ this[type].raw(String(data).trim());
824
+ };
825
+ }
826
+ /**
827
+ * Restores the original standard output and error streams, removing the Consola redirection.
828
+ */
829
+ restoreStd() {
830
+ this._restoreStream(this.options.stdout);
831
+ this._restoreStream(this.options.stderr);
832
+ }
833
+ _restoreStream(stream) {
834
+ if (!stream) {
835
+ return;
836
+ }
837
+ if (stream.__write) {
838
+ stream.write = stream.__write;
839
+ delete stream.__write;
840
+ }
841
+ }
842
+ /**
843
+ * Pauses logging, queues incoming logs until resumed.
844
+ */
845
+ pauseLogs() {
846
+ paused = true;
847
+ }
848
+ /**
849
+ * Resumes logging, processing any queued logs.
850
+ */
851
+ resumeLogs() {
852
+ paused = false;
853
+ const _queue = queue.splice(0);
854
+ for (const item of _queue) {
855
+ item[0]._logFn(item[1], item[2]);
856
+ }
857
+ }
858
+ /**
859
+ * Replaces logging methods with mocks if a mock function is provided.
860
+ *
861
+ * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
862
+ */
863
+ mockTypes(mockFn) {
864
+ const _mockFn = mockFn || this.options.mockFn;
865
+ this._mockFn = _mockFn;
866
+ if (typeof _mockFn !== "function") {
867
+ return;
868
+ }
869
+ for (const type in this.options.types) {
870
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
871
+ this[type].raw = this[type];
872
+ }
873
+ }
874
+ _wrapLogFn(defaults, isRaw) {
875
+ return (...args) => {
876
+ if (paused) {
877
+ queue.push([this, defaults, args, isRaw]);
878
+ return;
879
+ }
880
+ return this._logFn(defaults, args, isRaw);
881
+ };
882
+ }
883
+ _logFn(defaults, args, isRaw) {
884
+ if ((defaults.level || 0) > this.level) {
885
+ return false;
886
+ }
887
+ const logObj = {
888
+ date: /* @__PURE__ */ new Date(),
889
+ args: [],
890
+ ...defaults,
891
+ level: _normalizeLogLevel(defaults.level, this.options.types)
892
+ };
893
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) {
894
+ Object.assign(logObj, args[0]);
895
+ } else {
896
+ logObj.args = [...args];
897
+ }
898
+ if (logObj.message) {
899
+ logObj.args.unshift(logObj.message);
900
+ delete logObj.message;
901
+ }
902
+ if (logObj.additional) {
903
+ if (!Array.isArray(logObj.additional)) {
904
+ logObj.additional = logObj.additional.split("\n");
905
+ }
906
+ logObj.args.push("\n" + logObj.additional.join("\n"));
907
+ delete logObj.additional;
908
+ }
909
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
910
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
911
+ const resolveLog = (newLog = false) => {
912
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
913
+ if (this._lastLog.object && repeated > 0) {
914
+ const args2 = [...this._lastLog.object.args];
915
+ if (repeated > 1) {
916
+ args2.push(`(repeated ${repeated} times)`);
917
+ }
918
+ this._log({ ...this._lastLog.object, args: args2 });
919
+ this._lastLog.count = 1;
920
+ }
921
+ if (newLog) {
922
+ this._lastLog.object = logObj;
923
+ this._log(logObj);
924
+ }
925
+ };
926
+ clearTimeout(this._lastLog.timeout);
927
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
928
+ this._lastLog.time = logObj.date;
929
+ if (diffTime < this.options.throttle) {
930
+ try {
931
+ const serializedLog = JSON.stringify([
932
+ logObj.type,
933
+ logObj.tag,
934
+ logObj.args
935
+ ]);
936
+ const isSameLog = this._lastLog.serialized === serializedLog;
937
+ this._lastLog.serialized = serializedLog;
938
+ if (isSameLog) {
939
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
940
+ if (this._lastLog.count > this.options.throttleMin) {
941
+ this._lastLog.timeout = setTimeout(
942
+ resolveLog,
943
+ this.options.throttle
944
+ );
945
+ return;
946
+ }
947
+ }
948
+ } catch {
949
+ }
950
+ }
951
+ resolveLog(true);
952
+ }
953
+ _log(logObj) {
954
+ for (const reporter of this.options.reporters) {
955
+ reporter.log(logObj, {
956
+ options: this.options
957
+ });
958
+ }
959
+ }
960
+ }
961
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
962
+ if (input === void 0) {
963
+ return defaultLevel;
964
+ }
965
+ if (typeof input === "number") {
966
+ return input;
967
+ }
968
+ if (types[input] && types[input].level !== void 0) {
969
+ return types[input].level;
970
+ }
971
+ return defaultLevel;
972
+ }
973
+ Consola.prototype.add = Consola.prototype.addReporter;
974
+ Consola.prototype.remove = Consola.prototype.removeReporter;
975
+ Consola.prototype.clear = Consola.prototype.removeReporter;
976
+ Consola.prototype.withScope = Consola.prototype.withTag;
977
+ Consola.prototype.mock = Consola.prototype.mockTypes;
978
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
979
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
980
+ function createConsola$1(options = {}) {
981
+ return new Consola(options);
982
+ }
983
+
984
+ class BrowserReporter {
985
+ options;
986
+ defaultColor;
987
+ levelColorMap;
988
+ typeColorMap;
989
+ constructor(options) {
990
+ this.options = { ...options };
991
+ this.defaultColor = "#7f8c8d";
992
+ this.levelColorMap = {
993
+ 0: "#c0392b",
994
+ // Red
995
+ 1: "#f39c12",
996
+ // Yellow
997
+ 3: "#00BCD4"
998
+ // Cyan
999
+ };
1000
+ this.typeColorMap = {
1001
+ success: "#2ecc71"
1002
+ // Green
1003
+ };
1004
+ }
1005
+ _getLogFn(level) {
1006
+ if (level < 1) {
1007
+ return console.__error || console.error;
1008
+ }
1009
+ if (level === 1) {
1010
+ return console.__warn || console.warn;
1011
+ }
1012
+ return console.__log || console.log;
1013
+ }
1014
+ log(logObj) {
1015
+ const consoleLogFn = this._getLogFn(logObj.level);
1016
+ const type = logObj.type === "log" ? "" : logObj.type;
1017
+ const tag = logObj.tag || "";
1018
+ const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
1019
+ const style = `
1020
+ background: ${color};
1021
+ border-radius: 0.5em;
1022
+ color: white;
1023
+ font-weight: bold;
1024
+ padding: 2px 0.5em;
1025
+ `;
1026
+ const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
1027
+ if (typeof logObj.args[0] === "string") {
1028
+ consoleLogFn(
1029
+ `${badge}%c ${logObj.args[0]}`,
1030
+ style,
1031
+ // Empty string as style resets to default console style
1032
+ "",
1033
+ ...logObj.args.slice(1)
1034
+ );
1035
+ } else {
1036
+ consoleLogFn(badge, style, ...logObj.args);
1037
+ }
1038
+ }
1039
+ }
1040
+
1041
+ function createConsola(options = {}) {
1042
+ const consola2 = createConsola$1({
1043
+ reporters: options.reporters || [new BrowserReporter({})],
1044
+ prompt(message, options2 = {}) {
1045
+ if (options2.type === "confirm") {
1046
+ return Promise.resolve(confirm(message));
1047
+ }
1048
+ return Promise.resolve(prompt(message));
1049
+ },
1050
+ ...options
1051
+ });
1052
+ return consola2;
1053
+ }
1054
+ const consola = createConsola();
1055
+
1056
+ function createLogger(PLUGIN_NAME, verbose) {
1057
+ const prefix = chalk.blue.bold(`
1058
+ [${PLUGIN_NAME}]`);
1059
+ return {
1060
+ log: (message) => {
1061
+ if (verbose) {
1062
+ consola.log(`${prefix} ${chalk.white(message)}`);
1063
+ }
1064
+ },
1065
+ success: (message) => {
1066
+ if (verbose) {
1067
+ consola.success(`${prefix} ${chalk.green(message)}`);
1068
+ }
1069
+ },
1070
+ error: (message, error) => {
1071
+ consola.error(`${prefix} ${chalk.red(message)}`, error);
1072
+ },
1073
+ pathReplace: (from, to) => {
1074
+ if (verbose) {
1075
+ consola.log(`${prefix} ${chalk.gray(from)} ${chalk.yellow("======>")} ${chalk.cyan(to)}`);
1076
+ }
1077
+ }
1078
+ };
1079
+ }
1080
+ function escapeRegExp(str) {
1081
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1082
+ }
1083
+ function replaceStaticToCdn(code, assetDir, cdnBasePath, logger) {
1084
+ const escapedStaticPrefix = escapeRegExp(assetDir);
1085
+ const cssUrlRE = new RegExp(
1086
+ `url\\(\\s*(['"]?)(${escapedStaticPrefix}[^'")\\s]+)\\1\\s*\\)`,
1087
+ "g"
1088
+ );
1089
+ let transformed = code.replace(cssUrlRE, (match, quote, originalPath) => {
1090
+ try {
1091
+ if (originalPath.startsWith("http") || originalPath.startsWith("data:")) {
1092
+ return match;
1093
+ }
1094
+ const outputFileName = `${cdnBasePath}${originalPath}`;
1095
+ logger.pathReplace(originalPath, outputFileName);
1096
+ return `url(${quote || ""}${outputFileName}${quote || ""})`;
1097
+ } catch (error) {
1098
+ logger.error(`\u5904\u7406 CSS \u5931\u8D25`, error);
1099
+ return match;
1100
+ }
1101
+ });
1102
+ const stringRE = new RegExp(
1103
+ `(['"])(${escapedStaticPrefix}[^'"]*)\\1`,
1104
+ "g"
1105
+ );
1106
+ transformed = transformed.replace(stringRE, (match, quote, originalPath) => {
1107
+ try {
1108
+ if (originalPath.startsWith("http") || originalPath.startsWith("data:")) {
1109
+ return match;
1110
+ }
1111
+ const outputFileName = `${cdnBasePath}${originalPath}`;
1112
+ logger.pathReplace(originalPath, outputFileName);
1113
+ return `${quote}${outputFileName}${quote}`;
1114
+ } catch (error) {
1115
+ logger.error(`\u5904\u7406\u5B57\u7B26\u4E32\u5931\u8D25`, error);
1116
+ return match;
1117
+ }
1118
+ });
1119
+ return transformed;
1120
+ }
1121
+ function UniCdn(opt) {
1122
+ const PLUGIN_NAME = "vite-plugin-uni-cdn";
1123
+ const defaultOption = {
1124
+ cdn: "",
1125
+ sourceDir: "static/cdn",
1126
+ include: ["**/*.{vue,css,scss,sass,less,styl}"],
1127
+ exclude: ["**/node_modules/**", "**/uni_modules/**", "**/dist/**", "**/unpackage/**"],
1128
+ deleteOutputFiles: true,
1129
+ verbose: true
1130
+ };
1131
+ const options = { ...defaultOption, ...opt };
1132
+ const cdnBasePath = options.cdn ? options.cdn.endsWith("/") ? options.cdn.slice(0, -1) : options.cdn : "";
1133
+ if (!cdnBasePath || !options.sourceDir) {
1134
+ return { name: PLUGIN_NAME };
1135
+ }
1136
+ const logger = createLogger(PLUGIN_NAME, options.verbose ?? true);
1137
+ const filter = createFilter(options.include, options.exclude);
1138
+ let isSrc = false;
1139
+ let projectRoot = "";
1140
+ let sourceDirAbs = "";
1141
+ let assetDir = "";
1142
+ let outputDir = "";
1143
+ return {
1144
+ name: PLUGIN_NAME,
1145
+ async configResolved(resolvedConfig) {
1146
+ projectRoot = resolvedConfig.root;
1147
+ const normalizeSourceDir = normalizePath(path.normalize(options.sourceDir));
1148
+ const relSourceDir = normalizeSourceDir.replace(/^\/+/, "");
1149
+ sourceDirAbs = normalizePath(path.resolve(projectRoot, relSourceDir));
1150
+ try {
1151
+ await fs.access(sourceDirAbs);
1152
+ } catch (error) {
1153
+ const err = error;
1154
+ logger.error("\u66FF\u6362\u8D44\u6E90\u76EE\u5F55\u4E0D\u5B58\u5728", err);
1155
+ return;
1156
+ }
1157
+ isSrc = relSourceDir.startsWith("src/");
1158
+ const staticSubPath = isSrc ? relSourceDir.slice("src/".length) : relSourceDir;
1159
+ assetDir = `/${staticSubPath.replace(/^\/+/, "")}`;
1160
+ logger.log(`\u5DE5\u7A0B\u6839\u76EE\u5F55: ${projectRoot}`);
1161
+ logger.log(`\u66FF\u6362\u8D44\u6E90\u76EE\u5F55: ${sourceDirAbs}`);
1162
+ logger.log(`\u5339\u914D\u8D44\u6E90\u524D\u7F00: ${assetDir}`);
1163
+ outputDir = normalizePath(
1164
+ path.resolve(
1165
+ resolvedConfig.build.outDir,
1166
+ staticSubPath
1167
+ )
1168
+ );
1169
+ logger.log(`\u8F93\u51FA\u76EE\u5F55: ${outputDir}`);
1170
+ },
1171
+ transform(code, id) {
1172
+ if (!sourceDirAbs || !assetDir || !code) {
1173
+ return { code };
1174
+ }
1175
+ const [filepath] = id.split("?", 2);
1176
+ if (!filter(filepath)) {
1177
+ return { code };
1178
+ }
1179
+ const transformed = replaceStaticToCdn(code, assetDir, cdnBasePath, logger);
1180
+ return { code: transformed };
1181
+ },
1182
+ generateBundle(_options, bundle) {
1183
+ if (!sourceDirAbs || !assetDir) {
1184
+ return;
1185
+ }
1186
+ for (const [fileName, chunk] of Object.entries(bundle)) {
1187
+ if (chunk.type === "asset") {
1188
+ if (typeof chunk.source !== "string") {
1189
+ continue;
1190
+ }
1191
+ if (!/\.(?:css|js|mjs|html)$/.test(fileName)) {
1192
+ continue;
1193
+ }
1194
+ const before = chunk.source;
1195
+ chunk.source = replaceStaticToCdn(before, assetDir, cdnBasePath, logger);
1196
+ } else if (chunk.type === "chunk") {
1197
+ const before = chunk.code;
1198
+ chunk.code = replaceStaticToCdn(before, assetDir, cdnBasePath, logger);
1199
+ }
1200
+ }
1201
+ },
1202
+ async closeBundle() {
1203
+ if (!sourceDirAbs || !assetDir) {
1204
+ return;
1205
+ }
1206
+ if (!options.deleteOutputFiles) {
1207
+ logger.log("\u5DF2\u7981\u7528\u8F93\u51FA\u6587\u4EF6\u5220\u9664\u529F\u80FD");
1208
+ return;
1209
+ }
1210
+ try {
1211
+ await fs.access(outputDir);
1212
+ await fs.rm(outputDir, { recursive: true, force: true, maxRetries: 2 });
1213
+ logger.success(`\u5DF2\u6210\u529F\u5220\u9664\u76EE\u5F55: ${outputDir}`);
1214
+ } catch (error) {
1215
+ const err = error;
1216
+ if (err.code === "ENOENT") {
1217
+ logger.log(`\u76EE\u5F55\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u5220\u9664: ${outputDir}`);
1218
+ } else {
1219
+ logger.error(`\u5220\u9664\u76EE\u5F55\u5931\u8D25: ${outputDir}`, err);
1220
+ }
1221
+ }
1222
+ }
1223
+ };
1224
+ }
1225
+
1226
+ export { UniCdn as default };