-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
288 lines (224 loc) · 7.98 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
const puppeteer = require("puppeteer")
const log = require('loglevel')
const path = require("path")
const fs = require('fs')
const http = require('http');
const https = require('https');
let browser
let page
let screenShotPath = ".screenshot"
let userAgent = "CloudWatchSynthetics-Local"
let index = 0
let logLevel = 1;
function setLogLevel(l) {
console.info("local-logger setting log level to ", l);
if (typeof l === "number" && (l === 0 || l === 1 || l === 2 || l === 3)) {
logLevel = l
log.setLevel(l + 1)
return
}
throw new Error("log level must be 0 | 1 | 2 | 3")
}
function getLogLevel() {
return logLevel
}
exports.setLogLevel = setLogLevel
exports.getLogLevel = getLogLevel
exports.debug = function () { log.debug.apply(log, arguments) }
exports.error = function () { log.error.apply(log, arguments) }
exports.info = function () { log.info.apply(log, arguments) }
exports.log = function () { log.log.apply(log, arguments) }
exports.warn = function () { log.warn.apply(log, arguments) }
exports.addUserAgent = async (page, userAgentString) => {
userAgent += " " + userAgentString
await page.setUserAgent(userAgent)
}
exports.getCanaryUserAgentString = () => {
return userAgent
}
function setConfig(config){
return;
}
function getConfiguration() {
return {
setConfig: setConfig
}
}
exports.getConfiguration = getConfiguration
function setUpDebugLoggingOfPage(page) {
// Emitted when the DOM is parsed and ready (without waiting for resources)
page.once('domcontentloaded', () => log.info('✅ DOM is ready'));
// Emitted when the page is fully loaded
page.once('load', () => log.info('✅ Page is loaded'));
// Emitted when the page attaches a frame
page.on('frameattached', () => log.info('✅ Frame is attached'));
// Emitted when a frame within the page is navigated to a new URL
page.on('framenavigated', () => log.info('👉 Frame is navigated'));
// Emitted when a script within the page uses `console.timeStamp`
// @ts-ignore
page.on('metrics', data => log.info(`👉 Timestamp added at ${data.metrics.Timestamp}`));
// Emitted when a script within the page uses `console`
// @ts-ignore
page.on('console', message => log.info(`[${message.type()}] 👉 ${message.text()}`));
// Emitted when the page emits an error event (for example, the page crashes)
// @ts-ignore
page.on('error', error => log.error(`❌ ${error}`));
// Emitted when a script within the page has uncaught exception
// @ts-ignore
page.on('pageerror', error => log.error(`❌ ${error}`));
// Emitted when a script within the page uses `alert`, `prompt`, `confirm` or `beforeunload`
// @ts-ignore
page.on('dialog', async dialog => {
log.info(`👉 ${dialog.message()}`);
await dialog.dismiss();
});
// Emitted when a new page, that belongs to the browser context, is opened
page.on('popup', () => log.info('👉 New page is opened'));
// Emitted when the page produces a request
// @ts-ignore
page.on('request', request => log.info(`👉 Request: ${request.url()}`));
// Emitted when a request, which is produced by the page, fails
// @ts-ignore
page.on('requestfailed', request => log.info(`❌ Failed request: ${request.url()}`));
// Emitted when a request, which is produced by the page, finishes successfully
// @ts-ignore
page.on('requestfinished', request => log.info(`👉 Finished request: ${request.url()}`));
// Emitted when a response is received
// @ts-ignore
page.on('response', response => log.info(`👉 Response: ${response.url()}`));
// Emitted when the page creates a dedicated WebWorker
// @ts-ignore
page.on('workercreated', worker => log.info(`👉 Worker: ${worker.url()}`));
// Emitted when the page destroys a dedicated WebWorker
// @ts-ignore
page.on('workerdestroyed', worker => log.info(`👉 Destroyed worker: ${worker.url()}`));
// Emitted when the page detaches a frame
page.on('framedetached', () => log.info('✅ Frame is detached'));
// Emitted after the page is closed
page.once('close', () => log.info('✅ Page is closed'));
}
exports.getPage = async () => {
const pages = await this.browser.pages()
console.log(pages.length)
if (pages.length <= 1) {
this.page = await this.browser.newPage()
}
if(logLevel === 0){
log.warn("Attaching debug logger to page")
setUpDebugLoggingOfPage(this.page);
}
return this.page
}
exports.executeHttpStep = async (stepName, requestOptions, validateFn, stepConfig) => {
let req;
if(requestOptions['protocol'] === 'https:'){
req = https.request(requestOptions, validateFn);
}else{
req = http.request(requestOptions, validateFn);
}
if(requestOptions['body']) {
req.write(requestOptions['body'])
}
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
console.info(`PASS ${stepName}` )
}
exports.executeStep = async (stepName = null, func) => {
index++;
let currIdx = index
let name = ""
if (stepName !== null) {
name = `-${stepName}`
}
log.info(`executeStep "${currIdx}${name}" start`)
await this.page.screenshot({path: path.join(screenShotPath, `${currIdx}${name}-starting.png`)})
const start = Date.now()
try {
await func()
log.info(`executeStep "${currIdx}${name}" succeeded`)
await this.page.screenshot({path: path.join(screenShotPath, `${currIdx}${name}-succeeded.png`)})
} catch (e) {
log.info(e)
log.info(`executeStep "${currIdx}${name}" failed`)
await this.page.screenshot({path: path.join(screenShotPath, `${currIdx}${name}-failed.png`)})
throw e
} finally {
const end = Date.now()
const d = end - start
log.info(`${name}: ${Math.floor(d / 1000)} seconds`)
}
}
exports.takeScreenshot = async (stepName, suffix) => {
index++;
let currIdx = index
return await this.page.screenshot({path: path.join(screenShotPath, `${currIdx}-${stepName}-${suffix}.png`)})
}
exports.getRequestResponseLogHelper = () => {
return helper
}
exports.setRequestResponseLogHelper = (newHelper) => {
helper = newHelper
}
let helper = function () {
let RequestResponseLogHelper = () => {
this.request = {url: true, resourceType: false, method: false, headers: false, postData: false};
this.response = {status: true, statusText: true, url: true, remoteAddress: false, headers: false};
}
RequestResponseLogHelper.prototype.withLogRequestUrl = (b) => {
this.request.url = b
}
RequestResponseLogHelper.prototype.withLogRequestResourceType = (b) => {
this.request.resourceType = b
}
RequestResponseLogHelper.prototype.withLogRequestMethod = (b) => {
this.request.method = b
}
RequestResponseLogHelper.prototype.withLogRequestHeaders = (b) => {
this.request.headers = b
}
RequestResponseLogHelper.prototype.withLogRequestPostData = (b) => {
this.request.postData = b
}
RequestResponseLogHelper.prototype.withLogResponseStatus = (b) => {
this.response.status = b
}
RequestResponseLogHelper.prototype.withLogResponseStatusText = (b) => {
this.response.statusText = b
}
RequestResponseLogHelper.prototype.withLogResponseUrl = (b) => {
this.response.url = b
}
RequestResponseLogHelper.prototype.withLogResponseRemoteAddress = (b) => {
this.response.remoteAddress = b
}
RequestResponseLogHelper.prototype.withLogResponseHeaders = (b) => {
this.response.headers = b
}
return {
RequestResponseLogHelper: RequestResponseLogHelper
}
}
// ***********************************************************************
exports.start = async (headlessMode, screenshotDir, slowMo=0) => {
if (!fs.existsSync(screenshotDir)) {
fs.mkdirSync(screenshotDir)
}
screenShotPath=screenshotDir
log.debug(`Saving screenshots to ${screenshotDir}`);
this.browser = await puppeteer.launch({
headless: headlessMode,
defaultViewport: {
width: 1024,
height: 768,
},
slowMo: slowMo
})
if(slowMo>0) {
log.warn(`Browser slowed down by ${slowMo}`)
}
}
exports.close = async () => {
await this.browser.close()
}