@elastic/synthetics 1.0.0-beta.4 → 1.0.0-beta.40

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.
Files changed (220) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +137 -160
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +159 -31
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/config.d.ts +3 -5
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +7 -6
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/browser-service.d.ts +1 -1
  11. package/dist/core/browser-service.d.ts.map +1 -1
  12. package/dist/core/browser-service.js +7 -6
  13. package/dist/core/browser-service.js.map +1 -1
  14. package/dist/core/expect.d.ts +25 -25
  15. package/dist/core/expect.d.ts.map +1 -1
  16. package/dist/core/expect.js.map +1 -1
  17. package/dist/core/gatherer.d.ts +4 -8
  18. package/dist/core/gatherer.d.ts.map +1 -1
  19. package/dist/core/gatherer.js +50 -15
  20. package/dist/core/gatherer.js.map +1 -1
  21. package/dist/core/index.d.ts +5 -1
  22. package/dist/core/index.d.ts.map +1 -1
  23. package/dist/core/index.js +23 -11
  24. package/dist/core/index.js.map +1 -1
  25. package/dist/core/logger.d.ts +0 -1
  26. package/dist/core/logger.d.ts.map +1 -1
  27. package/dist/core/logger.js +3 -16
  28. package/dist/core/logger.js.map +1 -1
  29. package/dist/core/runner.d.ts +12 -63
  30. package/dist/core/runner.d.ts.map +1 -1
  31. package/dist/core/runner.js +156 -90
  32. package/dist/core/runner.js.map +1 -1
  33. package/dist/core/transform.d.ts +37 -0
  34. package/dist/core/transform.d.ts.map +1 -0
  35. package/dist/core/transform.js +148 -0
  36. package/dist/core/transform.js.map +1 -0
  37. package/dist/dsl/index.js +5 -1
  38. package/dist/dsl/index.js.map +1 -1
  39. package/dist/dsl/journey.d.ts +9 -4
  40. package/dist/dsl/journey.d.ts.map +1 -1
  41. package/dist/dsl/journey.js +37 -9
  42. package/dist/dsl/journey.js.map +1 -1
  43. package/dist/dsl/monitor.d.ts +83 -0
  44. package/dist/dsl/monitor.d.ts.map +1 -0
  45. package/dist/dsl/monitor.js +108 -0
  46. package/dist/dsl/monitor.js.map +1 -0
  47. package/dist/dsl/step.d.ts +3 -2
  48. package/dist/dsl/step.d.ts.map +1 -1
  49. package/dist/dsl/step.js +6 -1
  50. package/dist/dsl/step.js.map +1 -1
  51. package/dist/formatter/javascript.d.ts +98 -0
  52. package/dist/formatter/javascript.d.ts.map +1 -0
  53. package/dist/formatter/javascript.js +298 -0
  54. package/dist/formatter/javascript.js.map +1 -0
  55. package/dist/generator/index.d.ts +24 -0
  56. package/dist/generator/index.d.ts.map +1 -0
  57. package/dist/generator/index.js +241 -0
  58. package/dist/generator/index.js.map +1 -0
  59. package/dist/{reporters/reporter.js → generator/utils.d.ts} +5 -3
  60. package/dist/generator/utils.d.ts.map +1 -0
  61. package/dist/generator/utils.js +84 -0
  62. package/dist/generator/utils.js.map +1 -0
  63. package/dist/helpers.d.ts +28 -3
  64. package/dist/helpers.d.ts.map +1 -1
  65. package/dist/helpers.js +152 -20
  66. package/dist/helpers.js.map +1 -1
  67. package/dist/index.d.ts +6 -7
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +5 -26
  70. package/dist/index.js.map +1 -1
  71. package/dist/loader.d.ts +34 -0
  72. package/dist/loader.d.ts.map +1 -0
  73. package/dist/loader.js +149 -0
  74. package/dist/loader.js.map +1 -0
  75. package/dist/locations/index.d.ts +45 -0
  76. package/dist/locations/index.d.ts.map +1 -0
  77. package/dist/locations/index.js +83 -0
  78. package/dist/locations/index.js.map +1 -0
  79. package/dist/{reporters/reporter.d.ts → locations/public-locations.d.ts} +12 -8
  80. package/dist/locations/public-locations.d.ts.map +1 -0
  81. package/dist/locations/public-locations.js +41 -0
  82. package/dist/locations/public-locations.js.map +1 -0
  83. package/dist/options.d.ts +41 -0
  84. package/dist/options.d.ts.map +1 -0
  85. package/dist/options.js +198 -0
  86. package/dist/options.js.map +1 -0
  87. package/dist/plugins/browser-console.d.ts +5 -4
  88. package/dist/plugins/browser-console.d.ts.map +1 -1
  89. package/dist/plugins/browser-console.js +44 -24
  90. package/dist/plugins/browser-console.js.map +1 -1
  91. package/dist/plugins/index.js +5 -1
  92. package/dist/plugins/index.js.map +1 -1
  93. package/dist/plugins/network.d.ts +20 -33
  94. package/dist/plugins/network.d.ts.map +1 -1
  95. package/dist/plugins/network.js +177 -216
  96. package/dist/plugins/network.js.map +1 -1
  97. package/dist/plugins/performance.d.ts +4 -19
  98. package/dist/plugins/performance.d.ts.map +1 -1
  99. package/dist/plugins/performance.js +6 -5
  100. package/dist/plugins/performance.js.map +1 -1
  101. package/dist/plugins/plugin-manager.d.ts +9 -5
  102. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  103. package/dist/plugins/plugin-manager.js +46 -30
  104. package/dist/plugins/plugin-manager.js.map +1 -1
  105. package/dist/plugins/tracing.d.ts +6 -6
  106. package/dist/plugins/tracing.d.ts.map +1 -1
  107. package/dist/plugins/tracing.js +10 -7
  108. package/dist/plugins/tracing.js.map +1 -1
  109. package/dist/push/bundler.d.ts +35 -0
  110. package/dist/push/bundler.d.ts.map +1 -0
  111. package/dist/push/bundler.js +131 -0
  112. package/dist/push/bundler.js.map +1 -0
  113. package/dist/push/index.d.ts +9 -0
  114. package/dist/push/index.d.ts.map +1 -0
  115. package/dist/push/index.js +227 -0
  116. package/dist/push/index.js.map +1 -0
  117. package/dist/push/kibana_api.d.ts +56 -0
  118. package/dist/push/kibana_api.d.ts.map +1 -0
  119. package/dist/push/kibana_api.js +135 -0
  120. package/dist/push/kibana_api.js.map +1 -0
  121. package/dist/push/monitor.d.ts +51 -0
  122. package/dist/push/monitor.d.ts.map +1 -0
  123. package/dist/push/monitor.js +244 -0
  124. package/dist/push/monitor.js.map +1 -0
  125. package/dist/{parse_args.d.ts → push/plugin.d.ts} +9 -6
  126. package/dist/push/plugin.d.ts.map +1 -0
  127. package/dist/push/plugin.js +66 -0
  128. package/dist/push/plugin.js.map +1 -0
  129. package/dist/push/request.d.ts +45 -0
  130. package/dist/push/request.d.ts.map +1 -0
  131. package/dist/push/request.js +109 -0
  132. package/dist/push/request.js.map +1 -0
  133. package/dist/push/utils.d.ts +31 -0
  134. package/dist/push/utils.d.ts.map +1 -0
  135. package/dist/push/utils.js +64 -0
  136. package/dist/push/utils.js.map +1 -0
  137. package/dist/reporters/base.d.ts +14 -6
  138. package/dist/reporters/base.d.ts.map +1 -1
  139. package/dist/reporters/base.js +58 -50
  140. package/dist/reporters/base.js.map +1 -1
  141. package/dist/reporters/index.d.ts +18 -8
  142. package/dist/reporters/index.d.ts.map +1 -1
  143. package/dist/reporters/index.js.map +1 -1
  144. package/dist/reporters/json.d.ts +18 -62
  145. package/dist/reporters/json.d.ts.map +1 -1
  146. package/dist/reporters/json.js +149 -179
  147. package/dist/reporters/json.js.map +1 -1
  148. package/dist/reporters/junit.d.ts +7 -1
  149. package/dist/reporters/junit.d.ts.map +1 -1
  150. package/dist/reporters/junit.js +90 -95
  151. package/dist/reporters/junit.js.map +1 -1
  152. package/dist/sdk/lh-trace-processor.d.ts +35 -9
  153. package/dist/sdk/lh-trace-processor.d.ts.map +1 -1
  154. package/dist/sdk/lh-trace-processor.js +114 -53
  155. package/dist/sdk/lh-trace-processor.js.map +1 -1
  156. package/dist/sdk/trace-metrics.d.ts +4 -4
  157. package/dist/sdk/trace-metrics.d.ts.map +1 -1
  158. package/dist/sdk/trace-metrics.js +3 -4
  159. package/dist/sdk/trace-metrics.js.map +1 -1
  160. package/dist/sdk/trace-processor.d.ts +11 -3
  161. package/dist/sdk/trace-processor.d.ts.map +1 -1
  162. package/dist/sdk/trace-processor.js +17 -9
  163. package/dist/sdk/trace-processor.js.map +1 -1
  164. package/package.json +39 -24
  165. package/src/cli.ts +219 -151
  166. package/src/common_types.ts +192 -31
  167. package/src/config.ts +3 -6
  168. package/src/core/expect.ts +58 -24
  169. package/src/core/gatherer.ts +59 -24
  170. package/src/core/index.ts +36 -15
  171. package/src/core/logger.ts +1 -12
  172. package/src/core/runner.ts +151 -136
  173. package/src/core/transform.ts +160 -0
  174. package/src/dsl/journey.ts +39 -6
  175. package/src/dsl/monitor.ts +140 -0
  176. package/src/dsl/step.ts +9 -2
  177. package/src/formatter/javascript.ts +367 -0
  178. package/src/generator/index.ts +308 -0
  179. package/src/generator/utils.ts +84 -0
  180. package/src/helpers.ts +159 -13
  181. package/src/index.ts +22 -22
  182. package/src/loader.ts +167 -0
  183. package/src/locations/index.ts +95 -0
  184. package/src/{reporters/reporter.ts → locations/public-locations.ts} +12 -9
  185. package/src/options.ts +227 -0
  186. package/src/plugins/browser-console.ts +30 -8
  187. package/src/plugins/network.ts +208 -267
  188. package/src/plugins/performance.ts +6 -22
  189. package/src/plugins/plugin-manager.ts +49 -31
  190. package/src/plugins/tracing.ts +8 -9
  191. package/src/push/bundler.ts +112 -0
  192. package/src/push/index.ts +282 -0
  193. package/src/push/kibana_api.ts +191 -0
  194. package/src/push/monitor.ts +276 -0
  195. package/src/push/plugin.ts +66 -0
  196. package/src/push/request.ts +141 -0
  197. package/src/push/utils.ts +77 -0
  198. package/src/reporters/base.ts +63 -52
  199. package/src/reporters/index.ts +26 -3
  200. package/src/reporters/json.ts +188 -202
  201. package/src/reporters/junit.ts +98 -93
  202. package/src/sdk/lh-trace-processor.ts +132 -68
  203. package/src/sdk/trace-metrics.ts +8 -4
  204. package/src/sdk/trace-processor.ts +28 -13
  205. package/templates/.github/workflows/run-synthetics.yml +27 -0
  206. package/templates/README.md +21 -0
  207. package/templates/journeys/advanced-example-helpers.ts +54 -0
  208. package/templates/journeys/advanced-example.journey.ts +43 -0
  209. package/templates/journeys/example.journey.ts +18 -0
  210. package/templates/lightweight/heartbeat.yml +7 -0
  211. package/templates/synthetics.config.ts +35 -0
  212. package/CHANGELOG.md +0 -131
  213. package/NOTICE.txt +0 -221
  214. package/dist/parse_args.d.ts.map +0 -1
  215. package/dist/parse_args.js +0 -95
  216. package/dist/parse_args.js.map +0 -1
  217. package/dist/reporters/reporter.d.ts.map +0 -1
  218. package/dist/reporters/reporter.js.map +0 -1
  219. package/dist/tsconfig.tsbuildinfo +0 -1888
  220. package/src/parse_args.ts +0 -135
