@midscene/cli 1.17.8-beta-20261106101231.0 → 1.17.8

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.
@@ -1,4420 +1 @@
1
- import * as __rspack_external_os from "os";
2
- import * as __rspack_external_tty from "tty";
3
- import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
4
- import { basename, dirname, extname, join, relative, resolve as external_node_path_resolve, sep } from "node:path";
5
- import { createHash } from "node:crypto";
6
- import { ReportMergingTool } from "@midscene/core";
7
- import { getMidsceneRunSubDir } from "@midscene/shared/common";
8
- import { getDebug } from "@midscene/shared/logger";
9
- import { parseYamlScript, resolveWebTarget } from "@midscene/core/yaml";
10
- import { buildChromeArgs, buildDownloadBehavior, defaultViewportHeight, defaultViewportWidth } from "@midscene/web/puppeteer-agent-launcher";
11
- import lodash_merge from "lodash.merge";
12
- import puppeteer from "puppeteer";
13
- import { createYamlPlayer } from "@midscene/test/internal/yaml-runtime";
14
- import { stripVTControlCharacters } from "node:util";
15
- import node_process from "node:process";
16
- import { createRequire } from "node:module";
17
- import { pathToFileURL } from "node:url";
18
- import { serializeError } from "@midscene/shared/agent-tools/error-formatter";
19
- var __webpack_modules__ = {
20
- "../../node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js" (module, __unused_rspack_exports, __webpack_require__) {
21
- module = __webpack_require__.nmd(module);
22
- const wrapAnsi16 = (fn, offset)=>(...args)=>{
23
- const code = fn(...args);
24
- return `\u001B[${code + offset}m`;
25
- };
26
- const wrapAnsi256 = (fn, offset)=>(...args)=>{
27
- const code = fn(...args);
28
- return `\u001B[${38 + offset};5;${code}m`;
29
- };
30
- const wrapAnsi16m = (fn, offset)=>(...args)=>{
31
- const rgb = fn(...args);
32
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
33
- };
34
- const ansi2ansi = (n)=>n;
35
- const rgb2rgb = (r, g, b)=>[
36
- r,
37
- g,
38
- b
39
- ];
40
- const setLazyProperty = (object, property, get)=>{
41
- Object.defineProperty(object, property, {
42
- get: ()=>{
43
- const value = get();
44
- Object.defineProperty(object, property, {
45
- value,
46
- enumerable: true,
47
- configurable: true
48
- });
49
- return value;
50
- },
51
- enumerable: true,
52
- configurable: true
53
- });
54
- };
55
- let colorConvert;
56
- const makeDynamicStyles = (wrap, targetSpace, identity, isBackground)=>{
57
- if (void 0 === colorConvert) colorConvert = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js");
58
- const offset = isBackground ? 10 : 0;
59
- const styles = {};
60
- for (const [sourceSpace, suite] of Object.entries(colorConvert)){
61
- const name = 'ansi16' === sourceSpace ? 'ansi' : sourceSpace;
62
- if (sourceSpace === targetSpace) styles[name] = wrap(identity, offset);
63
- else if ('object' == typeof suite) styles[name] = wrap(suite[targetSpace], offset);
64
- }
65
- return styles;
66
- };
67
- function assembleStyles() {
68
- const codes = new Map();
69
- const styles = {
70
- modifier: {
71
- reset: [
72
- 0,
73
- 0
74
- ],
75
- bold: [
76
- 1,
77
- 22
78
- ],
79
- dim: [
80
- 2,
81
- 22
82
- ],
83
- italic: [
84
- 3,
85
- 23
86
- ],
87
- underline: [
88
- 4,
89
- 24
90
- ],
91
- inverse: [
92
- 7,
93
- 27
94
- ],
95
- hidden: [
96
- 8,
97
- 28
98
- ],
99
- strikethrough: [
100
- 9,
101
- 29
102
- ]
103
- },
104
- color: {
105
- black: [
106
- 30,
107
- 39
108
- ],
109
- red: [
110
- 31,
111
- 39
112
- ],
113
- green: [
114
- 32,
115
- 39
116
- ],
117
- yellow: [
118
- 33,
119
- 39
120
- ],
121
- blue: [
122
- 34,
123
- 39
124
- ],
125
- magenta: [
126
- 35,
127
- 39
128
- ],
129
- cyan: [
130
- 36,
131
- 39
132
- ],
133
- white: [
134
- 37,
135
- 39
136
- ],
137
- blackBright: [
138
- 90,
139
- 39
140
- ],
141
- redBright: [
142
- 91,
143
- 39
144
- ],
145
- greenBright: [
146
- 92,
147
- 39
148
- ],
149
- yellowBright: [
150
- 93,
151
- 39
152
- ],
153
- blueBright: [
154
- 94,
155
- 39
156
- ],
157
- magentaBright: [
158
- 95,
159
- 39
160
- ],
161
- cyanBright: [
162
- 96,
163
- 39
164
- ],
165
- whiteBright: [
166
- 97,
167
- 39
168
- ]
169
- },
170
- bgColor: {
171
- bgBlack: [
172
- 40,
173
- 49
174
- ],
175
- bgRed: [
176
- 41,
177
- 49
178
- ],
179
- bgGreen: [
180
- 42,
181
- 49
182
- ],
183
- bgYellow: [
184
- 43,
185
- 49
186
- ],
187
- bgBlue: [
188
- 44,
189
- 49
190
- ],
191
- bgMagenta: [
192
- 45,
193
- 49
194
- ],
195
- bgCyan: [
196
- 46,
197
- 49
198
- ],
199
- bgWhite: [
200
- 47,
201
- 49
202
- ],
203
- bgBlackBright: [
204
- 100,
205
- 49
206
- ],
207
- bgRedBright: [
208
- 101,
209
- 49
210
- ],
211
- bgGreenBright: [
212
- 102,
213
- 49
214
- ],
215
- bgYellowBright: [
216
- 103,
217
- 49
218
- ],
219
- bgBlueBright: [
220
- 104,
221
- 49
222
- ],
223
- bgMagentaBright: [
224
- 105,
225
- 49
226
- ],
227
- bgCyanBright: [
228
- 106,
229
- 49
230
- ],
231
- bgWhiteBright: [
232
- 107,
233
- 49
234
- ]
235
- }
236
- };
237
- styles.color.gray = styles.color.blackBright;
238
- styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
239
- styles.color.grey = styles.color.blackBright;
240
- styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
241
- for (const [groupName, group] of Object.entries(styles)){
242
- for (const [styleName, style] of Object.entries(group)){
243
- styles[styleName] = {
244
- open: `\u001B[${style[0]}m`,
245
- close: `\u001B[${style[1]}m`
246
- };
247
- group[styleName] = styles[styleName];
248
- codes.set(style[0], style[1]);
249
- }
250
- Object.defineProperty(styles, groupName, {
251
- value: group,
252
- enumerable: false
253
- });
254
- }
255
- Object.defineProperty(styles, 'codes', {
256
- value: codes,
257
- enumerable: false
258
- });
259
- styles.color.close = '\u001B[39m';
260
- styles.bgColor.close = '\u001B[49m';
261
- setLazyProperty(styles.color, 'ansi', ()=>makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
262
- setLazyProperty(styles.color, 'ansi256', ()=>makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
263
- setLazyProperty(styles.color, 'ansi16m', ()=>makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
264
- setLazyProperty(styles.bgColor, 'ansi', ()=>makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
265
- setLazyProperty(styles.bgColor, 'ansi256', ()=>makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
266
- setLazyProperty(styles.bgColor, 'ansi16m', ()=>makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
267
- return styles;
268
- }
269
- Object.defineProperty(module, 'exports', {
270
- enumerable: true,
271
- get: assembleStyles
272
- });
273
- },
274
- "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js" (module, __unused_rspack_exports, __webpack_require__) {
275
- const ansiStyles = __webpack_require__("../../node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js");
276
- const { stdout: stdoutColor, stderr: stderrColor } = __webpack_require__("../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js");
277
- const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/util.js");
278
- const { isArray } = Array;
279
- const levelMapping = [
280
- 'ansi',
281
- 'ansi',
282
- 'ansi256',
283
- 'ansi16m'
284
- ];
285
- const styles = Object.create(null);
286
- const applyOptions = (object, options = {})=>{
287
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) throw new Error('The `level` option should be an integer from 0 to 3');
288
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
289
- object.level = void 0 === options.level ? colorLevel : options.level;
290
- };
291
- class ChalkClass {
292
- constructor(options){
293
- return chalkFactory(options);
294
- }
295
- }
296
- const chalkFactory = (options)=>{
297
- const chalk = {};
298
- applyOptions(chalk, options);
299
- chalk.template = (...arguments_)=>chalkTag(chalk.template, ...arguments_);
300
- Object.setPrototypeOf(chalk, Chalk.prototype);
301
- Object.setPrototypeOf(chalk.template, chalk);
302
- chalk.template.constructor = ()=>{
303
- throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
304
- };
305
- chalk.template.Instance = ChalkClass;
306
- return chalk.template;
307
- };
308
- function Chalk(options) {
309
- return chalkFactory(options);
310
- }
311
- for (const [styleName, style] of Object.entries(ansiStyles))styles[styleName] = {
312
- get () {
313
- const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
314
- Object.defineProperty(this, styleName, {
315
- value: builder
316
- });
317
- return builder;
318
- }
319
- };
320
- styles.visible = {
321
- get () {
322
- const builder = createBuilder(this, this._styler, true);
323
- Object.defineProperty(this, 'visible', {
324
- value: builder
325
- });
326
- return builder;
327
- }
328
- };
329
- const usedModels = [
330
- 'rgb',
331
- 'hex',
332
- 'keyword',
333
- 'hsl',
334
- 'hsv',
335
- 'hwb',
336
- 'ansi',
337
- 'ansi256'
338
- ];
339
- for (const model of usedModels)styles[model] = {
340
- get () {
341
- const { level } = this;
342
- return function(...arguments_) {
343
- const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
344
- return createBuilder(this, styler, this._isEmpty);
345
- };
346
- }
347
- };
348
- for (const model of usedModels){
349
- const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
350
- styles[bgModel] = {
351
- get () {
352
- const { level } = this;
353
- return function(...arguments_) {
354
- const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
355
- return createBuilder(this, styler, this._isEmpty);
356
- };
357
- }
358
- };
359
- }
360
- const proto = Object.defineProperties(()=>{}, {
361
- ...styles,
362
- level: {
363
- enumerable: true,
364
- get () {
365
- return this._generator.level;
366
- },
367
- set (level) {
368
- this._generator.level = level;
369
- }
370
- }
371
- });
372
- const createStyler = (open, close, parent)=>{
373
- let openAll;
374
- let closeAll;
375
- if (void 0 === parent) {
376
- openAll = open;
377
- closeAll = close;
378
- } else {
379
- openAll = parent.openAll + open;
380
- closeAll = close + parent.closeAll;
381
- }
382
- return {
383
- open,
384
- close,
385
- openAll,
386
- closeAll,
387
- parent
388
- };
389
- };
390
- const createBuilder = (self, _styler, _isEmpty)=>{
391
- const builder = (...arguments_)=>{
392
- if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) return applyStyle(builder, chalkTag(builder, ...arguments_));
393
- return applyStyle(builder, 1 === arguments_.length ? '' + arguments_[0] : arguments_.join(' '));
394
- };
395
- Object.setPrototypeOf(builder, proto);
396
- builder._generator = self;
397
- builder._styler = _styler;
398
- builder._isEmpty = _isEmpty;
399
- return builder;
400
- };
401
- const applyStyle = (self, string)=>{
402
- if (self.level <= 0 || !string) return self._isEmpty ? '' : string;
403
- let styler = self._styler;
404
- if (void 0 === styler) return string;
405
- const { openAll, closeAll } = styler;
406
- if (-1 !== string.indexOf('\u001B')) while(void 0 !== styler){
407
- string = stringReplaceAll(string, styler.close, styler.open);
408
- styler = styler.parent;
409
- }
410
- const lfIndex = string.indexOf('\n');
411
- if (-1 !== lfIndex) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
412
- return openAll + string + closeAll;
413
- };
414
- let template;
415
- const chalkTag = (chalk, ...strings)=>{
416
- const [firstString] = strings;
417
- if (!isArray(firstString) || !isArray(firstString.raw)) return strings.join(' ');
418
- const arguments_ = strings.slice(1);
419
- const parts = [
420
- firstString.raw[0]
421
- ];
422
- for(let i = 1; i < firstString.length; i++)parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
423
- if (void 0 === template) template = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/templates.js");
424
- return template(chalk, parts.join(''));
425
- };
426
- Object.defineProperties(Chalk.prototype, styles);
427
- const chalk = Chalk();
428
- chalk.supportsColor = stdoutColor;
429
- chalk.stderr = Chalk({
430
- level: stderrColor ? stderrColor.level : 0
431
- });
432
- chalk.stderr.supportsColor = stderrColor;
433
- module.exports = chalk;
434
- },
435
- "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/templates.js" (module) {
436
- const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
437
- const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
438
- const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
439
- const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
440
- const ESCAPES = new Map([
441
- [
442
- 'n',
443
- '\n'
444
- ],
445
- [
446
- 'r',
447
- '\r'
448
- ],
449
- [
450
- 't',
451
- '\t'
452
- ],
453
- [
454
- 'b',
455
- '\b'
456
- ],
457
- [
458
- 'f',
459
- '\f'
460
- ],
461
- [
462
- 'v',
463
- '\v'
464
- ],
465
- [
466
- '0',
467
- '\0'
468
- ],
469
- [
470
- '\\',
471
- '\\'
472
- ],
473
- [
474
- 'e',
475
- '\u001B'
476
- ],
477
- [
478
- 'a',
479
- '\u0007'
480
- ]
481
- ]);
482
- function unescape(c) {
483
- const u = 'u' === c[0];
484
- const bracket = '{' === c[1];
485
- if (u && !bracket && 5 === c.length || 'x' === c[0] && 3 === c.length) return String.fromCharCode(parseInt(c.slice(1), 16));
486
- if (u && bracket) return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
487
- return ESCAPES.get(c) || c;
488
- }
489
- function parseArguments(name, arguments_) {
490
- const results = [];
491
- const chunks = arguments_.trim().split(/\s*,\s*/g);
492
- let matches;
493
- for (const chunk of chunks){
494
- const number = Number(chunk);
495
- if (Number.isNaN(number)) if (matches = chunk.match(STRING_REGEX)) results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character)=>escape ? unescape(escape) : character));
496
- else throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
497
- else results.push(number);
498
- }
499
- return results;
500
- }
501
- function parseStyle(style) {
502
- STYLE_REGEX.lastIndex = 0;
503
- const results = [];
504
- let matches;
505
- while(null !== (matches = STYLE_REGEX.exec(style))){
506
- const name = matches[1];
507
- if (matches[2]) {
508
- const args = parseArguments(name, matches[2]);
509
- results.push([
510
- name
511
- ].concat(args));
512
- } else results.push([
513
- name
514
- ]);
515
- }
516
- return results;
517
- }
518
- function buildStyle(chalk, styles) {
519
- const enabled = {};
520
- for (const layer of styles)for (const style of layer.styles)enabled[style[0]] = layer.inverse ? null : style.slice(1);
521
- let current = chalk;
522
- for (const [styleName, styles] of Object.entries(enabled))if (Array.isArray(styles)) {
523
- if (!(styleName in current)) throw new Error(`Unknown Chalk style: ${styleName}`);
524
- current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
525
- }
526
- return current;
527
- }
528
- module.exports = (chalk, temporary)=>{
529
- const styles = [];
530
- const chunks = [];
531
- let chunk = [];
532
- temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character)=>{
533
- if (escapeCharacter) chunk.push(unescape(escapeCharacter));
534
- else if (style) {
535
- const string = chunk.join('');
536
- chunk = [];
537
- chunks.push(0 === styles.length ? string : buildStyle(chalk, styles)(string));
538
- styles.push({
539
- inverse,
540
- styles: parseStyle(style)
541
- });
542
- } else if (close) {
543
- if (0 === styles.length) throw new Error('Found extraneous } in Chalk template literal');
544
- chunks.push(buildStyle(chalk, styles)(chunk.join('')));
545
- chunk = [];
546
- styles.pop();
547
- } else chunk.push(character);
548
- });
549
- chunks.push(chunk.join(''));
550
- if (styles.length > 0) {
551
- const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${1 === styles.length ? '' : 's'} (\`}\`)`;
552
- throw new Error(errMessage);
553
- }
554
- return chunks.join('');
555
- };
556
- },
557
- "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/util.js" (module) {
558
- const stringReplaceAll = (string, substring, replacer)=>{
559
- let index = string.indexOf(substring);
560
- if (-1 === index) return string;
561
- const substringLength = substring.length;
562
- let endIndex = 0;
563
- let returnValue = '';
564
- do {
565
- returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
566
- endIndex = index + substringLength;
567
- index = string.indexOf(substring, endIndex);
568
- }while (-1 !== index);
569
- returnValue += string.substr(endIndex);
570
- return returnValue;
571
- };
572
- const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index)=>{
573
- let endIndex = 0;
574
- let returnValue = '';
575
- do {
576
- const gotCR = '\r' === string[index - 1];
577
- returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
578
- endIndex = index + 1;
579
- index = string.indexOf('\n', endIndex);
580
- }while (-1 !== index);
581
- returnValue += string.substr(endIndex);
582
- return returnValue;
583
- };
584
- module.exports = {
585
- stringReplaceAll,
586
- stringEncaseCRLFWithFirstIndex
587
- };
588
- },
589
- "../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js" (module, __unused_rspack_exports, __webpack_require__) {
590
- const cssKeywords = __webpack_require__("../../node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js");
591
- const reverseKeywords = {};
592
- for (const key of Object.keys(cssKeywords))reverseKeywords[cssKeywords[key]] = key;
593
- const convert = {
594
- rgb: {
595
- channels: 3,
596
- labels: 'rgb'
597
- },
598
- hsl: {
599
- channels: 3,
600
- labels: 'hsl'
601
- },
602
- hsv: {
603
- channels: 3,
604
- labels: 'hsv'
605
- },
606
- hwb: {
607
- channels: 3,
608
- labels: 'hwb'
609
- },
610
- cmyk: {
611
- channels: 4,
612
- labels: 'cmyk'
613
- },
614
- xyz: {
615
- channels: 3,
616
- labels: 'xyz'
617
- },
618
- lab: {
619
- channels: 3,
620
- labels: 'lab'
621
- },
622
- lch: {
623
- channels: 3,
624
- labels: 'lch'
625
- },
626
- hex: {
627
- channels: 1,
628
- labels: [
629
- 'hex'
630
- ]
631
- },
632
- keyword: {
633
- channels: 1,
634
- labels: [
635
- 'keyword'
636
- ]
637
- },
638
- ansi16: {
639
- channels: 1,
640
- labels: [
641
- 'ansi16'
642
- ]
643
- },
644
- ansi256: {
645
- channels: 1,
646
- labels: [
647
- 'ansi256'
648
- ]
649
- },
650
- hcg: {
651
- channels: 3,
652
- labels: [
653
- 'h',
654
- 'c',
655
- 'g'
656
- ]
657
- },
658
- apple: {
659
- channels: 3,
660
- labels: [
661
- 'r16',
662
- 'g16',
663
- 'b16'
664
- ]
665
- },
666
- gray: {
667
- channels: 1,
668
- labels: [
669
- 'gray'
670
- ]
671
- }
672
- };
673
- module.exports = convert;
674
- for (const model of Object.keys(convert)){
675
- if (!('channels' in convert[model])) throw new Error('missing channels property: ' + model);
676
- if (!('labels' in convert[model])) throw new Error('missing channel labels property: ' + model);
677
- if (convert[model].labels.length !== convert[model].channels) throw new Error('channel and label counts mismatch: ' + model);
678
- const { channels, labels } = convert[model];
679
- delete convert[model].channels;
680
- delete convert[model].labels;
681
- Object.defineProperty(convert[model], 'channels', {
682
- value: channels
683
- });
684
- Object.defineProperty(convert[model], 'labels', {
685
- value: labels
686
- });
687
- }
688
- convert.rgb.hsl = function(rgb) {
689
- const r = rgb[0] / 255;
690
- const g = rgb[1] / 255;
691
- const b = rgb[2] / 255;
692
- const min = Math.min(r, g, b);
693
- const max = Math.max(r, g, b);
694
- const delta = max - min;
695
- let h;
696
- let s;
697
- if (max === min) h = 0;
698
- else if (r === max) h = (g - b) / delta;
699
- else if (g === max) h = 2 + (b - r) / delta;
700
- else if (b === max) h = 4 + (r - g) / delta;
701
- h = Math.min(60 * h, 360);
702
- if (h < 0) h += 360;
703
- const l = (min + max) / 2;
704
- s = max === min ? 0 : l <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
705
- return [
706
- h,
707
- 100 * s,
708
- 100 * l
709
- ];
710
- };
711
- convert.rgb.hsv = function(rgb) {
712
- let rdif;
713
- let gdif;
714
- let bdif;
715
- let h;
716
- let s;
717
- const r = rgb[0] / 255;
718
- const g = rgb[1] / 255;
719
- const b = rgb[2] / 255;
720
- const v = Math.max(r, g, b);
721
- const diff = v - Math.min(r, g, b);
722
- const diffc = function(c) {
723
- return (v - c) / 6 / diff + 0.5;
724
- };
725
- if (0 === diff) {
726
- h = 0;
727
- s = 0;
728
- } else {
729
- s = diff / v;
730
- rdif = diffc(r);
731
- gdif = diffc(g);
732
- bdif = diffc(b);
733
- if (r === v) h = bdif - gdif;
734
- else if (g === v) h = 1 / 3 + rdif - bdif;
735
- else if (b === v) h = 2 / 3 + gdif - rdif;
736
- if (h < 0) h += 1;
737
- else if (h > 1) h -= 1;
738
- }
739
- return [
740
- 360 * h,
741
- 100 * s,
742
- 100 * v
743
- ];
744
- };
745
- convert.rgb.hwb = function(rgb) {
746
- const r = rgb[0];
747
- const g = rgb[1];
748
- let b = rgb[2];
749
- const h = convert.rgb.hsl(rgb)[0];
750
- const w = 1 / 255 * Math.min(r, Math.min(g, b));
751
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
752
- return [
753
- h,
754
- 100 * w,
755
- 100 * b
756
- ];
757
- };
758
- convert.rgb.cmyk = function(rgb) {
759
- const r = rgb[0] / 255;
760
- const g = rgb[1] / 255;
761
- const b = rgb[2] / 255;
762
- const k = Math.min(1 - r, 1 - g, 1 - b);
763
- const c = (1 - r - k) / (1 - k) || 0;
764
- const m = (1 - g - k) / (1 - k) || 0;
765
- const y = (1 - b - k) / (1 - k) || 0;
766
- return [
767
- 100 * c,
768
- 100 * m,
769
- 100 * y,
770
- 100 * k
771
- ];
772
- };
773
- function comparativeDistance(x, y) {
774
- return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
775
- }
776
- convert.rgb.keyword = function(rgb) {
777
- const reversed = reverseKeywords[rgb];
778
- if (reversed) return reversed;
779
- let currentClosestDistance = 1 / 0;
780
- let currentClosestKeyword;
781
- for (const keyword of Object.keys(cssKeywords)){
782
- const value = cssKeywords[keyword];
783
- const distance = comparativeDistance(rgb, value);
784
- if (distance < currentClosestDistance) {
785
- currentClosestDistance = distance;
786
- currentClosestKeyword = keyword;
787
- }
788
- }
789
- return currentClosestKeyword;
790
- };
791
- convert.keyword.rgb = function(keyword) {
792
- return cssKeywords[keyword];
793
- };
794
- convert.rgb.xyz = function(rgb) {
795
- let r = rgb[0] / 255;
796
- let g = rgb[1] / 255;
797
- let b = rgb[2] / 255;
798
- r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
799
- g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
800
- b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
801
- const x = 0.4124 * r + 0.3576 * g + 0.1805 * b;
802
- const y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
803
- const z = 0.0193 * r + 0.1192 * g + 0.9505 * b;
804
- return [
805
- 100 * x,
806
- 100 * y,
807
- 100 * z
808
- ];
809
- };
810
- convert.rgb.lab = function(rgb) {
811
- const xyz = convert.rgb.xyz(rgb);
812
- let x = xyz[0];
813
- let y = xyz[1];
814
- let z = xyz[2];
815
- x /= 95.047;
816
- y /= 100;
817
- z /= 108.883;
818
- x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
819
- y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
820
- z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
821
- const l = 116 * y - 16;
822
- const a = 500 * (x - y);
823
- const b = 200 * (y - z);
824
- return [
825
- l,
826
- a,
827
- b
828
- ];
829
- };
830
- convert.hsl.rgb = function(hsl) {
831
- const h = hsl[0] / 360;
832
- const s = hsl[1] / 100;
833
- const l = hsl[2] / 100;
834
- let t2;
835
- let t3;
836
- let val;
837
- if (0 === s) {
838
- val = 255 * l;
839
- return [
840
- val,
841
- val,
842
- val
843
- ];
844
- }
845
- t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
846
- const t1 = 2 * l - t2;
847
- const rgb = [
848
- 0,
849
- 0,
850
- 0
851
- ];
852
- for(let i = 0; i < 3; i++){
853
- t3 = h + 1 / 3 * -(i - 1);
854
- if (t3 < 0) t3++;
855
- if (t3 > 1) t3--;
856
- val = 6 * t3 < 1 ? t1 + (t2 - t1) * 6 * t3 : 2 * t3 < 1 ? t2 : 3 * t3 < 2 ? t1 + (t2 - t1) * (2 / 3 - t3) * 6 : t1;
857
- rgb[i] = 255 * val;
858
- }
859
- return rgb;
860
- };
861
- convert.hsl.hsv = function(hsl) {
862
- const h = hsl[0];
863
- let s = hsl[1] / 100;
864
- let l = hsl[2] / 100;
865
- let smin = s;
866
- const lmin = Math.max(l, 0.01);
867
- l *= 2;
868
- s *= l <= 1 ? l : 2 - l;
869
- smin *= lmin <= 1 ? lmin : 2 - lmin;
870
- const v = (l + s) / 2;
871
- const sv = 0 === l ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
872
- return [
873
- h,
874
- 100 * sv,
875
- 100 * v
876
- ];
877
- };
878
- convert.hsv.rgb = function(hsv) {
879
- const h = hsv[0] / 60;
880
- const s = hsv[1] / 100;
881
- let v = hsv[2] / 100;
882
- const hi = Math.floor(h) % 6;
883
- const f = h - Math.floor(h);
884
- const p = 255 * v * (1 - s);
885
- const q = 255 * v * (1 - s * f);
886
- const t = 255 * v * (1 - s * (1 - f));
887
- v *= 255;
888
- switch(hi){
889
- case 0:
890
- return [
891
- v,
892
- t,
893
- p
894
- ];
895
- case 1:
896
- return [
897
- q,
898
- v,
899
- p
900
- ];
901
- case 2:
902
- return [
903
- p,
904
- v,
905
- t
906
- ];
907
- case 3:
908
- return [
909
- p,
910
- q,
911
- v
912
- ];
913
- case 4:
914
- return [
915
- t,
916
- p,
917
- v
918
- ];
919
- case 5:
920
- return [
921
- v,
922
- p,
923
- q
924
- ];
925
- }
926
- };
927
- convert.hsv.hsl = function(hsv) {
928
- const h = hsv[0];
929
- const s = hsv[1] / 100;
930
- const v = hsv[2] / 100;
931
- const vmin = Math.max(v, 0.01);
932
- let sl;
933
- let l;
934
- l = (2 - s) * v;
935
- const lmin = (2 - s) * vmin;
936
- sl = s * vmin;
937
- sl /= lmin <= 1 ? lmin : 2 - lmin;
938
- sl = sl || 0;
939
- l /= 2;
940
- return [
941
- h,
942
- 100 * sl,
943
- 100 * l
944
- ];
945
- };
946
- convert.hwb.rgb = function(hwb) {
947
- const h = hwb[0] / 360;
948
- let wh = hwb[1] / 100;
949
- let bl = hwb[2] / 100;
950
- const ratio = wh + bl;
951
- let f;
952
- if (ratio > 1) {
953
- wh /= ratio;
954
- bl /= ratio;
955
- }
956
- const i = Math.floor(6 * h);
957
- const v = 1 - bl;
958
- f = 6 * h - i;
959
- if ((0x01 & i) !== 0) f = 1 - f;
960
- const n = wh + f * (v - wh);
961
- let r;
962
- let g;
963
- let b;
964
- switch(i){
965
- default:
966
- case 6:
967
- case 0:
968
- r = v;
969
- g = n;
970
- b = wh;
971
- break;
972
- case 1:
973
- r = n;
974
- g = v;
975
- b = wh;
976
- break;
977
- case 2:
978
- r = wh;
979
- g = v;
980
- b = n;
981
- break;
982
- case 3:
983
- r = wh;
984
- g = n;
985
- b = v;
986
- break;
987
- case 4:
988
- r = n;
989
- g = wh;
990
- b = v;
991
- break;
992
- case 5:
993
- r = v;
994
- g = wh;
995
- b = n;
996
- break;
997
- }
998
- return [
999
- 255 * r,
1000
- 255 * g,
1001
- 255 * b
1002
- ];
1003
- };
1004
- convert.cmyk.rgb = function(cmyk) {
1005
- const c = cmyk[0] / 100;
1006
- const m = cmyk[1] / 100;
1007
- const y = cmyk[2] / 100;
1008
- const k = cmyk[3] / 100;
1009
- const r = 1 - Math.min(1, c * (1 - k) + k);
1010
- const g = 1 - Math.min(1, m * (1 - k) + k);
1011
- const b = 1 - Math.min(1, y * (1 - k) + k);
1012
- return [
1013
- 255 * r,
1014
- 255 * g,
1015
- 255 * b
1016
- ];
1017
- };
1018
- convert.xyz.rgb = function(xyz) {
1019
- const x = xyz[0] / 100;
1020
- const y = xyz[1] / 100;
1021
- const z = xyz[2] / 100;
1022
- let r;
1023
- let g;
1024
- let b;
1025
- r = 3.2406 * x + -1.5372 * y + -0.4986 * z;
1026
- g = -0.9689 * x + 1.8758 * y + 0.0415 * z;
1027
- b = 0.0557 * x + -0.204 * y + 1.0570 * z;
1028
- r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : 12.92 * r;
1029
- g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : 12.92 * g;
1030
- b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : 12.92 * b;
1031
- r = Math.min(Math.max(0, r), 1);
1032
- g = Math.min(Math.max(0, g), 1);
1033
- b = Math.min(Math.max(0, b), 1);
1034
- return [
1035
- 255 * r,
1036
- 255 * g,
1037
- 255 * b
1038
- ];
1039
- };
1040
- convert.xyz.lab = function(xyz) {
1041
- let x = xyz[0];
1042
- let y = xyz[1];
1043
- let z = xyz[2];
1044
- x /= 95.047;
1045
- y /= 100;
1046
- z /= 108.883;
1047
- x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
1048
- y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
1049
- z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
1050
- const l = 116 * y - 16;
1051
- const a = 500 * (x - y);
1052
- const b = 200 * (y - z);
1053
- return [
1054
- l,
1055
- a,
1056
- b
1057
- ];
1058
- };
1059
- convert.lab.xyz = function(lab) {
1060
- const l = lab[0];
1061
- const a = lab[1];
1062
- const b = lab[2];
1063
- let x;
1064
- let y;
1065
- let z;
1066
- y = (l + 16) / 116;
1067
- x = a / 500 + y;
1068
- z = y - b / 200;
1069
- const y2 = y ** 3;
1070
- const x2 = x ** 3;
1071
- const z2 = z ** 3;
1072
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
1073
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
1074
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
1075
- x *= 95.047;
1076
- y *= 100;
1077
- z *= 108.883;
1078
- return [
1079
- x,
1080
- y,
1081
- z
1082
- ];
1083
- };
1084
- convert.lab.lch = function(lab) {
1085
- const l = lab[0];
1086
- const a = lab[1];
1087
- const b = lab[2];
1088
- let h;
1089
- const hr = Math.atan2(b, a);
1090
- h = 360 * hr / 2 / Math.PI;
1091
- if (h < 0) h += 360;
1092
- const c = Math.sqrt(a * a + b * b);
1093
- return [
1094
- l,
1095
- c,
1096
- h
1097
- ];
1098
- };
1099
- convert.lch.lab = function(lch) {
1100
- const l = lch[0];
1101
- const c = lch[1];
1102
- const h = lch[2];
1103
- const hr = h / 360 * 2 * Math.PI;
1104
- const a = c * Math.cos(hr);
1105
- const b = c * Math.sin(hr);
1106
- return [
1107
- l,
1108
- a,
1109
- b
1110
- ];
1111
- };
1112
- convert.rgb.ansi16 = function(args, saturation = null) {
1113
- const [r, g, b] = args;
1114
- let value = null === saturation ? convert.rgb.hsv(args)[2] : saturation;
1115
- value = Math.round(value / 50);
1116
- if (0 === value) return 30;
1117
- let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
1118
- if (2 === value) ansi += 60;
1119
- return ansi;
1120
- };
1121
- convert.hsv.ansi16 = function(args) {
1122
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
1123
- };
1124
- convert.rgb.ansi256 = function(args) {
1125
- const r = args[0];
1126
- const g = args[1];
1127
- const b = args[2];
1128
- if (r === g && g === b) {
1129
- if (r < 8) return 16;
1130
- if (r > 248) return 231;
1131
- return Math.round((r - 8) / 247 * 24) + 232;
1132
- }
1133
- const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
1134
- return ansi;
1135
- };
1136
- convert.ansi16.rgb = function(args) {
1137
- let color = args % 10;
1138
- if (0 === color || 7 === color) {
1139
- if (args > 50) color += 3.5;
1140
- color = color / 10.5 * 255;
1141
- return [
1142
- color,
1143
- color,
1144
- color
1145
- ];
1146
- }
1147
- const mult = (~~(args > 50) + 1) * 0.5;
1148
- const r = (1 & color) * mult * 255;
1149
- const g = (color >> 1 & 1) * mult * 255;
1150
- const b = (color >> 2 & 1) * mult * 255;
1151
- return [
1152
- r,
1153
- g,
1154
- b
1155
- ];
1156
- };
1157
- convert.ansi256.rgb = function(args) {
1158
- if (args >= 232) {
1159
- const c = (args - 232) * 10 + 8;
1160
- return [
1161
- c,
1162
- c,
1163
- c
1164
- ];
1165
- }
1166
- args -= 16;
1167
- let rem;
1168
- const r = Math.floor(args / 36) / 5 * 255;
1169
- const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
1170
- const b = rem % 6 / 5 * 255;
1171
- return [
1172
- r,
1173
- g,
1174
- b
1175
- ];
1176
- };
1177
- convert.rgb.hex = function(args) {
1178
- const integer = ((0xFF & Math.round(args[0])) << 16) + ((0xFF & Math.round(args[1])) << 8) + (0xFF & Math.round(args[2]));
1179
- const string = integer.toString(16).toUpperCase();
1180
- return '000000'.substring(string.length) + string;
1181
- };
1182
- convert.hex.rgb = function(args) {
1183
- const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
1184
- if (!match) return [
1185
- 0,
1186
- 0,
1187
- 0
1188
- ];
1189
- let colorString = match[0];
1190
- if (3 === match[0].length) colorString = colorString.split('').map((char)=>char + char).join('');
1191
- const integer = parseInt(colorString, 16);
1192
- const r = integer >> 16 & 0xFF;
1193
- const g = integer >> 8 & 0xFF;
1194
- const b = 0xFF & integer;
1195
- return [
1196
- r,
1197
- g,
1198
- b
1199
- ];
1200
- };
1201
- convert.rgb.hcg = function(rgb) {
1202
- const r = rgb[0] / 255;
1203
- const g = rgb[1] / 255;
1204
- const b = rgb[2] / 255;
1205
- const max = Math.max(Math.max(r, g), b);
1206
- const min = Math.min(Math.min(r, g), b);
1207
- const chroma = max - min;
1208
- let grayscale;
1209
- let hue;
1210
- grayscale = chroma < 1 ? min / (1 - chroma) : 0;
1211
- hue = chroma <= 0 ? 0 : max === r ? (g - b) / chroma % 6 : max === g ? 2 + (b - r) / chroma : 4 + (r - g) / chroma;
1212
- hue /= 6;
1213
- hue %= 1;
1214
- return [
1215
- 360 * hue,
1216
- 100 * chroma,
1217
- 100 * grayscale
1218
- ];
1219
- };
1220
- convert.hsl.hcg = function(hsl) {
1221
- const s = hsl[1] / 100;
1222
- const l = hsl[2] / 100;
1223
- const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
1224
- let f = 0;
1225
- if (c < 1.0) f = (l - 0.5 * c) / (1.0 - c);
1226
- return [
1227
- hsl[0],
1228
- 100 * c,
1229
- 100 * f
1230
- ];
1231
- };
1232
- convert.hsv.hcg = function(hsv) {
1233
- const s = hsv[1] / 100;
1234
- const v = hsv[2] / 100;
1235
- const c = s * v;
1236
- let f = 0;
1237
- if (c < 1.0) f = (v - c) / (1 - c);
1238
- return [
1239
- hsv[0],
1240
- 100 * c,
1241
- 100 * f
1242
- ];
1243
- };
1244
- convert.hcg.rgb = function(hcg) {
1245
- const h = hcg[0] / 360;
1246
- const c = hcg[1] / 100;
1247
- const g = hcg[2] / 100;
1248
- if (0.0 === c) return [
1249
- 255 * g,
1250
- 255 * g,
1251
- 255 * g
1252
- ];
1253
- const pure = [
1254
- 0,
1255
- 0,
1256
- 0
1257
- ];
1258
- const hi = h % 1 * 6;
1259
- const v = hi % 1;
1260
- const w = 1 - v;
1261
- let mg = 0;
1262
- switch(Math.floor(hi)){
1263
- case 0:
1264
- pure[0] = 1;
1265
- pure[1] = v;
1266
- pure[2] = 0;
1267
- break;
1268
- case 1:
1269
- pure[0] = w;
1270
- pure[1] = 1;
1271
- pure[2] = 0;
1272
- break;
1273
- case 2:
1274
- pure[0] = 0;
1275
- pure[1] = 1;
1276
- pure[2] = v;
1277
- break;
1278
- case 3:
1279
- pure[0] = 0;
1280
- pure[1] = w;
1281
- pure[2] = 1;
1282
- break;
1283
- case 4:
1284
- pure[0] = v;
1285
- pure[1] = 0;
1286
- pure[2] = 1;
1287
- break;
1288
- default:
1289
- pure[0] = 1;
1290
- pure[1] = 0;
1291
- pure[2] = w;
1292
- }
1293
- mg = (1.0 - c) * g;
1294
- return [
1295
- (c * pure[0] + mg) * 255,
1296
- (c * pure[1] + mg) * 255,
1297
- (c * pure[2] + mg) * 255
1298
- ];
1299
- };
1300
- convert.hcg.hsv = function(hcg) {
1301
- const c = hcg[1] / 100;
1302
- const g = hcg[2] / 100;
1303
- const v = c + g * (1.0 - c);
1304
- let f = 0;
1305
- if (v > 0.0) f = c / v;
1306
- return [
1307
- hcg[0],
1308
- 100 * f,
1309
- 100 * v
1310
- ];
1311
- };
1312
- convert.hcg.hsl = function(hcg) {
1313
- const c = hcg[1] / 100;
1314
- const g = hcg[2] / 100;
1315
- const l = g * (1.0 - c) + 0.5 * c;
1316
- let s = 0;
1317
- if (l > 0.0 && l < 0.5) s = c / (2 * l);
1318
- else if (l >= 0.5 && l < 1.0) s = c / (2 * (1 - l));
1319
- return [
1320
- hcg[0],
1321
- 100 * s,
1322
- 100 * l
1323
- ];
1324
- };
1325
- convert.hcg.hwb = function(hcg) {
1326
- const c = hcg[1] / 100;
1327
- const g = hcg[2] / 100;
1328
- const v = c + g * (1.0 - c);
1329
- return [
1330
- hcg[0],
1331
- (v - c) * 100,
1332
- (1 - v) * 100
1333
- ];
1334
- };
1335
- convert.hwb.hcg = function(hwb) {
1336
- const w = hwb[1] / 100;
1337
- const b = hwb[2] / 100;
1338
- const v = 1 - b;
1339
- const c = v - w;
1340
- let g = 0;
1341
- if (c < 1) g = (v - c) / (1 - c);
1342
- return [
1343
- hwb[0],
1344
- 100 * c,
1345
- 100 * g
1346
- ];
1347
- };
1348
- convert.apple.rgb = function(apple) {
1349
- return [
1350
- apple[0] / 65535 * 255,
1351
- apple[1] / 65535 * 255,
1352
- apple[2] / 65535 * 255
1353
- ];
1354
- };
1355
- convert.rgb.apple = function(rgb) {
1356
- return [
1357
- rgb[0] / 255 * 65535,
1358
- rgb[1] / 255 * 65535,
1359
- rgb[2] / 255 * 65535
1360
- ];
1361
- };
1362
- convert.gray.rgb = function(args) {
1363
- return [
1364
- args[0] / 100 * 255,
1365
- args[0] / 100 * 255,
1366
- args[0] / 100 * 255
1367
- ];
1368
- };
1369
- convert.gray.hsl = function(args) {
1370
- return [
1371
- 0,
1372
- 0,
1373
- args[0]
1374
- ];
1375
- };
1376
- convert.gray.hsv = convert.gray.hsl;
1377
- convert.gray.hwb = function(gray) {
1378
- return [
1379
- 0,
1380
- 100,
1381
- gray[0]
1382
- ];
1383
- };
1384
- convert.gray.cmyk = function(gray) {
1385
- return [
1386
- 0,
1387
- 0,
1388
- 0,
1389
- gray[0]
1390
- ];
1391
- };
1392
- convert.gray.lab = function(gray) {
1393
- return [
1394
- gray[0],
1395
- 0,
1396
- 0
1397
- ];
1398
- };
1399
- convert.gray.hex = function(gray) {
1400
- const val = 0xFF & Math.round(gray[0] / 100 * 255);
1401
- const integer = (val << 16) + (val << 8) + val;
1402
- const string = integer.toString(16).toUpperCase();
1403
- return '000000'.substring(string.length) + string;
1404
- };
1405
- convert.rgb.gray = function(rgb) {
1406
- const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1407
- return [
1408
- val / 255 * 100
1409
- ];
1410
- };
1411
- },
1412
- "../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js" (module, __unused_rspack_exports, __webpack_require__) {
1413
- const conversions = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js");
1414
- const route = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js");
1415
- const convert = {};
1416
- const models = Object.keys(conversions);
1417
- function wrapRaw(fn) {
1418
- const wrappedFn = function(...args) {
1419
- const arg0 = args[0];
1420
- if (null == arg0) return arg0;
1421
- if (arg0.length > 1) args = arg0;
1422
- return fn(args);
1423
- };
1424
- if ('conversion' in fn) wrappedFn.conversion = fn.conversion;
1425
- return wrappedFn;
1426
- }
1427
- function wrapRounded(fn) {
1428
- const wrappedFn = function(...args) {
1429
- const arg0 = args[0];
1430
- if (null == arg0) return arg0;
1431
- if (arg0.length > 1) args = arg0;
1432
- const result = fn(args);
1433
- if ('object' == typeof result) for(let len = result.length, i = 0; i < len; i++)result[i] = Math.round(result[i]);
1434
- return result;
1435
- };
1436
- if ('conversion' in fn) wrappedFn.conversion = fn.conversion;
1437
- return wrappedFn;
1438
- }
1439
- models.forEach((fromModel)=>{
1440
- convert[fromModel] = {};
1441
- Object.defineProperty(convert[fromModel], 'channels', {
1442
- value: conversions[fromModel].channels
1443
- });
1444
- Object.defineProperty(convert[fromModel], 'labels', {
1445
- value: conversions[fromModel].labels
1446
- });
1447
- const routes = route(fromModel);
1448
- const routeModels = Object.keys(routes);
1449
- routeModels.forEach((toModel)=>{
1450
- const fn = routes[toModel];
1451
- convert[fromModel][toModel] = wrapRounded(fn);
1452
- convert[fromModel][toModel].raw = wrapRaw(fn);
1453
- });
1454
- });
1455
- module.exports = convert;
1456
- },
1457
- "../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js" (module, __unused_rspack_exports, __webpack_require__) {
1458
- const conversions = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js");
1459
- function buildGraph() {
1460
- const graph = {};
1461
- const models = Object.keys(conversions);
1462
- for(let len = models.length, i = 0; i < len; i++)graph[models[i]] = {
1463
- distance: -1,
1464
- parent: null
1465
- };
1466
- return graph;
1467
- }
1468
- function deriveBFS(fromModel) {
1469
- const graph = buildGraph();
1470
- const queue = [
1471
- fromModel
1472
- ];
1473
- graph[fromModel].distance = 0;
1474
- while(queue.length){
1475
- const current = queue.pop();
1476
- const adjacents = Object.keys(conversions[current]);
1477
- for(let len = adjacents.length, i = 0; i < len; i++){
1478
- const adjacent = adjacents[i];
1479
- const node = graph[adjacent];
1480
- if (-1 === node.distance) {
1481
- node.distance = graph[current].distance + 1;
1482
- node.parent = current;
1483
- queue.unshift(adjacent);
1484
- }
1485
- }
1486
- }
1487
- return graph;
1488
- }
1489
- function link(from, to) {
1490
- return function(args) {
1491
- return to(from(args));
1492
- };
1493
- }
1494
- function wrapConversion(toModel, graph) {
1495
- const path = [
1496
- graph[toModel].parent,
1497
- toModel
1498
- ];
1499
- let fn = conversions[graph[toModel].parent][toModel];
1500
- let cur = graph[toModel].parent;
1501
- while(graph[cur].parent){
1502
- path.unshift(graph[cur].parent);
1503
- fn = link(conversions[graph[cur].parent][cur], fn);
1504
- cur = graph[cur].parent;
1505
- }
1506
- fn.conversion = path;
1507
- return fn;
1508
- }
1509
- module.exports = function(fromModel) {
1510
- const graph = deriveBFS(fromModel);
1511
- const conversion = {};
1512
- const models = Object.keys(graph);
1513
- for(let len = models.length, i = 0; i < len; i++){
1514
- const toModel = models[i];
1515
- const node = graph[toModel];
1516
- if (null !== node.parent) conversion[toModel] = wrapConversion(toModel, graph);
1517
- }
1518
- return conversion;
1519
- };
1520
- },
1521
- "../../node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js" (module) {
1522
- module.exports = {
1523
- aliceblue: [
1524
- 240,
1525
- 248,
1526
- 255
1527
- ],
1528
- antiquewhite: [
1529
- 250,
1530
- 235,
1531
- 215
1532
- ],
1533
- aqua: [
1534
- 0,
1535
- 255,
1536
- 255
1537
- ],
1538
- aquamarine: [
1539
- 127,
1540
- 255,
1541
- 212
1542
- ],
1543
- azure: [
1544
- 240,
1545
- 255,
1546
- 255
1547
- ],
1548
- beige: [
1549
- 245,
1550
- 245,
1551
- 220
1552
- ],
1553
- bisque: [
1554
- 255,
1555
- 228,
1556
- 196
1557
- ],
1558
- black: [
1559
- 0,
1560
- 0,
1561
- 0
1562
- ],
1563
- blanchedalmond: [
1564
- 255,
1565
- 235,
1566
- 205
1567
- ],
1568
- blue: [
1569
- 0,
1570
- 0,
1571
- 255
1572
- ],
1573
- blueviolet: [
1574
- 138,
1575
- 43,
1576
- 226
1577
- ],
1578
- brown: [
1579
- 165,
1580
- 42,
1581
- 42
1582
- ],
1583
- burlywood: [
1584
- 222,
1585
- 184,
1586
- 135
1587
- ],
1588
- cadetblue: [
1589
- 95,
1590
- 158,
1591
- 160
1592
- ],
1593
- chartreuse: [
1594
- 127,
1595
- 255,
1596
- 0
1597
- ],
1598
- chocolate: [
1599
- 210,
1600
- 105,
1601
- 30
1602
- ],
1603
- coral: [
1604
- 255,
1605
- 127,
1606
- 80
1607
- ],
1608
- cornflowerblue: [
1609
- 100,
1610
- 149,
1611
- 237
1612
- ],
1613
- cornsilk: [
1614
- 255,
1615
- 248,
1616
- 220
1617
- ],
1618
- crimson: [
1619
- 220,
1620
- 20,
1621
- 60
1622
- ],
1623
- cyan: [
1624
- 0,
1625
- 255,
1626
- 255
1627
- ],
1628
- darkblue: [
1629
- 0,
1630
- 0,
1631
- 139
1632
- ],
1633
- darkcyan: [
1634
- 0,
1635
- 139,
1636
- 139
1637
- ],
1638
- darkgoldenrod: [
1639
- 184,
1640
- 134,
1641
- 11
1642
- ],
1643
- darkgray: [
1644
- 169,
1645
- 169,
1646
- 169
1647
- ],
1648
- darkgreen: [
1649
- 0,
1650
- 100,
1651
- 0
1652
- ],
1653
- darkgrey: [
1654
- 169,
1655
- 169,
1656
- 169
1657
- ],
1658
- darkkhaki: [
1659
- 189,
1660
- 183,
1661
- 107
1662
- ],
1663
- darkmagenta: [
1664
- 139,
1665
- 0,
1666
- 139
1667
- ],
1668
- darkolivegreen: [
1669
- 85,
1670
- 107,
1671
- 47
1672
- ],
1673
- darkorange: [
1674
- 255,
1675
- 140,
1676
- 0
1677
- ],
1678
- darkorchid: [
1679
- 153,
1680
- 50,
1681
- 204
1682
- ],
1683
- darkred: [
1684
- 139,
1685
- 0,
1686
- 0
1687
- ],
1688
- darksalmon: [
1689
- 233,
1690
- 150,
1691
- 122
1692
- ],
1693
- darkseagreen: [
1694
- 143,
1695
- 188,
1696
- 143
1697
- ],
1698
- darkslateblue: [
1699
- 72,
1700
- 61,
1701
- 139
1702
- ],
1703
- darkslategray: [
1704
- 47,
1705
- 79,
1706
- 79
1707
- ],
1708
- darkslategrey: [
1709
- 47,
1710
- 79,
1711
- 79
1712
- ],
1713
- darkturquoise: [
1714
- 0,
1715
- 206,
1716
- 209
1717
- ],
1718
- darkviolet: [
1719
- 148,
1720
- 0,
1721
- 211
1722
- ],
1723
- deeppink: [
1724
- 255,
1725
- 20,
1726
- 147
1727
- ],
1728
- deepskyblue: [
1729
- 0,
1730
- 191,
1731
- 255
1732
- ],
1733
- dimgray: [
1734
- 105,
1735
- 105,
1736
- 105
1737
- ],
1738
- dimgrey: [
1739
- 105,
1740
- 105,
1741
- 105
1742
- ],
1743
- dodgerblue: [
1744
- 30,
1745
- 144,
1746
- 255
1747
- ],
1748
- firebrick: [
1749
- 178,
1750
- 34,
1751
- 34
1752
- ],
1753
- floralwhite: [
1754
- 255,
1755
- 250,
1756
- 240
1757
- ],
1758
- forestgreen: [
1759
- 34,
1760
- 139,
1761
- 34
1762
- ],
1763
- fuchsia: [
1764
- 255,
1765
- 0,
1766
- 255
1767
- ],
1768
- gainsboro: [
1769
- 220,
1770
- 220,
1771
- 220
1772
- ],
1773
- ghostwhite: [
1774
- 248,
1775
- 248,
1776
- 255
1777
- ],
1778
- gold: [
1779
- 255,
1780
- 215,
1781
- 0
1782
- ],
1783
- goldenrod: [
1784
- 218,
1785
- 165,
1786
- 32
1787
- ],
1788
- gray: [
1789
- 128,
1790
- 128,
1791
- 128
1792
- ],
1793
- green: [
1794
- 0,
1795
- 128,
1796
- 0
1797
- ],
1798
- greenyellow: [
1799
- 173,
1800
- 255,
1801
- 47
1802
- ],
1803
- grey: [
1804
- 128,
1805
- 128,
1806
- 128
1807
- ],
1808
- honeydew: [
1809
- 240,
1810
- 255,
1811
- 240
1812
- ],
1813
- hotpink: [
1814
- 255,
1815
- 105,
1816
- 180
1817
- ],
1818
- indianred: [
1819
- 205,
1820
- 92,
1821
- 92
1822
- ],
1823
- indigo: [
1824
- 75,
1825
- 0,
1826
- 130
1827
- ],
1828
- ivory: [
1829
- 255,
1830
- 255,
1831
- 240
1832
- ],
1833
- khaki: [
1834
- 240,
1835
- 230,
1836
- 140
1837
- ],
1838
- lavender: [
1839
- 230,
1840
- 230,
1841
- 250
1842
- ],
1843
- lavenderblush: [
1844
- 255,
1845
- 240,
1846
- 245
1847
- ],
1848
- lawngreen: [
1849
- 124,
1850
- 252,
1851
- 0
1852
- ],
1853
- lemonchiffon: [
1854
- 255,
1855
- 250,
1856
- 205
1857
- ],
1858
- lightblue: [
1859
- 173,
1860
- 216,
1861
- 230
1862
- ],
1863
- lightcoral: [
1864
- 240,
1865
- 128,
1866
- 128
1867
- ],
1868
- lightcyan: [
1869
- 224,
1870
- 255,
1871
- 255
1872
- ],
1873
- lightgoldenrodyellow: [
1874
- 250,
1875
- 250,
1876
- 210
1877
- ],
1878
- lightgray: [
1879
- 211,
1880
- 211,
1881
- 211
1882
- ],
1883
- lightgreen: [
1884
- 144,
1885
- 238,
1886
- 144
1887
- ],
1888
- lightgrey: [
1889
- 211,
1890
- 211,
1891
- 211
1892
- ],
1893
- lightpink: [
1894
- 255,
1895
- 182,
1896
- 193
1897
- ],
1898
- lightsalmon: [
1899
- 255,
1900
- 160,
1901
- 122
1902
- ],
1903
- lightseagreen: [
1904
- 32,
1905
- 178,
1906
- 170
1907
- ],
1908
- lightskyblue: [
1909
- 135,
1910
- 206,
1911
- 250
1912
- ],
1913
- lightslategray: [
1914
- 119,
1915
- 136,
1916
- 153
1917
- ],
1918
- lightslategrey: [
1919
- 119,
1920
- 136,
1921
- 153
1922
- ],
1923
- lightsteelblue: [
1924
- 176,
1925
- 196,
1926
- 222
1927
- ],
1928
- lightyellow: [
1929
- 255,
1930
- 255,
1931
- 224
1932
- ],
1933
- lime: [
1934
- 0,
1935
- 255,
1936
- 0
1937
- ],
1938
- limegreen: [
1939
- 50,
1940
- 205,
1941
- 50
1942
- ],
1943
- linen: [
1944
- 250,
1945
- 240,
1946
- 230
1947
- ],
1948
- magenta: [
1949
- 255,
1950
- 0,
1951
- 255
1952
- ],
1953
- maroon: [
1954
- 128,
1955
- 0,
1956
- 0
1957
- ],
1958
- mediumaquamarine: [
1959
- 102,
1960
- 205,
1961
- 170
1962
- ],
1963
- mediumblue: [
1964
- 0,
1965
- 0,
1966
- 205
1967
- ],
1968
- mediumorchid: [
1969
- 186,
1970
- 85,
1971
- 211
1972
- ],
1973
- mediumpurple: [
1974
- 147,
1975
- 112,
1976
- 219
1977
- ],
1978
- mediumseagreen: [
1979
- 60,
1980
- 179,
1981
- 113
1982
- ],
1983
- mediumslateblue: [
1984
- 123,
1985
- 104,
1986
- 238
1987
- ],
1988
- mediumspringgreen: [
1989
- 0,
1990
- 250,
1991
- 154
1992
- ],
1993
- mediumturquoise: [
1994
- 72,
1995
- 209,
1996
- 204
1997
- ],
1998
- mediumvioletred: [
1999
- 199,
2000
- 21,
2001
- 133
2002
- ],
2003
- midnightblue: [
2004
- 25,
2005
- 25,
2006
- 112
2007
- ],
2008
- mintcream: [
2009
- 245,
2010
- 255,
2011
- 250
2012
- ],
2013
- mistyrose: [
2014
- 255,
2015
- 228,
2016
- 225
2017
- ],
2018
- moccasin: [
2019
- 255,
2020
- 228,
2021
- 181
2022
- ],
2023
- navajowhite: [
2024
- 255,
2025
- 222,
2026
- 173
2027
- ],
2028
- navy: [
2029
- 0,
2030
- 0,
2031
- 128
2032
- ],
2033
- oldlace: [
2034
- 253,
2035
- 245,
2036
- 230
2037
- ],
2038
- olive: [
2039
- 128,
2040
- 128,
2041
- 0
2042
- ],
2043
- olivedrab: [
2044
- 107,
2045
- 142,
2046
- 35
2047
- ],
2048
- orange: [
2049
- 255,
2050
- 165,
2051
- 0
2052
- ],
2053
- orangered: [
2054
- 255,
2055
- 69,
2056
- 0
2057
- ],
2058
- orchid: [
2059
- 218,
2060
- 112,
2061
- 214
2062
- ],
2063
- palegoldenrod: [
2064
- 238,
2065
- 232,
2066
- 170
2067
- ],
2068
- palegreen: [
2069
- 152,
2070
- 251,
2071
- 152
2072
- ],
2073
- paleturquoise: [
2074
- 175,
2075
- 238,
2076
- 238
2077
- ],
2078
- palevioletred: [
2079
- 219,
2080
- 112,
2081
- 147
2082
- ],
2083
- papayawhip: [
2084
- 255,
2085
- 239,
2086
- 213
2087
- ],
2088
- peachpuff: [
2089
- 255,
2090
- 218,
2091
- 185
2092
- ],
2093
- peru: [
2094
- 205,
2095
- 133,
2096
- 63
2097
- ],
2098
- pink: [
2099
- 255,
2100
- 192,
2101
- 203
2102
- ],
2103
- plum: [
2104
- 221,
2105
- 160,
2106
- 221
2107
- ],
2108
- powderblue: [
2109
- 176,
2110
- 224,
2111
- 230
2112
- ],
2113
- purple: [
2114
- 128,
2115
- 0,
2116
- 128
2117
- ],
2118
- rebeccapurple: [
2119
- 102,
2120
- 51,
2121
- 153
2122
- ],
2123
- red: [
2124
- 255,
2125
- 0,
2126
- 0
2127
- ],
2128
- rosybrown: [
2129
- 188,
2130
- 143,
2131
- 143
2132
- ],
2133
- royalblue: [
2134
- 65,
2135
- 105,
2136
- 225
2137
- ],
2138
- saddlebrown: [
2139
- 139,
2140
- 69,
2141
- 19
2142
- ],
2143
- salmon: [
2144
- 250,
2145
- 128,
2146
- 114
2147
- ],
2148
- sandybrown: [
2149
- 244,
2150
- 164,
2151
- 96
2152
- ],
2153
- seagreen: [
2154
- 46,
2155
- 139,
2156
- 87
2157
- ],
2158
- seashell: [
2159
- 255,
2160
- 245,
2161
- 238
2162
- ],
2163
- sienna: [
2164
- 160,
2165
- 82,
2166
- 45
2167
- ],
2168
- silver: [
2169
- 192,
2170
- 192,
2171
- 192
2172
- ],
2173
- skyblue: [
2174
- 135,
2175
- 206,
2176
- 235
2177
- ],
2178
- slateblue: [
2179
- 106,
2180
- 90,
2181
- 205
2182
- ],
2183
- slategray: [
2184
- 112,
2185
- 128,
2186
- 144
2187
- ],
2188
- slategrey: [
2189
- 112,
2190
- 128,
2191
- 144
2192
- ],
2193
- snow: [
2194
- 255,
2195
- 250,
2196
- 250
2197
- ],
2198
- springgreen: [
2199
- 0,
2200
- 255,
2201
- 127
2202
- ],
2203
- steelblue: [
2204
- 70,
2205
- 130,
2206
- 180
2207
- ],
2208
- tan: [
2209
- 210,
2210
- 180,
2211
- 140
2212
- ],
2213
- teal: [
2214
- 0,
2215
- 128,
2216
- 128
2217
- ],
2218
- thistle: [
2219
- 216,
2220
- 191,
2221
- 216
2222
- ],
2223
- tomato: [
2224
- 255,
2225
- 99,
2226
- 71
2227
- ],
2228
- turquoise: [
2229
- 64,
2230
- 224,
2231
- 208
2232
- ],
2233
- violet: [
2234
- 238,
2235
- 130,
2236
- 238
2237
- ],
2238
- wheat: [
2239
- 245,
2240
- 222,
2241
- 179
2242
- ],
2243
- white: [
2244
- 255,
2245
- 255,
2246
- 255
2247
- ],
2248
- whitesmoke: [
2249
- 245,
2250
- 245,
2251
- 245
2252
- ],
2253
- yellow: [
2254
- 255,
2255
- 255,
2256
- 0
2257
- ],
2258
- yellowgreen: [
2259
- 154,
2260
- 205,
2261
- 50
2262
- ]
2263
- };
2264
- },
2265
- "../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js" (module) {
2266
- module.exports = (flag, argv = process.argv)=>{
2267
- const prefix = flag.startsWith('-') ? '' : 1 === flag.length ? '-' : '--';
2268
- const position = argv.indexOf(prefix + flag);
2269
- const terminatorPosition = argv.indexOf('--');
2270
- return -1 !== position && (-1 === terminatorPosition || position < terminatorPosition);
2271
- };
2272
- },
2273
- "../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js" (module, __unused_rspack_exports, __webpack_require__) {
2274
- const os = __webpack_require__("os");
2275
- const tty = __webpack_require__("tty");
2276
- const hasFlag = __webpack_require__("../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js");
2277
- const { env } = process;
2278
- let forceColor;
2279
- if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) forceColor = 0;
2280
- else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) forceColor = 1;
2281
- if ('FORCE_COLOR' in env) forceColor = 'true' === env.FORCE_COLOR ? 1 : 'false' === env.FORCE_COLOR ? 0 : 0 === env.FORCE_COLOR.length ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
2282
- function translateLevel(level) {
2283
- if (0 === level) return false;
2284
- return {
2285
- level,
2286
- hasBasic: true,
2287
- has256: level >= 2,
2288
- has16m: level >= 3
2289
- };
2290
- }
2291
- function supportsColor(haveStream, streamIsTTY) {
2292
- if (0 === forceColor) return 0;
2293
- if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) return 3;
2294
- if (hasFlag('color=256')) return 2;
2295
- if (haveStream && !streamIsTTY && void 0 === forceColor) return 0;
2296
- const min = forceColor || 0;
2297
- if ('dumb' === env.TERM) return min;
2298
- if ('win32' === process.platform) {
2299
- const osRelease = os.release().split('.');
2300
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
2301
- return 1;
2302
- }
2303
- if ('CI' in env) {
2304
- if ([
2305
- 'TRAVIS',
2306
- 'CIRCLECI',
2307
- 'APPVEYOR',
2308
- 'GITLAB_CI',
2309
- 'GITHUB_ACTIONS',
2310
- 'BUILDKITE'
2311
- ].some((sign)=>sign in env) || 'codeship' === env.CI_NAME) return 1;
2312
- return min;
2313
- }
2314
- if ('TEAMCITY_VERSION' in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2315
- if ('truecolor' === env.COLORTERM) return 3;
2316
- if ('TERM_PROGRAM' in env) {
2317
- const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
2318
- switch(env.TERM_PROGRAM){
2319
- case 'iTerm.app':
2320
- return version >= 3 ? 3 : 2;
2321
- case 'Apple_Terminal':
2322
- return 2;
2323
- }
2324
- }
2325
- if (/-256(color)?$/i.test(env.TERM)) return 2;
2326
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
2327
- if ('COLORTERM' in env) return 1;
2328
- return min;
2329
- }
2330
- function getSupportLevel(stream) {
2331
- const level = supportsColor(stream, stream && stream.isTTY);
2332
- return translateLevel(level);
2333
- }
2334
- module.exports = {
2335
- supportsColor: getSupportLevel,
2336
- stdout: translateLevel(supportsColor(true, tty.isatty(1))),
2337
- stderr: translateLevel(supportsColor(true, tty.isatty(2)))
2338
- };
2339
- },
2340
- os (module) {
2341
- module.exports = __rspack_external_os;
2342
- },
2343
- tty (module) {
2344
- module.exports = __rspack_external_tty;
2345
- }
2346
- };
2347
- var __webpack_module_cache__ = {};
2348
- function __webpack_require__(moduleId) {
2349
- var cachedModule = __webpack_module_cache__[moduleId];
2350
- if (void 0 !== cachedModule) return cachedModule.exports;
2351
- var module = __webpack_module_cache__[moduleId] = {
2352
- id: moduleId,
2353
- loaded: false,
2354
- exports: {}
2355
- };
2356
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
2357
- module.loaded = true;
2358
- return module.exports;
2359
- }
2360
- (()=>{
2361
- __webpack_require__.n = (module)=>{
2362
- var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
2363
- __webpack_require__.d(getter, {
2364
- a: getter
2365
- });
2366
- return getter;
2367
- };
2368
- })();
2369
- (()=>{
2370
- __webpack_require__.d = (exports, definition)=>{
2371
- for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
2372
- enumerable: true,
2373
- get: definition[key]
2374
- });
2375
- };
2376
- })();
2377
- (()=>{
2378
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
2379
- })();
2380
- (()=>{
2381
- __webpack_require__.nmd = (module)=>{
2382
- module.paths = [];
2383
- if (!module.children) module.children = [];
2384
- return module;
2385
- };
2386
- })();
2387
- const warnRetryReport = getDebug('execution-summary', {
2388
- console: true
2389
- });
2390
- const notExecutedError = 'Not executed (previous task failed)';
2391
- function createNotExecutedYamlResult(file) {
2392
- return {
2393
- file,
2394
- success: false,
2395
- executed: false,
2396
- output: void 0,
2397
- report: void 0,
2398
- duration: 0,
2399
- resultType: 'notExecuted',
2400
- error: notExecutedError
2401
- };
2402
- }
2403
- function createUnexpectedYamlResult(options) {
2404
- const { file, error, duration, player } = options;
2405
- const output = player?.output;
2406
- return {
2407
- file,
2408
- success: false,
2409
- executed: true,
2410
- output: output && existsSync(output) ? output : void 0,
2411
- report: player?.reportFile || void 0,
2412
- duration,
2413
- resultType: 'failed',
2414
- error: error.message
2415
- };
2416
- }
2417
- function isYamlPlayerSuccessful(player) {
2418
- return 'error' !== player.status && !player.taskStatusList?.some((task)=>'error' === task.status);
2419
- }
2420
- function createExecutedYamlResult(options) {
2421
- const { file, player, duration } = options;
2422
- const hasPlayerError = 'error' === player.status;
2423
- const hasFailedTasks = !isYamlPlayerSuccessful(player) && !hasPlayerError;
2424
- let success;
2425
- let resultType;
2426
- if (hasPlayerError) {
2427
- success = false;
2428
- resultType = 'failed';
2429
- } else if (hasFailedTasks) {
2430
- success = false;
2431
- resultType = 'partialFailed';
2432
- } else {
2433
- success = true;
2434
- resultType = 'success';
2435
- }
2436
- let outputPath = player.output || void 0;
2437
- if (outputPath && !existsSync(outputPath)) outputPath = void 0;
2438
- let errorMessage;
2439
- if (player.errorInSetup?.message) errorMessage = player.errorInSetup.message;
2440
- else if (hasPlayerError || hasFailedTasks) {
2441
- const taskErrors = player.taskStatusList?.filter((task)=>'error' === task.status && task.error?.message).map((task)=>task.error.message);
2442
- errorMessage = taskErrors && taskErrors.length > 0 ? taskErrors.join('; ') : hasPlayerError ? 'Execution failed' : 'Some tasks failed';
2443
- }
2444
- return {
2445
- file,
2446
- success,
2447
- executed: true,
2448
- output: outputPath,
2449
- report: player.reportFile || void 0,
2450
- duration,
2451
- resultType,
2452
- error: errorMessage
2453
- };
2454
- }
2455
- function resolveYamlMaxAttempts(retry) {
2456
- if (!Number.isFinite(retry) || !retry || retry < 1) return 1;
2457
- return Math.floor(retry) + 1;
2458
- }
2459
- function createYamlAttempt(result, attempt) {
2460
- return {
2461
- attempt,
2462
- success: result.success,
2463
- output: result.output,
2464
- report: result.report,
2465
- error: result.error,
2466
- duration: result.duration,
2467
- resultType: result.resultType
2468
- };
2469
- }
2470
- function getYamlAttemptsDuration(attempts) {
2471
- return attempts.reduce((total, attempt)=>total + (attempt.duration ?? 0), 0);
2472
- }
2473
- const retryAttemptReportPath = (reportFile, attempt)=>{
2474
- if ('index.html' === basename(reportFile)) {
2475
- const reportDir = dirname(reportFile);
2476
- return join(dirname(reportDir), `${basename(reportDir)}-attempt-${attempt}`, 'index.html');
2477
- }
2478
- const extension = extname(reportFile);
2479
- const stem = basename(reportFile, extension);
2480
- return join(dirname(reportFile), `${stem}-attempt-${attempt}${extension}`);
2481
- };
2482
- function preserveYamlAttemptReport(attempt) {
2483
- const source = attempt.report;
2484
- if (!source || !existsSync(source)) return attempt;
2485
- const target = retryAttemptReportPath(source, attempt.attempt);
2486
- if ('index.html' === basename(source)) {
2487
- const sourceDir = dirname(source);
2488
- const targetDir = dirname(target);
2489
- rmSync(targetDir, {
2490
- recursive: true,
2491
- force: true
2492
- });
2493
- cpSync(sourceDir, targetDir, {
2494
- recursive: true
2495
- });
2496
- rmSync(sourceDir, {
2497
- recursive: true,
2498
- force: true
2499
- });
2500
- } else {
2501
- copyFileSync(source, target);
2502
- unlinkSync(source);
2503
- }
2504
- return {
2505
- ...attempt,
2506
- report: target
2507
- };
2508
- }
2509
- function getExecutionSummary(results) {
2510
- return {
2511
- total: results.length,
2512
- successful: getResultsByType(results, 'success').length,
2513
- failed: getResultsByType(results, 'failed').length,
2514
- partialFailed: getResultsByType(results, 'partialFailed').length,
2515
- notExecuted: getResultsByType(results, 'notExecuted').length,
2516
- totalDuration: results.reduce((sum, r)=>sum + (r.duration || 0), 0)
2517
- };
2518
- }
2519
- function getResultsByType(results, resultType) {
2520
- return results.filter((result)=>result.resultType === resultType);
2521
- }
2522
- function getResultFilesByType(results, resultType) {
2523
- return getResultsByType(results, resultType).map((result)=>result.file);
2524
- }
2525
- function getSummaryAbsolutePath(summary) {
2526
- return external_node_path_resolve(getMidsceneRunSubDir('output'), summary);
2527
- }
2528
- const toOutputRelativePath = (outputDir, filePath)=>{
2529
- const relativePath = relative(outputDir, filePath);
2530
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
2531
- };
2532
- const toTestStatus = (attempt)=>{
2533
- if (attempt.success) return 'passed';
2534
- if ('notExecuted' === attempt.resultType) return 'skipped';
2535
- return 'failed';
2536
- };
2537
- const safeReportNamePart = (value)=>value.replace(/[:*?"<>|# ]/g, '-');
2538
- const createRetryReportName = (file)=>{
2539
- const fileName = basename(file, extname(file)) || 'yaml';
2540
- const fileHash = createHash('sha1').update(external_node_path_resolve(file)).digest('hex').slice(0, 8);
2541
- return `${safeReportNamePart(fileName)}-${fileHash}-retry-attempts`;
2542
- };
2543
- const createRetryAttemptReport = (result)=>{
2544
- const attemptsWithReports = result.attempts?.filter((attempt)=>attempt.report && existsSync(attempt.report));
2545
- if (!attemptsWithReports || attemptsWithReports.length <= 1) return;
2546
- const tool = new ReportMergingTool();
2547
- for (const attempt of attemptsWithReports){
2548
- const status = toTestStatus(attempt);
2549
- tool.append({
2550
- reportFilePath: attempt.report,
2551
- reportAttributes: {
2552
- testDuration: attempt.duration ?? 0,
2553
- testStatus: status,
2554
- testTitle: `Attempt ${attempt.attempt}: ${status} - ${basename(result.file)}`,
2555
- testId: `${safeReportNamePart(basename(result.file))}-attempt-${attempt.attempt}`,
2556
- testDescription: attempt.error ?? (attempt.success ? 'YAML attempt passed' : 'YAML attempt failed')
2557
- }
2558
- });
2559
- }
2560
- return tool.mergeReports(createRetryReportName(result.file), {
2561
- outputDir: getMidsceneRunSubDir('report'),
2562
- overwrite: true
2563
- }) || void 0;
2564
- };
2565
- const errorMessageOf = (error)=>error instanceof Error ? error.message : String(error);
2566
- const warnRetryReportFailure = (message)=>{
2567
- try {
2568
- mkdirSync(getMidsceneRunSubDir('log'), {
2569
- recursive: true
2570
- });
2571
- warnRetryReport(message);
2572
- } catch {}
2573
- };
2574
- const createRetryAttemptReportSafely = (result)=>{
2575
- try {
2576
- return {
2577
- report: createRetryAttemptReport(result),
2578
- failed: false
2579
- };
2580
- } catch (error) {
2581
- warnRetryReportFailure(`Failed to merge retry attempt report for ${result.file}: ${errorMessageOf(error)}`);
2582
- return {
2583
- failed: true
2584
- };
2585
- }
2586
- };
2587
- function writeExecutionSummaryFile(summary, results) {
2588
- const indexPath = getSummaryAbsolutePath(summary);
2589
- const outputDir = dirname(indexPath);
2590
- mkdirSync(outputDir, {
2591
- recursive: true
2592
- });
2593
- const executionSummary = getExecutionSummary(results);
2594
- const indexData = {
2595
- summary: {
2596
- ...executionSummary,
2597
- generatedAt: new Date().toLocaleString()
2598
- },
2599
- results: results.map((result)=>{
2600
- const retryReport = createRetryAttemptReportSafely(result);
2601
- return {
2602
- script: relative(outputDir, result.file),
2603
- success: result.success,
2604
- resultType: result.resultType,
2605
- output: result.output ? toOutputRelativePath(outputDir, result.output) : void 0,
2606
- report: result.report ? relative(outputDir, result.report) : void 0,
2607
- retryReport: retryReport.report ? relative(outputDir, retryReport.report) : !retryReport.failed && result.retryReport ? relative(outputDir, result.retryReport) : void 0,
2608
- attempts: result.attempts?.map((attempt)=>({
2609
- attempt: attempt.attempt,
2610
- success: attempt.success,
2611
- resultType: attempt.resultType,
2612
- output: attempt.output ? toOutputRelativePath(outputDir, attempt.output) : void 0,
2613
- report: attempt.report ? relative(outputDir, attempt.report) : void 0,
2614
- error: attempt.error,
2615
- duration: attempt.duration
2616
- })),
2617
- error: result.error,
2618
- duration: result.duration
2619
- };
2620
- })
2621
- };
2622
- writeFileSync(indexPath, JSON.stringify(indexData, null, 2));
2623
- return indexPath;
2624
- }
2625
- function printExecutionPlan(config) {
2626
- if (config.setup) {
2627
- console.log(" Setup script:");
2628
- console.log(` - ${config.setup}`);
2629
- }
2630
- console.log(' Scripts:');
2631
- for (const file of config.files)console.log(` - ${file}`);
2632
- console.log('📋 Execution plan');
2633
- console.log(` Concurrency: ${config.concurrent}`);
2634
- console.log(` Keep window: ${config.keepWindow}`);
2635
- console.log(` Headed: ${config.headed}`);
2636
- console.log(` Continue on error: ${config.continueOnError}`);
2637
- console.log(` Retry: ${config.retry ?? 0}`);
2638
- console.log(` Share browser context: ${config.shareBrowserContext ?? false}`);
2639
- console.log(` Reuse browser page: ${config.reusePage ?? false}`);
2640
- console.log(` Summary output: ${config.summary}`);
2641
- }
2642
- function printExecutionFinished() {
2643
- console.log('Execution finished:');
2644
- }
2645
- const printResultArtifacts = (result)=>{
2646
- if (result.report) console.log(` Report: ${result.report}`);
2647
- if (result.output) console.log(` Output: ${result.output}`);
2648
- };
2649
- function printExecutionSummary(results, summaryPath) {
2650
- const summary = getExecutionSummary(results);
2651
- const successfulFiles = getResultsByType(results, 'success');
2652
- const failedFiles = getResultsByType(results, 'failed');
2653
- const partialFailedFiles = getResultsByType(results, 'partialFailed');
2654
- const notExecutedFiles = getResultsByType(results, 'notExecuted');
2655
- const success = 0 === summary.failed && 0 === summary.partialFailed && 0 === summary.notExecuted;
2656
- console.log('\n📊 Execution Summary:');
2657
- console.log(` Total files: ${summary.total}`);
2658
- console.log(` Successful: ${summary.successful}`);
2659
- console.log(` Failed: ${summary.failed}`);
2660
- console.log(` Partial failed: ${summary.partialFailed}`);
2661
- console.log(` Not executed: ${summary.notExecuted}`);
2662
- console.log(` Duration: ${(summary.totalDuration / 1000).toFixed(2)}s`);
2663
- console.log(` Summary: ${summaryPath}`);
2664
- if (successfulFiles.length > 0) {
2665
- console.log('\n✅ Successful files:');
2666
- successfulFiles.forEach((result)=>{
2667
- console.log(` ${result.file}`);
2668
- printResultArtifacts(result);
2669
- });
2670
- }
2671
- if (failedFiles.length > 0) {
2672
- console.log('\n❌ Failed files');
2673
- failedFiles.forEach((result)=>{
2674
- console.log(` ${result.file}`);
2675
- if (result.error) console.log(` Error: ${result.error}`);
2676
- });
2677
- }
2678
- if (partialFailedFiles.length > 0) {
2679
- console.log('\n⚠️ Partial failed files (some tasks failed with continueOnError)');
2680
- partialFailedFiles.forEach((result)=>{
2681
- console.log(` ${result.file}`);
2682
- if (result.error) console.log(` Error: ${result.error}`);
2683
- });
2684
- }
2685
- if (notExecutedFiles.length > 0) {
2686
- console.log('\n⏸️ Not executed files');
2687
- notExecutedFiles.forEach((result)=>{
2688
- console.log(` ${result.file}`);
2689
- });
2690
- }
2691
- if (success) console.log('\n🎉 All files executed successfully!');
2692
- else console.log('\n⚠️ Some files failed or were not executed.');
2693
- return success;
2694
- }
2695
- function _define_property(obj, key, value) {
2696
- if (key in obj) Object.defineProperty(obj, key, {
2697
- value: value,
2698
- enumerable: true,
2699
- configurable: true,
2700
- writable: true
2701
- });
2702
- else obj[key] = value;
2703
- return obj;
2704
- }
2705
- const normalizeBatchError = (error)=>error instanceof Error ? error : new Error('Unexpected YAML execution failure', {
2706
- cause: error
2707
- });
2708
- class YamlBatchExecutionError extends Error {
2709
- constructor(error, occurrences){
2710
- const cause = normalizeBatchError(error);
2711
- super(cause.message, {
2712
- cause
2713
- }), _define_property(this, "results", void 0), _define_property(this, "occurrences", void 0);
2714
- this.name = 'YamlBatchExecutionError';
2715
- this.occurrences = occurrences.map(({ caseId, result })=>({
2716
- caseId,
2717
- result
2718
- }));
2719
- this.results = this.occurrences.map(({ result })=>result);
2720
- }
2721
- }
2722
- function isYamlBatchExecutionError(error) {
2723
- return error instanceof YamlBatchExecutionError;
2724
- }
2725
- class Node {
2726
- value;
2727
- next;
2728
- constructor(value){
2729
- this.value = value;
2730
- }
2731
- }
2732
- class Queue {
2733
- #head;
2734
- #tail;
2735
- #size;
2736
- constructor(){
2737
- this.clear();
2738
- }
2739
- enqueue(value) {
2740
- const node = new Node(value);
2741
- if (this.#head) {
2742
- this.#tail.next = node;
2743
- this.#tail = node;
2744
- } else {
2745
- this.#head = node;
2746
- this.#tail = node;
2747
- }
2748
- this.#size++;
2749
- }
2750
- dequeue() {
2751
- const current = this.#head;
2752
- if (!current) return;
2753
- this.#head = this.#head.next;
2754
- this.#size--;
2755
- return current.value;
2756
- }
2757
- peek() {
2758
- if (!this.#head) return;
2759
- return this.#head.value;
2760
- }
2761
- clear() {
2762
- this.#head = void 0;
2763
- this.#tail = void 0;
2764
- this.#size = 0;
2765
- }
2766
- get size() {
2767
- return this.#size;
2768
- }
2769
- *[Symbol.iterator]() {
2770
- let current = this.#head;
2771
- while(current){
2772
- yield current.value;
2773
- current = current.next;
2774
- }
2775
- }
2776
- *drain() {
2777
- while(this.#head)yield this.dequeue();
2778
- }
2779
- }
2780
- function pLimit(concurrency) {
2781
- validateConcurrency(concurrency);
2782
- const queue = new Queue();
2783
- let activeCount = 0;
2784
- const resumeNext = ()=>{
2785
- if (activeCount < concurrency && queue.size > 0) {
2786
- queue.dequeue()();
2787
- activeCount++;
2788
- }
2789
- };
2790
- const next = ()=>{
2791
- activeCount--;
2792
- resumeNext();
2793
- };
2794
- const run = async (function_, resolve, arguments_)=>{
2795
- const result = (async ()=>function_(...arguments_))();
2796
- resolve(result);
2797
- try {
2798
- await result;
2799
- } catch {}
2800
- next();
2801
- };
2802
- const enqueue = (function_, resolve, arguments_)=>{
2803
- new Promise((internalResolve)=>{
2804
- queue.enqueue(internalResolve);
2805
- }).then(run.bind(void 0, function_, resolve, arguments_));
2806
- (async ()=>{
2807
- await Promise.resolve();
2808
- if (activeCount < concurrency) resumeNext();
2809
- })();
2810
- };
2811
- const generator = (function_, ...arguments_)=>new Promise((resolve)=>{
2812
- enqueue(function_, resolve, arguments_);
2813
- });
2814
- Object.defineProperties(generator, {
2815
- activeCount: {
2816
- get: ()=>activeCount
2817
- },
2818
- pendingCount: {
2819
- get: ()=>queue.size
2820
- },
2821
- clearQueue: {
2822
- value () {
2823
- queue.clear();
2824
- }
2825
- },
2826
- concurrency: {
2827
- get: ()=>concurrency,
2828
- set (newConcurrency) {
2829
- validateConcurrency(newConcurrency);
2830
- concurrency = newConcurrency;
2831
- queueMicrotask(()=>{
2832
- while(activeCount < concurrency && queue.size > 0)resumeNext();
2833
- });
2834
- }
2835
- }
2836
- });
2837
- return generator;
2838
- }
2839
- function validateConcurrency(concurrency) {
2840
- if (!((Number.isInteger(concurrency) || concurrency === 1 / 0) && concurrency > 0)) throw new TypeError('Expected `concurrency` to be a number from 1 and up');
2841
- }
2842
- var chalk_source = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js");
2843
- var source_default = /*#__PURE__*/ __webpack_require__.n(chalk_source);
2844
- function resolveIsTTY(env = process.env, stdoutIsTTY = process.stdout.isTTY) {
2845
- if (env.MIDSCENE_CLI_LOG_ON_NON_TTY || env.NO_COLOR || 'dumb' === env.TERM || env.CI) return false;
2846
- return Boolean(stdoutIsTTY);
2847
- }
2848
- const isTTY = resolveIsTTY();
2849
- const indent = ' ';
2850
- const spinnerInterval = 80;
2851
- const spinnerFrames = [
2852
- '◰',
2853
- '◳',
2854
- '◲',
2855
- '◱'
2856
- ];
2857
- const currentSpinningFrame = ()=>spinnerFrames[Math.floor(Date.now() / spinnerInterval) % spinnerFrames.length];
2858
- function indicatorForStatus(status) {
2859
- if ('init' === status) return source_default().gray('◌');
2860
- if ('running' === status) return source_default().yellowBright(currentSpinningFrame());
2861
- if ('done' === status) return source_default().green('✔︎');
2862
- if ('error' === status) return source_default().red('✘');
2863
- }
2864
- const contextInfo = (context)=>{
2865
- const filePath = context.file;
2866
- const filePathToShow = relative(process.cwd(), filePath);
2867
- const fileNameToPrint = `${source_default().gray(`${filePathToShow}`)}`;
2868
- const fileStatusText = indicatorForStatus(context.player.status);
2869
- const contextActionText = void 0 === context.player.currentTaskIndex && 'running' === context.player.status ? source_default().gray('(navigating)') : '';
2870
- const errorText = context.player.errorInSetup ? `\n${indent}${source_default().red('error:')} ${context.player.errorInSetup?.message}\n${indent}${indent}${context.player.errorInSetup?.stack}` : '';
2871
- const outputFile = context.player.output;
2872
- const outputText = outputFile && Object.keys(context.player.result || {}).length > 0 ? `\n${indent}${source_default().gray(`output: ${outputFile}`)}` : '';
2873
- const reportFile = context.player.reportFile;
2874
- const reportText = reportFile ? `\n${indent}${source_default().gray(`report: ${reportFile}`)}` : '';
2875
- const agentStatusTip = context.player.agentStatusTip;
2876
- const agentStatusText = agentStatusTip ? `\n${indent}${source_default().gray(`agent status: ${agentStatusTip}`)}` : '';
2877
- const mergedText = `${fileStatusText} ${fileNameToPrint} ${contextActionText}${outputText}${reportText}${errorText}${agentStatusText}`.trim();
2878
- return {
2879
- fileNameToPrint,
2880
- fileStatusText,
2881
- contextActionText,
2882
- outputText,
2883
- reportText,
2884
- mergedText
2885
- };
2886
- };
2887
- const singleTaskInfo = (task)=>{
2888
- let stepText = '';
2889
- if ('init' === task.status) stepText = '';
2890
- else if ('running' === task.status || 'error' === task.status) if (void 0 === task.currentStep) stepText = source_default().gray('(navigating)');
2891
- else if ('number' == typeof task.currentStep) {
2892
- const actionText = '';
2893
- stepText = source_default().gray(`(task ${task.currentStep + 1}/${task.totalSteps}${actionText})`.trim());
2894
- } else stepText = source_default().gray('(unknown task)');
2895
- const errorText = 'error' === task.status ? `\n${indent}${source_default().gray('error:')}\n${indent}${indent}${task.error?.message}` : '';
2896
- const statusText = indicatorForStatus(task.status);
2897
- const mergedLine = `${statusText} ${task.name} ${stepText}${errorText}`;
2898
- return {
2899
- nameText: task.name,
2900
- stepText,
2901
- errorText,
2902
- itemStatusText: statusText,
2903
- mergedLine
2904
- };
2905
- };
2906
- function paddingLines(lines) {
2907
- return lines.map((line)=>`${indent}${line}`);
2908
- }
2909
- const contextTaskListSummary = (taskStatusArray, context)=>{
2910
- const prefixLines = [];
2911
- const currentLine = [];
2912
- const suffixText = [];
2913
- const { mergedText: fileInfo } = contextInfo(context);
2914
- if (!context.player.errorInSetup) for (const task of taskStatusArray){
2915
- const { mergedLine } = singleTaskInfo(task);
2916
- if ('init' === context.player.status) suffixText.push(mergedLine);
2917
- else if ('running' === context.player.status) currentLine.push(mergedLine);
2918
- else if ('done' === context.player.status) prefixLines.push(mergedLine);
2919
- else if ('error' === context.player.status) prefixLines.push(mergedLine);
2920
- }
2921
- const lines = [
2922
- fileInfo
2923
- ];
2924
- if (prefixLines.length > 0) lines.push(...paddingLines(prefixLines));
2925
- if (currentLine.length > 0) lines.push(...paddingLines(currentLine));
2926
- if (suffixText.length > 0) lines.push(...paddingLines(suffixText));
2927
- return lines.join('\n');
2928
- };
2929
- const formatYamlProgressSnapshot = (message, attempt, totalAttempts)=>totalAttempts > 1 ? `Attempt ${attempt}/${totalAttempts}\n${message}` : message;
2930
- const copyProperty = (to, from, property, ignoreNonConfigurable)=>{
2931
- if ('length' === property || 'prototype' === property) return;
2932
- if ('arguments' === property || 'caller' === property) return;
2933
- const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
2934
- const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
2935
- if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) return;
2936
- Object.defineProperty(to, property, fromDescriptor);
2937
- };
2938
- const canCopyProperty = function(toDescriptor, fromDescriptor) {
2939
- return void 0 === toDescriptor || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
2940
- };
2941
- const changePrototype = (to, from)=>{
2942
- const fromPrototype = Object.getPrototypeOf(from);
2943
- if (fromPrototype === Object.getPrototypeOf(to)) return;
2944
- Object.setPrototypeOf(to, fromPrototype);
2945
- };
2946
- const wrappedToString = (withName, fromBody)=>`/* Wrapped ${withName}*/\n${fromBody}`;
2947
- const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
2948
- const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
2949
- const changeToString = (to, from, name)=>{
2950
- const withName = '' === name ? '' : `with ${name.trim()}() `;
2951
- const newToString = wrappedToString.bind(null, withName, from.toString());
2952
- Object.defineProperty(newToString, 'name', toStringName);
2953
- const { writable, enumerable, configurable } = toStringDescriptor;
2954
- Object.defineProperty(to, 'toString', {
2955
- value: newToString,
2956
- writable,
2957
- enumerable,
2958
- configurable
2959
- });
2960
- };
2961
- function mimicFunction(to, from, { ignoreNonConfigurable = false } = {}) {
2962
- const { name } = to;
2963
- for (const property of Reflect.ownKeys(from))copyProperty(to, from, property, ignoreNonConfigurable);
2964
- changePrototype(to, from);
2965
- changeToString(to, from, name);
2966
- return to;
2967
- }
2968
- const calledFunctions = new WeakMap();
2969
- const onetime_onetime = (function_, options = {})=>{
2970
- if ('function' != typeof function_) throw new TypeError('Expected a function');
2971
- let returnValue;
2972
- let callCount = 0;
2973
- const functionName = function_.displayName || function_.name || '<anonymous>';
2974
- const onetime = function(...arguments_) {
2975
- calledFunctions.set(onetime, ++callCount);
2976
- if (1 === callCount) {
2977
- returnValue = function_.apply(this, arguments_);
2978
- function_ = void 0;
2979
- } else if (true === options.throw) throw new Error(`Function \`${functionName}\` can only be called once`);
2980
- return returnValue;
2981
- };
2982
- mimicFunction(onetime, function_);
2983
- calledFunctions.set(onetime, callCount);
2984
- return onetime;
2985
- };
2986
- onetime_onetime.callCount = (function_)=>{
2987
- if (!calledFunctions.has(function_)) throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
2988
- return calledFunctions.get(function_);
2989
- };
2990
- const node_modules_onetime = onetime_onetime;
2991
- const signals = [];
2992
- signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
2993
- if ('win32' !== process.platform) signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT');
2994
- if ('linux' === process.platform) signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
2995
- const processOk = (process1)=>!!process1 && 'object' == typeof process1 && 'function' == typeof process1.removeListener && 'function' == typeof process1.emit && 'function' == typeof process1.reallyExit && 'function' == typeof process1.listeners && 'function' == typeof process1.kill && 'number' == typeof process1.pid && 'function' == typeof process1.on;
2996
- const kExitEmitter = Symbol.for('signal-exit emitter');
2997
- const global = globalThis;
2998
- const ObjectDefineProperty = Object.defineProperty.bind(Object);
2999
- class Emitter {
3000
- emitted = {
3001
- afterExit: false,
3002
- exit: false
3003
- };
3004
- listeners = {
3005
- afterExit: [],
3006
- exit: []
3007
- };
3008
- count = 0;
3009
- id = Math.random();
3010
- constructor(){
3011
- if (global[kExitEmitter]) return global[kExitEmitter];
3012
- ObjectDefineProperty(global, kExitEmitter, {
3013
- value: this,
3014
- writable: false,
3015
- enumerable: false,
3016
- configurable: false
3017
- });
3018
- }
3019
- on(ev, fn) {
3020
- this.listeners[ev].push(fn);
3021
- }
3022
- removeListener(ev, fn) {
3023
- const list = this.listeners[ev];
3024
- const i = list.indexOf(fn);
3025
- if (-1 === i) return;
3026
- if (0 === i && 1 === list.length) list.length = 0;
3027
- else list.splice(i, 1);
3028
- }
3029
- emit(ev, code, signal) {
3030
- if (this.emitted[ev]) return false;
3031
- this.emitted[ev] = true;
3032
- let ret = false;
3033
- for (const fn of this.listeners[ev])ret = true === fn(code, signal) || ret;
3034
- if ('exit' === ev) ret = this.emit('afterExit', code, signal) || ret;
3035
- return ret;
3036
- }
3037
- }
3038
- class SignalExitBase {
3039
- }
3040
- const signalExitWrap = (handler)=>({
3041
- onExit (cb, opts) {
3042
- return handler.onExit(cb, opts);
3043
- },
3044
- load () {
3045
- return handler.load();
3046
- },
3047
- unload () {
3048
- return handler.unload();
3049
- }
3050
- });
3051
- class SignalExitFallback extends SignalExitBase {
3052
- onExit() {
3053
- return ()=>{};
3054
- }
3055
- load() {}
3056
- unload() {}
3057
- }
3058
- class SignalExit extends SignalExitBase {
3059
- #hupSig = 'win32' === mjs_process.platform ? 'SIGINT' : 'SIGHUP';
3060
- #emitter = new Emitter();
3061
- #process;
3062
- #originalProcessEmit;
3063
- #originalProcessReallyExit;
3064
- #sigListeners = {};
3065
- #loaded = false;
3066
- constructor(process1){
3067
- super();
3068
- this.#process = process1;
3069
- this.#sigListeners = {};
3070
- for (const sig of signals)this.#sigListeners[sig] = ()=>{
3071
- const listeners = this.#process.listeners(sig);
3072
- let { count } = this.#emitter;
3073
- const p = process1;
3074
- if ('object' == typeof p.__signal_exit_emitter__ && 'number' == typeof p.__signal_exit_emitter__.count) count += p.__signal_exit_emitter__.count;
3075
- if (listeners.length === count) {
3076
- this.unload();
3077
- const ret = this.#emitter.emit('exit', null, sig);
3078
- const s = 'SIGHUP' === sig ? this.#hupSig : sig;
3079
- if (!ret) process1.kill(process1.pid, s);
3080
- }
3081
- };
3082
- this.#originalProcessReallyExit = process1.reallyExit;
3083
- this.#originalProcessEmit = process1.emit;
3084
- }
3085
- onExit(cb, opts) {
3086
- if (!processOk(this.#process)) return ()=>{};
3087
- if (false === this.#loaded) this.load();
3088
- const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
3089
- this.#emitter.on(ev, cb);
3090
- return ()=>{
3091
- this.#emitter.removeListener(ev, cb);
3092
- if (0 === this.#emitter.listeners['exit'].length && 0 === this.#emitter.listeners['afterExit'].length) this.unload();
3093
- };
3094
- }
3095
- load() {
3096
- if (this.#loaded) return;
3097
- this.#loaded = true;
3098
- this.#emitter.count += 1;
3099
- for (const sig of signals)try {
3100
- const fn = this.#sigListeners[sig];
3101
- if (fn) this.#process.on(sig, fn);
3102
- } catch (_) {}
3103
- this.#process.emit = (ev, ...a)=>this.#processEmit(ev, ...a);
3104
- this.#process.reallyExit = (code)=>this.#processReallyExit(code);
3105
- }
3106
- unload() {
3107
- if (!this.#loaded) return;
3108
- this.#loaded = false;
3109
- signals.forEach((sig)=>{
3110
- const listener = this.#sigListeners[sig];
3111
- if (!listener) throw new Error('Listener not defined for signal: ' + sig);
3112
- try {
3113
- this.#process.removeListener(sig, listener);
3114
- } catch (_) {}
3115
- });
3116
- this.#process.emit = this.#originalProcessEmit;
3117
- this.#process.reallyExit = this.#originalProcessReallyExit;
3118
- this.#emitter.count -= 1;
3119
- }
3120
- #processReallyExit(code) {
3121
- if (!processOk(this.#process)) return 0;
3122
- this.#process.exitCode = code || 0;
3123
- this.#emitter.emit('exit', this.#process.exitCode, null);
3124
- return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
3125
- }
3126
- #processEmit(ev, ...args) {
3127
- const og = this.#originalProcessEmit;
3128
- if (!('exit' === ev && processOk(this.#process))) return og.call(this.#process, ev, ...args);
3129
- {
3130
- if ('number' == typeof args[0]) this.#process.exitCode = args[0];
3131
- const ret = og.call(this.#process, ev, ...args);
3132
- this.#emitter.emit('exit', this.#process.exitCode, null);
3133
- return ret;
3134
- }
3135
- }
3136
- }
3137
- const mjs_process = globalThis.process;
3138
- const { onExit, load, unload } = signalExitWrap(processOk(mjs_process) ? new SignalExit(mjs_process) : new SignalExitFallback());
3139
- const terminal = node_process.stderr.isTTY ? node_process.stderr : node_process.stdout.isTTY ? node_process.stdout : void 0;
3140
- const restoreCursor = terminal ? node_modules_onetime(()=>{
3141
- onExit(()=>{
3142
- terminal.write('\u001B[?25h');
3143
- }, {
3144
- alwaysLast: true
3145
- });
3146
- }) : ()=>{};
3147
- const restore_cursor = restoreCursor;
3148
- function tty_renderer_define_property(obj, key, value) {
3149
- if (key in obj) Object.defineProperty(obj, key, {
3150
- value: value,
3151
- enumerable: true,
3152
- configurable: true,
3153
- writable: true
3154
- });
3155
- else obj[key] = value;
3156
- return obj;
3157
- }
3158
- const DEFAULT_RENDER_INTERVAL = 160;
3159
- const ESC = '\x1B[';
3160
- const CLEAR_LINE = `${ESC}K`;
3161
- const MOVE_CURSOR_ONE_ROW_UP = `${ESC}1A`;
3162
- const HIDE_CURSOR = `${ESC}?25l`;
3163
- const SHOW_CURSOR = `${ESC}?25h`;
3164
- const SYNC_START = `${ESC}?2026h`;
3165
- const SYNC_END = `${ESC}?2026l`;
3166
- class TTYWindowRenderer {
3167
- start() {
3168
- this.finished = false;
3169
- this.renderInterval = setInterval(()=>this.flushBuffer(), this.options.interval);
3170
- }
3171
- stop() {
3172
- this.flushBuffer();
3173
- this.write(SHOW_CURSOR, 'output');
3174
- this.cleanups.splice(0).map((fn)=>fn());
3175
- clearInterval(this.renderInterval);
3176
- }
3177
- finish() {
3178
- this.finished = true;
3179
- this.flushBuffer();
3180
- clearInterval(this.renderInterval);
3181
- }
3182
- flushBuffer() {
3183
- if (0 === this.buffer.length) return this.render();
3184
- let current;
3185
- for (const next of this.buffer.splice(0)){
3186
- if (!current) {
3187
- current = next;
3188
- continue;
3189
- }
3190
- if (current.type !== next.type) {
3191
- this.render(current.message, current.type);
3192
- current = next;
3193
- continue;
3194
- }
3195
- current.message += next.message;
3196
- }
3197
- if (current) this.render(current?.message, current?.type);
3198
- }
3199
- render(message, type = 'output') {
3200
- if (this.finished) {
3201
- this.clearWindow();
3202
- return this.write(message || '', type);
3203
- }
3204
- const windowContent = this.options.getWindow();
3205
- const rowCount = getRenderedRowCount(windowContent, this.options.outputStream);
3206
- let padding = this.windowHeight - rowCount;
3207
- if (padding > 0 && message) padding -= getRenderedRowCount([
3208
- message
3209
- ], this.options.outputStream);
3210
- this.write(SYNC_START);
3211
- this.clearWindow();
3212
- if (message) this.write(message, type);
3213
- if (padding > 0) this.write('\n'.repeat(padding));
3214
- this.write(windowContent.join('\n'));
3215
- this.write(SYNC_END);
3216
- this.windowHeight = rowCount + Math.max(0, padding);
3217
- }
3218
- clearWindow() {
3219
- if (0 === this.windowHeight) return;
3220
- this.write(CLEAR_LINE);
3221
- for(let i = 1; i < this.windowHeight; i++)this.write(`${MOVE_CURSOR_ONE_ROW_UP}${CLEAR_LINE}`);
3222
- this.windowHeight = 0;
3223
- }
3224
- interceptStream(stream, type) {
3225
- const original = stream.write;
3226
- stream.write = (chunk, _, callback)=>{
3227
- if (chunk) if (this.finished) this.write(chunk.toString(), type);
3228
- else this.buffer.push({
3229
- type,
3230
- message: chunk.toString()
3231
- });
3232
- callback?.();
3233
- };
3234
- return function() {
3235
- stream.write = original;
3236
- };
3237
- }
3238
- write(message, type = 'output') {
3239
- this.streams[type](message);
3240
- }
3241
- constructor(options){
3242
- tty_renderer_define_property(this, "options", void 0);
3243
- tty_renderer_define_property(this, "streams", void 0);
3244
- tty_renderer_define_property(this, "buffer", []);
3245
- tty_renderer_define_property(this, "renderInterval", void 0);
3246
- tty_renderer_define_property(this, "windowHeight", 0);
3247
- tty_renderer_define_property(this, "finished", false);
3248
- tty_renderer_define_property(this, "cleanups", []);
3249
- this.options = {
3250
- interval: DEFAULT_RENDER_INTERVAL,
3251
- ...options
3252
- };
3253
- this.streams = {
3254
- output: options.outputStream.write.bind(options.outputStream),
3255
- error: options.errorStream.write.bind(options.errorStream)
3256
- };
3257
- this.cleanups.push(this.interceptStream(process.stdout, 'output'), this.interceptStream(process.stderr, 'error'));
3258
- restore_cursor();
3259
- this.write(HIDE_CURSOR, 'output');
3260
- this.start();
3261
- }
3262
- }
3263
- function getRenderedRowCount(contents, stream) {
3264
- let count = 0;
3265
- const columns = 'columns' in stream ? stream.columns : 80;
3266
- for (const content of contents){
3267
- const rows = content.split('\n');
3268
- for (const row of rows){
3269
- const text = stripVTControlCharacters(row);
3270
- count += Math.max(1, Math.ceil(text.length / columns));
3271
- }
3272
- }
3273
- return count;
3274
- }
3275
- function yaml_batch_executor_define_property(obj, key, value) {
3276
- if (key in obj) Object.defineProperty(obj, key, {
3277
- value: value,
3278
- enumerable: true,
3279
- configurable: true,
3280
- writable: true
3281
- });
3282
- else obj[key] = value;
3283
- return obj;
3284
- }
3285
- const batchWarning = getDebug('yaml-batch-executor', {
3286
- console: true
3287
- });
3288
- const normalizeExecutionError = (error)=>error instanceof Error ? error : new Error('Unexpected YAML execution failure', {
3289
- cause: error
3290
- });
3291
- const batchRuntimeTargetLabel = {
3292
- 'puppeteer-web': 'Puppeteer Web',
3293
- 'bridge-web': 'Web bridge mode',
3294
- android: 'Android',
3295
- ios: 'iOS',
3296
- harmony: 'HarmonyOS',
3297
- computer: 'Computer',
3298
- interface: 'Interface'
3299
- };
3300
- const resolveBatchRuntimeTarget = (config)=>{
3301
- const webTarget = resolveWebTarget(config);
3302
- const targets = [];
3303
- if (webTarget) targets.push(webTarget.target.bridgeMode ? 'bridge-web' : 'puppeteer-web');
3304
- if (void 0 !== config.android) targets.push('android');
3305
- if (void 0 !== config.ios) targets.push('ios');
3306
- if (void 0 !== config.harmony) targets.push('harmony');
3307
- if (void 0 !== config.computer) targets.push('computer');
3308
- if (void 0 !== config.interface) targets.push('interface');
3309
- return 1 === targets.length ? targets[0] : void 0;
3310
- };
3311
- const assertBrowserContextUsage = (setupContext, allContexts, shareBrowserContext)=>{
3312
- const resolvedTargets = allContexts.map((context)=>({
3313
- context,
3314
- target: resolveBatchRuntimeTarget(context.executionConfig)
3315
- }));
3316
- if (shareBrowserContext) {
3317
- const unsupported = resolvedTargets.find(({ target })=>target && 'puppeteer-web' !== target);
3318
- if (unsupported?.target) throw new Error(`shareBrowserContext only supports Puppeteer Web targets, but "${unsupported.context.file}" uses ${batchRuntimeTargetLabel[unsupported.target]}. Remove shareBrowserContext or use a Puppeteer Web target.`);
3319
- const browserCreationOptions = [
3320
- 'cdpEndpoint',
3321
- 'chromeArgs',
3322
- 'acceptInsecureCerts',
3323
- 'downloadPath'
3324
- ];
3325
- for (const { context, target } of resolvedTargets){
3326
- if ('puppeteer-web' !== target) continue;
3327
- const fileWebConfig = resolveWebTarget(context.sourceConfig)?.target;
3328
- const misplacedOptions = browserCreationOptions.filter((option)=>void 0 !== fileWebConfig?.[option]);
3329
- if (misplacedOptions.length > 0) throw new Error(`shareBrowserContext creates one browser from the batch global config, so browser-level option(s) ${misplacedOptions.map((option)=>`"${option}"`).join(', ')} in "${context.file}" would be ignored. Move them to the batch config's global Web target.`);
3330
- }
3331
- }
3332
- if (setupContext && !shareBrowserContext && 'puppeteer-web' === resolveBatchRuntimeTarget(setupContext.executionConfig)) throw new Error(`Puppeteer Web setup "${setupContext.file}" requires shareBrowserContext: true so its browser state can be shared with the main files.`);
3333
- };
3334
- const createSharedBrowserRuntime = async (browser, browserContextOptions, reusePage = false)=>{
3335
- const browserContext = await browser.createBrowserContext(browserContextOptions);
3336
- try {
3337
- const page = reusePage ? await browserContext.newPage() : void 0;
3338
- return {
3339
- browserContext,
3340
- page
3341
- };
3342
- } catch (error) {
3343
- try {
3344
- await browserContext.close();
3345
- } catch (cleanupError) {
3346
- batchWarning('failed to close the shared browser context after page creation failed; preserving the original error', cleanupError);
3347
- }
3348
- throw error;
3349
- }
3350
- };
3351
- class YamlBatchExecutor {
3352
- async run(options = {}) {
3353
- const generateSummary = options.generateSummary ?? true;
3354
- const shouldPrintExecutionPlan = options.printExecutionPlan ?? true;
3355
- const { keepWindow, headed } = this.config;
3356
- const setup = this.config.setup;
3357
- if (shouldPrintExecutionPlan) printExecutionPlan(this.config);
3358
- let setupContext;
3359
- const fileContextList = [];
3360
- let browser = null;
3361
- const sharedRuntime = {
3362
- current: null
3363
- };
3364
- let caseIndex = 0;
3365
- let executionError;
3366
- try {
3367
- if (setup) {
3368
- const fileConfig = await this.loadFileConfig(setup);
3369
- setupContext = await this.createFileContext(setup, fileConfig, {
3370
- headed,
3371
- keepWindow
3372
- }, this.caseIds[caseIndex++]);
3373
- }
3374
- for (const file of this.config.files){
3375
- const fileConfig = await this.loadFileConfig(file);
3376
- const context = await this.createFileContext(file, fileConfig, {
3377
- headed,
3378
- keepWindow
3379
- }, this.caseIds[caseIndex++]);
3380
- fileContextList.push(context);
3381
- }
3382
- if (setupContext) {
3383
- const setupPath = external_node_path_resolve(setupContext.file);
3384
- const conflict = fileContextList.find((ctx)=>external_node_path_resolve(ctx.file) === setupPath);
3385
- if (conflict) throw new Error(`"${conflict.file}" is used as both the setup file and a main file; a yaml file cannot be both`);
3386
- }
3387
- const allContexts = setupContext ? [
3388
- setupContext,
3389
- ...fileContextList
3390
- ] : fileContextList;
3391
- assertBrowserContextUsage(setupContext, allContexts, this.config.shareBrowserContext);
3392
- const needsBrowser = allContexts.some((ctx)=>void 0 !== resolveWebTarget(ctx.executionConfig));
3393
- let resetSetupRuntime;
3394
- if (needsBrowser && this.config.shareBrowserContext) {
3395
- const globalWebConfig = resolveWebTarget(this.config.globalConfig ?? {})?.target;
3396
- const downloadBehavior = buildDownloadBehavior(globalWebConfig?.downloadPath);
3397
- const browserContextOptions = downloadBehavior ? {
3398
- downloadBehavior
3399
- } : void 0;
3400
- if (globalWebConfig?.cdpEndpoint) browser = await puppeteer.connect({
3401
- browserWSEndpoint: globalWebConfig.cdpEndpoint,
3402
- defaultViewport: null,
3403
- downloadBehavior
3404
- });
3405
- else {
3406
- const width = globalWebConfig?.viewportWidth ?? defaultViewportWidth;
3407
- const height = globalWebConfig?.viewportHeight ?? defaultViewportHeight;
3408
- const args = buildChromeArgs({
3409
- userAgent: globalWebConfig?.userAgent,
3410
- windowSize: headed ? {
3411
- width,
3412
- height
3413
- } : void 0,
3414
- chromeArgs: globalWebConfig?.chromeArgs
3415
- });
3416
- browser = await puppeteer.launch({
3417
- headless: !headed,
3418
- defaultViewport: headed ? null : {
3419
- width,
3420
- height
3421
- },
3422
- downloadBehavior,
3423
- args,
3424
- acceptInsecureCerts: globalWebConfig?.acceptInsecureCerts
3425
- });
3426
- }
3427
- resetSetupRuntime = async ()=>{
3428
- if (!browser) throw new Error('Cannot create a shared runtime without a browser');
3429
- if (sharedRuntime.current) {
3430
- const staleRuntime = sharedRuntime.current;
3431
- sharedRuntime.current = null;
3432
- await staleRuntime.browserContext.close();
3433
- }
3434
- sharedRuntime.current = await createSharedBrowserRuntime(browser, browserContextOptions, this.config.reusePage);
3435
- for (const context of allContexts){
3436
- context.options.browser = browser;
3437
- context.options.browserContext = sharedRuntime.current.browserContext;
3438
- if (sharedRuntime.current.page) context.options.page = sharedRuntime.current.page;
3439
- }
3440
- };
3441
- await resetSetupRuntime();
3442
- }
3443
- const { executedResults, unexpectedResults, notExecutedContexts, unexpectedError } = await this.executeFiles(setupContext, fileContextList, {
3444
- onProgress: options.onProgress,
3445
- resetSetupRuntime
3446
- });
3447
- this.results = await this.processResults(executedResults, unexpectedResults, notExecutedContexts);
3448
- executionError = unexpectedError;
3449
- } catch (error) {
3450
- executionError = error;
3451
- } finally{
3452
- if (browser && !this.config.keepWindow) {
3453
- try {
3454
- if (sharedRuntime.current) {
3455
- await sharedRuntime.current.browserContext.close();
3456
- sharedRuntime.current = null;
3457
- }
3458
- } catch (error) {
3459
- if (executionError) batchWarning('failed to close the shared browser context after execution had already failed; preserving the original error', error);
3460
- else executionError = error;
3461
- }
3462
- try {
3463
- const isCdp = !!resolveWebTarget(this.config.globalConfig ?? {})?.target.cdpEndpoint;
3464
- if (isCdp) browser.disconnect();
3465
- else await browser.close();
3466
- } catch (error) {
3467
- if (executionError) batchWarning('failed to clean up the shared browser after execution had already failed; preserving the original error', error);
3468
- else executionError = error;
3469
- }
3470
- }
3471
- if (generateSummary) await this.generateOutputIndex();
3472
- }
3473
- if (executionError) throw new YamlBatchExecutionError(executionError, this.results);
3474
- return this.results;
3475
- }
3476
- async createFileContext(file, fileConfig, options, caseId) {
3477
- const { globalConfig } = this.config;
3478
- const clonedFileConfig = JSON.parse(JSON.stringify(fileConfig));
3479
- const executionConfig = lodash_merge(clonedFileConfig, globalConfig);
3480
- return {
3481
- caseId,
3482
- file,
3483
- sourceConfig: fileConfig,
3484
- executionConfig,
3485
- options
3486
- };
3487
- }
3488
- async executeFiles(setupContext, fileContextList, options) {
3489
- const { onProgress, resetSetupRuntime } = options;
3490
- const executedResults = [];
3491
- const unexpectedResults = [];
3492
- const notExecutedContexts = [];
3493
- const allFileContexts = [];
3494
- const fileContextsByCaseId = new Map();
3495
- const createFilePlayerContext = async (context)=>{
3496
- const fileContext = {
3497
- file: context.file,
3498
- player: await createYamlPlayer(context.file, context.executionConfig, context.options)
3499
- };
3500
- fileContextsByCaseId.set(context.caseId, fileContext);
3501
- return fileContext;
3502
- };
3503
- const initialContexts = setupContext ? [
3504
- setupContext
3505
- ] : fileContextList;
3506
- for (const context of initialContexts)allFileContexts.push(await createFilePlayerContext(context));
3507
- let ttyRenderer;
3508
- if (isTTY && !onProgress) {
3509
- const summaryContents = ()=>{
3510
- const summary = [
3511
- ''
3512
- ];
3513
- for (const context of allFileContexts)summary.push(contextTaskListSummary(context.player.taskStatusList, context));
3514
- summary.push('');
3515
- return summary;
3516
- };
3517
- ttyRenderer = new TTYWindowRenderer({
3518
- outputStream: process.stdout,
3519
- errorStream: process.stderr,
3520
- getWindow: summaryContents,
3521
- interval: spinnerInterval
3522
- });
3523
- ttyRenderer.start();
3524
- }
3525
- const reportProgressSnapshot = (context, attempt, totalAttempts)=>{
3526
- const summary = contextTaskListSummary(context.player.taskStatusList, context);
3527
- onProgress?.(formatYamlProgressSnapshot(summary, attempt, totalAttempts));
3528
- };
3529
- let unexpectedError;
3530
- try {
3531
- const executeFile = async (context, beforeRetry)=>{
3532
- const allFileContext = fileContextsByCaseId.get(context.caseId);
3533
- let lastAttemptStartTime;
3534
- try {
3535
- if (!allFileContext) throw new Error(`Player not found for file: ${context.file}`);
3536
- const totalAttempts = resolveYamlMaxAttempts(this.config.retry);
3537
- const attempts = [];
3538
- let executedContext;
3539
- for(let attempt = 1; attempt <= totalAttempts; attempt++){
3540
- if (attempt > 1) {
3541
- if (context.executionConfig.agent?.reportFileName) attempts[attempts.length - 1] = preserveYamlAttemptReport(attempts[attempts.length - 1]);
3542
- await beforeRetry?.();
3543
- allFileContext.player = await createYamlPlayer(context.file, context.executionConfig, context.options);
3544
- }
3545
- if (onProgress) reportProgressSnapshot(allFileContext, attempt, totalAttempts);
3546
- else if (!isTTY) {
3547
- const { mergedText } = contextInfo(allFileContext);
3548
- console.log(mergedText);
3549
- }
3550
- if (context.outputPath) allFileContext.player.output = context.outputPath;
3551
- const startTime = Date.now();
3552
- lastAttemptStartTime = startTime;
3553
- await allFileContext.player.run();
3554
- const duration = Date.now() - startTime;
3555
- const attemptResult = createExecutedYamlResult({
3556
- file: context.file,
3557
- player: allFileContext.player,
3558
- duration
3559
- });
3560
- attempts.push(createYamlAttempt(attemptResult, attempt));
3561
- const totalDuration = getYamlAttemptsDuration(attempts);
3562
- const yamlResult = {
3563
- ...attemptResult,
3564
- duration: totalDuration,
3565
- attempts: [
3566
- ...attempts
3567
- ]
3568
- };
3569
- executedContext = {
3570
- caseId: context.caseId,
3571
- file: context.file,
3572
- player: allFileContext.player,
3573
- duration: totalDuration,
3574
- yamlResult
3575
- };
3576
- if (onProgress) reportProgressSnapshot(executedContext, attempt, totalAttempts);
3577
- else if (!isTTY) console.log(contextTaskListSummary(allFileContext.player.taskStatusList, executedContext));
3578
- if (yamlResult.success) break;
3579
- }
3580
- if (!executedContext) throw new Error(`No attempts executed for file: ${context.file}`);
3581
- return {
3582
- kind: 'executed',
3583
- context: executedContext
3584
- };
3585
- } catch (error) {
3586
- const normalizedError = normalizeExecutionError(error);
3587
- return {
3588
- kind: 'unexpected',
3589
- context: {
3590
- caseId: context.caseId,
3591
- file: context.file,
3592
- error: normalizedError,
3593
- yamlResult: createUnexpectedYamlResult({
3594
- file: context.file,
3595
- error: normalizedError,
3596
- duration: void 0 === lastAttemptStartTime ? 0 : Date.now() - lastAttemptStartTime,
3597
- player: allFileContext?.player
3598
- })
3599
- }
3600
- };
3601
- }
3602
- };
3603
- let setupFailed = false;
3604
- if (setupContext) {
3605
- const outcome = await executeFile(setupContext, resetSetupRuntime);
3606
- if ('unexpected' === outcome.kind) {
3607
- unexpectedResults.push(outcome.context);
3608
- unexpectedError = outcome.context.error;
3609
- setupFailed = true;
3610
- } else {
3611
- executedResults.push(outcome.context);
3612
- setupFailed = !outcome.context.yamlResult.success;
3613
- }
3614
- }
3615
- if (setupFailed) for (const context of fileContextList)notExecutedContexts.push({
3616
- caseId: context.caseId,
3617
- file: context.file,
3618
- player: null
3619
- });
3620
- else {
3621
- if (setupContext) for (const context of fileContextList)allFileContexts.push(await createFilePlayerContext(context));
3622
- unexpectedError = await this.executeConcurrently(fileContextList, executeFile, executedResults, unexpectedResults, notExecutedContexts);
3623
- }
3624
- if (!isTTY && !onProgress) {
3625
- console.log('\n📋 Execution Results:');
3626
- for (const context of executedResults)console.log(contextTaskListSummary(context.player.taskStatusList, context));
3627
- }
3628
- } finally{
3629
- if (ttyRenderer) ttyRenderer.stop();
3630
- }
3631
- return {
3632
- executedResults,
3633
- unexpectedResults,
3634
- notExecutedContexts,
3635
- unexpectedError
3636
- };
3637
- }
3638
- async executeConcurrently(fileContextList, executeFile, executedResults, unexpectedResults, notExecutedContexts) {
3639
- const limit = pLimit(this.config.concurrent);
3640
- let unexpectedError;
3641
- const recordOutcome = (outcome)=>{
3642
- if ('unexpected' === outcome.kind) {
3643
- unexpectedResults.push(outcome.context);
3644
- unexpectedError ??= outcome.context.error;
3645
- } else executedResults.push(outcome.context);
3646
- };
3647
- if (this.config.continueOnError) {
3648
- const tasks = fileContextList.map((context)=>limit(async ()=>{
3649
- recordOutcome(await executeFile(context));
3650
- }));
3651
- await Promise.all(tasks);
3652
- } else {
3653
- let shouldStop = false;
3654
- const stopLock = {
3655
- value: false
3656
- };
3657
- const tasks = fileContextList.map((context)=>limit(async ()=>{
3658
- if (stopLock.value) return void notExecutedContexts.push({
3659
- caseId: context.caseId,
3660
- file: context.file,
3661
- player: null
3662
- });
3663
- const outcome = await executeFile(context);
3664
- recordOutcome(outcome);
3665
- if (('unexpected' === outcome.kind || !outcome.context.yamlResult.success) && !stopLock.value) {
3666
- stopLock.value = true;
3667
- shouldStop = true;
3668
- }
3669
- }));
3670
- await Promise.all(tasks);
3671
- if (shouldStop) {
3672
- for (const context of fileContextList)if (!executedResults.some((r)=>r.caseId === context.caseId) && !unexpectedResults.some((r)=>r.caseId === context.caseId) && !notExecutedContexts.some((ctx)=>ctx.caseId === context.caseId)) notExecutedContexts.push({
3673
- caseId: context.caseId,
3674
- file: context.file,
3675
- player: null
3676
- });
3677
- }
3678
- }
3679
- return unexpectedError;
3680
- }
3681
- async processResults(executedContexts, unexpectedContexts, notExecutedContexts) {
3682
- const resultsByCaseId = new Map();
3683
- for (const context of executedContexts)resultsByCaseId.set(context.caseId, context.yamlResult);
3684
- for (const context of unexpectedContexts)resultsByCaseId.set(context.caseId, context.yamlResult);
3685
- for (const context of notExecutedContexts)resultsByCaseId.set(context.caseId, createNotExecutedYamlResult(context.file));
3686
- return this.caseIds.map((caseId)=>{
3687
- const result = resultsByCaseId.get(caseId);
3688
- if (!result) throw new Error(`Batch result missing for case ID: ${caseId}`);
3689
- return {
3690
- caseId,
3691
- result
3692
- };
3693
- });
3694
- }
3695
- async loadFileConfig(file) {
3696
- const content = readFileSync(file, 'utf8');
3697
- return parseYamlScript(content, file);
3698
- }
3699
- async generateOutputIndex() {
3700
- try {
3701
- writeExecutionSummaryFile(this.config.summary, this.results.map(({ result })=>result));
3702
- printExecutionFinished();
3703
- } catch (error) {
3704
- console.error('Failed to generate output index:', error);
3705
- }
3706
- }
3707
- constructor(config, caseIds){
3708
- yaml_batch_executor_define_property(this, "config", void 0);
3709
- yaml_batch_executor_define_property(this, "caseIds", void 0);
3710
- yaml_batch_executor_define_property(this, "results", []);
3711
- this.config = config;
3712
- const occurrenceCount = config.files.length + (config.setup ? 1 : 0);
3713
- this.caseIds = caseIds ?? Array.from({
3714
- length: occurrenceCount
3715
- }, (_, index)=>`batch-occurrence-${index + 1}`);
3716
- if (this.caseIds.length !== occurrenceCount) throw new Error(`Batch occurrence identity mismatch: expected ${occurrenceCount} case ID(s), received ${this.caseIds.length}`);
3717
- if (new Set(this.caseIds).size !== this.caseIds.length) throw new Error('Batch occurrence case IDs must be unique');
3718
- if (config.reusePage && !config.shareBrowserContext) throw new Error('reusePage requires shareBrowserContext: true');
3719
- if (config.reusePage && 1 !== config.concurrent) throw new Error('reusePage requires concurrent: 1');
3720
- }
3721
- }
3722
- async function runYamlBatch(config, options = {}) {
3723
- const results = await new YamlBatchExecutor(config).run(options);
3724
- return results.map(({ result })=>result);
3725
- }
3726
- async function runYamlBatchWithCaseIds(config, caseIds, options = {}) {
3727
- return new YamlBatchExecutor(config, caseIds).run(options);
3728
- }
3729
- function batch_runner_define_property(obj, key, value) {
3730
- if (key in obj) Object.defineProperty(obj, key, {
3731
- value: value,
3732
- enumerable: true,
3733
- configurable: true,
3734
- writable: true
3735
- });
3736
- else obj[key] = value;
3737
- return obj;
3738
- }
3739
- class BatchRunner {
3740
- async run(options = {}) {
3741
- this.results = [];
3742
- try {
3743
- this.results = await runYamlBatch(this.config, options);
3744
- return this.results;
3745
- } catch (error) {
3746
- if (isYamlBatchExecutionError(error)) this.results = [
3747
- ...error.results
3748
- ];
3749
- throw error;
3750
- }
3751
- }
3752
- getExecutionSummary() {
3753
- return getExecutionSummary(this.results);
3754
- }
3755
- getFailedFiles() {
3756
- return getResultFilesByType(this.results, 'failed');
3757
- }
3758
- getPartialFailedFiles() {
3759
- return getResultFilesByType(this.results, 'partialFailed');
3760
- }
3761
- getNotExecutedFiles() {
3762
- return getResultFilesByType(this.results, 'notExecuted');
3763
- }
3764
- getSuccessfulFiles() {
3765
- return getResultFilesByType(this.results, 'success');
3766
- }
3767
- getResults() {
3768
- return [
3769
- ...this.results
3770
- ];
3771
- }
3772
- printExecutionSummary() {
3773
- return printExecutionSummary(this.results, getSummaryAbsolutePath(this.config.summary));
3774
- }
3775
- constructor(config){
3776
- batch_runner_define_property(this, "config", void 0);
3777
- batch_runner_define_property(this, "results", void 0);
3778
- this.config = config;
3779
- this.results = [];
3780
- }
3781
- }
3782
- const requireFromCliPackage = ()=>{
3783
- if ('undefined' != typeof __dirname) return createRequire(join(__dirname, 'index.js'));
3784
- const entry = process.argv[1] ? external_node_path_resolve(process.argv[1]) : join(process.cwd(), 'midscene-cli.js');
3785
- return createRequire(entry);
3786
- };
3787
- const resolvePackageFromRstestCore = (packageName)=>{
3788
- const require = requireFromCliPackage();
3789
- const rstestPackageJsonPath = require.resolve('@rstest/core/package.json');
3790
- return createRequire(rstestPackageJsonPath).resolve(packageName);
3791
- };
3792
- function resolveRstestCoreImportPath() {
3793
- const require = requireFromCliPackage();
3794
- return require.resolve('@rstest/core');
3795
- }
3796
- const DEFAULT_YAML_TEST_TIMEOUT = 0;
3797
- const RSTEST_YAML_BATCH_TEST_MODULE = 'virtual:midscene-yaml/batch.test.ts';
3798
- const RSTEST_YAML_BATCH_TEST_NAME = 'midscene yaml batch';
3799
- const RSTEST_YAML_SEQUENTIAL_TEST_MODULE = 'virtual:midscene-yaml/sequential.test.ts';
3800
- const toPosixPath = (value)=>value.split(sep).join('/');
3801
- const toImportLiteral = (value)=>JSON.stringify(toPosixPath(value));
3802
- const toVirtualModuleId = (fileStem)=>`virtual:midscene-yaml/${fileStem}.test.ts`;
3803
- const safeFileStem = (file, index)=>{
3804
- const base = basename(file, extname(file)).replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
3805
- return `${String(index + 1).padStart(3, '0')}-${base || 'case'}`;
3806
- };
3807
- const resolveTestName = (projectDir, yamlFile)=>{
3808
- const relativePath = relative(projectDir, yamlFile);
3809
- return toPosixPath(relativePath.startsWith('..') ? yamlFile : relativePath);
3810
- };
3811
- const createGeneratedCaseTestContent = (options)=>`import { test } from ${toImportLiteral(options.rstestCoreImport)};
3812
- import { defineYamlCaseTest } from ${toImportLiteral(options.frameworkImport)};
3813
-
3814
- const testOptionsList = ${JSON.stringify(options.testOptions, null, 2)};
3815
-
3816
- for (const testOptions of testOptionsList) {
3817
- defineYamlCaseTest(${options.sequential ? 'test.sequential' : 'test'}, testOptions);
3818
- }
3819
- `;
3820
- const createGeneratedBatchTestContent = (options)=>`import { test } from ${toImportLiteral(options.rstestCoreImport)};
3821
- import { defineYamlBatchTest } from ${toImportLiteral(options.frameworkImport)};
3822
-
3823
- const testOptions = ${JSON.stringify(options.testOptions, null, 2)};
3824
-
3825
- defineYamlBatchTest(test, testOptions);
3826
- `;
3827
- const resolveDefaultFrameworkImport = (moduleDir)=>{
3828
- const anchorDir = moduleDir ?? ('undefined' != typeof __dirname ? __dirname : void 0);
3829
- const candidates = [
3830
- anchorDir ? join(anchorDir, 'framework', 'index.js') : ''
3831
- ];
3832
- const entry = process.argv[1] ? external_node_path_resolve(process.argv[1]) : '';
3833
- if (entry) {
3834
- candidates.push(join(dirname(entry), 'framework', 'index.js'));
3835
- candidates.push(join(dirname(entry), '..', 'dist', 'lib', 'framework', 'index.js'));
3836
- }
3837
- const matched = candidates.filter(Boolean).find((candidate)=>existsSync(candidate));
3838
- return matched || '@midscene/cli/dist/lib/framework/index.js';
3839
- };
3840
- function createRstestYamlProject(options) {
3841
- const projectDir = external_node_path_resolve(options.projectDir || process.cwd());
3842
- const outputDir = options.outputDir || join(getMidsceneRunSubDir('tmp'), `rstest-yaml-${Date.now()}`);
3843
- const resultDir = options.resultDir || join(outputDir, 'results');
3844
- const frameworkImport = options.frameworkImport || resolveDefaultFrameworkImport();
3845
- const rstestCoreImport = options.rstestCoreImport || resolveRstestCoreImportPath();
3846
- const testTimeout = options.testTimeout ?? DEFAULT_YAML_TEST_TIMEOUT;
3847
- rmSync(outputDir, {
3848
- recursive: true,
3849
- force: true
3850
- });
3851
- mkdirSync(resultDir, {
3852
- recursive: true
3853
- });
3854
- const resultYamlFiles = options.batchConfig ? [
3855
- ...options.batchConfig.setup ? [
3856
- options.batchConfig.setup
3857
- ] : [],
3858
- ...options.batchConfig.files
3859
- ] : options.files;
3860
- const cases = resultYamlFiles.map((file, index)=>{
3861
- const yamlFile = external_node_path_resolve(file);
3862
- const testName = resolveTestName(projectDir, yamlFile);
3863
- const caseId = safeFileStem(yamlFile, index);
3864
- const resultFile = join(resultDir, `${caseId}.json`);
3865
- return {
3866
- caseId,
3867
- yamlFile,
3868
- resultFile,
3869
- testName,
3870
- retry: options.retry,
3871
- ...options.caseOptions?.[yamlFile] ? {
3872
- caseOptions: options.caseOptions[yamlFile]
3873
- } : {},
3874
- ...options.webRuntimeOptions?.[yamlFile] ? {
3875
- webRuntimeOptions: options.webRuntimeOptions[yamlFile]
3876
- } : {}
3877
- };
3878
- });
3879
- const baseProject = {
3880
- projectDir,
3881
- outputDir,
3882
- resultDir,
3883
- cases,
3884
- testTimeout,
3885
- bail: options.bail
3886
- };
3887
- if (options.batchConfig) {
3888
- const testOptions = {
3889
- caseIds: cases.map((item)=>item.caseId),
3890
- testName: RSTEST_YAML_BATCH_TEST_NAME,
3891
- config: options.batchConfig,
3892
- resultTargets: cases.map(({ caseId, yamlFile, resultFile })=>({
3893
- caseId,
3894
- yamlFile,
3895
- resultFile
3896
- }))
3897
- };
3898
- return {
3899
- ...baseProject,
3900
- modules: [
3901
- {
3902
- id: RSTEST_YAML_BATCH_TEST_MODULE,
3903
- caseIds: testOptions.caseIds,
3904
- source: createGeneratedBatchTestContent({
3905
- rstestCoreImport,
3906
- frameworkImport,
3907
- testOptions
3908
- })
3909
- }
3910
- ],
3911
- maxConcurrency: 1
3912
- };
3913
- }
3914
- if (1 === options.maxConcurrency) {
3915
- const caseIds = cases.map((item)=>item.caseId);
3916
- return {
3917
- ...baseProject,
3918
- modules: [
3919
- {
3920
- id: RSTEST_YAML_SEQUENTIAL_TEST_MODULE,
3921
- caseIds,
3922
- source: createGeneratedCaseTestContent({
3923
- rstestCoreImport,
3924
- frameworkImport,
3925
- testOptions: cases,
3926
- sequential: true
3927
- })
3928
- }
3929
- ],
3930
- maxConcurrency: 1,
3931
- retry: options.retry
3932
- };
3933
- }
3934
- return {
3935
- ...baseProject,
3936
- modules: cases.map((item)=>{
3937
- const id = toVirtualModuleId(item.caseId);
3938
- return {
3939
- id,
3940
- caseIds: [
3941
- item.caseId
3942
- ],
3943
- source: createGeneratedCaseTestContent({
3944
- rstestCoreImport,
3945
- frameworkImport,
3946
- testOptions: [
3947
- item
3948
- ],
3949
- sequential: false
3950
- })
3951
- };
3952
- }),
3953
- maxConcurrency: options.maxConcurrency,
3954
- retry: options.retry
3955
- };
3956
- }
3957
- const yamlProgressLogPrefix = '__MIDSCENE_YAML_PROGRESS__:';
3958
- const emitYamlProgress = (message)=>{
3959
- console.log(`${yamlProgressLogPrefix}${message}`);
3960
- };
3961
- const createYamlProgressReporter = ()=>({
3962
- onUserConsoleLog (log) {
3963
- if (!log.content.startsWith(yamlProgressLogPrefix)) return;
3964
- const message = log.content.slice(yamlProgressLogPrefix.length);
3965
- console.log(message.replace(/\r?\n$/, ''));
3966
- }
3967
- });
3968
- const RSTEST_YAML_CASE_IDS_META_KEY = 'midsceneYamlCaseIds';
3969
- const formatRunError = (error)=>error.stack || `${error.name || 'Error'}: ${error.message}`;
3970
- const collectRunErrors = (result)=>{
3971
- const messages = [];
3972
- const push = (error, label)=>{
3973
- const formatted = formatRunError(error);
3974
- messages.push(label ? `${label}: ${formatted}` : formatted);
3975
- };
3976
- for (const file of result.results){
3977
- for (const error of file.errors ?? [])push(error, file.name || file.testPath);
3978
- for (const testResult of file.results ?? [])for (const error of testResult.errors ?? [])push(error, testResult.name);
3979
- }
3980
- for (const error of result.unhandledErrors)push(error);
3981
- return Array.from(new Set(messages));
3982
- };
3983
- const rstest_runner_errorMessage = (error)=>error.message || error.name || 'YAML case failed';
3984
- const mapRunErrorsToCases = (project, result)=>{
3985
- const knownCaseIds = new Set(project.cases.map((item)=>item.caseId));
3986
- const errors = new Map();
3987
- const add = (caseId, message)=>{
3988
- if (knownCaseIds.has(caseId) && message && !errors.has(caseId)) errors.set(caseId, message);
3989
- };
3990
- const addCases = (caseIds, message)=>{
3991
- for (const caseId of caseIds)add(caseId, message);
3992
- };
3993
- const findModuleCaseIds = (file)=>{
3994
- for (const key of [
3995
- file.name,
3996
- file.testPath
3997
- ]){
3998
- if (!key) continue;
3999
- const matched = project.modules.find((item)=>key === item.id || key.includes(item.id));
4000
- if (matched) return matched.caseIds;
4001
- }
4002
- return [];
4003
- };
4004
- const metadataCaseIds = (testResult)=>{
4005
- const value = testResult.meta?.[RSTEST_YAML_CASE_IDS_META_KEY];
4006
- return Array.isArray(value) ? value.filter((item)=>'string' == typeof item) : [];
4007
- };
4008
- for (const file of result.results){
4009
- const moduleCaseIds = findModuleCaseIds(file);
4010
- for (const error of file.errors ?? [])addCases(moduleCaseIds, rstest_runner_errorMessage(error));
4011
- for (const testResult of file.results ?? []){
4012
- const caseIds = metadataCaseIds(testResult);
4013
- for (const error of testResult.errors ?? [])addCases(caseIds.length ? caseIds : moduleCaseIds, rstest_runner_errorMessage(error));
4014
- }
4015
- }
4016
- if (result.unhandledErrors.length) {
4017
- const message = rstest_runner_errorMessage(result.unhandledErrors[0]);
4018
- for (const item of project.cases)if (!errors.has(item.caseId) && !existsSync(item.resultFile)) errors.set(item.caseId, message);
4019
- }
4020
- return errors;
4021
- };
4022
- const writePendingCaseFailures = (project, caseErrors)=>{
4023
- for (const item of project.cases){
4024
- if (existsSync(item.resultFile)) continue;
4025
- const error = caseErrors.get(item.caseId);
4026
- if (!error) continue;
4027
- const failure = {
4028
- file: item.yamlFile,
4029
- success: false,
4030
- executed: true,
4031
- output: void 0,
4032
- report: void 0,
4033
- duration: 0,
4034
- resultType: 'failed',
4035
- error
4036
- };
4037
- mkdirSync(dirname(item.resultFile), {
4038
- recursive: true
4039
- });
4040
- writeFileSync(item.resultFile, JSON.stringify(failure, null, 2));
4041
- }
4042
- };
4043
- async function runRstestYamlProject(options) {
4044
- const [{ createRstest }, { rspack }] = await Promise.all([
4045
- import("@rstest/core/api"),
4046
- import(pathToFileURL(resolvePackageFromRstestCore('@rsbuild/core')).href)
4047
- ]);
4048
- const { project } = options;
4049
- const maxConcurrency = void 0 !== project.maxConcurrency ? Math.max(1, project.maxConcurrency) : void 0;
4050
- const config = {
4051
- root: project.projectDir,
4052
- include: project.modules.map((item)=>item.id),
4053
- testEnvironment: 'node',
4054
- testTimeout: project.testTimeout,
4055
- ...void 0 !== maxConcurrency ? {
4056
- maxConcurrency
4057
- } : {},
4058
- ...void 0 !== maxConcurrency ? {
4059
- pool: {
4060
- maxWorkers: maxConcurrency
4061
- }
4062
- } : {},
4063
- ...void 0 !== project.bail ? {
4064
- bail: project.bail
4065
- } : {},
4066
- ...void 0 !== project.retry && project.retry > 0 ? {
4067
- retry: project.retry
4068
- } : {},
4069
- reporters: 'pipe' === options.stdio ? [] : [
4070
- createYamlProgressReporter()
4071
- ],
4072
- tools: {
4073
- rspack: (_config, { appendPlugins })=>{
4074
- appendPlugins(new rspack.experiments.VirtualModulesPlugin(Object.fromEntries(project.modules.map((item)=>[
4075
- item.id,
4076
- item.source
4077
- ]))));
4078
- }
4079
- }
4080
- };
4081
- let result;
4082
- try {
4083
- const rstest = await createRstest({
4084
- cwd: options.cwd || project.projectDir,
4085
- config
4086
- });
4087
- result = await rstest.run();
4088
- } catch (error) {
4089
- const serialized = serializeError(error);
4090
- writePendingCaseFailures(project, new Map(project.cases.map((item)=>[
4091
- item.caseId,
4092
- serialized.message
4093
- ])));
4094
- if ('pipe' !== options.stdio) console.error(`\nYAML execution failed:\n${formatRunError(serialized)}`);
4095
- return 1;
4096
- }
4097
- const ok = 'pass' === result.status;
4098
- if (!ok) {
4099
- writePendingCaseFailures(project, mapRunErrorsToCases(project, result));
4100
- if ('pipe' !== options.stdio) {
4101
- const runErrors = collectRunErrors(result);
4102
- if (runErrors.length) console.error(`\nYAML execution failed:\n${runErrors.join('\n\n')}`);
4103
- }
4104
- }
4105
- return ok ? 0 : 1;
4106
- }
4107
- const defaultInProcessRunner = (config)=>new BatchRunner(config).run();
4108
- async function runConfigInMainProcess(config, commandOptions) {
4109
- const runner = commandOptions.inProcessRunner ?? defaultInProcessRunner;
4110
- const results = await runner(config);
4111
- const success = printExecutionSummary(results, getSummaryAbsolutePath(config.summary));
4112
- return success ? 0 : 1;
4113
- }
4114
- const createCaseOptions = (config)=>{
4115
- const caseOptions = {};
4116
- for (const file of config.files)caseOptions[external_node_path_resolve(file)] = {
4117
- globalConfig: config.globalConfig
4118
- };
4119
- return caseOptions;
4120
- };
4121
- const createWebRuntimeOptions = (config, runtimeOptions)=>{
4122
- const caseOptions = {};
4123
- for (const file of config.files)caseOptions[external_node_path_resolve(file)] = {
4124
- headed: runtimeOptions.headed ?? config.headed,
4125
- keepWindow: runtimeOptions.keepWindow ?? config.keepWindow
4126
- };
4127
- return caseOptions;
4128
- };
4129
- const readProjectResults = (project)=>project.cases.map((item)=>{
4130
- if (existsSync(item.resultFile)) return JSON.parse(readFileSync(item.resultFile, 'utf8'));
4131
- return createNotExecutedYamlResult(item.yamlFile);
4132
- });
4133
- async function runFrameworkTestConfig(config, commandOptions = {}) {
4134
- if (config.keepWindow) return runConfigInMainProcess(config, commandOptions);
4135
- printExecutionPlan(config);
4136
- const projectDir = external_node_path_resolve(commandOptions.projectDir || process.cwd());
4137
- const project = createRstestYamlProject({
4138
- files: config.files,
4139
- projectDir,
4140
- outputDir: commandOptions.outputDir,
4141
- frameworkImport: commandOptions.frameworkImport,
4142
- caseOptions: createCaseOptions(config),
4143
- webRuntimeOptions: createWebRuntimeOptions(config, commandOptions),
4144
- maxConcurrency: commandOptions.concurrent ?? config.concurrent,
4145
- bail: config.continueOnError ? 0 : 1,
4146
- retry: config.retry,
4147
- batchConfig: config.shareBrowserContext || config.setup ? config : void 0
4148
- });
4149
- const runner = commandOptions.rstestRunner || runRstestYamlProject;
4150
- const exitCode = await runner({
4151
- project,
4152
- cwd: projectDir,
4153
- stdio: commandOptions.stdio
4154
- });
4155
- const results = readProjectResults(project);
4156
- const summaryPath = writeExecutionSummaryFile(config.summary, results);
4157
- printExecutionFinished();
4158
- const success = printExecutionSummary(results, summaryPath);
4159
- return success ? exitCode : 1;
4160
- }
4161
- const writeResultFile = (resultFile, data)=>{
4162
- mkdirSync(dirname(resultFile), {
4163
- recursive: true
4164
- });
4165
- writeFileSync(resultFile, JSON.stringify(data, null, 2));
4166
- };
4167
- const batchFailureMessage = (results)=>{
4168
- const failed = results.filter((result)=>!result.success);
4169
- return failed.map((result)=>`${result.file}: ${result.error || result.resultType}`).join('\n');
4170
- };
4171
- async function runYamlBatchInRstest(options) {
4172
- const resultTargetsByCaseId = new Map();
4173
- for (const target of options.resultTargets){
4174
- if (resultTargetsByCaseId.has(target.caseId)) throw new Error(`Duplicate batch result target case ID: ${target.caseId}`);
4175
- resultTargetsByCaseId.set(target.caseId, target);
4176
- }
4177
- let executionError;
4178
- let occurrenceResults;
4179
- try {
4180
- occurrenceResults = await runYamlBatchWithCaseIds(options.config, options.resultTargets.map(({ caseId })=>caseId), {
4181
- generateSummary: false,
4182
- printExecutionPlan: false,
4183
- onProgress: emitYamlProgress
4184
- });
4185
- } catch (error) {
4186
- if (!isYamlBatchExecutionError(error)) throw error;
4187
- executionError = error;
4188
- occurrenceResults = error.occurrences;
4189
- }
4190
- const unmappedResults = [];
4191
- for (const { caseId, result } of occurrenceResults){
4192
- const target = resultTargetsByCaseId.get(caseId);
4193
- if (!target || external_node_path_resolve(target.yamlFile) !== external_node_path_resolve(result.file)) {
4194
- unmappedResults.push(caseId);
4195
- continue;
4196
- }
4197
- writeResultFile(target.resultFile, result);
4198
- resultTargetsByCaseId.delete(caseId);
4199
- }
4200
- if (executionError) throw executionError;
4201
- const unwrittenTargets = Array.from(resultTargetsByCaseId.keys());
4202
- if (unmappedResults.length || unwrittenTargets.length) throw new Error(`Batch result mapping mismatch: ${unmappedResults.length} result(s) had no target and ${unwrittenTargets.length} target(s) had no result`);
4203
- const results = occurrenceResults.map(({ result })=>result);
4204
- if (results.some((result)=>!result.success)) throw new Error(batchFailureMessage(results));
4205
- return results;
4206
- }
4207
- const taskErrorMessage = (task)=>{
4208
- if (task.error?.message) return task.error.message;
4209
- if ('error' === task.status) return `Task "${task.name}" failed`;
4210
- };
4211
- const cloneJson = (value)=>JSON.parse(JSON.stringify(value));
4212
- const yaml_case_errorMessageOf = (error)=>error instanceof Error ? error.message : String(error);
4213
- const normalizeTargetConfig = (config)=>{
4214
- if (config.target) {
4215
- config.web = {
4216
- ...config.target,
4217
- ...config.web
4218
- };
4219
- config.target = void 0;
4220
- }
4221
- };
4222
- const createExecutionConfig = (file, globalConfig)=>{
4223
- const content = readFileSync(file, 'utf8');
4224
- const fileConfig = cloneJson(parseYamlScript(content, file));
4225
- normalizeTargetConfig(fileConfig);
4226
- const clonedGlobalConfig = cloneJson(globalConfig);
4227
- normalizeTargetConfig(clonedGlobalConfig);
4228
- return lodash_merge(fileConfig, clonedGlobalConfig);
4229
- };
4230
- const getYamlPlayerFailure = (player)=>{
4231
- if (player.errorInSetup) return player.errorInSetup;
4232
- const failedMessages = player.taskStatusList?.map(taskErrorMessage).filter(Boolean) || [];
4233
- if ('error' === player.status || failedMessages.length > 0) {
4234
- const details = failedMessages.length ? failedMessages.join('; ') : 'YAML case failed';
4235
- const reportLine = player.reportFile ? `\nReport: ${player.reportFile}` : '';
4236
- const outputLine = player.output ? `\nOutput: ${player.output}` : '';
4237
- return new Error(`${details}${reportLine}${outputLine}`);
4238
- }
4239
- };
4240
- const createYamlCaseResult = (file, player, duration)=>{
4241
- const hasFailedTasks = player.taskStatusList?.some((task)=>'error' === task.status) ?? false;
4242
- const hasPlayerError = 'error' === player.status;
4243
- const outputPath = player.output && existsSync(player.output) ? player.output : void 0;
4244
- const reportFile = player.reportFile || void 0;
4245
- let errorMessage;
4246
- if (player.errorInSetup?.message) errorMessage = player.errorInSetup.message;
4247
- else if (hasPlayerError || hasFailedTasks) {
4248
- const taskErrors = player.taskStatusList?.filter((task)=>'error' === task.status && task.error?.message).map((task)=>task.error.message);
4249
- errorMessage = taskErrors && taskErrors.length > 0 ? taskErrors.join('; ') : hasPlayerError ? 'Execution failed' : 'Some tasks failed';
4250
- }
4251
- const resultType = hasPlayerError ? 'failed' : hasFailedTasks ? 'partialFailed' : 'success';
4252
- return {
4253
- file,
4254
- success: 'success' === resultType,
4255
- executed: true,
4256
- output: outputPath,
4257
- report: reportFile,
4258
- duration,
4259
- resultType,
4260
- error: errorMessage
4261
- };
4262
- };
4263
- const createYamlCaseFailure = (result)=>{
4264
- const reportLine = result.report ? `\nReport: ${result.report}` : '';
4265
- const outputLine = result.output ? `\nOutput: ${result.output}` : '';
4266
- return new Error(`${result.error || 'YAML case failed'}${reportLine}${outputLine}`);
4267
- };
4268
- const executeYamlCaseResult = async (options, onPlayerSnapshot)=>{
4269
- const file = external_node_path_resolve(options.file);
4270
- const startTime = Date.now();
4271
- const executionConfig = options.executionConfig || (options.globalConfig ? createExecutionConfig(file, options.globalConfig) : void 0);
4272
- const player = await createYamlPlayer(file, executionConfig, {
4273
- headed: options.headed,
4274
- keepWindow: options.keepWindow
4275
- });
4276
- const reportSnapshot = ()=>{
4277
- onPlayerSnapshot?.({
4278
- file,
4279
- player
4280
- });
4281
- };
4282
- reportSnapshot();
4283
- let runError;
4284
- try {
4285
- await player.run();
4286
- } catch (error) {
4287
- runError = error;
4288
- } finally{
4289
- reportSnapshot();
4290
- }
4291
- const result = createYamlCaseResult(file, player, Date.now() - startTime);
4292
- if (void 0 === runError) return result;
4293
- return {
4294
- ...result,
4295
- success: false,
4296
- resultType: 'failed',
4297
- error: result.error ?? yaml_case_errorMessageOf(runError)
4298
- };
4299
- };
4300
- function runYamlCaseResultWithSnapshots(options, onPlayerSnapshot) {
4301
- return executeYamlCaseResult(options, onPlayerSnapshot);
4302
- }
4303
- function runYamlCaseResult(options) {
4304
- return executeYamlCaseResult(options);
4305
- }
4306
- async function runYamlCase(options) {
4307
- const result = await runYamlCaseResult(options);
4308
- if (!result.success) throw createYamlCaseFailure(result);
4309
- return {
4310
- file: result.file,
4311
- output: result.output || void 0,
4312
- report: result.report,
4313
- duration: result.duration || 0
4314
- };
4315
- }
4316
- const rstest_entry_errorMessageOf = (error)=>error instanceof Error ? error.message : String(error);
4317
- const rstest_entry_writeResultFile = (resultFile, data)=>{
4318
- mkdirSync(dirname(resultFile), {
4319
- recursive: true
4320
- });
4321
- writeFileSync(resultFile, JSON.stringify(data, null, 2));
4322
- };
4323
- const attemptHistoryFileFor = (resultFile)=>`${resultFile}.attempts.json`;
4324
- const readAttemptHistory = (resultFile)=>{
4325
- const attemptHistoryFile = attemptHistoryFileFor(resultFile);
4326
- if (!existsSync(attemptHistoryFile)) return [];
4327
- return JSON.parse(readFileSync(attemptHistoryFile, 'utf8'));
4328
- };
4329
- const appendAttemptHistory = (resultFile, result, attempts)=>{
4330
- const nextAttempts = [
4331
- ...attempts,
4332
- createYamlAttempt(result, attempts.length + 1)
4333
- ];
4334
- mkdirSync(dirname(resultFile), {
4335
- recursive: true
4336
- });
4337
- writeFileSync(attemptHistoryFileFor(resultFile), JSON.stringify(nextAttempts, null, 2));
4338
- return {
4339
- ...result,
4340
- duration: getYamlAttemptsDuration(nextAttempts),
4341
- attempts: nextAttempts
4342
- };
4343
- };
4344
- const hasExplicitReportFileName = (file, caseOptions)=>{
4345
- if (caseOptions?.executionConfig) return Boolean(caseOptions.executionConfig.agent?.reportFileName);
4346
- const script = parseYamlScript(readFileSync(file, 'utf8'), file);
4347
- return Boolean(script.agent?.reportFileName);
4348
- };
4349
- const prepareAttemptHistory = (resultFile, attempts, preserveReport)=>{
4350
- if (!preserveReport || 0 === attempts.length) return attempts;
4351
- const nextAttempts = [
4352
- ...attempts
4353
- ];
4354
- nextAttempts[nextAttempts.length - 1] = preserveYamlAttemptReport(nextAttempts[nextAttempts.length - 1]);
4355
- writeFileSync(attemptHistoryFileFor(resultFile), JSON.stringify(nextAttempts, null, 2));
4356
- return nextAttempts;
4357
- };
4358
- const createRuntimeFailureResult = (file, startTime, error)=>({
4359
- file,
4360
- success: false,
4361
- executed: true,
4362
- duration: Date.now() - startTime,
4363
- resultType: 'failed',
4364
- error: rstest_entry_errorMessageOf(error)
4365
- });
4366
- const createYamlPlayerProgressReporter = (attempt, totalAttempts)=>({ file, player })=>{
4367
- const summary = contextTaskListSummary(player.taskStatusList, {
4368
- file,
4369
- player
4370
- });
4371
- emitYamlProgress(formatYamlProgressSnapshot(summary, attempt, totalAttempts));
4372
- };
4373
- const defineYamlCaseTest = (test, options)=>{
4374
- test(options.testName, {
4375
- meta: {
4376
- [RSTEST_YAML_CASE_IDS_META_KEY]: [
4377
- options.caseId
4378
- ]
4379
- }
4380
- }, async ()=>{
4381
- const file = external_node_path_resolve(options.yamlFile);
4382
- const startTime = Date.now();
4383
- let attempts = readAttemptHistory(options.resultFile);
4384
- const attempt = attempts.length + 1;
4385
- const totalAttempts = resolveYamlMaxAttempts(options.retry);
4386
- let result;
4387
- try {
4388
- if (attempt > 1) attempts = prepareAttemptHistory(options.resultFile, attempts, hasExplicitReportFileName(file, options.caseOptions));
4389
- result = await runYamlCaseResultWithSnapshots({
4390
- ...options.caseOptions,
4391
- ...options.webRuntimeOptions,
4392
- file
4393
- }, createYamlPlayerProgressReporter(attempt, totalAttempts));
4394
- result = appendAttemptHistory(options.resultFile, result, attempts);
4395
- rstest_entry_writeResultFile(options.resultFile, result);
4396
- if (!result.success) throw createYamlCaseFailure(result);
4397
- } catch (error) {
4398
- if (!result) {
4399
- const failureResult = appendAttemptHistory(options.resultFile, createRuntimeFailureResult(file, startTime, error), attempts);
4400
- rstest_entry_writeResultFile(options.resultFile, failureResult);
4401
- }
4402
- throw error;
4403
- }
4404
- });
4405
- };
4406
- const defineYamlBatchTest = (test, options)=>{
4407
- test(options.testName, {
4408
- meta: {
4409
- [RSTEST_YAML_CASE_IDS_META_KEY]: options.caseIds
4410
- }
4411
- }, async ()=>{
4412
- await runYamlBatchInRstest({
4413
- config: options.config,
4414
- resultTargets: options.resultTargets
4415
- });
4416
- });
4417
- };
4418
- export { createRstestYamlProject, createYamlCaseFailure, createYamlCaseResult, defineYamlBatchTest, defineYamlCaseTest, getYamlPlayerFailure, resolveRstestCoreImportPath, resolveTestName, runFrameworkTestConfig, runRstestYamlProject, runYamlBatchInRstest, runYamlCase, runYamlCaseResult };
4419
-
4420
- //# sourceMappingURL=index.mjs.map
1
+ export { createRstestYamlProject, createYamlCaseFailure, createYamlCaseResult, defineYamlBatchTest, defineYamlCaseTest, getYamlPlayerFailure, resolveRstestCoreImportPath, resolveTestName, runFrameworkTestConfig, runRstestYamlProject, runYamlBatchInRstest, runYamlCase, runYamlCaseResult } from "../998.mjs";