browserstack-cypress-cli 1.36.11 → 1.36.13

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.
@@ -4,7 +4,27 @@ const browserStackLog = (message) => {
4
4
  if (!Cypress.env('BROWSERSTACK_LOGS')) return;
5
5
  cy.task('browserstack_log', message);
6
6
  }
7
-
7
+
8
+ // Circuit breaker for a dead/unresponsive accessibility scanner.
9
+ // Each hung scan/save costs up to ACCESSIBILITY_SCAN_TIMEOUT (default 25s). Without a
10
+ // breaker, a scanner that never responds stalls EVERY test's afterEach (and every
11
+ // wrapped command) by that much. After N consecutive timeouts we stop attempting
12
+ // accessibility work for the remainder of this spec file (module state resets per spec).
13
+ let consecutiveA11yTimeouts = 0;
14
+ let a11yCircuitOpen = false;
15
+ let a11yCircuitLogged = false;
16
+ const getA11yCircuitLimit = () => parseInt(Cypress.env('ACCESSIBILITY_SCAN_CIRCUIT_LIMIT')) || 3;
17
+ const noteA11yTimeout = () => {
18
+ consecutiveA11yTimeouts += 1;
19
+ if (!a11yCircuitOpen && consecutiveA11yTimeouts >= getA11yCircuitLimit()) {
20
+ a11yCircuitOpen = true;
21
+ // eslint-disable-next-line no-console
22
+ console.warn('BrowserStack Accessibility: scanner did not respond ' + consecutiveA11yTimeouts + ' consecutive times; skipping accessibility scans for the remaining tests in this spec.');
23
+ }
24
+ };
25
+ const noteA11ySuccess = () => { consecutiveA11yTimeouts = 0; };
26
+
27
+
8
28
  const commandsToWrap = ['visit', 'click', 'type', 'request', 'dblclick', 'rightclick', 'clear', 'check', 'uncheck', 'select', 'trigger', 'selectFile', 'scrollIntoView', 'scroll', 'scrollTo', 'blur', 'focus', 'go', 'reload', 'submit', 'viewport', 'origin'];
9
29
  // scroll is not a default function in cypress.
10
30
  const commandToOverwrite = ['visit', 'click', 'type', 'request', 'dblclick', 'rightclick', 'clear', 'check', 'uncheck', 'select', 'trigger', 'selectFile', 'scrollIntoView', 'scrollTo', 'blur', 'focus', 'go', 'reload', 'submit', 'viewport', 'origin'];
@@ -44,56 +64,74 @@ const performModifiedScan = (originalFn, Subject, stateType, ...args) => {
44
64
  }
45
65
 
46
66
  const performScan = (win, payloadToSend) =>
