-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
3267 lines (3189 loc) · 95.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cypress_cloud_exports = {};
__export(cypress_cloud_exports, {
run: () => run2
});
module.exports = __toCommonJS(cypress_cloud_exports);
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = getImportMetaUrl();
var import_register = require("source-map-support/register.js");
var import_module = require("module");
var require2 = (0, import_module.createRequire)(importMetaUrl);
var import_child_process = __toESM(require("child_process"));
var orginal = import_child_process.default.spawn;
import_child_process.default.spawn = function(command, args, options) {
if (command.match(/Cypress/)) {
const process2 = orginal(command, args, {
...options,
stdio: ["pipe", "pipe", "pipe"]
});
return process2;
}
return orginal(command, args, options);
};
var import_debug = __toESM(require("debug"));
var import_http = __toESM(require("http"));
var import_lil_http_terminator = __toESM(require("lil-http-terminator"));
var import_ts_pattern = require("ts-pattern");
var WebSocket = __toESM(require("ws"));
var Event = ((Event2) => {
Event2["RUN_CANCELLED"] = "run:cancelled";
Event2["RUN_RESULT"] = "run:result";
Event2["TEST_AFTER_RUN"] = "test:after:run";
Event2["TEST_BEFORE_RUN"] = "test:before:run";
Event2["AFTER_SCREENSHOT"] = "after:screenshot";
Event2["AFTER_SPEC"] = "after:spec";
return Event2;
})(Event || {});
var allEvents = Object.values(Event);
var import_events = __toESM(require("events"));
var _pubsub = null;
var getPubSub = () => {
if (!_pubsub) {
_pubsub = new import_events.default();
}
return _pubsub;
};
var debug = (0, import_debug.default)("cc:ws");
var server = null;
var wss = null;
var httpTerminator = null;
var getWSSPort = () => (0, import_ts_pattern.match)(server?.address()).with({ port: import_ts_pattern.P.number }, (address) => address.port).otherwise(() => 0);
var stopWSS = async () => {
debug("terminating wss server: %d", getWSSPort());
if (!httpTerminator) {
debug("no wss server");
return;
}
const { success, code, message, error: error2 } = await httpTerminator.terminate();
if (!success) {
if (code === "TIMED_OUT")
error2(message);
if (code === "SERVER_ERROR")
error2(message, error2);
if (code === "INTERNAL_ERROR")
error2(message, error2);
}
debug("terminated wss server: %d", getWSSPort());
};
var startWSS = () => {
if (wss) {
return;
}
server = import_http.default.createServer().on("listening", () => {
if (!server) {
throw new Error("Server not initialized");
}
wss = new WebSocket.WebSocketServer({
server
});
debug("starting wss on port %d", getWSSPort());
wss.on("connection", function connection(ws) {
ws.on("message", function incoming(event) {
const message = JSON.parse(event.toString());
getPubSub().emit(message.type, message.payload);
});
});
}).listen();
httpTerminator = (0, import_lil_http_terminator.default)({
server
});
};
var import_debug2 = __toESM(require("debug"));
var debug2 = (0, import_debug2.default)("cc:capture");
var _write = process.stdout.write;
var _log = process.log;
var restore = function() {
process.stdout.write = _write;
process.log = _log;
};
var stdout = function() {
debug2("capturing stdout");
let logs = [];
const { write } = process.stdout;
const { log: log2 } = process;
if (log2) {
process.log = function(str) {
logs.push(str);
return log2.apply(this, arguments);
};
}
process.stdout.write = function(str) {
logs.push(str);
return write.apply(this, arguments);
};
return {
toString() {
return logs.join("");
},
data: logs,
restore,
reset: () => {
debug2("resetting captured stdout");
logs = [];
}
};
};
var initialOutput = "";
var capturedOutput = null;
var initCapture = () => capturedOutput = stdout();
var cutInitialOutput = () => {
if (!capturedOutput)
throw new Error("capturedOutput is null");
initialOutput = capturedOutput.toString();
capturedOutput.reset();
};
var resetCapture = () => {
if (!capturedOutput)
throw new Error("capturedOutput is null");
capturedOutput.reset();
};
var getCapturedOutput = () => {
if (!capturedOutput)
throw new Error("capturedOutput is null");
return capturedOutput.toString();
};
var getInitialOutput = () => initialOutput;
var _runId = void 0;
var setRunId = (runId) => {
_runId = runId;
};
var _cypressVersion = void 0;
var setCypressVersion = (cypressVersion) => {
_cypressVersion = cypressVersion;
};
var _ccVersion = void 0;
var setCcVersion = (v) => {
_ccVersion = v;
};
var cypressPkg = require2("cypress/package.json");
var pkg = require2("@krivega/cc/package.json");
initCapture();
setCypressVersion(cypressPkg.version);
setCcVersion(pkg.version);
var import_debug25 = __toESM(require("debug"));
function getLegalNotice() {
return `
Copyright (C) ${(/* @__PURE__ */ new Date()).getFullYear()} cc
`;
}
var import_axios = require("axios");
var isRetriableError = (err) => {
if (err.code === "ECONNABORTED") {
return true;
}
if (err.code === "ECONNREFUSED") {
return true;
}
if (err.code === "ETIMEDOUT") {
return true;
}
if (!(0, import_axios.isAxiosError)(err)) {
return false;
}
return !!(err?.response?.status && 500 <= err.response.status && err.response.status < 600);
};
var getDelay = (i) => [5 * 1e3, 10 * 1e3, 30 * 1e3][i - 1];
var baseURL = "set baseURL";
var getAPIBaseUrl = () => baseURL ?? "set baseURL";
var setAPIBaseUrl = (url) => baseURL = url ?? "set baseURL";
var import_axios2 = __toESM(require("axios"));
var import_axios_retry = __toESM(require("axios-retry"));
var import_debug10 = __toESM(require("debug"));
var import_lodash5 = __toESM(require("lodash"));
var import_pretty_ms = __toESM(require("pretty-ms"));
var import_debug7 = __toESM(require("debug"));
var import_ts_pattern3 = require("ts-pattern");
var import_cy2 = require("cy2");
var import_debug6 = __toESM(require("debug"));
var import_execa = __toESM(require("execa"));
var import_fs = __toESM(require("fs"));
var ValidationError = class extends Error {
constructor(message) {
super(message);
this.name = "";
}
};
var import_tmp_promise = require("tmp-promise");
var createTempFile = async () => {
const { path: path5 } = await (0, import_tmp_promise.file)();
return path5;
};
var import_chalk = __toESM(require("chalk"));
var import_util = __toESM(require("util"));
var log = (...args) => console.log(import_util.default.format(...args));
var info = log;
var format = import_util.default.format;
var withError = (msg) => import_chalk.default.bgRed.white(" ERROR ") + " " + msg;
var withWarning = (msg) => import_chalk.default.bgYellow.black(" WARNING ") + " " + msg;
var warn = (...args) => log(withWarning(import_util.default.format(...args)));
var error = (...args) => log(withError(import_util.default.format(...args)) + "\n");
var title = (color, ...args) => info("\n " + import_chalk.default[color].bold(import_util.default.format(...args)) + " \n");
var divider = () => console.log("\n" + import_chalk.default.gray(Array(100).fill("=").join("")) + "\n");
var spacer = (n = 0) => console.log(Array(n).fill("").join("\n"));
var cyan = import_chalk.default.cyan;
var blue = import_chalk.default.blueBright;
var red = import_chalk.default.red;
var green = import_chalk.default.greenBright;
var gray = import_chalk.default.gray;
var white = import_chalk.default.white;
var magenta = import_chalk.default.magenta;
var bold = import_chalk.default.bold;
var dim = import_chalk.default.dim;
var import_debug4 = __toESM(require("debug"));
var import_lodash = __toESM(require("lodash"));
var import_debug3 = __toESM(require("debug"));
var import_ts_pattern2 = require("ts-pattern");
function shouldEnablePluginDebug(param) {
return (0, import_ts_pattern2.match)(param).with(import_ts_pattern2.P.nullish, () => false).with("none", () => false).with(true, () => true).with("all", () => true).with("cc", () => true).with(
import_ts_pattern2.P.array(import_ts_pattern2.P.string),
(v) => v.includes("all") || v.includes("cc")
).otherwise(() => false);
}
function activateDebug(mode) {
(0, import_ts_pattern2.match)(mode).with(import_ts_pattern2.P.instanceOf(Array), (i) => i.forEach(setDebugMode)).with(true, () => setDebugMode("all")).with(
import_ts_pattern2.P.union(
"all",
"cc",
"cypress",
"commit-info"
),
(i) => setDebugMode(i)
).otherwise(() => setDebugMode("none"));
}
function setDebugMode(mode) {
if (mode === "none") {
return;
}
const tokens = new Set(process.env.DEBUG ? process.env.DEBUG.split(",") : []);
(0, import_ts_pattern2.match)(mode).with("all", () => {
tokens.add("commit-info");
tokens.add("cc:*");
tokens.add("cypress:*");
}).with("cc", () => tokens.add("cc:*")).with("cypress", () => tokens.add("cypress:*")).with("commit-info", () => tokens.add("commit-info")).otherwise(() => {
});
import_debug3.default.enable(Array.from(tokens).join(","));
}
var import_bluebird = __toESM(require("bluebird"));
import_bluebird.default.Promise.config({
cancellation: true
});
var BPromise = import_bluebird.default.Promise;
var safe = (fn, ifFaled, ifSucceed) => async (...args) => {
try {
const r = await fn(...args);
ifSucceed();
return r;
} catch (e) {
return ifFaled(e);
}
};
var sortObjectKeys = (obj) => {
return Object.keys(obj).sort().reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
};
var import_nanoid = require("nanoid");
var getRandomString = (0, import_nanoid.customAlphabet)("abcdefghijklmnopqrstuvwxyz", 10);
var debug4 = (0, import_debug4.default)("cc:boot");
function getBootstrapArgs({
params,
tempFilePath
}) {
return import_lodash.default.chain(getCypressCLIParams(params)).thru((opts) => ({
...opts,
env: {
...opts.env ?? {},
cc_marker: true,
cc_temp_file: tempFilePath,
cc_debug_enabled: shouldEnablePluginDebug(params.cloudDebug)
}
})).tap((opts) => {
debug4("cypress bootstrap params: %o", opts);
}).thru((opts) => ({
...opts,
env: sortObjectKeys(opts.env ?? {})
})).thru(serializeOptions).tap((opts) => {
debug4("cypress bootstrap serialized params: %o", opts);
}).thru((args) => {
return [
...args,
"--spec",
getRandomString(),
params.testingType === "component" ? "--component" : "--e2e"
];
}).value();
}
function getCypressCLIParams(params) {
const result = getCypressRunAPIParams(params);
const testingType = result.testingType === "component" ? {
component: true
} : {};
return {
...import_lodash.default.omit(result, "testingType"),
...testingType
};
}
function serializeOptions(options) {
return Object.entries(options).flatMap(([key, value]) => {
const _key = dashed(key);
if (typeof value === "boolean") {
return value === true ? [`--${_key}`] : [`--${_key}`, false];
}
if (import_lodash.default.isObject(value)) {
return [`--${_key}`, serializeComplexParam(value)];
}
return [`--${_key}`, value.toString()];
});
}
function serializeComplexParam(param) {
return JSON.stringify(param);
}
var dashed = (v) => v.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
var debug5 = (0, import_debug6.default)("cc:boot");
var bootCypress = async (params) => {
debug5("booting cypress...");
const tempFilePath = await createTempFile();
const cypressBin = await (0, import_cy2.getBinPath)(require2.resolve("cypress"));
debug5("cypress executable location: %s", cypressBin);
const args = getBootstrapArgs({ tempFilePath, params });
debug5("booting cypress with args: %o", args);
const { stdout: stdout2, stderr } = await execCypress(cypressBin, args);
if (!import_fs.default.existsSync(tempFilePath)) {
throw new Error(
`Cannot resolve cypress configuration from ${tempFilePath}. Please report the issue.`
);
}
try {
const f = import_fs.default.readFileSync(tempFilePath, "utf-8");
if (!f) {
throw new Error("Is @krivega/cc/plugin installed?");
}
debug5("cypress config '%s': '%s'", tempFilePath, f);
return JSON.parse(f);
} catch (err) {
debug5("read config temp file failed: %o", err);
info(bold("Cypress stdout:\n"), stdout2);
info(bold("Cypress stderr:\n"), stderr);
throw new ValidationError(`Unable to resolve cypress configuration
- make sure that '@krivega/cc/plugin' is installed
- report the issue together with cypress stdout and stderr
`);
}
};
async function execCypress(cypressBin, args) {
let stdout2 = "";
let stderr = "";
try {
await (0, import_execa.default)(cypressBin, ["run", ...args], {
stdio: "pipe",
env: {
...process.env,
CYPRESS_RECORD_KEY: void 0,
CYPRESS_PROJECT_ID: void 0
}
});
} catch (err) {
debug5("exec cypress failed (certain failures are expected): %o", err);
stdout2 = err.stdout;
stderr = err.stderr;
}
return { stdout: stdout2, stderr };
}
var import_is_absolute = __toESM(require("is-absolute"));
var import_lodash2 = __toESM(require("lodash"));
var import_path = __toESM(require("path"));
var defaultFilenames = [
"cc.config.js",
"cc.config.cjs",
"cc.config.mjs"
];
function getConfigFilePath(projectRoot = null, explicitConfigFilePath) {
const prefix = projectRoot ?? process.cwd();
if (import_lodash2.default.isString(explicitConfigFilePath) && (0, import_is_absolute.default)(explicitConfigFilePath)) {
return [explicitConfigFilePath];
}
if (import_lodash2.default.isString(explicitConfigFilePath)) {
return [normalizePath(prefix, explicitConfigFilePath)];
}
return defaultFilenames.map((p) => normalizePath(prefix, p));
}
function normalizePath(prefix, filename) {
return `file://${import_path.default.resolve(prefix, filename)}`;
}
var debug6 = (0, import_debug7.default)("cc:config");
var _config = null;
var defaultConfig = {
e2e: {
batchSize: 3
},
component: {
batchSize: 5
},
cloudServiceUrl: "set baseURL",
networkHeaders: void 0
};
async function getCcConfig(projectRoot, explicitConfigFilePath) {
if (_config) {
return _config;
}
const configFilePath = getConfigFilePath(projectRoot, explicitConfigFilePath);
for (const filepath of configFilePath) {
const config = (0, import_ts_pattern3.match)(await loadConfigFile(filepath)).with({ default: import_ts_pattern3.P.not(import_ts_pattern3.P.nullish) }, (c) => c.default).with(import_ts_pattern3.P.not(import_ts_pattern3.P.nullish), (c) => c).otherwise(() => null);
if (config) {
debug6("loaded cc config from '%s'\n%O", filepath, config);
info(`Using config file: ${dim(filepath)}`);
_config = {
...defaultConfig,
...config
};
return _config;
}
}
warn(
"Failed to load config file, falling back to the default config. Attempted locations: %s",
configFilePath
);
_config = defaultConfig;
return _config;
}
async function loadConfigFile(filepath) {
try {
debug6("loading cc config file from '%s'", filepath);
return await import(filepath);
} catch (e) {
debug6("failed loading config file from: %s", e);
return null;
}
}
async function getMergedConfig(params) {
debug6("resolving cypress config");
const cypressResolvedConfig = await bootCypress(params);
debug6("cypress resolvedConfig: %O", cypressResolvedConfig);
const rawE2EPattern = cypressResolvedConfig.rawJson?.e2e?.specPattern;
let additionalIgnorePattern = [];
if (params.testingType === "component" && rawE2EPattern) {
additionalIgnorePattern = rawE2EPattern;
}
const result = {
projectRoot: cypressResolvedConfig?.projectRoot || process.cwd(),
projectId: params.projectId,
specPattern: cypressResolvedConfig?.specPattern || "**/*.*",
excludeSpecPattern: (
cypressResolvedConfig?.resolved.excludeSpecPattern.value ?? []
),
additionalIgnorePattern,
resolved: cypressResolvedConfig,
experimentalCoverageRecording: params.experimentalCoverageRecording
};
debug6("merged config: %O", result);
return result;
}
var import_debug8 = __toESM(require("debug"));
var import_lodash3 = __toESM(require("lodash"));
var debug7 = (0, import_debug8.default)("cc:validateParams");
async function resolveCcParams(params) {
const configFromFile = await getCcConfig(
params.project,
params.cloudConfigFile
);
debug7("resolving cc params: %o", params);
debug7("resolving cc config file: %o", configFromFile);
const cloudServiceUrl = params.cloudServiceUrl ?? process.env.CC_API_URL ?? configFromFile.cloudServiceUrl;
const recordKey = params.recordKey ?? process.env.CC_RECORD_KEY ?? configFromFile.recordKey;
const projectId = params.projectId ?? process.env.CC_PROJECT_ID ?? configFromFile.projectId;
const testingType = params.testingType ?? "e2e";
let batchSize = params.batchSize;
if (!batchSize) {
batchSize = testingType === "e2e" ? configFromFile.e2e.batchSize : configFromFile.component.batchSize;
}
return {
...params,
cloudServiceUrl,
recordKey,
projectId,
batchSize,
testingType
};
}
var projectIdError = `Cannot resolve projectId. Please use one of the following:
- provide it as a "projectId" property for "run" API method
- set CC_PROJECT_ID environment variable
- set "projectId" in "cc.config.{c}js" file`;
var cloudServiceUrlError = `Cannot resolve cloud service URL. Please use one of the following:
- provide it as a "cloudServiceUrl" property for "run" API method
- set CC_API_URL environment variable
- set "cloudServiceUrl" in "cc.config.{c}js" file`;
var cloudServiceInvalidUrlError = `Invalid cloud service URL provided`;
var recordKeyError = `Cannot resolve record key. Please use one of the following:
- pass it as a CLI flag '-k, --key <record-key>'
- provide it as a "recordKey" property for "run" API method
- set CC_RECORD_KEY environment variable
- set "recordKey" in "cc.config.{c}js" file
`;
async function validateParams(_params) {
const params = await resolveCcParams(_params);
debug7("validating cc params: %o", params);
if (!params.cloudServiceUrl) {
throw new ValidationError(cloudServiceUrlError);
}
if (!params.projectId) {
throw new ValidationError(projectIdError);
}
if (!params.recordKey) {
throw new ValidationError(recordKeyError);
}
validateURL(params.cloudServiceUrl);
const requiredParameters = [
"testingType",
"batchSize",
"projectId"
];
requiredParameters.forEach((key) => {
if (typeof params[key] === "undefined") {
error('Missing required parameter "%s"', key);
throw new Error("Missing required parameter");
}
});
params.tag = parseTags(params.tag);
params.autoCancelAfterFailures = getAutoCancelValue(
params.autoCancelAfterFailures
);
debug7("validated cc params: %o", params);
return params;
}
function getAutoCancelValue(value) {
if (typeof value === "undefined") {
return void 0;
}
if (typeof value === "boolean") {
return value ? 1 : false;
}
if (typeof value === "number" && value > 0) {
return value;
}
throw new ValidationError(
`autoCancelAfterFailures: should be a positive integer or "false". Got: "${value}"`
);
}
function isOffline(params) {
return params.record === false;
}
function parseTags(tagString) {
if (!tagString) {
return [];
}
if (Array.isArray(tagString)) {
return tagString.filter(Boolean);
}
return tagString.split(",").map((tag) => tag.trim()).filter(Boolean);
}
function validateURL(url) {
try {
new URL(url);
} catch (err) {
throw new ValidationError(`${cloudServiceInvalidUrlError}: "${url}"`);
}
}
function getCypressRunAPIParams(params) {
return {
...import_lodash3.default.pickBy(
import_lodash3.default.omit(params, [
"cloudDebug",
"cloudConfigFile",
"autoCancelAfterFailures",
"cloudServiceUrl",
"batchSize",
"projectId",
"key",
"recordKey",
"record",
"group",
"parallel",
"tag",
"ciBuildId",
"spec",
"exit",
"headless",
"experimentalCoverageRecording"
]),
Boolean
),
record: false,
env: {
...params.env,
cc_debug_enabled: shouldEnablePluginDebug(params.cloudDebug)
}
};
}
function preprocessParams(params) {
return {
...params,
spec: processSpecParam(params.spec)
};
}
function processSpecParam(spec) {
if (!spec) {
return void 0;
}
if (Array.isArray(spec)) {
return import_lodash3.default.flatten(spec.map((i) => i.split(",")));
}
return spec.split(",");
}
var import_lodash4 = __toESM(require("lodash"));
function maybePrintErrors(err) {
if (!err.response?.data || !err.response?.status) {
return;
}
const { message, errors } = err.response.data;
switch (err.response.status) {
case 401:
warn("Received 401 Unauthorized");
break;
case 422:
spacer(1);
warn(...formatGenericError(message, errors));
spacer(1);
break;
default:
break;
}
}
function formatGenericError(message, errors) {
if (!import_lodash4.default.isString(message)) {
return ["Unexpected error from the cloud service"];
}
if (errors?.length === 0) {
return [message];
}
return [
message,
`
${(errors ?? []).map((e) => ` - ${e}`).join("\n")}
`
];
}
var debug8 = (0, import_debug10.default)("cc:api");
var MAX_RETRIES = 3;
var TIMEOUT_MS = 30 * 1e3;
var _client = null;
async function getClient() {
if (_client) {
return _client;
}
const ccConfig = await getCcConfig();
_client = import_axios2.default.create({
baseURL: getAPIBaseUrl(),
timeout: TIMEOUT_MS
});
_client.interceptors.request.use((config) => {
const ccyVerson = _ccVersion ?? "0.0.0";
const headers = {
...config.headers,
"x-cypress-request-attempt": config["axios-retry"]?.retryCount ?? 0,
"x-cypress-version": _cypressVersion ?? "0.0.0",
"x-ccy-version": ccyVerson,
"User-Agent": `@krivega/cc/${ccyVerson}`
};
if (_runId) {
headers["x-cypress-run-id"] = _runId;
}
if (!headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
if (ccConfig.networkHeaders) {
const filteredHeaders = import_lodash5.default.omit(ccConfig.networkHeaders, [
"x-cypress-request-attempt",
"x-cypress-version",
"x-ccy-version",
"x-cypress-run-id",
"Content-Type"
]);
debug8("using custom network headers: %o", filteredHeaders);
Object.assign(headers, filteredHeaders);
}
const req = {
...config,
headers
};
debug8("network request: %o", {
...import_lodash5.default.pick(req, "method", "url", "headers"),
data: Buffer.isBuffer(req.data) ? "buffer" : req.data
});
return req;
});
(0, import_axios_retry.default)(_client, {
retries: MAX_RETRIES,
retryCondition: isRetriableError,
retryDelay: getDelay,
onRetry,
shouldResetTimeout: true
});
return _client;
}
function onRetry(retryCount, err, config) {
warn(
"Network request '%s' failed: '%s'. Next attempt is in %s (%d/%d).",
`${config.method} ${config.url}`,
err.message,
(0, import_pretty_ms.default)(getDelay(retryCount)),
retryCount,
MAX_RETRIES
);
}
var makeRequest = async (config) => {
return (await getClient())(config).then((res) => {
debug8("network response: %o", import_lodash5.default.omit(res, "request", "config"));
return res;
}).catch((error2) => {
maybePrintErrors(error2);
throw new ValidationError(error2.message);
});
};
var import_lodash6 = __toESM(require("lodash"));
function printWarnings(warnings) {
warn("Notice from cloud service:");
warnings.map((w) => {
spacer(1);
info(magenta.bold(w.message));
Object.entries(import_lodash6.default.omit(w, "message")).map(([key, value]) => {
info("- %s: %s", key, value);
});
spacer(1);
});
}
var createRun = async (payload) => {
const response = await makeRequest({
method: "POST",
url: "/runs",
data: payload
});
if ((response.data.warnings?.length ?? 0) > 0) {
printWarnings(response.data.warnings);
}
return response.data;
};
var createInstance = async ({
runId,
groupId,
machineId,
platform: platform2
}) => {
const response = await makeRequest({
method: "POST",
url: `runs/${runId}/instances`,
data: {
runId,
groupId,
machineId,
platform: platform2
}
});
return response.data;
};
var createBatchedInstances = async (data) => {
const respone = await makeRequest({
method: "POST",
url: `runs/${data.runId}/cy/instances`,
data
});
return respone.data;
};
var setInstanceTests = (instanceId, payload) => makeRequest({
method: "POST",
url: `instances/${instanceId}/tests`,
data: payload
}).then((result) => result.data);
var updateInstanceResults = (instanceId, payload) => makeRequest({
method: "POST",
url: `instances/${instanceId}/results`,
data: payload
}).then((result) => result.data);
var reportInstanceResultsMerged = (instanceId, payload) => makeRequest({
method: "POST",
url: `instances/${instanceId}/cy/results`,
data: payload
}).then((result) => result.data);
var updateInstanceStdout = (instanceId, stdout2) => makeRequest({
method: "PUT",
url: `instances/${instanceId}/stdout`,
data: {
stdout: stdout2
}
});
var import_debug11 = __toESM(require("debug"));
var import_lodash7 = __toESM(require("lodash"));
var debug9 = (0, import_debug11.default)("cc:ci");
var join = (char, ...pieces) => {
return import_lodash7.default.chain(pieces).compact().join(char).value();
};
var toCamelObject = (obj, key) => {
return import_lodash7.default.set(obj, import_lodash7.default.camelCase(key), process.env[key]);
};
var extract = (envKeys) => {
return import_lodash7.default.transform(envKeys, toCamelObject, {});
};
var isTeamFoundation = () => {
return process.env.TF_BUILD && process.env.TF_BUILD_BUILDNUMBER;
};
var isAzureCi = () => {
return process.env.TF_BUILD && process.env.AZURE_HTTP_USER_AGENT;
};
var isAWSCodeBuild = () => {
return import_lodash7.default.some(process.env, (val, key) => {
return /^CODEBUILD_/.test(key);
});
};
var isBamboo = () => {
return process.env.bamboo_buildNumber;
};
var isCodeshipBasic = () => {
return process.env.CI_NAME && process.env.CI_NAME === "codeship" && process.env.CODESHIP;
};
var isCodeshipPro = () => {
return process.env.CI_NAME && process.env.CI_NAME === "codeship" && !process.env.CODESHIP;
};
var isConcourse = () => {
return import_lodash7.default.some(process.env, (val, key) => {
return /^CONCOURSE_/.test(key);
});
};
var isGitlab = () => {
return process.env.GITLAB_CI || process.env.CI_SERVER_NAME && /^GitLab/.test(process.env.CI_SERVER_NAME);
};
var isGoogleCloud = () => {
return process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT;
};
var isJenkins = () => {
return process.env.JENKINS_URL || process.env.JENKINS_HOME || process.env.JENKINS_VERSION || process.env.HUDSON_URL || process.env.HUDSON_HOME;
};
var isWercker = () => {
return process.env.WERCKER || process.env.WERCKER_MAIN_PIPELINE_STARTED;
};
var CI_PROVIDERS = {
appveyor: "APPVEYOR",
azure: isAzureCi,
awsCodeBuild: isAWSCodeBuild,
bamboo: isBamboo,
bitbucket: "BITBUCKET_BUILD_NUMBER",
buildkite: "BUILDKITE",
circle: "CIRCLECI",
codeshipBasic: isCodeshipBasic,
codeshipPro: isCodeshipPro,
concourse: isConcourse,
codeFresh: "CF_BUILD_ID",
drone: "DRONE",
githubActions: "GITHUB_ACTIONS",
gitlab: isGitlab,
goCD: "GO_JOB_NAME",
googleCloud: isGoogleCloud,
jenkins: isJenkins,
semaphore: "SEMAPHORE",
shippable: "SHIPPABLE",
teamcity: "TEAMCITY_VERSION",
teamfoundation: isTeamFoundation,
travis: "TRAVIS",
wercker: isWercker,
netlify: "NETLIFY",
layerci: "LAYERCI"
};
function _detectProviderName() {
const { env } = process;
return import_lodash7.default.findKey(CI_PROVIDERS, (value) => {
if (import_lodash7.default.isString(value)) {
return env[value];
}
if (import_lodash7.default.isFunction(value)) {
return value();
}
});
}
var _providerCiParams = () => {
return {
appveyor: extract([
"APPVEYOR_JOB_ID",
"APPVEYOR_ACCOUNT_NAME",
"APPVEYOR_PROJECT_SLUG",
"APPVEYOR_BUILD_NUMBER",
"APPVEYOR_BUILD_VERSION",
"APPVEYOR_PULL_REQUEST_NUMBER",
"APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"
]),
azure: extract([
"BUILD_BUILDID",
"BUILD_BUILDNUMBER",
"BUILD_CONTAINERID",
"BUILD_REPOSITORY_URI"
]),
awsCodeBuild: extract([
"CODEBUILD_BUILD_ID",
"CODEBUILD_BUILD_NUMBER",
"CODEBUILD_RESOLVED_SOURCE_VERSION",
"CODEBUILD_SOURCE_REPO_URL",
"CODEBUILD_SOURCE_VERSION"
]),
bamboo: extract([
"bamboo_buildNumber",
"bamboo_buildResultsUrl",
"bamboo_planRepository_repositoryUrl",
"bamboo_buildKey"
]),
bitbucket: extract([
"BITBUCKET_REPO_SLUG",
"BITBUCKET_REPO_OWNER",
"BITBUCKET_BUILD_NUMBER",
"BITBUCKET_PARALLEL_STEP",
"BITBUCKET_STEP_RUN_NUMBER",
"BITBUCKET_PR_ID",
"BITBUCKET_PR_DESTINATION_BRANCH",
"BITBUCKET_PR_DESTINATION_COMMIT"