@serwist/next 8.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.
@@ -0,0 +1,930 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var path = require('node:path');
6
+ var node_url = require('node:url');
7
+ var webpackPlugin = require('@serwist/webpack-plugin');
8
+ var internal = require('@serwist/webpack-plugin/internal');
9
+ var cleanWebpackPlugin = require('clean-webpack-plugin');
10
+ var fg = require('fast-glob');
11
+ var crypto = require('node:crypto');
12
+ var fs = require('node:fs');
13
+ var node_module = require('node:module');
14
+ var process = require('node:process');
15
+ var os = require('node:os');
16
+ var tty = require('node:tty');
17
+
18
+ /**
19
+ * Find the first truthy value in an array.
20
+ * @param arr
21
+ * @param fn
22
+ * @returns
23
+ */ const findFirstTruthy = (arr, fn)=>{
24
+ for (const i of arr){
25
+ const resolved = fn(i);
26
+ if (resolved) {
27
+ return resolved;
28
+ }
29
+ }
30
+ return undefined;
31
+ };
32
+
33
+ const getFileHash = (file)=>crypto.createHash("md5").update(fs.readFileSync(file)).digest("hex");
34
+
35
+ const getContentHash = (file, isDev)=>{
36
+ if (isDev) {
37
+ return "development";
38
+ }
39
+ return getFileHash(file).slice(0, 16);
40
+ };
41
+
42
+ node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.old.cjs', document.baseURI).href)));
43
+
44
+ const loadTSConfig = (baseDir, relativeTSConfigPath)=>{
45
+ try {
46
+ // Find tsconfig.json file
47
+ const tsConfigPath = findFirstTruthy([
48
+ relativeTSConfigPath ?? "tsconfig.json",
49
+ "jsconfig.json"
50
+ ], (filePath)=>{
51
+ const resolvedPath = path.join(baseDir, filePath);
52
+ return fs.existsSync(resolvedPath) ? resolvedPath : undefined;
53
+ });
54
+ if (!tsConfigPath) {
55
+ return undefined;
56
+ }
57
+ // Read tsconfig.json file
58
+ const tsConfigFile = JSON.parse(fs.readFileSync(tsConfigPath, "utf-8"));
59
+ return tsConfigFile;
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ };
64
+
65
+ const ANSI_BACKGROUND_OFFSET = 10;
66
+ const wrapAnsi16 = (offset = 0)=>(code)=>`\u001B[${code + offset}m`;
67
+ const wrapAnsi256 = (offset = 0)=>(code)=>`\u001B[${38 + offset};5;${code}m`;
68
+ const wrapAnsi16m = (offset = 0)=>(red, green, blue)=>`\u001B[${38 + offset};2;${red};${green};${blue}m`;
69
+ const styles$1 = {
70
+ modifier: {
71
+ reset: [
72
+ 0,
73
+ 0
74
+ ],
75
+ // 21 isn't widely supported and 22 does the same thing
76
+ bold: [
77
+ 1,
78
+ 22
79
+ ],
80
+ dim: [
81
+ 2,
82
+ 22
83
+ ],
84
+ italic: [
85
+ 3,
86
+ 23
87
+ ],
88
+ underline: [
89
+ 4,
90
+ 24
91
+ ],
92
+ overline: [
93
+ 53,
94
+ 55
95
+ ],
96
+ inverse: [
97
+ 7,
98
+ 27
99
+ ],
100
+ hidden: [
101
+ 8,
102
+ 28
103
+ ],
104
+ strikethrough: [
105
+ 9,
106
+ 29
107
+ ]
108
+ },
109
+ color: {
110
+ black: [
111
+ 30,
112
+ 39
113
+ ],
114
+ red: [
115
+ 31,
116
+ 39
117
+ ],
118
+ green: [
119
+ 32,
120
+ 39
121
+ ],
122
+ yellow: [
123
+ 33,
124
+ 39
125
+ ],
126
+ blue: [
127
+ 34,
128
+ 39
129
+ ],
130
+ magenta: [
131
+ 35,
132
+ 39
133
+ ],
134
+ cyan: [
135
+ 36,
136
+ 39
137
+ ],
138
+ white: [
139
+ 37,
140
+ 39
141
+ ],
142
+ // Bright color
143
+ blackBright: [
144
+ 90,
145
+ 39
146
+ ],
147
+ gray: [
148
+ 90,
149
+ 39
150
+ ],
151
+ grey: [
152
+ 90,
153
+ 39
154
+ ],
155
+ redBright: [
156
+ 91,
157
+ 39
158
+ ],
159
+ greenBright: [
160
+ 92,
161
+ 39
162
+ ],
163
+ yellowBright: [
164
+ 93,
165
+ 39
166
+ ],
167
+ blueBright: [
168
+ 94,
169
+ 39
170
+ ],
171
+ magentaBright: [
172
+ 95,
173
+ 39
174
+ ],
175
+ cyanBright: [
176
+ 96,
177
+ 39
178
+ ],
179
+ whiteBright: [
180
+ 97,
181
+ 39
182
+ ]
183
+ },
184
+ bgColor: {
185
+ bgBlack: [
186
+ 40,
187
+ 49
188
+ ],
189
+ bgRed: [
190
+ 41,
191
+ 49
192
+ ],
193
+ bgGreen: [
194
+ 42,
195
+ 49
196
+ ],
197
+ bgYellow: [
198
+ 43,
199
+ 49
200
+ ],
201
+ bgBlue: [
202
+ 44,
203
+ 49
204
+ ],
205
+ bgMagenta: [
206
+ 45,
207
+ 49
208
+ ],
209
+ bgCyan: [
210
+ 46,
211
+ 49
212
+ ],
213
+ bgWhite: [
214
+ 47,
215
+ 49
216
+ ],
217
+ // Bright color
218
+ bgBlackBright: [
219
+ 100,
220
+ 49
221
+ ],
222
+ bgGray: [
223
+ 100,
224
+ 49
225
+ ],
226
+ bgGrey: [
227
+ 100,
228
+ 49
229
+ ],
230
+ bgRedBright: [
231
+ 101,
232
+ 49
233
+ ],
234
+ bgGreenBright: [
235
+ 102,
236
+ 49
237
+ ],
238
+ bgYellowBright: [
239
+ 103,
240
+ 49
241
+ ],
242
+ bgBlueBright: [
243
+ 104,
244
+ 49
245
+ ],
246
+ bgMagentaBright: [
247
+ 105,
248
+ 49
249
+ ],
250
+ bgCyanBright: [
251
+ 106,
252
+ 49
253
+ ],
254
+ bgWhiteBright: [
255
+ 107,
256
+ 49
257
+ ]
258
+ }
259
+ };
260
+ Object.keys(styles$1.modifier);
261
+ const foregroundColorNames = Object.keys(styles$1.color);
262
+ const backgroundColorNames = Object.keys(styles$1.bgColor);
263
+ [
264
+ ...foregroundColorNames,
265
+ ...backgroundColorNames
266
+ ];
267
+ function assembleStyles() {
268
+ const codes = new Map();
269
+ for (const [groupName, group] of Object.entries(styles$1)){
270
+ for (const [styleName, style] of Object.entries(group)){
271
+ styles$1[styleName] = {
272
+ open: `\u001B[${style[0]}m`,
273
+ close: `\u001B[${style[1]}m`
274
+ };
275
+ group[styleName] = styles$1[styleName];
276
+ codes.set(style[0], style[1]);
277
+ }
278
+ Object.defineProperty(styles$1, groupName, {
279
+ value: group,
280
+ enumerable: false
281
+ });
282
+ }
283
+ Object.defineProperty(styles$1, 'codes', {
284
+ value: codes,
285
+ enumerable: false
286
+ });
287
+ styles$1.color.close = '\u001B[39m';
288
+ styles$1.bgColor.close = '\u001B[49m';
289
+ styles$1.color.ansi = wrapAnsi16();
290
+ styles$1.color.ansi256 = wrapAnsi256();
291
+ styles$1.color.ansi16m = wrapAnsi16m();
292
+ styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
293
+ styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
294
+ styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
295
+ // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
296
+ Object.defineProperties(styles$1, {
297
+ rgbToAnsi256: {
298
+ value (red, green, blue) {
299
+ // We use the extended greyscale palette here, with the exception of
300
+ // black and white. normal palette only has 4 greyscale shades.
301
+ if (red === green && green === blue) {
302
+ if (red < 8) {
303
+ return 16;
304
+ }
305
+ if (red > 248) {
306
+ return 231;
307
+ }
308
+ return Math.round((red - 8) / 247 * 24) + 232;
309
+ }
310
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
311
+ },
312
+ enumerable: false
313
+ },
314
+ hexToRgb: {
315
+ value (hex) {
316
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
317
+ if (!matches) {
318
+ return [
319
+ 0,
320
+ 0,
321
+ 0
322
+ ];
323
+ }
324
+ let [colorString] = matches;
325
+ if (colorString.length === 3) {
326
+ colorString = [
327
+ ...colorString
328
+ ].map((character)=>character + character).join('');
329
+ }
330
+ const integer = Number.parseInt(colorString, 16);
331
+ return [
332
+ /* eslint-disable no-bitwise */ integer >> 16 & 0xFF,
333
+ integer >> 8 & 0xFF,
334
+ integer & 0xFF
335
+ ];
336
+ },
337
+ enumerable: false
338
+ },
339
+ hexToAnsi256: {
340
+ value: (hex)=>styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
341
+ enumerable: false
342
+ },
343
+ ansi256ToAnsi: {
344
+ value (code) {
345
+ if (code < 8) {
346
+ return 30 + code;
347
+ }
348
+ if (code < 16) {
349
+ return 90 + (code - 8);
350
+ }
351
+ let red;
352
+ let green;
353
+ let blue;
354
+ if (code >= 232) {
355
+ red = ((code - 232) * 10 + 8) / 255;
356
+ green = red;
357
+ blue = red;
358
+ } else {
359
+ code -= 16;
360
+ const remainder = code % 36;
361
+ red = Math.floor(code / 36) / 5;
362
+ green = Math.floor(remainder / 6) / 5;
363
+ blue = remainder % 6 / 5;
364
+ }
365
+ const value = Math.max(red, green, blue) * 2;
366
+ if (value === 0) {
367
+ return 30;
368
+ }
369
+ // eslint-disable-next-line no-bitwise
370
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
371
+ if (value === 2) {
372
+ result += 60;
373
+ }
374
+ return result;
375
+ },
376
+ enumerable: false
377
+ },
378
+ rgbToAnsi: {
379
+ value: (red, green, blue)=>styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
380
+ enumerable: false
381
+ },
382
+ hexToAnsi: {
383
+ value: (hex)=>styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
384
+ enumerable: false
385
+ }
386
+ });
387
+ return styles$1;
388
+ }
389
+ const ansiStyles = assembleStyles();
390
+
391
+ // From: https://github.com/sindresorhus/has-flag/blob/main/index.js
392
+ /// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {
393
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
394
+ const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
395
+ const position = argv.indexOf(prefix + flag);
396
+ const terminatorPosition = argv.indexOf('--');
397
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
398
+ }
399
+ const { env } = process;
400
+ let flagForceColor;
401
+ if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) {
402
+ flagForceColor = 0;
403
+ } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
404
+ flagForceColor = 1;
405
+ }
406
+ function envForceColor() {
407
+ if ('FORCE_COLOR' in env) {
408
+ if (env.FORCE_COLOR === 'true') {
409
+ return 1;
410
+ }
411
+ if (env.FORCE_COLOR === 'false') {
412
+ return 0;
413
+ }
414
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
415
+ }
416
+ }
417
+ function translateLevel(level) {
418
+ if (level === 0) {
419
+ return false;
420
+ }
421
+ return {
422
+ level,
423
+ hasBasic: true,
424
+ has256: level >= 2,
425
+ has16m: level >= 3
426
+ };
427
+ }
428
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
429
+ const noFlagForceColor = envForceColor();
430
+ if (noFlagForceColor !== undefined) {
431
+ flagForceColor = noFlagForceColor;
432
+ }
433
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
434
+ if (forceColor === 0) {
435
+ return 0;
436
+ }
437
+ if (sniffFlags) {
438
+ if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
439
+ return 3;
440
+ }
441
+ if (hasFlag('color=256')) {
442
+ return 2;
443
+ }
444
+ }
445
+ // Check for Azure DevOps pipelines.
446
+ // Has to be above the `!streamIsTTY` check.
447
+ if ('TF_BUILD' in env && 'AGENT_NAME' in env) {
448
+ return 1;
449
+ }
450
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
451
+ return 0;
452
+ }
453
+ const min = forceColor || 0;
454
+ if (env.TERM === 'dumb') {
455
+ return min;
456
+ }
457
+ if (process.platform === 'win32') {
458
+ // Windows 10 build 10586 is the first Windows release that supports 256 colors.
459
+ // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
460
+ const osRelease = os.release().split('.');
461
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586) {
462
+ return Number(osRelease[2]) >= 14_931 ? 3 : 2;
463
+ }
464
+ return 1;
465
+ }
466
+ if ('CI' in env) {
467
+ if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) {
468
+ return 3;
469
+ }
470
+ if ([
471
+ 'TRAVIS',
472
+ 'CIRCLECI',
473
+ 'APPVEYOR',
474
+ 'GITLAB_CI',
475
+ 'BUILDKITE',
476
+ 'DRONE'
477
+ ].some((sign)=>sign in env) || env.CI_NAME === 'codeship') {
478
+ return 1;
479
+ }
480
+ return min;
481
+ }
482
+ if ('TEAMCITY_VERSION' in env) {
483
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
484
+ }
485
+ if (env.COLORTERM === 'truecolor') {
486
+ return 3;
487
+ }
488
+ if (env.TERM === 'xterm-kitty') {
489
+ return 3;
490
+ }
491
+ if ('TERM_PROGRAM' in env) {
492
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
493
+ switch(env.TERM_PROGRAM){
494
+ case 'iTerm.app':
495
+ {
496
+ return version >= 3 ? 3 : 2;
497
+ }
498
+ case 'Apple_Terminal':
499
+ {
500
+ return 2;
501
+ }
502
+ }
503
+ }
504
+ if (/-256(color)?$/i.test(env.TERM)) {
505
+ return 2;
506
+ }
507
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
508
+ return 1;
509
+ }
510
+ if ('COLORTERM' in env) {
511
+ return 1;
512
+ }
513
+ return min;
514
+ }
515
+ function createSupportsColor(stream, options = {}) {
516
+ const level = _supportsColor(stream, {
517
+ streamIsTTY: stream && stream.isTTY,
518
+ ...options
519
+ });
520
+ return translateLevel(level);
521
+ }
522
+ const supportsColor = {
523
+ stdout: createSupportsColor({
524
+ isTTY: tty.isatty(1)
525
+ }),
526
+ stderr: createSupportsColor({
527
+ isTTY: tty.isatty(2)
528
+ })
529
+ };
530
+
531
+ // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
532
+ function stringReplaceAll(string, substring, replacer) {
533
+ let index = string.indexOf(substring);
534
+ if (index === -1) {
535
+ return string;
536
+ }
537
+ const substringLength = substring.length;
538
+ let endIndex = 0;
539
+ let returnValue = '';
540
+ do {
541
+ returnValue += string.slice(endIndex, index) + substring + replacer;
542
+ endIndex = index + substringLength;
543
+ index = string.indexOf(substring, endIndex);
544
+ }while (index !== -1)
545
+ returnValue += string.slice(endIndex);
546
+ return returnValue;
547
+ }
548
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
549
+ let endIndex = 0;
550
+ let returnValue = '';
551
+ do {
552
+ const gotCR = string[index - 1] === '\r';
553
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
554
+ endIndex = index + 1;
555
+ index = string.indexOf('\n', endIndex);
556
+ }while (index !== -1)
557
+ returnValue += string.slice(endIndex);
558
+ return returnValue;
559
+ }
560
+
561
+ const { stdout: stdoutColor, stderr: stderrColor } = supportsColor;
562
+ const GENERATOR = Symbol('GENERATOR');
563
+ const STYLER = Symbol('STYLER');
564
+ const IS_EMPTY = Symbol('IS_EMPTY');
565
+ // `supportsColor.level` → `ansiStyles.color[name]` mapping
566
+ const levelMapping = [
567
+ 'ansi',
568
+ 'ansi',
569
+ 'ansi256',
570
+ 'ansi16m'
571
+ ];
572
+ const styles = Object.create(null);
573
+ const applyOptions = (object, options = {})=>{
574
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
575
+ throw new Error('The `level` option should be an integer from 0 to 3');
576
+ }
577
+ // Detect level if not set manually
578
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
579
+ object.level = options.level === undefined ? colorLevel : options.level;
580
+ };
581
+ const chalkFactory = (options)=>{
582
+ const chalk = (...strings)=>strings.join(' ');
583
+ applyOptions(chalk, options);
584
+ Object.setPrototypeOf(chalk, createChalk.prototype);
585
+ return chalk;
586
+ };
587
+ function createChalk(options) {
588
+ return chalkFactory(options);
589
+ }
590
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
591
+ for (const [styleName, style] of Object.entries(ansiStyles)){
592
+ styles[styleName] = {
593
+ get () {
594
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
595
+ Object.defineProperty(this, styleName, {
596
+ value: builder
597
+ });
598
+ return builder;
599
+ }
600
+ };
601
+ }
602
+ styles.visible = {
603
+ get () {
604
+ const builder = createBuilder(this, this[STYLER], true);
605
+ Object.defineProperty(this, 'visible', {
606
+ value: builder
607
+ });
608
+ return builder;
609
+ }
610
+ };
611
+ const getModelAnsi = (model, level, type, ...arguments_)=>{
612
+ if (model === 'rgb') {
613
+ if (level === 'ansi16m') {
614
+ return ansiStyles[type].ansi16m(...arguments_);
615
+ }
616
+ if (level === 'ansi256') {
617
+ return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
618
+ }
619
+ return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
620
+ }
621
+ if (model === 'hex') {
622
+ return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
623
+ }
624
+ return ansiStyles[type][model](...arguments_);
625
+ };
626
+ const usedModels = [
627
+ 'rgb',
628
+ 'hex',
629
+ 'ansi256'
630
+ ];
631
+ for (const model of usedModels){
632
+ styles[model] = {
633
+ get () {
634
+ const { level } = this;
635
+ return function(...arguments_) {
636
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
637
+ return createBuilder(this, styler, this[IS_EMPTY]);
638
+ };
639
+ }
640
+ };
641
+ const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
642
+ styles[bgModel] = {
643
+ get () {
644
+ const { level } = this;
645
+ return function(...arguments_) {
646
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
647
+ return createBuilder(this, styler, this[IS_EMPTY]);
648
+ };
649
+ }
650
+ };
651
+ }
652
+ const proto = Object.defineProperties(()=>{}, {
653
+ ...styles,
654
+ level: {
655
+ enumerable: true,
656
+ get () {
657
+ return this[GENERATOR].level;
658
+ },
659
+ set (level) {
660
+ this[GENERATOR].level = level;
661
+ }
662
+ }
663
+ });
664
+ const createStyler = (open, close, parent)=>{
665
+ let openAll;
666
+ let closeAll;
667
+ if (parent === undefined) {
668
+ openAll = open;
669
+ closeAll = close;
670
+ } else {
671
+ openAll = parent.openAll + open;
672
+ closeAll = close + parent.closeAll;
673
+ }
674
+ return {
675
+ open,
676
+ close,
677
+ openAll,
678
+ closeAll,
679
+ parent
680
+ };
681
+ };
682
+ const createBuilder = (self, _styler, _isEmpty)=>{
683
+ // Single argument is hot path, implicit coercion is faster than anything
684
+ // eslint-disable-next-line no-implicit-coercion
685
+ const builder = (...arguments_)=>applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
686
+ // We alter the prototype because we must return a function, but there is
687
+ // no way to create a function with a different prototype
688
+ Object.setPrototypeOf(builder, proto);
689
+ builder[GENERATOR] = self;
690
+ builder[STYLER] = _styler;
691
+ builder[IS_EMPTY] = _isEmpty;
692
+ return builder;
693
+ };
694
+ const applyStyle = (self, string)=>{
695
+ if (self.level <= 0 || !string) {
696
+ return self[IS_EMPTY] ? '' : string;
697
+ }
698
+ let styler = self[STYLER];
699
+ if (styler === undefined) {
700
+ return string;
701
+ }
702
+ const { openAll, closeAll } = styler;
703
+ if (string.includes('\u001B')) {
704
+ while(styler !== undefined){
705
+ // Replace any instances already present with a re-opening code
706
+ // otherwise only the part of the string until said closing code
707
+ // will be colored, and the rest will simply be 'plain'.
708
+ string = stringReplaceAll(string, styler.close, styler.open);
709
+ styler = styler.parent;
710
+ }
711
+ }
712
+ // We can move both next actions out of loop, because remaining actions in loop won't have
713
+ // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
714
+ // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
715
+ const lfIndex = string.indexOf('\n');
716
+ if (lfIndex !== -1) {
717
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
718
+ }
719
+ return openAll + string + closeAll;
720
+ };
721
+ Object.defineProperties(createChalk.prototype, styles);
722
+ const chalk = createChalk();
723
+ createChalk({
724
+ level: stderrColor ? stderrColor.level : 0
725
+ });
726
+ var chalk$1 = chalk;
727
+
728
+ const mapLoggingMethodToConsole = {
729
+ wait: "log",
730
+ error: "error",
731
+ warn: "warn",
732
+ info: "log",
733
+ event: "log"
734
+ };
735
+ const prefixes = {
736
+ wait: `${chalk$1.white(chalk$1.bold("○"))} (serwist)`,
737
+ error: `${chalk$1.red(chalk$1.bold("X"))} (serwist)`,
738
+ warn: `${chalk$1.yellow(chalk$1.bold("⚠"))} (serwist)`,
739
+ info: `${chalk$1.white(chalk$1.bold("○"))} (serwist)`,
740
+ event: `${chalk$1.green(chalk$1.bold("✓"))} (serwist)`
741
+ };
742
+ const prefixedLog = (prefixType, ...message)=>{
743
+ const consoleMethod = mapLoggingMethodToConsole[prefixType];
744
+ const prefix = prefixes[prefixType];
745
+ if ((message[0] === "" || message[0] === undefined) && message.length === 1) {
746
+ message.shift();
747
+ }
748
+ // If there's no message, don't print the prefix but a new line
749
+ if (message.length === 0) {
750
+ console[consoleMethod]("");
751
+ } else {
752
+ console[consoleMethod](" " + prefix, ...message);
753
+ }
754
+ };
755
+ const info = (...message)=>{
756
+ prefixedLog("info", ...message);
757
+ };
758
+ const event = (...message)=>{
759
+ prefixedLog("event", ...message);
760
+ };
761
+
762
+ const __dirname$1 = node_url.fileURLToPath(new URL(".", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.old.cjs', document.baseURI).href))));
763
+ const withPWAInit = (pluginOptions)=>{
764
+ return (nextConfig = {})=>({
765
+ ...nextConfig,
766
+ webpack (config, options) {
767
+ const webpack = options.webpack;
768
+ const { buildId, dev } = options;
769
+ const basePath = options.config.basePath || "/";
770
+ const tsConfigJson = loadTSConfig(options.dir, nextConfig?.typescript?.tsconfigPath);
771
+ const { cacheOnFrontEndNav = false, disable = false, scope = basePath, swUrl = "sw.js", register = true, reloadOnOnline = true, ...buildOptions } = pluginOptions;
772
+ if (typeof nextConfig.webpack === "function") {
773
+ config = nextConfig.webpack(config, options);
774
+ }
775
+ if (disable) {
776
+ options.isServer && info("PWA support is disabled.");
777
+ return config;
778
+ }
779
+ if (!config.plugins) {
780
+ config.plugins = [];
781
+ }
782
+ event(`Compiling for ${options.isServer ? "server" : "client (static)"}...`);
783
+ const _sw = path.posix.join(basePath, swUrl);
784
+ const _scope = path.posix.join(scope, "/");
785
+ config.plugins.push(new webpack.DefinePlugin({
786
+ "self.__SERWIST_SW_ENTRY.sw": `'${_sw}'`,
787
+ "self.__SERWIST_SW_ENTRY.scope": `'${_scope}'`,
788
+ "self.__SERWIST_SW_ENTRY.cacheOnFrontEndNav": `${Boolean(cacheOnFrontEndNav)}`,
789
+ "self.__SERWIST_SW_ENTRY.register": `${Boolean(register)}`,
790
+ "self.__SERWIST_SW_ENTRY.reloadOnOnline": `${Boolean(reloadOnOnline)}`
791
+ }));
792
+ const swEntryJs = path.join(__dirname$1, "sw-entry.js");
793
+ const entry = config.entry;
794
+ config.entry = ()=>entry().then((entries)=>{
795
+ if (entries["main.js"] && !entries["main.js"].includes(swEntryJs)) {
796
+ if (Array.isArray(entries["main.js"])) {
797
+ entries["main.js"].unshift(swEntryJs);
798
+ } else if (typeof entries["main.js"] === "string") {
799
+ entries["main.js"] = [
800
+ swEntryJs,
801
+ entries["main.js"]
802
+ ];
803
+ }
804
+ }
805
+ if (entries["main-app"] && !entries["main-app"].includes(swEntryJs)) {
806
+ if (Array.isArray(entries["main-app"])) {
807
+ entries["main-app"].unshift(swEntryJs);
808
+ } else if (typeof entries["main-app"] === "string") {
809
+ entries["main-app"] = [
810
+ swEntryJs,
811
+ entries["main-app"]
812
+ ];
813
+ }
814
+ }
815
+ return entries;
816
+ });
817
+ if (!options.isServer) {
818
+ if (!register) {
819
+ info("Service worker won't be automatically registered as per the config, please call the following code in componentDidMount or useEffect:");
820
+ info(` window.serwist.register()`);
821
+ if (!tsConfigJson?.compilerOptions?.types?.includes("@serwist/next/typings")) {
822
+ info("You may also want to add @serwist/next/typings to compilerOptions.types in your tsconfig.json/jsconfig.json.");
823
+ }
824
+ }
825
+ const { swSrc: providedSwSrc, swDest: providedSwDest, additionalPrecacheEntries, exclude = [], modifyURLPrefix = {}, manifestTransforms = [], ...otherBuildOptions } = buildOptions;
826
+ let swSrc = providedSwSrc, swDest = providedSwDest;
827
+ if (!path.isAbsolute(swSrc)) {
828
+ swSrc = path.join(options.dir, swSrc);
829
+ }
830
+ if (!path.isAbsolute(swDest)) {
831
+ swDest = path.join(options.dir, swDest);
832
+ }
833
+ const destDir = path.dirname(swDest);
834
+ const shouldBuildSWEntryWorker = cacheOnFrontEndNav;
835
+ let swEntryPublicPath = undefined;
836
+ if (shouldBuildSWEntryWorker) {
837
+ const swEntryWorkerSrc = path.join(__dirname$1, `sw-entry-worker.js`);
838
+ const swEntryName = `swe-worker-${getContentHash(swEntryWorkerSrc, dev)}.js`;
839
+ swEntryPublicPath = path.posix.join(basePath, swEntryName);
840
+ const swEntryWorkerDest = path.join(destDir, swEntryName);
841
+ config.plugins.push(new internal.ChildCompilationPlugin({
842
+ src: swEntryWorkerSrc,
843
+ dest: swEntryWorkerDest
844
+ }));
845
+ }
846
+ config.plugins.push(new webpack.DefinePlugin({
847
+ "self.__SERWIST_SW_ENTRY.swEntryWorker": swEntryPublicPath && `'${swEntryPublicPath}'`
848
+ }));
849
+ info(`Service worker: ${swDest}`);
850
+ info(` URL: ${_sw}`);
851
+ info(` Scope: ${_scope}`);
852
+ config.plugins.push(new cleanWebpackPlugin.CleanWebpackPlugin({
853
+ cleanOnceBeforeBuildPatterns: [
854
+ path.join(destDir, "swe-worker-*.js"),
855
+ path.join(destDir, "swe-worker-*.js.map"),
856
+ swDest
857
+ ]
858
+ }));
859
+ // Precache files in public folder
860
+ let resolvedManifestEntries = additionalPrecacheEntries ?? [];
861
+ if (!resolvedManifestEntries) {
862
+ const swDestFileName = path.basename(swDest);
863
+ resolvedManifestEntries = fg.sync([
864
+ "**/*",
865
+ // Include these in case the user outputs these files to `public`.
866
+ "!swe-worker-*.js",
867
+ "!swe-worker-*.js.map",
868
+ `!${swDestFileName.replace(/^\/+/, "")}`,
869
+ `!${swDestFileName.replace(/^\/+/, "")}.map`
870
+ ], {
871
+ cwd: "public"
872
+ }).map((f)=>({
873
+ url: path.posix.join(basePath, f),
874
+ revision: getFileHash(`public/${f}`)
875
+ }));
876
+ }
877
+ const publicPath = config.output?.publicPath;
878
+ config.plugins.push(new webpackPlugin.InjectManifest({
879
+ swSrc,
880
+ swDest,
881
+ disablePrecacheManifest: dev,
882
+ additionalPrecacheEntries: dev ? [] : resolvedManifestEntries,
883
+ exclude: [
884
+ ...exclude,
885
+ ({ asset })=>{
886
+ if (asset.name.startsWith("server/") || asset.name.match(/^((app-|^)build-manifest\.json|react-loadable-manifest\.json)$/)) {
887
+ return true;
888
+ }
889
+ if (dev && !asset.name.startsWith("static/runtime/")) {
890
+ return true;
891
+ }
892
+ return false;
893
+ }
894
+ ],
895
+ modifyURLPrefix: {
896
+ ...modifyURLPrefix,
897
+ "/_next/../public/": "/"
898
+ },
899
+ manifestTransforms: [
900
+ ...manifestTransforms,
901
+ async (manifestEntries, compilation)=>{
902
+ const manifest = manifestEntries.map((m)=>{
903
+ m.url = m.url.replace("/_next//static/image", "/_next/static/image");
904
+ m.url = m.url.replace("/_next//static/media", "/_next/static/media");
905
+ if (m.revision === null) {
906
+ let key = m.url;
907
+ if (typeof publicPath === "string" && key.startsWith(publicPath)) {
908
+ key = m.url.substring(publicPath.length);
909
+ }
910
+ const asset = compilation.assetsInfo.get(key);
911
+ m.revision = asset ? asset.contenthash || buildId : buildId;
912
+ }
913
+ m.url = m.url.replace(/\[/g, "%5B").replace(/\]/g, "%5D");
914
+ return m;
915
+ });
916
+ return {
917
+ manifest,
918
+ warnings: []
919
+ };
920
+ }
921
+ ],
922
+ ...otherBuildOptions
923
+ }));
924
+ }
925
+ return config;
926
+ }
927
+ });
928
+ };
929
+
930
+ exports.default = withPWAInit;