47
- new Promise(async (resolve, reject) => {
48
- const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
49
- if (!isHttpOrHttps) {
50
- return resolve();
67
+ new Promise((resolve) => {
68
+ // This promise MUST always settle (never hang, never reject). It runs inside the
69
+ // global afterEach; if it hangs, cy.wrap()'s 30s timeout fails the hook and Cypress skips
70
+ // the rest of the spec. Failure modes guarded here:
71
+ // - the injected scanner never dispatches A11Y_SCAN_FINISHED (page mid-navigation / slow scan)
72
+ // - win is cross-origin (e.g. an SSO redirect) so win.location / win.document throw synchronously
73
+ if (a11yCircuitOpen) {
74
+ // Scanner has repeatedly not responded in this spec — don't stall this test too.
75
+ return resolve("Accessibility scan skipped: scanner unresponsive (circuit open)");
51
76
  }
77
+ let settled = false;
78
+ const finish = (val) => { if (!settled) { settled = true; clearTimeout(overallTimer); resolve(val); } };
79
+ const overallTimeout = parseInt(Cypress.env('ACCESSIBILITY_SCAN_TIMEOUT')) || 25000;
80
+ const overallTimer = setTimeout(() => { noteA11yTimeout(); finish("Accessibility scan timed out"); }, overallTimeout);
52
81
 
53
- function findAccessibilityAutomationElement() {
54
- return win.document.querySelector("#accessibility-automation-element");
55
- }
82
+ try {
83
+ const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
84
+ if (!isHttpOrHttps) {
85
+ return finish();
86
+ }
56
87
 
57
- function waitForScannerReadiness(retryCount = 100, retryInterval = 100) {
58
- return new Promise(async (resolve, reject) => {
59
- let count = 0;
60
- const intervalID = setInterval(async () => {
61
- if (count > retryCount) {
62
- clearInterval(intervalID);
63
- return reject(
64
- new Error(
65
- "Accessibility Automation Scanner is not ready on the page."
66
- )
67
- );
68
- } else if (findAccessibilityAutomationElement()) {
69
- clearInterval(intervalID);
70
- return resolve("Scanner set");
71
- } else {
72
- count += 1;
73
- }
74
- }, retryInterval);
75
- });
76
- }
88
+ function findAccessibilityAutomationElement() {
89
+ return win.document.querySelector("#accessibility-automation-element");
90
+ }
77
91
 
78
- function startScan() {
79
- function onScanComplete() {
80
- win.removeEventListener("A11Y_SCAN_FINISHED", onScanComplete);
81
- return resolve();
92
+ function waitForScannerReadiness(retryCount = 100, retryInterval = 100) {
93
+ return new Promise((resolve, reject) => {
94
+ let count = 0;
95
+ const intervalID = setInterval(() => {
96
+ if (count > retryCount) {
97
+ clearInterval(intervalID);
98
+ return reject(
99
+ new Error(
100
+ "Accessibility Automation Scanner is not ready on the page."
101
+ )
102
+ );
103
+ } else if (findAccessibilityAutomationElement()) {
104
+ clearInterval(intervalID);
105
+ return resolve("Scanner set");
106
+ } else {
107
+ count += 1;
108
+ }
109
+ }, retryInterval);
110
+ });
82
111
  }
83
112
 
84
- win.addEventListener("A11Y_SCAN_FINISHED", onScanComplete);
85
- const e = new CustomEvent("A11Y_SCAN", { detail: payloadToSend });
86
- win.dispatchEvent(e);
87
- }
113
+ function startScan() {
114
+ function onScanComplete() {
115
+ win.removeEventListener("A11Y_SCAN_FINISHED", onScanComplete);
116
+ if (!settled) noteA11ySuccess();
117
+ return finish();
118
+ }
88
119
 
89
- if (findAccessibilityAutomationElement()) {
90
- startScan();
91
- } else {
92
- waitForScannerReadiness()
93
- .then(startScan)
94
- .catch(async (err) => {
95
- return resolve("Scanner is not ready on the page after multiple retries. performscan");
96
- });
120
+ win.addEventListener("A11Y_SCAN_FINISHED", onScanComplete);
121
+ const e = new CustomEvent("A11Y_SCAN", { detail: payloadToSend });
122
+ win.dispatchEvent(e);
123
+ }
124
+
125
+ if (findAccessibilityAutomationElement()) {
126
+ startScan();
127
+ } else {
128
+ waitForScannerReadiness()
129
+ .then(startScan)
130
+ .catch(() => finish("Scanner is not ready on the page after multiple retries. performscan"));
131
+ }
132
+ } catch (err) {
133
+ // cross-origin window access or any unexpected error must not fail the hook
134
+ finish();
97
135
  }
98
136
  })
99
137
 
@@ -206,11 +244,20 @@ new Promise((resolve) => {
206
244
  });
207
245
 
208
246
  const saveTestResults = (win, payloadToSend) =>
209
- new Promise( (resolve, reject) => {
247
+ new Promise((resolve) => {
248
+ // Must always settle (see performScan note) so a slow/absent A11Y_RESULTS_SAVED
249
+ // event or a cross-origin window cannot fail the afterEach hook.
250
+ if (a11yCircuitOpen) {
251
+ return resolve("Accessibility results save skipped: scanner unresponsive (circuit open)");
252
+ }
253
+ let settled = false;
254
+ const finish = (val) => { if (!settled) { settled = true; clearTimeout(overallTimer); resolve(val); } };
255
+ const overallTimeout = parseInt(Cypress.env('ACCESSIBILITY_SCAN_TIMEOUT')) || 25000;
256
+ const overallTimer = setTimeout(() => { noteA11yTimeout(); finish("Accessibility results save timed out"); }, overallTimeout);
210
257
  try {
211
258
  const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
212
259
  if (!isHttpOrHttps) {
213
- resolve("Unable to save accessibility results, Invalid URL.");
260
+ finish("Unable to save accessibility results, Invalid URL.");
214
261
  return;
215
262
  }
216
263
 
@@ -241,7 +288,9 @@ new Promise( (resolve, reject) => {
241
288
 
242
289
  function saveResults() {
243
290
  function onResultsSaved(event) {
244
- return resolve();
291
+ win.removeEventListener("A11Y_RESULTS_SAVED", onResultsSaved);
292
+ if (!settled) noteA11ySuccess();
293
+ return finish();
245
294
  }
246
295
  win.addEventListener("A11Y_RESULTS_SAVED", onResultsSaved);
247
296
  const e = new CustomEvent("A11Y_SAVE_RESULTS", {
@@ -255,13 +304,11 @@ new Promise( (resolve, reject) => {
255
304
  } else {
256
305
  waitForScannerReadiness()
257
306
  .then(saveResults)
258
- .catch(async (err) => {
259
- return resolve("Scanner is not ready on the page after multiple retries. after run");
260
- });
307
+ .catch(() => finish("Scanner is not ready on the page after multiple retries. after run"));
261
308
  }
262
309
  } catch(error) {
263
- browserStackLog(`Error in saving results with error: ${error.message}`);
264
- return resolve();
310
+ browserStackLog(`Error in saving results with error: ${error.message}`);
311
+ finish();
265
312
  }
266
313
 
267
314
  })
@@ -317,6 +364,17 @@ commandToOverwrite.forEach((command) => {
317
364
  });
318
365
 
319
366
  afterEach(() => {
367
+ // Nothing that happens inside this accessibility hook may fail the user's
368
+ // test or abort the remaining tests in the spec. Cypress chains have no .catch, so
369
+ // suppress any failure raised while this hook's commands run (e.g. cy.window() on a
370
+ // cross-origin page after an SSO redirect, or a cy.task that is not registered) via
371
+ // the per-test 'fail' listener. Returning false prevents Cypress from failing the
372
+ // test; the listener is scoped to the current test and auto-removed afterwards.
373
+ cy.on('fail', (err) => {
374
+ // eslint-disable-next-line no-console
375
+ console.warn(`BrowserStack Accessibility: suppressed afterEach error: ${err && err.message}`);
376
+ return false;
377
+ });
320
378
  const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest;
321
379
  cy.window().then(async (win) => {
322
380
  let shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
@@ -279,7 +279,11 @@ module.exports = function run(args, rawArgs) {
279
279
 
280
280
  let test_zip_size = utils.fetchZipSize(path.join(process.cwd(), config.fileName));
281
281
  let npm_zip_size = utils.fetchZipSize(path.join(process.cwd(), config.packageFileName));
282
- let node_modules_size = await utils.fetchFolderSize(path.join(process.cwd(), "node_modules"));
282
+ // Perf: node_modules size is instrumentation-only, so don't block the upload on
283
+ // walking the tree — start the walk here and await it only after the upload has
284
+ // completed (in the common case it resolves while the upload is in flight, adding
285
+ // zero wall-clock; fetchFolderSize never rejects, so the floating promise is safe).
286
+ let nodeModulesSizePromise = utils.fetchFolderSize(path.join(process.cwd(), "node_modules"));
283
287
 
284
288
  if (Constants.turboScaleObj.enabled) {
285
289
  // Note: Calculating md5 here for turboscale force-upload so that we don't need to re-calculate at hub
@@ -306,6 +310,9 @@ module.exports = function run(args, rawArgs) {
306
310
  markBlockEnd('zip.zipUpload');
307
311
  markBlockEnd('zip');
308
312
 
313
+ // Walk was started before the upload; usually already resolved by now.
314
+ let node_modules_size = await nodeModulesSizePromise;
315
+
309
316
  if (process.env.BROWSERSTACK_TEST_ACCESSIBILITY === 'true') {
310
317
  supportFileCleanup();
311
318
  }
@@ -58,7 +58,12 @@ const archiveSpecs = (runSettings, filePath, excludeFiles, md5data) => {
58
58
 
59
59
  let ignoreFiles = utils.getFilesToIgnore(runSettings, excludeFiles);
60
60
  logger.debug(`Patterns ignored during zip ${ignoreFiles}`);
61
- archive.glob(`**/*.+(${Constants.allowedFileTypes.join("|")})`, { cwd: cypressFolderPath, matchBase: true, ignore: ignoreFiles, dot:true });
61
+ // Perf: `ignore` filters entries only AFTER the walk visits them, so the
62
+ // globber still descends into node_modules/.git/etc. `skip` prunes those directories
63
+ // from the traversal entirely — on large monorepos this cuts zip creation from
64
+ // minutes to seconds without changing the archive contents.
65
+ let skipDirectories = utils.getDirectorySkipPatterns(ignoreFiles);
66
+ archive.glob(`**/*.+(${Constants.allowedFileTypes.join("|")})`, { cwd: cypressFolderPath, matchBase: true, ignore: ignoreFiles, skip: skipDirectories, dot:true });
62
67
 
63
68
  let packageJSON = {};
64
69
 
@@ -25,6 +25,9 @@ const checkSpecsMd5 = (runSettings, args, instrumentBlocks) => {
25
25
  let options = {
26
26
  cwd: cypressFolderPath,
27
27
  ignore: ignoreFiles,
28
+ // Perf: prune ignored directories from the md5 walk instead of
29
+ // filtering entries after descending into them (see utils.getDirectorySkipPatterns).
30
+ skip: utils.getDirectorySkipPatterns(ignoreFiles),
28
31
  pattern: `**/*.+(${Constants.allowedFileTypes.join("|")})`
29
32
  };
30
33
  hashHelper.hashWrapper(options, instrumentBlocks).then(function (data) {
@@ -92,7 +92,20 @@ function generateTscCommandAndTempTsConfig(bsConfig, bstack_node_modules_path, c
92
92
  "listEmittedFiles": true,
93
93
  // Ensure these are always set regardless of base tsconfig
94
94
  "allowSyntheticDefaultImports": true,
95
- "esModuleInterop": true
95
+ "esModuleInterop": true,
96
+ // Force a clean, self-contained JS emit even when the extended tsconfig
97
+ // (common in NX / monorepo setups) sets options that suppress or redirect
98
+ // the JS output. Without these overrides, base options such as
99
+ // noEmit / emitDeclarationOnly / composite / noEmitOnError leave the
100
+ // compiled cypress config missing, surfacing as
101
+ // "Cypress config file not found at: ...tmpBstackCompiledJs/...".
102
+ "noEmit": false,
103
+ "emitDeclarationOnly": false,
104
+ "composite": false,
105
+ "declaration": false,
106
+ "declarationMap": false,
107
+ "noEmitOnError": false,
108
+ "incremental": false
96
109
  },
97
110
  include: [cypress_config_filepath]
98
111
  };
@@ -137,13 +150,25 @@ function generateTscCommandAndTempTsConfig(bsConfig, bstack_node_modules_path, c
137
150
  ? `set NODE_PATH=${bstack_node_modules_path}`
138
151
  : `NODE_PATH="${bstack_node_modules_path}"`;
139
152
 
140
- const tscCommand = `${setNodePath} && node "${typescript_path}" --project "${tempTsConfigPath}" && ${setNodePath} && node "${tsc_alias_path}" --project "${tempTsConfigPath}" --verbose`;
153
+ // Use '&' (unconditional) instead of '&&' between tsc and tsc-alias so the alias
154
+ // rewrite ALWAYS runs even when tsc exits non-zero. tsc returns a non-zero exit
155
+ // code on any type error (very common when a single config file is compiled out of
156
+ // its normal monorepo project context), which with '&&' would skip tsc-alias and
157
+ // leave path aliases (e.g. @org/lib) un-rewritten -> the compiled config fails to
158
+ // require -> "Cypress config file not found". convertTsConfig already
159
+ // tolerates tsc errors by parsing the emitted-files output.
160
+ const tscCommand = `${setNodePath} && node "${typescript_path}" --project "${tempTsConfigPath}" & ${setNodePath} && node "${tsc_alias_path}" --project "${tempTsConfigPath}" --verbose`;
141
161
  logger.info(`TypeScript compilation command: ${tscCommand}`);
142
162
  return { tscCommand, tempTsConfigPath };
143
163
  } else {
144
- // Unix/Linux/macOS: Use ; to separate commands or && to chain
164
+ // Unix/Linux/macOS: Use ';' (unconditional) between tsc and tsc-alias so the alias
165
+ // rewrite ALWAYS runs even when tsc exits non-zero (type errors are common when a
166
+ // single config file is compiled out of its monorepo context). With '&&', a tsc
167
+ // error would skip tsc-alias and leave path aliases (e.g. @org/lib) un-rewritten,
168
+ // making the compiled config impossible to require. convertTsConfig
169
+ // already tolerates tsc errors by parsing the emitted-files output.
145
170
  const nodePathPrefix = `NODE_PATH=${bstack_node_modules_path}`;
146
- const tscCommand = `${nodePathPrefix} node "${typescript_path}" --project "${tempTsConfigPath}" && ${nodePathPrefix} node "${tsc_alias_path}" --project "${tempTsConfigPath}" --verbose`;
171
+ const tscCommand = `${nodePathPrefix} node "${typescript_path}" --project "${tempTsConfigPath}" ; ${nodePathPrefix} node "${tsc_alias_path}" --project "${tempTsConfigPath}" --verbose`;
147
172
  logger.info(`TypeScript compilation command: ${tscCommand}`);
148
173
  return { tscCommand, tempTsConfigPath };
149
174
  }
@@ -889,7 +889,7 @@ exports.setLocalMode = (bsConfig, args) => {
889
889
  if (localModeInferred && localModeUndefined) {
890
890
  bsConfig.connection_settings.local_mode_inferred = local_mode;
891
891
  }
892
- logger.debug(`local_mode set to ${bsConfig.connection_settings.local_mode_inferred}`);
892
+ logger.debug(`local_mode set to ${bsConfig.connection_settings.local_mode}`);
893
893
  }
894
894
  };
895
895
 
@@ -1103,7 +1103,43 @@ exports.getFilesToIgnore = (runSettings, excludeFiles, logging = true) => {
1103
1103
  return ignoreFiles;
1104
1104
  }
1105
1105
 
1106
+ // Perf: derive directory-pruning patterns from the ignore list.
1107
+ // readdir-glob (used both by archiver.glob for tests.zip and by hashUtil for the
1108
+ // spec md5 check) applies `ignore` per-entry AFTER walking, so it still descends
1109
+ // into node_modules/.git/dist etc. On large monorepos that walk alone takes
1110
+ // minutes ("Creating tests.zip" stalls). Its `skip` option instead prevents
1111
+ // DESCENDING into matching directories. Any ignore pattern ending in '/**' is
1112
+ // safe to reuse as a skip: if a directory matches '<x>/**' then every descendant
1113
+ // also matches it, so pruning cannot change which files end up included.
1114
+ exports.getDirectorySkipPatterns = (ignoreFiles) => {
1115
+ return (ignoreFiles || []).filter((pattern) =>
1116
+ typeof pattern === 'string' && pattern.endsWith('/**')
1117
+ );
1118
+ }
1119
+
1120
+ // glob.sync can throw deep inside minimatch (e.g. "expand is not a function" /
1121
+ // "brace_expansion_1.default is not a function") when a project force-resolves an
1122
+ // incompatible 'brace-expansion'/'minimatch' major (e.g. brace-expansion@5) across the
1123
+ // dependency tree via yarn resolutions / npm overrides. That crash used to abort spec
1124
+ // discovery in getNumberOfSpecFiles and produce a build with 0 executed tests (or crash the
1125
+ // run entirely). Degrade gracefully: log once and return no matches so the run still proceeds
1126
+ // (specs are resolved on BrowserStack regardless of the local count).
1127
+ let _loggedGlobFailure = false;
1128
+ const safeGlobSync = (pattern, options) => {
1129
+ try {
1130
+ return glob.sync(pattern, options);
1131
+ } catch (err) {
1132
+ if (!_loggedGlobFailure) {
1133
+ _loggedGlobFailure = true;
1134
+ logger.warn(`Could not enumerate spec files locally (glob failed: ${err && err.message}). This usually means an incompatible 'brace-expansion'/'minimatch' version was forced via package resolutions/overrides. Continuing — specs will be resolved on BrowserStack; local parallelisation may be reduced.`);
1135
+ }
1136
+ return [];
1137
+ }
1138
+ };
1139
+ exports.safeGlobSync = safeGlobSync;
1140
+
1106
1141
  exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig, turboScaleSession=false) => {
1142
+ try {
1107
1143
  let defaultSpecFolder
1108
1144
  let testFolderPath
1109
1145
  let globCypressConfigSpecPatterns = []
@@ -1128,7 +1164,7 @@ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig, turboScaleSession
1128
1164
  const filesMatched = [];
1129
1165
  globCypressConfigSpecPatterns.forEach(specPattern => {
1130
1166
  filesMatched.push(
1131
- ...glob.sync(specPattern, {
1167
+ ...safeGlobSync(specPattern, {
1132
1168
  cwd: bsConfig.run_settings.cypressProjectDir, matchBase: true, ignore: ignoreFiles
1133
1169
  })
1134
1170
  );
@@ -1158,7 +1194,7 @@ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig, turboScaleSession
1158
1194
  let fileMatchedWithConfigSpecPattern = []
1159
1195
  globCypressConfigSpecPatterns.forEach(specPattern => {
1160
1196
  fileMatchedWithConfigSpecPattern.push(
1161
- ...glob.sync(specPattern, {
1197
+ ...safeGlobSync(specPattern, {
1162
1198
  cwd: bsConfig.run_settings.cypressProjectDir, matchBase: true, ignore: ignoreFiles
1163
1199
  })
1164
1200
  );
@@ -1167,7 +1203,7 @@ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig, turboScaleSession
1167
1203
 
1168
1204
  let files
1169
1205
  if (globSearchPattern) {
1170
- let fileMatchedWithBstackSpecPattern = glob.sync(globSearchPattern, {
1206
+ let fileMatchedWithBstackSpecPattern = safeGlobSync(globSearchPattern, {
1171
1207
  cwd: bsConfig.run_settings.cypressProjectDir, matchBase: true, ignore: ignoreFiles
1172
1208
  });
1173
1209
  fileMatchedWithBstackSpecPattern = fileMatchedWithBstackSpecPattern.map((file) => path.resolve(bsConfig.run_settings.cypressProjectDir, file))
@@ -1195,6 +1231,11 @@ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig, turboScaleSession
1195
1231
  bsConfig.run_settings.specs = files;
1196
1232
  }
1197
1233
  return files;
1234
+ } catch (err) {
1235
+ // Backstop: never let spec-counting crash the run. Proceed without a local count.
1236
+ logger.warn(`Could not determine spec files locally: ${err && err.message}. Continuing; specs will be resolved on BrowserStack.`);
1237
+ return [];
1238
+ }
1198
1239
  };
1199
1240
 
1200
1241
  exports.sanitizeSpecsPattern = (pattern) => {
@@ -1349,6 +1390,10 @@ exports.isJSONInvalid = (err, args) => {
1349
1390
  }
1350
1391
 
1351
1392
  exports.deleteBaseUrlFromError = (err) => {
1393
+ // Guard against non-string errors. This is called from the run's error handler
1394
+ // (isJSONInvalid); if a real Error object reaches it, err.replace(...) throws a secondary
1395
+ // TypeError that masks the original failure.
1396
+ if (typeof err !== 'string') return err;
1352
1397
  return err.replace(/To test ([\s\S]*)on BrowserStack/g, 'To test on BrowserStack');
1353
1398
  }
1354
1399
 
@@ -1431,7 +1476,7 @@ exports.setEnforceSettingsConfig = (bsConfig, args) => {
1431
1476
  let specFilesMatched = [];
1432
1477
  specConfigs.forEach(specPattern => {
1433
1478
  specFilesMatched.push(
1434
- ...glob.sync(specPattern, {
1479
+ ...safeGlobSync(specPattern, {
1435
1480
  cwd: bsConfig.run_settings.cypressProjectDir, matchBase: true, ignore: ignoreFiles
1436
1481
  })
1437
1482
  );
@@ -1722,13 +1767,20 @@ exports.fetchZipSize = (fileName) => {
1722
1767
  }
1723
1768
  }
1724
1769
 
1725
- const getDirectorySize = async function(dir) {
1770
+ const getDirectorySize = async function(dir, deadline) {
1726
1771
  try{
1772
+ // Perf: this telemetry-only walk recursively stats every file (it is
1773
+ // pointed at node_modules in runs.js). On large monorepos it blocked the pipeline
1774
+ // between archiving and uploading for tens of seconds. Stop descending once the
1775
+ // deadline passes — folder size is best-effort telemetry, never worth stalling a run.
1776
+ if (deadline && Date.now() > deadline) {
1777
+ return 0;
1778
+ }
1727
1779
  const subdirs = (await readdir(dir));
1728
1780
  const files = await Promise.all(subdirs.map(async (subdir) => {
1729
1781
  const res = path.resolve(dir, subdir);
1730
1782
  const s = (await stat(res));
1731
- return s.isDirectory() ? getDirectorySize(res) : (s.size);
1783
+ return s.isDirectory() ? getDirectorySize(res, deadline) : (s.size);
1732
1784
  }));
1733
1785
  return files.reduce((a, f) => a+f, 0);
1734
1786
  }catch(e){
@@ -1738,10 +1790,15 @@ const getDirectorySize = async function(dir) {
1738
1790
  }
1739
1791
  };
1740
1792
 
1741
- exports.fetchFolderSize = async (dir) => {
1793
+ exports.fetchFolderSize = async (dir, timeoutMs = 5000) => {
1742
1794
  try {
1743
1795
  if(fs.existsSync(dir)){
1744
- return (await getDirectorySize(dir) / 1024 / 1024);
1796
+ const deadline = Date.now() + timeoutMs;
1797
+ const size = (await getDirectorySize(dir, deadline) / 1024 / 1024);
1798
+ if (Date.now() > deadline) {
1799
+ logger.debug(`Folder size calculation for ${dir} exceeded ${timeoutMs}ms; reporting partial size.`);
1800
+ }
1801
+ return size;
1745
1802
  }
1746
1803
  return 0;
1747
1804
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browserstack-cypress-cli",
3
- "version": "1.36.11",
3
+ "version": "1.36.13",
4
4
  "description": "BrowserStack Cypress CLI for Cypress integration with BrowserStack's remote devices.",
5
5
  "main": "index.js",
6
6
  "scripts": {