-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
script_utils.ts
56 lines (46 loc) · 1.82 KB
/
script_utils.ts
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
import _ from 'lodash'
import Bluebird from 'bluebird'
import $networkUtils from './network_utils'
import $sourceMapUtils from './source_map_utils'
const fetchScript = (scriptWindow, script) => {
return $networkUtils.fetch(script.relativeUrl, scriptWindow)
.then((contents) => {
return [script, contents]
})
}
const extractSourceMap = ([script, contents]) => {
script.fullyQualifiedUrl = `${window.top!.location.origin}${script.relativeUrl}`.replace(/ /g, '%20')
const sourceMap = $sourceMapUtils.extractSourceMap(script, contents)
return $sourceMapUtils.initializeSourceMapConsumer(script, sourceMap)
.catch((_err) => {
// if WebAssembly is missing, we can't consume source maps, but it shouldn't block Cy
// like in WebKit on Windows: https://github.com/microsoft/playwright/issues/2876
})
.then(() => [script, contents])
}
const evalScripts = (specWindow, scripts: any = []) => {
_.each(scripts, ([script, contents]) => {
specWindow.eval(`${contents}\n//# sourceURL=${script.fullyQualifiedUrl}`)
})
return null
}
const runScriptsFromUrls = (specWindow, scripts) => {
return Bluebird
.map<any, any>(scripts, (script) => fetchScript(specWindow, script))
.map(extractSourceMap)
.then((scripts) => evalScripts(specWindow, scripts))
}
// Supports either scripts as objects or as async import functions
export default {
runScripts: (specWindow, scripts) => {
// if scripts contains at least one promise
if (scripts.length && typeof scripts[0] === 'function') {
// chain the loading promises
// NOTE: since in evalScripts, scripts are evaluated in order,
// we chose to respect this constraint here too.
// indeed _.each goes through the array in order
return Bluebird.each(scripts, (script: any) => script())
}
return runScriptsFromUrls(specWindow, scripts)
},
}