-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlauncher.ts
More file actions
1260 lines (1131 loc) · 65.7 KB
/
Copy pathlauncher.ts
File metadata and controls
1260 lines (1131 loc) · 65.7 KB
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
import fs from 'node:fs'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { promisify, format } from 'node:util'
import { performance, PerformanceObserver } from 'node:perf_hooks'
import os from 'node:os'
import { SevereServiceError } from 'webdriverio'
import * as BrowserstackLocalLauncher from 'browserstack-local'
import { getProductMap } from './testHub/utils.js'
import TestOpsConfig from './testOps/testOpsConfig.js'
import type { Capabilities, Services, Options } from '@wdio/types'
import { startPercy, stopPercy, getBestPlatformForPercySnapshot } from './Percy/PercyHelper.js'
import type { BrowserstackConfig, BrowserstackOptions, App, AppConfig, AppUploadResponse, UserConfig } from './types.js'
import {
BSTACK_SERVICE_VERSION,
NOT_ALLOWED_KEYS_IN_CAPS, PERF_MEASUREMENT_ENV, RERUN_ENV, RERUN_TESTS_ENV,
AUTOLOGCAPTURE_NOTIFICATION,
BROWSERSTACK_TESTHUB_UUID,
VALID_APP_EXTENSION,
BROWSERSTACK_PERCY,
BROWSERSTACK_OBSERVABILITY,
WDIO_NAMING_PREFIX,
BROWSERSTACK_TEST_REPORTING,
TEST_REPORTING_PROJECT_NAME
} from './constants.js'
import {
launchTestSession,
shouldAddServiceVersion,
stopBuildUpstream,
getCiInfo,
isBStackSession,
isUndefined,
isAccessibilityAutomationSession,
isTrue,
getBrowserStackUser,
getBrowserStackKey,
uploadLogs,
ObjectsAreEqual, getBasicAuthHeader,
isValidCapsForHealing,
getBooleanValueFromString,
validateCapsWithNonBstackA11y,
mergeChromeOptions,
isValidEnabledValue,
isMultiRemoteCaps,
coerceStringBooleans,
validateSkipAppOverride
} from './util.js'
import CrashReporter from './crash-reporter.js'
import { initWdioConfigPath, isAutoCaptureLogsDisabled, publishAutoCaptureDisabled } from './configCapture.js'
import { finalizeOrphanedRuns } from './testOps/openRunsJournal.js'
import { BStackLogger } from './bstackLogger.js'
import { PercyLogger } from './Percy/PercyLogger.js'
import type Percy from './Percy/Percy.js'
import BrowserStackConfig from './config.js'
import { setupExitHandlers } from './exitHandler.js'
import { sendFinish, sendStart } from './instrumentation/funnelInstrumentation.js'
import AiHandler from './ai-handler.js'
import PerformanceTester from './instrumentation/performance/performance-tester.js'
import * as PERFORMANCE_SDK_EVENTS from './instrumentation/performance/constants.js'
import { BrowserstackCLI } from './cli/index.js'
import { CLIUtils } from './cli/cliUtils.js'
import accessibilityScripts from './scripts/accessibility-scripts.js'
import { _fetch as fetch } from './fetchWrapper.js'
type BrowserstackLocal = BrowserstackLocalLauncher.Local & {
pid?: number
stop(callback: (err?: Error) => void): void
}
export default class BrowserstackLauncherService implements Services.ServiceInstance {
browserstackLocal?: BrowserstackLocal
private _buildName?: string
private _projectName?: string
private _buildTag?: string
private _buildIdentifier?: string
private _accessibilityAutomation?: boolean
private _percy?: Percy
private _percyBestPlatformCaps?: WebdriverIO.Capabilities
private readonly browserStackConfig: BrowserStackConfig
constructor (
private _options: BrowserstackConfig & BrowserstackOptions,
capabilities: Capabilities.TestrunnerCapabilities,
private _config: Options.Testrunner
) {
BStackLogger.clearLogFile()
PercyLogger.clearLogFile()
setupExitHandlers()
// added to maintain backward compatibility with webdriverIO v5
if (!this._config) {
this._config = _options
}
//normalizing testReporting config and env variables
if (!isUndefined(_options.testReporting)){
_options.testObservability = _options.testReporting
}
if (!isUndefined(_options.testReportingOptions)){
_options.testObservabilityOptions = _options.testReportingOptions
}
if (!isUndefined(process.env[BROWSERSTACK_TEST_REPORTING])){
process.env[BROWSERSTACK_OBSERVABILITY] = process.env[BROWSERSTACK_TEST_REPORTING]
}
if (!isUndefined(process.env[TEST_REPORTING_PROJECT_NAME])){
process.env.TEST_OBSERVABILITY_PROJECT_NAME = process.env[TEST_REPORTING_PROJECT_NAME]
}
if (!isUndefined(process.env.TEST_REPORTING_BUILD_NAME)) {
process.env.TEST_OBSERVABILITY_BUILD_NAME = process.env.TEST_REPORTING_BUILD_NAME
}
if (!isUndefined(process.env.TEST_REPORTING_BUILD_TAG)) {
process.env.TEST_OBSERVABILITY_BUILD_TAG = process.env.TEST_REPORTING_BUILD_TAG
}
this.browserStackConfig = BrowserStackConfig.getInstance(_options, _config, capabilities)
BStackLogger.debug(`_options data: ${JSON.stringify(_options)}`)
BStackLogger.debug(`webdriver capabilities data: ${JSON.stringify(capabilities)}`)
const configCopy = JSON.parse(JSON.stringify(_config))
CrashReporter.recursivelyRedactKeysFromObject(configCopy, ['user', 'username', 'key', 'accesskey', 'password'])
BStackLogger.debug(`_config data: ${JSON.stringify(configCopy)}`)
if (Array.isArray(capabilities)) {
capabilities
.flatMap((c) => {
if ('alwaysMatch' in c) {
return c.alwaysMatch as WebdriverIO.Capabilities
}
if (Object.values(c).length > 0 && Object.values(c).every(c => typeof c === 'object' && c.capabilities)) {
return Object.values(c).map((o) => o.capabilities) as WebdriverIO.Capabilities[]
}
return c as WebdriverIO.Capabilities
})
.forEach((capability: WebdriverIO.Capabilities) => {
if (!capability['bstack:options']) {
// Skipping adding of service version if session is not of browserstack
if (isBStackSession(this._config)) {
const extensionCaps = Object.keys(capability).filter((cap) => cap.includes(':'))
if (extensionCaps.length) {
capability['bstack:options'] = { wdioService: BSTACK_SERVICE_VERSION }
if (!isUndefined(capability['browserstack.accessibility'])) {
this._accessibilityAutomation ||= isTrue(capability['browserstack.accessibility'])
} else if (isTrue(this._options.accessibility)) {
capability['bstack:options'].accessibility = true
}
} else if (shouldAddServiceVersion(this._config, this._options.testObservability)) {
capability['browserstack.wdioService'] = BSTACK_SERVICE_VERSION
}
}
// Need this details for sending data to Test Reporting and Analytics
this._buildIdentifier = capability['browserstack.buildIdentifier']?.toString()
// @ts-expect-error ToDo: fix invalid cap
this._buildName = capability.build?.toString()
} else {
capability['bstack:options'].wdioService = BSTACK_SERVICE_VERSION
this._buildName = capability['bstack:options'].buildName
this._projectName = capability['bstack:options'].projectName
this._buildTag = capability['bstack:options'].buildTag
this._buildIdentifier = capability['bstack:options'].buildIdentifier
if (!isUndefined(capability['bstack:options'].accessibility)) {
this._accessibilityAutomation ||= isTrue(capability['bstack:options'].accessibility)
} else if (isTrue(this._options.accessibility)) {
capability['bstack:options'].accessibility = (isTrue(this._options.accessibility))
}
}
})
} else if (typeof capabilities === 'object') {
Object.entries(capabilities as Capabilities.RequestedMultiremoteCapabilities).forEach(([, caps]) => {
if (!(caps.capabilities as WebdriverIO.Capabilities)['bstack:options']) {
if (isBStackSession(this._config)) {
const extensionCaps = Object.keys(caps.capabilities).filter((cap) => cap.includes(':'))
if (extensionCaps.length) {
(caps.capabilities as WebdriverIO.Capabilities)['bstack:options'] = { wdioService: BSTACK_SERVICE_VERSION }
if (!isUndefined((caps.capabilities as WebdriverIO.Capabilities)['browserstack.accessibility'])) {
this._accessibilityAutomation ||= isTrue((caps.capabilities as WebdriverIO.Capabilities)['browserstack.accessibility'])
} else if (isTrue(this._options.accessibility)) {
(caps.capabilities as WebdriverIO.Capabilities)['bstack:options'] = { wdioService: BSTACK_SERVICE_VERSION, accessibility: (isTrue(this._options.accessibility)) }
}
} else if (shouldAddServiceVersion(this._config, this._options.testObservability)) {
(caps.capabilities as WebdriverIO.Capabilities)['browserstack.wdioService'] = BSTACK_SERVICE_VERSION
}
}
this._buildIdentifier = (caps.capabilities as WebdriverIO.Capabilities)['browserstack.buildIdentifier']
} else {
const bstackOptions = (caps.capabilities as WebdriverIO.Capabilities)['bstack:options']
bstackOptions!.wdioService = BSTACK_SERVICE_VERSION
this._buildName = bstackOptions!.buildName
this._projectName = bstackOptions!.projectName
this._buildTag = bstackOptions!.buildTag
this._buildIdentifier = bstackOptions!.buildIdentifier
if (!isUndefined(bstackOptions!.accessibility)) {
this._accessibilityAutomation ||= isTrue(bstackOptions!.accessibility)
} else if (isTrue(this._options.accessibility)) {
bstackOptions!.accessibility = isTrue(this._options.accessibility)
}
}
})
}
this.browserStackConfig.buildIdentifier = this._buildIdentifier
this.browserStackConfig.buildName = this._buildName
PerformanceTester.startMonitoring('performance-report-launcher.csv')
if (!isUndefined(this._options.accessibility)) {
this._accessibilityAutomation ||= isTrue(this._options.accessibility)
}
this._options.accessibility = this._accessibilityAutomation
// Default is true unless explicitly set to false
this._options.testObservability = this._options.testObservability !== false
if (this._options.testObservability
&&
// update files to run if it's a rerun
process.env[RERUN_ENV] && process.env[RERUN_TESTS_ENV]
) {
this._config.specs = process.env[RERUN_TESTS_ENV].split(',')
}
try {
CrashReporter.setConfigDetails(this._config, capabilities, this._options)
} catch (error: unknown) {
BStackLogger.error(`[Crash_Report_Upload] Config processing failed due to ${error}`)
}
}
@PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_SETUP)
async onWorkerStart (cid: string, caps: WebdriverIO.Capabilities) {
try {
if (this._options.percy && this._percyBestPlatformCaps) {
const isThisBestPercyPlatform = ObjectsAreEqual(caps, this._percyBestPlatformCaps)
if (isThisBestPercyPlatform) {
process.env.BEST_PLATFORM_CID = cid
}
}
} catch (err) {
PercyLogger.error(`Error while setting best platform for Percy snapshot at worker start ${err}`)
}
}
@PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_PRE_TEST)
async onPrepare (config: Options.Testrunner, capabilities: Capabilities.TestrunnerCapabilities | WebdriverIO.Capabilities) {
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.INIT)
// Resolve the user's wdio config path ONCE, here, while the freshly parsed config
// still carries the CLI's `config-path` positional, and publish it on the env for
// the upload path. Re-deriving it at archive time from cwd is the exact bug
// SDK-5993 fixed in the Node SDK (silently dropped the config on every monorepo /
// subdir CI run). Best-effort: never blocks the run.
if (!publishAutoCaptureDisabled(this._options)) {
BStackLogger.info(AUTOLOGCAPTURE_NOTIFICATION)
initWdioConfigPath(config)
}
// skipAppOverride: emit the fixed warning once + handle the 3 edge cases before anything
// else. Runs once here in the launcher (main process). Edge-2 (explicit false + no app) is a
// deliberate pre-session config error, surfaced as SevereServiceError so the run aborts cleanly.
try {
validateSkipAppOverride(this._options)
} catch (error) {
throw new SevereServiceError((error as Error).message)
}
// Keep the config singleton consistent: validateSkipAppOverride clears this._options.app on the
// edge-1 conflict, but browserStackConfig.app was copied earlier in the constructor.
this.browserStackConfig.app = this._options.app
// Send Funnel start request
await sendStart(this.browserStackConfig)
// Convert glob patterns in specs to resolved relative paths
if (config.specs && Array.isArray(config.specs) && isValidEnabledValue(this._options.testOrchestrationOptions?.runSmartSelection?.enabled)) {
try {
// Import glob for expanding file patterns
const glob = (await import('glob')).sync
const path = await import('node:path')
// Use ConfigParser.getFilePaths equivalent logic to expand specs
const expandedSpecs: string[] = []
for (const specPattern of config.specs) {
if (typeof specPattern === 'string') {
if (specPattern.startsWith('file://')) {
expandedSpecs.push(specPattern)
continue
}
// Expand glob pattern to relative paths
const pattern = specPattern.replace(/\\/g, '/')
// Use config.rootDir which is set to the config file's directory
const rootDir = config.rootDir || process.cwd()
// Get current working directory for final relative path calculation
const cwd = process.cwd()
const filenames = glob(pattern, {
cwd: rootDir,
matchBase: true
}) || []
// Convert paths to be relative to the current working directory (where command is run)
filenames
.forEach((filename: string) => {
let absolutePath = filename
// If filename is not absolute, resolve it relative to rootDir (config file's directory)
if (!path.isAbsolute(filename)) {
absolutePath = path.resolve(rootDir, filename)
}
// Make path relative to current working directory
let relativePath = path.relative(cwd, absolutePath)
// Normalize path separators for consistency (Windows compatibility)
relativePath = relativePath.replace(/\\/g, '/')
expandedSpecs.push(relativePath)
})
}
}
if (expandedSpecs.length > 0) {
BStackLogger.info(`Expanded specs from glob patterns to ${expandedSpecs.length} files`)
config.specs = expandedSpecs
}
} catch (error) {
BStackLogger.error(`Failed to expand spec patterns: ${error}`)
}
}
try {
// Detect if multi-remote and disable CLI for those sessions
const isMultiremote = isMultiRemoteCaps(capabilities as Capabilities.TestrunnerCapabilities)
process.env.BROWSERSTACK_IS_MULTIREMOTE = String(isMultiremote)
if (CLIUtils.checkCLISupportedFrameworks(config.framework) && !isMultiremote) {
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.START)
CLIUtils.setFrameworkDetail(WDIO_NAMING_PREFIX + config.framework, 'WebdriverIO')
const binconfig = CLIUtils.getBinConfig(config, capabilities as Capabilities.RequestedStandaloneCapabilities | Capabilities.RequestedStandaloneCapabilities[], this._options, this._buildTag)
await BrowserstackCLI.getInstance().bootstrap(this._options, config, binconfig)
BStackLogger.debug(`Is CLI running ${BrowserstackCLI.getInstance().isRunning()}`)
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.START)
}
} catch (err) {
BStackLogger.error(`Error while starting CLI ${err}`)
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.START, false, format(err))
}
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.INIT)
// Setting up healing for those sessions where we don't add the service version capability as it indicates that the session is not being run on BrowserStack
if (!shouldAddServiceVersion(this._config, this._options.testObservability, capabilities as Capabilities.BrowserStackCapabilities)) {
try {
if ((capabilities as Capabilities.BrowserStackCapabilities).browserName) {
capabilities = await AiHandler.setup(this._config, this.browserStackConfig, this._options, capabilities as WebdriverIO.Capabilities, false)
} else if ( Array.isArray(capabilities)){
for (let i = 0; i < capabilities.length; i++) {
if ((capabilities[i] as Capabilities.BrowserStackCapabilities).browserName) {
capabilities[i] = await AiHandler.setup(this._config, this.browserStackConfig, this._options, capabilities[i] as WebdriverIO.Capabilities, false)
}
}
} else if (isValidCapsForHealing(capabilities)) {
// setting up healing in case capabilities.xyz.capabilities.browserName where xyz can be anything:
capabilities = await AiHandler.setup(this._config, this.browserStackConfig, this._options, capabilities, true)
}
} catch (err) {
if (this._options.selfHeal === true) {
BStackLogger.warn(`Error while setting up Browserstack healing Extension ${err}. Disabling healing for this session.`)
}
}
}
/**
* Upload app to BrowserStack if valid file path to app is given.
* Update app value of capability directly if app_url, custom_id, shareable_id is given
*/
if (!BrowserstackCLI.getInstance().isRunning()) {
if (!this._options.app) {
BStackLogger.debug('app is not defined in browserstack-service config, skipping ...')
} else {
let app: App = {}
const appConfig: AppConfig | string = this._options.app
try {
app = await this._validateApp(appConfig)
} catch (error: unknown){
throw new SevereServiceError((error as Error).message)
}
if (VALID_APP_EXTENSION.includes(path.extname(app.app!))){
if (fs.existsSync(app.app!)) {
const data: AppUploadResponse = await this._uploadApp(app)
BStackLogger.info(`app upload completed: ${JSON.stringify(data)}`)
app.app = data.app_url
} else if (app.customId){
app.app = app.customId
} else {
throw new SevereServiceError(`[Invalid app path] app path ${app.app} is not correct, Provide correct path to app under test`)
}
}
BStackLogger.info(`Using app: ${app.app}`)
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'app', app.app)
}
}
/**
* buildIdentifier in service options will take precedence over specified in capabilities
*/
if (this._options.buildIdentifier) {
this._buildIdentifier = this._options.buildIdentifier
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'buildIdentifier', this._buildIdentifier)
}
/**
* evaluate buildIdentifier in case unique execution identifiers are present
* e.g., ${BUILD_NUMBER} and ${DATE_TIME}
*/
this._handleBuildIdentifier(capabilities as Capabilities.TestrunnerCapabilities)
// remove accessibilityOptions from the capabilities if present
this._updateObjectTypeCaps(capabilities as Capabilities.TestrunnerCapabilities, 'accessibilityOptions')
const shouldSetupPercy = this._options.percy || (isUndefined(this._options.percy) && this._options.app)
let buildStartResponse = null
const classicBuildStartAttempted = !BrowserstackCLI.getInstance().isRunning() && Boolean(this._options.testObservability || this._accessibilityAutomation || shouldSetupPercy)
if (classicBuildStartAttempted) {
BStackLogger.debug('Sending launch start event')
buildStartResponse = await launchTestSession(this._options, this._config, {
projectName: this._projectName,
buildName: this._buildName,
buildTag: this._buildTag,
bstackServiceVersion: BSTACK_SERVICE_VERSION,
buildIdentifier: this._buildIdentifier
}, this.browserStackConfig, this._accessibilityAutomation)
}
//added checks for Accessibility running on non-bstack infra
if (isAccessibilityAutomationSession(this._accessibilityAutomation) && (process.env.BROWSERSTACK_TURBOSCALE || !shouldAddServiceVersion(this._config, this._options.testObservability))){
const overrideOptions: Partial<Capabilities.ChromeOptions> = accessibilityScripts.ChromeExtension
this._updateObjectTypeCaps(capabilities, 'goog:chromeOptions', overrideOptions)
}
if (buildStartResponse?.accessibility) {
if (isUndefined(this._accessibilityAutomation)) {
this.browserStackConfig.accessibility = buildStartResponse.accessibility.success as boolean
this._accessibilityAutomation = buildStartResponse.accessibility.success as boolean
this._options.accessibility = buildStartResponse.accessibility.success as boolean
if (buildStartResponse.accessibility.success === true) {
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'accessibility', 'true')
}
}
}
this.browserStackConfig.accessibility = this._accessibilityAutomation
// Mirror the accessibility fold-back above for observability: if the classic build-start
// was attempted with observability requested but observability did not succeed
// (BROWSERSTACK_OBSERVABILITY !== 'true' — an explicit block sets 'false', a transport/parse
// failure leaves it unset because launchTestSession's error handler returns null), fold that
// outcome into config so the session's buildProductMap reports observability:false. Keying on
// the attempt (not on buildStartResponse being truthy) also covers the null-on-error case. The
// CLI/gRPC flow owns its own build-start, so classicBuildStartAttempted stays false there.
const observabilityBuildStartBlocked = classicBuildStartAttempted && Boolean(this._options.testObservability) && !isTrue(process.env[BROWSERSTACK_OBSERVABILITY])
if (observabilityBuildStartBlocked) {
this.browserStackConfig.testObservability.enabled = false
}
if (this._accessibilityAutomation && this._options.accessibilityOptions) {
// SDK-3737: coerce stringified booleans (e.g. autoScanning: 'false') to real
// booleans so boolean-typed accessibility options are honoured instead of
// being dropped by W3C caps validation.
const filteredOpts = coerceStringBooleans(Object.keys(this._options.accessibilityOptions)
.filter(key => !NOT_ALLOWED_KEYS_IN_CAPS.includes(key))
.reduce((opts, key) => {
return {
...opts,
[key]: this._options.accessibilityOptions?.[key]
}
}, {} as Record<string, unknown>))
this._updateObjectTypeCaps(capabilities as Capabilities.TestrunnerCapabilities, 'accessibilityOptions', filteredOpts)
} else if (isAccessibilityAutomationSession(this._accessibilityAutomation)) {
this._updateObjectTypeCaps(capabilities as Capabilities.TestrunnerCapabilities, 'accessibilityOptions', {})
}
this._removeCliOnlyCapabilityOptions(capabilities as Capabilities.TestrunnerCapabilities)
if (shouldSetupPercy) {
try {
const bestPlatformPercyCaps = getBestPlatformForPercySnapshot(capabilities as Capabilities.TestrunnerCapabilities)
this._percyBestPlatformCaps = bestPlatformPercyCaps as WebdriverIO.Capabilities
process.env[BROWSERSTACK_PERCY] = 'false'
await this.setupPercy(this._options, this._config, {
projectName: this._projectName
})
this._updateBrowserStackPercyConfig()
} catch (err) {
PercyLogger.error(`Error while setting up Percy ${err}`)
}
}
// Skip stamping testhubBuildUuid only when the observability build-start was blocked
// and no other TestHub product (accessibility) succeeded — otherwise the Automate
// session gets orphan-linked to a TestHub build that was never created (a blocked
// build-start still returns a build_hashed_id), keeping it counted as an SDK
// observability session. Every other case keeps the prior behavior.
if (!(observabilityBuildStartBlocked && !this._accessibilityAutomation)) {
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'testhubBuildUuid')
}
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'buildProductMap')
if (isValidEnabledValue(this._options.testOrchestrationOptions?.runSmartSelection?.enabled)){
// Helper function to convert specs from cwd-relative to rootDir-relative
const convertToRootDirRelative = (specs: string[]): string[] => {
const rootDir = config.rootDir || process.cwd()
const cwd = process.cwd()
return specs.map((spec: string) => {
if (typeof spec !== 'string') {
return spec
}
// Convert from cwd-relative to absolute
const absolutePath = path.isAbsolute(spec) ? spec : path.resolve(cwd, spec)
// Then make it relative to rootDir (config file's directory)
const relativePath = path.relative(rootDir, absolutePath)
// Normalize path separators
return relativePath.replace(/\\/g, '/')
})
}
// Apply test orchestration if enabled
try {
// Import dynamically to avoid circular dependencies
const { applyOrchestrationIfEnabled } = await import('./testorchestration/apply-orchestration.js')
if (config.specs && config.specs.length > 0 && this._options.testObservability && isValidEnabledValue(this._options.testOrchestrationOptions?.runSmartSelection?.enabled)) {
BStackLogger.info('Applying test orchestration')
// Ensure we're passing string[] to applyOrchestrationIfEnabled
const specs = (config.specs as string[]).filter(spec => typeof spec === 'string')
console.log(`Specs before orchestration: ${specs}`)
const orderedSpecs = await applyOrchestrationIfEnabled(specs, this._options)
console.log(`Specs after orchestration before conversion: ${orderedSpecs}`)
// Use ordered specs if available, otherwise use original specs
const specsToConvert = orderedSpecs && orderedSpecs.length > 0 ? orderedSpecs : specs
config.specs = convertToRootDirRelative(specsToConvert)
console.log(`Specs after orchestration: ${config.specs}`)
BStackLogger.info('Test specs updated with orchestrated order')
}
} catch (error) {
BStackLogger.error(`Error applying test orchestration: ${error}`)
// On error, we still need to convert specs from cwd-relative to rootDir-relative
if (config.specs && config.specs.length > 0) {
const specs = (config.specs as string[]).filter(spec => typeof spec === 'string')
config.specs = convertToRootDirRelative(specs)
BStackLogger.debug(`Specs converted back to rootDir-relative after error: ${config.specs}`)
}
}
}
// local binary will be handled by CLI
if (BrowserstackCLI.getInstance().isRunning()) {
return
}
if (!this._options.browserstackLocal) {
return BStackLogger.info('browserstackLocal is not enabled - skipping...')
}
const opts = {
key: this._config.key,
...this._options.opts
}
this.browserstackLocal = new BrowserstackLocalLauncher.Local()
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'local')
if (opts.localIdentifier) {
this._updateCaps(capabilities as Capabilities.TestrunnerCapabilities, 'localIdentifier', opts.localIdentifier)
}
/**
* measure BrowserStack tunnel boot time
*/
const obs = new PerformanceObserver((list) => {
const entry = list.getEntries()[0]
BStackLogger.info(`Browserstack Local successfully started after ${entry.duration}ms`)
})
obs.observe({ entryTypes: ['measure'] })
let timer: NodeJS.Timeout
performance.mark('tbTunnelStart')
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.AUTOMATE_EVENTS.LOCAL_START)
return Promise.race([
promisify(this.browserstackLocal.start.bind(this.browserstackLocal))(opts),
new Promise((resolve, reject) => {
/* istanbul ignore next */
timer = setTimeout(function () {
reject('Browserstack Local failed to start within 60 seconds!')
}, 60000)
})]
).then(function (result) {
clearTimeout(timer)
performance.mark('tbTunnelEnd')
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.AUTOMATE_EVENTS.LOCAL_START)
performance.measure('bootTime', 'tbTunnelStart', 'tbTunnelEnd')
return Promise.resolve(result)
}, function (err) {
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.AUTOMATE_EVENTS.LOCAL_START, false, err)
clearTimeout(timer)
return Promise.reject(err)
})
}
@PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_CLEANUP)
async onComplete () {
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_CLEANUP)
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_ON_STOP)
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.STOP)
try {
const isCLIEnabled = BrowserstackCLI.getInstance().isRunning()
BStackLogger.debug('Inside OnComplete hook..')
BStackLogger.debug('Sending stop launch event')
// SDK-4671: before stopping the build, synthesize TestRunFinished for any
// test runs whose worker died mid-test, else they stay 'in progress' on TRA.
await finalizeOrphanedRuns()
// SDK-7061: capture the stop result so we only mark the build stopped when it
// actually succeeded. A failed stop must leave buildStopped=false so the
// process-exit cleanup re-stop path can still close the build.
let stopResult: { status?: string } | undefined
try {
stopResult = await (isCLIEnabled ? BrowserstackCLI.getInstance().stop() : stopBuildUpstream()) as { status?: string } | undefined
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.STOP)
} catch (err) {
BStackLogger.error(`Error while stopping CLI ${err}`)
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.STOP, false, format(err))
}
if (process.env[BROWSERSTACK_OBSERVABILITY] && process.env[BROWSERSTACK_TESTHUB_UUID]) {
console.log(`\nVisit https://automation.browserstack.com/builds/${process.env[BROWSERSTACK_TESTHUB_UUID]} to view build report, insights, and many more debugging information all at one place!\n`)
}
// CLI path manages its own build lifecycle; for the direct-HTTP path only
// mark stopped when stopBuildUpstream returned success (SDK-7061).
if (isCLIEnabled || stopResult?.status === 'success') {
this.browserStackConfig.testObservability.buildStopped = true
}
await PerformanceTester.stopAndGenerate('performance-launcher.html')
if (process.env[PERF_MEASUREMENT_ENV]) {
PerformanceTester.calculateTimes(['launchTestSession', 'stopBuildUpstream'])
if (!process.env.START_TIME) {
return
}
const duration = (new Date()).getTime() - (new Date(process.env.START_TIME)).getTime()
BStackLogger.info(`Total duration is ${duration / 1000} s`)
}
BStackLogger.info(`BrowserStack service run ended for id: ${this.browserStackConfig?.sdkRunID} testhub id: ${TestOpsConfig.getInstance()?.buildHashedId}`)
await sendFinish(this.browserStackConfig, isCLIEnabled)
try {
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_SEND_LOGS)
await this._uploadServiceLogs()
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_SEND_LOGS)
} catch (error) {
BStackLogger.debug(`Failed to upload BrowserStack WDIO Service logs ${error}`)
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_SEND_LOGS, false, format(error))
}
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_ON_STOP)
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_CLEANUP)
await PerformanceTester.stopAndGenerate('performance-launcher.html')
} catch (error) {
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_ON_STOP, false, format(error))
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_CLEANUP, false, format(error))
await PerformanceTester.stopAndGenerate('performance-launcher.html')
BStackLogger.error(`Error in onComplete hook: ${error}`)
}
BStackLogger.clearLogger()
if (this._options.percy) {
await this.stopPercy()
PercyLogger.clearLogger()
}
// local binary will be handled by CLI
if (BrowserstackCLI.getInstance().isRunning()) {
return
}
if (!this.browserstackLocal || !this.browserstackLocal.isRunning()) {
return
}
if (this._options.forcedStop) {
const pid = this.browserstackLocal.pid as number
process.kill(pid)
return pid
}
let timer: NodeJS.Timeout
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.AUTOMATE_EVENTS.LOCAL_STOP)
return Promise.race([
new Promise<void>((resolve, reject) => {
this.browserstackLocal?.stop((err: Error) => {
if (err) {
return reject(err)
}
resolve()
})
}),
new Promise((resolve, reject) => {
/* istanbul ignore next */
timer = setTimeout(
() => reject(new Error('Browserstack Local failed to stop within 60 seconds!')),
60000
)
})]
).then(function (result) {
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.AUTOMATE_EVENTS.LOCAL_STOP)
clearTimeout(timer)
return Promise.resolve(result)
}, function (err) {
PerformanceTester.end(PERFORMANCE_SDK_EVENTS.AUTOMATE_EVENTS.LOCAL_STOP, false, err)
clearTimeout(timer)
return Promise.reject(err)
})
}
async setupPercy(options: BrowserstackConfig & Options.Testrunner, config: Options.Testrunner, bsConfig: UserConfig) {
if (this._percy?.isRunning()) {
process.env[BROWSERSTACK_PERCY] = 'true'
return
}
try {
this._percy = await startPercy(options, config, bsConfig)
if (!this._percy || (typeof this._percy === 'object' && Object.keys(this._percy).length === 0)) {
throw new Error('Could not start percy, check percy logs for info.')
}
PercyLogger.info('Percy started successfully')
process.env[BROWSERSTACK_PERCY] = 'true'
let signal = 0
const handler = async () => {
signal++
if (signal === 1) {
await this.stopPercy()
}
}
process.on('beforeExit', handler)
process.on('SIGINT', handler)
process.on('SIGTERM', handler)
} catch (err) {
PercyLogger.debug(`Error in percy setup ${format(err)}`)
process.env[BROWSERSTACK_PERCY] = 'false'
}
}
async stopPercy() {
if (!this._percy || !this._percy.isRunning()) {
return
}
try {
await stopPercy(this._percy)
PercyLogger.info('Percy stopped')
} catch (err) {
PercyLogger.error('Error occured while stopping percy : ' + err)
}
}
@PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.APP_AUTOMATE_EVENTS.APP_UPLOAD)
async _uploadApp(app:App): Promise<AppUploadResponse> {
BStackLogger.info(`uploading app ${app.app} ${app.customId? `and custom_id: ${app.customId}` : ''} to browserstack`)
const form = new FormData()
if (app.app) {
const fileName = path.basename(app.app)
const fileBuffer = await readFile(app.app)
const fileBlob = new Blob([new Uint8Array(fileBuffer)])
form.append('file', fileBlob, fileName)
}
if (app.customId) {
form.append('custom_id', app.customId)
}
const headers: Record<string, string> = {
Authorization: getBasicAuthHeader(this._config.user as string, this._config.key as string),
}
const res = await fetch('https://api-cloud.browserstack.com/app-automate/upload', {
method: 'POST',
body: form,
headers
})
if (!res.ok) {
throw new SevereServiceError(`app upload failed ${res.body}`)
}
return await res.json() as AppUploadResponse
}
/**
* @param {String | AppConfig} appConfig <string>: should be "app file path" or "app_url" or "custom_id" or "shareable_id".
* <object>: only "path" and "custom_id" should coexist as multiple properties.
*/
async _validateApp (appConfig: AppConfig | string): Promise<App> {
const app: App = {}
if (typeof appConfig === 'string'){
app.app = appConfig
} else if (typeof appConfig === 'object' && Object.keys(appConfig).length) {
if (Object.keys(appConfig).length > 2 || (Object.keys(appConfig).length === 2 && (!appConfig.path || !appConfig.custom_id))) {
throw new SevereServiceError(`keys ${Object.keys(appConfig)} can't co-exist as app values, use any one property from
{id<string>, path<string>, custom_id<string>, shareable_id<string>}, only "path" and "custom_id" can co-exist.`)
}
app.app = appConfig.id || appConfig.path || appConfig.custom_id || appConfig.shareable_id
app.customId = appConfig.custom_id
} else {
throw new SevereServiceError('[Invalid format] app should be string or an object')
}
if (!app.app) {
throw new SevereServiceError(`[Invalid app property] supported properties are {id<string>, path<string>, custom_id<string>, shareable_id<string>}.
For more details please visit https://www.browserstack.com/docs/app-automate/appium/set-up-tests/specify-app ')`)
}
return app
}
async _uploadServiceLogs() {
// uploadLogs records the SDK_UPLOAD_LOGS event with status/failure for every
// return path (no creds, archive failure, upload no-response, exception), so
// measureWrapper is no longer needed here.
const clientBuildUuid = this._getClientBuildUuid()
const response = await uploadLogs(
getBrowserStackUser(this._config),
getBrowserStackKey(this._config),
clientBuildUuid,
{ disableAutoCaptureLogs: isAutoCaptureLogsDisabled(this._options), config: this._config }
)
// Treat a truthy response carrying a non-success status as a server-side
// rejection, not a delivery — a delivered upload must not be repeated by
// the exit-time cleanup rescue; failed/skipped uploads stay eligible for it.
const delivered = !!response && !(response.status && response.status !== 'success')
if (delivered) {
this.browserStackConfig.logsUploaded = true
BStackLogger.info(`Upload response: ${JSON.stringify(response, null, 2)}`)
BStackLogger.logToFile(`Response - ${format(response)}`, 'debug')
}
}
private _removeCliOnlyCapabilityOptions(capabilities?: Capabilities.TestrunnerCapabilities | WebdriverIO.Capabilities) {
if (!capabilities || typeof capabilities !== 'object') {
return
}
const strip = (capability: WebdriverIO.Capabilities) => {
const capabilityRecord = capability as Record<string, unknown>
const bstackOptions = capabilityRecord['bstack:options'] as Record<string, unknown> | undefined
if (bstackOptions && typeof bstackOptions === 'object') {
NOT_ALLOWED_KEYS_IN_CAPS.forEach(key => delete bstackOptions[key])
}
NOT_ALLOWED_KEYS_IN_CAPS.forEach(key => delete capabilityRecord[`browserstack.${key}`])
const alwaysMatch = (capability as WebdriverIO.Capabilities & { alwaysMatch?: WebdriverIO.Capabilities }).alwaysMatch
if (alwaysMatch && typeof alwaysMatch === 'object') {
strip(alwaysMatch)
}
}
if (Array.isArray(capabilities)) {
capabilities
.flatMap((c) => {
if (Object.values(c).length > 0 && Object.values(c).every(c => typeof c === 'object' && c.capabilities)) {
return Object.values(c).map((o) => o.capabilities) as WebdriverIO.Capabilities[]
}
return c as WebdriverIO.Capabilities
})
.forEach(strip)
} else {
Object.entries(capabilities as Capabilities.RequestedMultiremoteCapabilities).forEach(([, caps]) => {
strip(caps.capabilities as WebdriverIO.Capabilities)
})
}
}
_updateObjectTypeCaps(capabilities?: Capabilities.TestrunnerCapabilities | WebdriverIO.Capabilities, capType?: string, value?: { [key: string]: unknown }) {
try {
if (Array.isArray(capabilities)) {
capabilities
.flatMap((c) => {
if ('alwaysMatch' in c) {
return c.alwaysMatch as WebdriverIO.Capabilities
}
if (Object.values(c).length > 0 && Object.values(c).every(c => typeof c === 'object' && c.capabilities)) {
return Object.values(c).map((o) => o.capabilities) as WebdriverIO.Capabilities[]
}
return c as WebdriverIO.Capabilities
})
.forEach((capability: WebdriverIO.Capabilities) => {
if (
validateCapsWithNonBstackA11y(capability.browserName, capability.browserVersion) &&
capType === 'goog:chromeOptions' && value
) {
const chromeOptions = capability['goog:chromeOptions'] as unknown as Capabilities.ChromeOptions
if (chromeOptions){
const finalChromeOptions = mergeChromeOptions(chromeOptions, value)
capability['goog:chromeOptions'] = finalChromeOptions
} else {
capability['goog:chromeOptions'] = value
}
return
}
if (!capability['bstack:options']) {
const extensionCaps = Object.keys(capability).filter((cap) => cap.includes(':'))
if (extensionCaps.length) {
if (capType === 'accessibilityOptions' && value) {
capability['bstack:options'] = { accessibilityOptions: value }
}
} else if (capType === 'accessibilityOptions') {
if (value) {
const accessibilityOpts = { ...value }
// @ts-expect-error fix invalid cap
if (capability?.accessibility) {
accessibilityOpts.authToken = process.env.BSTACK_A11Y_JWT
accessibilityOpts.scannerVersion = process.env.BSTACK_A11Y_SCANNER_VERSION
}
capability['browserstack.accessibilityOptions'] = accessibilityOpts
} else {
delete capability['browserstack.accessibilityOptions']
}
}
} else if (capType === 'accessibilityOptions') {
if (value) {
const accessibilityOpts = { ...value }
if (capability['bstack:options'].accessibility) {
accessibilityOpts.authToken = process.env.BSTACK_A11Y_JWT
accessibilityOpts.scannerVersion = process.env.BSTACK_A11Y_SCANNER_VERSION
}
capability['bstack:options'].accessibilityOptions = accessibilityOpts
} else {
delete capability['bstack:options'].accessibilityOptions
}
}
})
} else if (typeof capabilities === 'object') {
Object.entries(capabilities as Capabilities.RequestedMultiremoteCapabilities).forEach(([, caps]) => {
if (
validateCapsWithNonBstackA11y(
(caps.capabilities as WebdriverIO.Capabilities).browserName,
(caps.capabilities as WebdriverIO.Capabilities).browserVersion
) &&
capType === 'goog:chromeOptions' && value
) {
const chromeOptions = (caps.capabilities as WebdriverIO.Capabilities)['goog:chromeOptions'] as unknown as Capabilities.ChromeOptions
if (chromeOptions) {
const finalChromeOptions = mergeChromeOptions(chromeOptions, value);
(caps.capabilities as WebdriverIO.Capabilities)['goog:chromeOptions'] = finalChromeOptions
} else {
(caps.capabilities as WebdriverIO.Capabilities)['goog:chromeOptions'] = value
}
return
}
if (!(caps.capabilities as WebdriverIO.Capabilities)['bstack:options']) {
const extensionCaps = Object.keys(caps.capabilities).filter((cap) => cap.includes(':'))
if (extensionCaps.length) {
if (capType === 'accessibilityOptions' && value) {
(caps.capabilities as WebdriverIO.Capabilities)['bstack:options'] = { accessibilityOptions: value }
}
} else if (capType === 'accessibilityOptions') {
if (value) {
const accessibilityOpts = { ...value }
if ((caps.capabilities as WebdriverIO.Capabilities)['browserstack.accessibility']) {
accessibilityOpts.authToken = process.env.BSTACK_A11Y_JWT
accessibilityOpts.scannerVersion = process.env.BSTACK_A11Y_SCANNER_VERSION
}
(caps.capabilities as WebdriverIO.Capabilities)['browserstack.accessibilityOptions'] = accessibilityOpts
} else {
delete (caps.capabilities as WebdriverIO.Capabilities)['browserstack.accessibilityOptions']
}
}