@@ -0,0 +1,308 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+ import { execSync } from 'child_process';
26
+ import { existsSync } from 'fs';
27
+ import { mkdir, readFile, writeFile } from 'fs/promises';
28
+ import { bold, cyan, yellow } from 'kleur/colors';
29
+ import { join, relative, dirname, basename } from 'path';
30
+ // @ts-ignore-next-line: has no exported member 'Input'
31
+ import { prompt, Input } from 'enquirer';
32
+ import {
33
+ getMonitorManagementURL,
34
+ progress,
35
+ write as stdWrite,
36
+ } from '../helpers';
37
+ import {
38
+ getPackageManager,
39
+ replaceTemplates,
40
+ runCommand,
41
+ cloudIDToKibanaURL,
42
+ } from './utils';
43
+ import { formatLocations, getLocations, groupLocations } from '../locations';
44
+ import { ALLOWED_SCHEDULES } from '../dsl/monitor';
45
+ import type { ProjectSettings } from '../common_types';
46
+
47
+ // Templates that are required for setting up new synthetics project
48
+ const templateDir = join(__dirname, '..', '..', 'templates');
49
+
50
+ type PromptOptions = ProjectSettings & {
51
+ locations: Array<string>;
52
+ privateLocations: Array<string>;
53
+ schedule: number;
54
+ };
55
+
56
+ // exported for testing
57
+ export const REGULAR_FILES_PATH = [
58
+ 'journeys/example.journey.ts',
59
+ 'journeys/advanced-example-helpers.ts',
60
+ 'journeys/advanced-example.journey.ts',
61
+ 'lightweight/heartbeat.yml',
62
+ '.github/workflows/run-synthetics.yml',
63
+ 'README.md',
64
+ ];
65
+ export const CONFIG_PATH = 'synthetics.config.ts';
66
+
67
+ export class Generator {
68
+ pkgManager = 'npm';
69
+ constructor(public projectDir: string) {}
70
+
71
+ async directory() {
72
+ progress(
73
+ `Initializing Synthetics project in '${
74
+ relative(process.cwd(), this.projectDir) || '.'
75
+ }'`
76
+ );
77
+ if (!existsSync(this.projectDir)) {
78
+ await mkdir(this.projectDir);
79
+ }
80
+ }
81
+
82
+ async questions() {
83
+ if (process.env.TEST_QUESTIONS) {
84
+ return JSON.parse(process.env.TEST_QUESTIONS);
85
+ }
86
+
87
+ const { onCloud } = await prompt<{ onCloud: string }>({
88
+ type: 'confirm',
89
+ name: 'onCloud',
90
+ initial: 'y',
91
+ message: 'Do you use Elastic Cloud',
92
+ });
93
+ const url = await new Input({
94
+ header: onCloud
95
+ ? yellow(
96
+ 'Get cloud.id from your deployment https://www.elastic.co/guide/en/cloud/current/ec-cloud-id.html'
97
+ )
98
+ : '',
99
+ message: onCloud
100
+ ? 'What is your cloud.id'
101
+ : 'What is the url of your Kibana instance',
102
+ name: 'url',
103
+ required: true,
104
+ result(value) {
105
+ return onCloud ? cloudIDToKibanaURL(value) : value;
106
+ },
107
+ }).run();
108
+
109
+ const auth = await new Input({
110
+ name: 'auth',
111
+ header: yellow(
112
+ `Generate API key from Kibana ${getMonitorManagementURL(url)}`
113
+ ),
114
+ required: true,
115
+ message: 'What is your API key',
116
+ }).run();
117
+
118
+ const allLocations = await getLocations({ url, auth });
119
+ const locChoices = formatLocations(allLocations);
120
+ if (locChoices.length === 0) {
121
+ throw 'Follow the docs to set up your first private locations - https://www.elastic.co/guide/en/observability/current/uptime-set-up-choose-agent.html#private-locations';
122
+ }
123
+
124
+ const monitorQues = [
125
+ {
126
+ type: 'select',
127
+ name: 'locations',
128
+ hint: '(Use <space> to select, <return> to submit)',
129
+ message: 'Select the locations where you want to run monitors',
130
+ choices: locChoices,
131
+ multiple: true,
132
+ validate(value) {
133
+ return value.length === 0 ? `Select at least one option.` : true;
134
+ },
135
+ },
136
+ {
137
+ type: 'select',
138
+ name: 'schedule',
139
+ message: 'Set default schedule in minutes for all monitors',
140
+ initial: 3, // Index of the third array item which is 10 minutes
141
+ choices: ALLOWED_SCHEDULES.map(String),
142
+ required: true,
143
+ result(value) {
144
+ return Number(value) as any;
145
+ },
146
+ },
147
+ {
148
+ type: 'input',
149
+ name: 'id',
150
+ message: 'Choose project id to logically group monitors',
151
+ initial: basename(this.projectDir),
152
+ },
153
+ {
154
+ type: 'input',
155
+ name: 'space',
156
+ message: 'Choose the target Kibana space',
157
+ initial: 'default',
158
+ },
159
+ ];
160
+
161
+ // Split and group private and public locations from the answered list.
162
+ const answers = await prompt<PromptOptions>(monitorQues);
163
+ const { locations, privateLocations } = groupLocations(answers.locations);
164
+ return { ...answers, url, locations, privateLocations };
165
+ }
166
+
167
+ async files(answers: PromptOptions) {
168
+ const fileMap = new Map<string, string>();
169
+
170
+ // Setup Synthetics config file
171
+ fileMap.set(
172
+ CONFIG_PATH,
173
+ replaceTemplates(
174
+ await readFile(join(templateDir, CONFIG_PATH), 'utf-8'),
175
+ answers
176
+ )
177
+ );
178
+
179
+ // Setup non-templated files
180
+ Promise.all(
181
+ REGULAR_FILES_PATH.map(async file => {
182
+ fileMap.set(file, await readFile(join(templateDir, file), 'utf-8'));
183
+ })
184
+ ).catch(e => {
185
+ throw e;
186
+ });
187
+
188
+ // Create files
189
+ for (const [relativePath, content] of fileMap) {
190
+ await this.createFile(relativePath, content);
191
+ }
192
+ }
193
+
194
+ async createFile(relativePath: string, content: string, override = false) {
195
+ const absolutePath = join(this.projectDir, relativePath);
196
+
197
+ if (!override && existsSync(absolutePath)) {
198
+ const { override } = await prompt<{ override: boolean }>({
199
+ type: 'confirm',
200
+ name: 'override',
201
+ message: `File ${relativePath} already exists. Override it?`,
202
+ initial: false,
203
+ });
204
+ if (!override) return;
205
+ }
206
+
207
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
208
+ await mkdir(dirname(absolutePath), { recursive: true });
209
+ await writeFile(absolutePath, content, 'utf-8');
210
+ }
211
+
212
+ async package() {
213
+ this.pkgManager = await getPackageManager(this.projectDir);
214
+ const commands = new Map<string, string>();
215
+ commands.set(
216
+ `Setting up project using ${this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'}`,
217
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
218
+ );
219
+
220
+ const pkgName = '@elastic/synthetics';
221
+ commands.set(
222
+ `Installing @elastic/synthetics library`,
223
+ this.pkgManager == 'yarn'
224
+ ? `yarn add -dev ${pkgName} --silent`
225
+ : `npm i -d ${pkgName} --quiet`
226
+ );
227
+
228
+ // Execute commands
229
+ for (const [name, command] of commands) {
230
+ progress(`${name}...`);
231
+ execSync(command, {
232
+ stdio: 'inherit',
233
+ cwd: this.projectDir,
234
+ });
235
+ }
236
+ }
237
+
238
+ async patchPkgJSON() {
239
+ const filename = 'package.json';
240
+ const pkgJSON = JSON.parse(
241
+ await readFile(join(this.projectDir, filename), 'utf-8')
242
+ );
243
+
244
+ if (!pkgJSON.scripts) {
245
+ pkgJSON.scripts = {};
246
+ }
247
+ // Add test command
248
+ if (!pkgJSON.scripts.test) {
249
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
250
+ }
251
+ // Add push command
252
+ if (!pkgJSON.scripts.push) {
253
+ pkgJSON.scripts.push = 'npx @elastic/synthetics push';
254
+ }
255
+
256
+ await this.createFile(
257
+ filename,
258
+ JSON.stringify(pkgJSON, null, 2) + '\n',
259
+ true
260
+ );
261
+ }
262
+
263
+ async patchGitIgnore() {
264
+ const gitIgnorePath = join(this.projectDir, '.gitignore');
265
+ let gitIgnore = '';
266
+ if (existsSync(gitIgnorePath)) {
267
+ const contents = await readFile(gitIgnorePath, 'utf-8');
268
+ gitIgnore += contents.trimEnd() + '\n';
269
+ }
270
+ if (!gitIgnore.includes('node_modules')) {
271
+ gitIgnore += 'node_modules/\n';
272
+ }
273
+ if (!gitIgnore.includes('.synthetics')) {
274
+ gitIgnore += '.synthetics/\n';
275
+ }
276
+ await writeFile(gitIgnorePath, gitIgnore, 'utf-8');
277
+ }
278
+
279
+ banner() {
280
+ stdWrite(
281
+ bold(`
282
+ All set, you can run below commands inside: ${this.projectDir}:
283
+
284
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
285
+
286
+ Push monitors to Kibana: ${cyan(
287
+ 'SYNTHETICS_API_KEY=<value> ' + runCommand(this.pkgManager, 'push')
288
+ )}
289
+
290
+ ${yellow(
291
+ 'Make sure to configure the SYNTHETICS_API_KEY before pushing monitors to Kibana.'
292
+ )}
293
+
294
+ Visit https://www.elastic.co/guide/en/observability/current/synthetic-run-tests.html to learn more.
295
+ `)
296
+ );
297
+ }
298
+
299
+ async setup() {
300
+ await this.directory();
301
+ const answers = await this.questions();
302
+ await this.package();
303
+ await this.files(answers);
304
+ await this.patchPkgJSON();
305
+ await this.patchGitIgnore();
306
+ this.banner();
307
+ }
308
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import { existsSync } from 'fs';
27
+ import { join } from 'path';
28
+
29
+ export async function getPackageManager(dir: string) {
30
+ if (existsSync(join(dir, 'yarn.lock'))) {
31
+ return 'yarn';
32
+ }
33
+ return 'npm';
34
+ }
35
+
36
+ export function runCommand(pkgManager: string, command: string) {
37
+ if (pkgManager === 'yarn') {
38
+ return `yarn ${command}`;
39
+ }
40
+ return `npm run ${command}`;
41
+ }
42
+
43
+ export function replaceTemplates(input: string, values: Record<string, any>) {
44
+ for (const key in values) {
45
+ const finalValue = values[key];
46
+ input = input.replace(new RegExp(`'{{` + key + `}}'`, 'g'), () => {
47
+ if (Array.isArray(finalValue)) {
48
+ return String(finalValue)
49
+ .split(',')
50
+ .filter(Boolean)
51
+ .map(f => `'${f}'`);
52
+ }
53
+ if (typeof finalValue == 'number') {
54
+ return Number(finalValue);
55
+ }
56
+ if (typeof finalValue == 'string') {
57
+ return `'${finalValue}'`;
58
+ }
59
+ return finalValue;
60
+ });
61
+ }
62
+ return input;
63
+ }
64
+
65
+ export function cloudIDToKibanaURL(id: string) {
66
+ const ID_SEPARATOR = ':';
67
+ const VALUE_SEPARATOR = '$';
68
+ // Ignore values before the separator
69
+ const index = id.lastIndexOf(ID_SEPARATOR);
70
+ if (index >= 0) {
71
+ id = id.substring(index + 1);
72
+ }
73
+
74
+ // Decode the base64 string
75
+ const decoded = Buffer.from(id, 'base64').toString();
76
+ const words = decoded.split(VALUE_SEPARATOR);
77
+
78
+ // construct the kibana and ES urls from decoded value
79
+ const [host, port = '443'] = words[0].split(ID_SEPARATOR);
80
+ const [kibanaId, kibanaPort = port] = words[2].split(ID_SEPARATOR);
81
+ const kibanaURL = `https://${kibanaId}.${host}:${kibanaPort}`;
82
+
83
+ return kibanaURL;
84
+ }
package/src/helpers.ts CHANGED
@@ -23,16 +23,21 @@
23
23
  *
24
24
  */
25
25
 
26
- import { red, green, yellow, cyan } from 'kleur/colors';
26
+ import { red, green, yellow, cyan, bold, grey } from 'kleur/colors';
27
27
  import os from 'os';
28
28
  import { resolve, join, dirname } from 'path';
29
29
  import fs from 'fs';
30
- import { promisify } from 'util';
30
+ import { lstat, readdir } from 'fs/promises';
31
31
  import { performance } from 'perf_hooks';
32
- import { HooksArgs, HooksCallback } from './common_types';
32
+ import sourceMapSupport from 'source-map-support';
33
+ import {
34
+ HooksArgs,
35
+ HooksCallback,
36
+ NetworkConditions,
37
+ Location,
38
+ ThrottlingOptions,
39
+ } from './common_types';
33
40
 
34
- const statAsync = promisify(fs.lstat);
35
- const readAsync = promisify(fs.readdir);
36
41
  const SEPARATOR = '\n';
37
42
 
38
43
  export function noop() {}
@@ -41,11 +46,17 @@ export function indent(lines: string, tab = ' ') {
41
46
  return lines.replace(/^/gm, tab);
42
47
  }
43
48
 
49
+ /**
50
+ * Disable unicode symbols for windows, the underlying
51
+ * FS stream has a known issue in windows
52
+ */
53
+ const NO_UTF8_SUPPORT = process.platform === 'win32';
44
54
  export const symbols = {
45
- warning: yellow('⚠'),
55
+ warning: yellow(NO_UTF8_SUPPORT ? '!' : '⚠'),
46
56
  skipped: cyan('-'),
47
- succeeded: green('✓'),
48
- failed: red('✖'),
57
+ progress: cyan('>'),
58
+ succeeded: green(NO_UTF8_SUPPORT ? 'ok' : '✓'),
59
+ failed: red(NO_UTF8_SUPPORT ? 'x' : '✖'),
49
60
  };
50
61
 
51
62
  export function generateUniqueId() {
@@ -159,11 +170,11 @@ export async function totalist(
159
170
  pre = ''
160
171
  ) {
161
172
  dir = resolve('.', dir);
162
- await readAsync(dir).then(arr => {
173
+ await readdir(dir).then(arr => {
163
174
  return Promise.all(
164
175
  arr.map(str => {
165
176
  const abs = join(dir, str);
166
- return statAsync(abs).then(stats =>
177
+ return lstat(abs).then(stats =>
167
178
  stats.isDirectory()
168
179
  ? totalist(abs, callback, join(pre, str))
169
180
  : callback(join(pre, str), abs)
@@ -222,10 +233,21 @@ export function rewriteErrorStack(stack: string, indexes: [number, number]) {
222
233
  return stack;
223
234
  }
224
235
 
225
- export function formatError(error: Error) {
226
- if (!(error instanceof Error)) {
236
+ // formatError prefers receiving proper Errors, but since at runtime
237
+ // non Error exceptions can be thrown, it tolerates though. The
238
+ // redundant type Error | any expresses that.
239
+ export function formatError(error: Error | any) {
240
+ if (error === undefined || error === null) {
227
241
  return;
228
242
  }
243
+
244
+ if (!(error instanceof Error)) {
245
+ return {
246
+ message: `Error "${error}" received, with type "${typeof error}". (Do not throw exceptions without using \`new Error("my message")\`)`,
247
+ name: '',
248
+ stack: '',
249
+ };
250
+ }
229
251
  const { name, message, stack } = error;
230
252
  const indexes = findPWLogsIndexes(message);
231
253
  return {
@@ -236,13 +258,137 @@ export function formatError(error: Error) {
236
258
  }
237
259
 
238
260
  const cwd = process.cwd();
261
+ /**
262
+ * All the settings that are related to the Synthetics is stored
263
+ * under this directory
264
+ * Examples: Screenshots, Project setup
265
+ */
266
+ export const SYNTHETICS_PATH = join(cwd, '.synthetics');
239
267
  /**
240
268
  * Synthetics cache path that is based on the process id to make sure
241
269
  * each process does not modify the caching layer used by other process
242
270
  * once we move to executing journeys in parallel
243
271
  */
244
- export const CACHE_PATH = join(cwd, '.synthetics', process.pid.toString());
272
+ export const CACHE_PATH = join(SYNTHETICS_PATH, process.pid.toString());
245
273
 
246
274
  export function getDurationInUs(duration: number) {
247
275
  return Math.trunc(duration * 1e6);
248
276
  }
277
+
278
+ export function megabitsToBytes(megabytes: number) {
279
+ return (megabytes * 1024 * 1024) / 8;
280
+ }
281
+
282
+ export const DEFAULT_THROTTLING_OPTIONS: ThrottlingOptions = {
283
+ download: 5,
284
+ upload: 3,
285
+ latency: 20,
286
+ };
287
+
288
+ /**
289
+ * Transforms the CLI throttling arguments in to format
290
+ * expected by Chrome devtools protocol NetworkConditions
291
+ */
292
+ export function getNetworkConditions(
293
+ throttlingOpts: ThrottlingOptions
294
+ ): NetworkConditions {
295
+ return {
296
+ downloadThroughput: megabitsToBytes(throttlingOpts.download),
297
+ uploadThroughput: megabitsToBytes(throttlingOpts.upload), // Devtools CDP expects format to be in bytes/second
298
+ latency: throttlingOpts.latency, // milliseconds,
299
+ offline: false,
300
+ };
301
+ }
302
+
303
+ const dstackTraceLimit = 10;
304
+
305
+ // Uses the V8 Stacktrace API to get the function location
306
+ // information - https://v8.dev/docs/stack-trace-api#customizing-stack-traces
307
+ export function wrapFnWithLocation<A extends unknown[], R>(
308
+ func: (location: Location, ...args: A) => R
309
+ ): (...args: A) => R {
310
+ return (...args) => {
311
+ const _prepareStackTrace = Error.prepareStackTrace;
312
+ Error.prepareStackTrace = (_, stackFrames) => {
313
+ // Deafult CallSite would not map to the original transpiled source
314
+ // correctly, So we use source-map-support to map the CallSite to the
315
+ // original source from our cached source map
316
+ const frame: NodeJS.CallSite = sourceMapSupport.wrapCallSite(
317
+ stackFrames[1]
318
+ );
319
+ return {
320
+ file: frame.getFileName(),
321
+ line: frame.getLineNumber(),
322
+ column: frame.getColumnNumber(),
323
+ };
324
+ };
325
+ Error.stackTraceLimit = 2;
326
+ const obj: { stack: Location } = {} as any;
327
+ Error.captureStackTrace(obj);
328
+ const location = obj.stack;
329
+ Error.stackTraceLimit = dstackTraceLimit;
330
+ Error.prepareStackTrace = _prepareStackTrace;
331
+ return func(location, ...args);
332
+ };
333
+ }
334
+
335
+ // Safely parse ND JSON (Newline delimitted JSON) chunks
336
+ export function safeNDJSONParse(data: string | string[]) {
337
+ // data may not be at proper newline boundaries, so we make sure everything is split
338
+ // on proper newlines
339
+ const chunks = Array.isArray(data) ? data : [data];
340
+ const lines = chunks.join('\n').split(/\r?\n/);
341
+ return lines
342
+ .filter(l => l.match(/\S/)) // remove blank lines
343
+ .map(line => {
344
+ try {
345
+ return JSON.parse(line);
346
+ } catch (e) {
347
+ throw `Error ${e} could not parse data '${line}'`;
348
+ }
349
+ });
350
+ }
351
+
352
+ // Console helpers
353
+ export function write(message: string, live?: boolean) {
354
+ process.stderr.write(message + (live ? '\r' : '\n'));
355
+ }
356
+
357
+ export function progress(message: string) {
358
+ write(cyan(bold(`${symbols.progress} ${message}`)));
359
+ }
360
+
361
+ export async function liveProgress(promise: Promise<any>, message: string) {
362
+ const start = now();
363
+ const interval = setInterval(() => {
364
+ apiProgress(`${message} (${Math.trunc(now() - start)}ms)`, true);
365
+ }, 500);
366
+ promise.finally(() => clearInterval(interval));
367
+ const result = await promise;
368
+ apiProgress(`${message} (${Math.trunc(now() - start)}ms)`);
369
+ return result;
370
+ }
371
+
372
+ export function apiProgress(message: string, live = false) {
373
+ write(grey(`> ${message}`), live);
374
+ }
375
+
376
+ export function error(message: string) {
377
+ write(red(message));
378
+ }
379
+
380
+ export function done(message: string) {
381
+ write(bold(green(`${symbols['succeeded']} ${message}`)));
382
+ }
383
+
384
+ export function warn(message: string) {
385
+ write(bold(yellow(`${symbols['warning']} ${message}`)));
386
+ }
387
+
388
+ export function removeTrailingSlash(url: string) {
389
+ return url.replace(/\/+$/, '');
390
+ }
391
+
392
+ export function getMonitorManagementURL(url) {
393
+ return removeTrailingSlash(url) + '/app/uptime/manage-monitors/all';
394
+ }
package/src/index.ts CHANGED
@@ -24,35 +24,24 @@
24
24
  */
25
25
 
26
26
  import { runner } from './core';
27
- import { RunOptions } from './core/runner';
28
- import { setLogger } from './core/logger';
29
- import sourceMapSupport from 'source-map-support';
27
+ import { RunOptions } from './common_types';
30
28
 
31
29
  export async function run(options: RunOptions) {
32
- /**
33
- * Install source map support
34
- */
35
- sourceMapSupport.install({
36
- environment: 'node',
37
- });
38
- /**
39
- * set up logger with appropriate file descriptor
40
- * to capture all the DEBUG logs when run through heartbeat
41
- */
42
- setLogger(options.outfd);
43
-
44
- try {
45
- return await runner.run(options);
46
- } catch (e) {
47
- console.error('Failed to run the test', e);
48
- process.exit(1);
49
- }
30
+ return runner.run(options);
50
31
  }
51
32
 
52
33
  /**
53
34
  * Export all core module functions
54
35
  */
55
- export { beforeAll, afterAll, journey, step, before, after } from './core';
36
+ export {
37
+ journey,
38
+ step,
39
+ monitor,
40
+ beforeAll,
41
+ afterAll,
42
+ before,
43
+ after,
44
+ } from './core';
56
45
  export { expect } from './core/expect';
57
46
  /**
58
47
  * Export all the driver related types to be consumed
@@ -63,6 +52,7 @@ export type {
63
52
  ChromiumBrowser,
64
53
  ChromiumBrowserContext,
65
54
  CDPSession,
55
+ APIRequestContext,
66
56
  } from 'playwright-chromium';
67
57
 
68
58
  /**
@@ -70,3 +60,13 @@ export type {
70
60
  */
71
61
  export type { default as Runner } from './core/runner';
72
62
  export type { Reporter, ReporterOptions } from './reporters';
63
+
64
+ export type { SyntheticsConfig } from './common_types';
65
+ export type {
66
+ Action,
67
+ ActionInContext,
68
+ Signal,
69
+ Step,
70
+ Steps,
71
+ actionTitle,
72
+ } from './formatter/javascript';