@elastic/synthetics 1.0.0-beta.3 → 1.0.0-beta.32

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 (202) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +123 -161
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +159 -34
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/config.d.ts +2 -5
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +5 -5
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/browser-service.js +5 -5
  11. package/dist/core/browser-service.js.map +1 -1
  12. package/dist/core/expect.d.ts +25 -25
  13. package/dist/core/expect.d.ts.map +1 -1
  14. package/dist/core/expect.js.map +1 -1
  15. package/dist/core/gatherer.d.ts +4 -8
  16. package/dist/core/gatherer.d.ts.map +1 -1
  17. package/dist/core/gatherer.js +49 -15
  18. package/dist/core/gatherer.js.map +1 -1
  19. package/dist/core/index.d.ts +5 -1
  20. package/dist/core/index.d.ts.map +1 -1
  21. package/dist/core/index.js +23 -11
  22. package/dist/core/index.js.map +1 -1
  23. package/dist/core/logger.d.ts +0 -1
  24. package/dist/core/logger.d.ts.map +1 -1
  25. package/dist/core/logger.js +3 -16
  26. package/dist/core/logger.js.map +1 -1
  27. package/dist/core/runner.d.ts +21 -65
  28. package/dist/core/runner.d.ts.map +1 -1
  29. package/dist/core/runner.js +212 -93
  30. package/dist/core/runner.js.map +1 -1
  31. package/dist/dsl/index.js +5 -1
  32. package/dist/dsl/index.js.map +1 -1
  33. package/dist/dsl/journey.d.ts +9 -4
  34. package/dist/dsl/journey.d.ts.map +1 -1
  35. package/dist/dsl/journey.js +27 -7
  36. package/dist/dsl/journey.js.map +1 -1
  37. package/dist/dsl/monitor.d.ts +66 -0
  38. package/dist/dsl/monitor.d.ts.map +1 -0
  39. package/dist/dsl/monitor.js +63 -0
  40. package/dist/dsl/monitor.js.map +1 -0
  41. package/dist/dsl/step.d.ts +3 -2
  42. package/dist/dsl/step.d.ts.map +1 -1
  43. package/dist/dsl/step.js +2 -1
  44. package/dist/dsl/step.js.map +1 -1
  45. package/dist/formatter/javascript.d.ts +98 -0
  46. package/dist/formatter/javascript.d.ts.map +1 -0
  47. package/dist/formatter/javascript.js +295 -0
  48. package/dist/formatter/javascript.js.map +1 -0
  49. package/dist/generator/index.d.ts +29 -0
  50. package/dist/generator/index.d.ts.map +1 -0
  51. package/dist/generator/index.js +240 -0
  52. package/dist/generator/index.js.map +1 -0
  53. package/dist/{reporters/reporter.js → generator/utils.d.ts} +5 -3
  54. package/dist/generator/utils.d.ts.map +1 -0
  55. package/dist/generator/utils.js +80 -0
  56. package/dist/generator/utils.js.map +1 -0
  57. package/dist/helpers.d.ts +24 -1
  58. package/dist/helpers.d.ts.map +1 -1
  59. package/dist/helpers.js +126 -19
  60. package/dist/helpers.js.map +1 -1
  61. package/dist/index.d.ts +6 -7
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +5 -26
  64. package/dist/index.js.map +1 -1
  65. package/dist/{parse_args.d.ts → loader.d.ts} +2 -5
  66. package/dist/loader.d.ts.map +1 -0
  67. package/dist/loader.js +152 -0
  68. package/dist/loader.js.map +1 -0
  69. package/dist/locations/index.d.ts +45 -0
  70. package/dist/locations/index.d.ts.map +1 -0
  71. package/dist/locations/index.js +90 -0
  72. package/dist/locations/index.js.map +1 -0
  73. package/dist/{reporters/reporter.d.ts → locations/public-locations.d.ts} +12 -8
  74. package/dist/locations/public-locations.d.ts.map +1 -0
  75. package/dist/locations/public-locations.js +41 -0
  76. package/dist/locations/public-locations.js.map +1 -0
  77. package/dist/options.d.ts +41 -0
  78. package/dist/options.d.ts.map +1 -0
  79. package/dist/options.js +182 -0
  80. package/dist/options.js.map +1 -0
  81. package/dist/plugins/browser-console.d.ts +5 -4
  82. package/dist/plugins/browser-console.d.ts.map +1 -1
  83. package/dist/plugins/browser-console.js +27 -8
  84. package/dist/plugins/browser-console.js.map +1 -1
  85. package/dist/plugins/index.js +5 -1
  86. package/dist/plugins/index.js.map +1 -1
  87. package/dist/plugins/network.d.ts +20 -33
  88. package/dist/plugins/network.d.ts.map +1 -1
  89. package/dist/plugins/network.js +173 -214
  90. package/dist/plugins/network.js.map +1 -1
  91. package/dist/plugins/performance.d.ts +4 -19
  92. package/dist/plugins/performance.d.ts.map +1 -1
  93. package/dist/plugins/performance.js +5 -5
  94. package/dist/plugins/performance.js.map +1 -1
  95. package/dist/plugins/plugin-manager.d.ts +9 -5
  96. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  97. package/dist/plugins/plugin-manager.js +44 -29
  98. package/dist/plugins/plugin-manager.js.map +1 -1
  99. package/dist/plugins/tracing.d.ts +6 -6
  100. package/dist/plugins/tracing.d.ts.map +1 -1
  101. package/dist/plugins/tracing.js +8 -7
  102. package/dist/plugins/tracing.js.map +1 -1
  103. package/dist/push/bundler.d.ts +34 -0
  104. package/dist/push/bundler.d.ts.map +1 -0
  105. package/dist/push/bundler.js +123 -0
  106. package/dist/push/bundler.js.map +1 -0
  107. package/dist/push/index.d.ts +33 -0
  108. package/dist/push/index.d.ts.map +1 -0
  109. package/dist/push/index.js +174 -0
  110. package/dist/push/index.js.map +1 -0
  111. package/dist/push/monitor.d.ts +34 -0
  112. package/dist/push/monitor.d.ts.map +1 -0
  113. package/dist/push/monitor.js +78 -0
  114. package/dist/push/monitor.js.map +1 -0
  115. package/{src/reporters/reporter.ts → dist/push/plugin.d.ts} +8 -10
  116. package/dist/push/plugin.d.ts.map +1 -0
  117. package/dist/push/plugin.js +133 -0
  118. package/dist/push/plugin.js.map +1 -0
  119. package/dist/push/request.d.ts +43 -0
  120. package/dist/push/request.d.ts.map +1 -0
  121. package/dist/push/request.js +83 -0
  122. package/dist/push/request.js.map +1 -0
  123. package/dist/reporters/base.d.ts +14 -6
  124. package/dist/reporters/base.d.ts.map +1 -1
  125. package/dist/reporters/base.js +54 -48
  126. package/dist/reporters/base.js.map +1 -1
  127. package/dist/reporters/index.d.ts +18 -8
  128. package/dist/reporters/index.d.ts.map +1 -1
  129. package/dist/reporters/index.js.map +1 -1
  130. package/dist/reporters/json.d.ts +18 -67
  131. package/dist/reporters/json.d.ts.map +1 -1
  132. package/dist/reporters/json.js +153 -175
  133. package/dist/reporters/json.js.map +1 -1
  134. package/dist/reporters/junit.d.ts +7 -1
  135. package/dist/reporters/junit.d.ts.map +1 -1
  136. package/dist/reporters/junit.js +94 -89
  137. package/dist/reporters/junit.js.map +1 -1
  138. package/dist/sdk/lh-trace-processor.d.ts +35 -9
  139. package/dist/sdk/lh-trace-processor.d.ts.map +1 -1
  140. package/dist/sdk/lh-trace-processor.js +114 -53
  141. package/dist/sdk/lh-trace-processor.js.map +1 -1
  142. package/dist/sdk/trace-metrics.d.ts +4 -4
  143. package/dist/sdk/trace-metrics.d.ts.map +1 -1
  144. package/dist/sdk/trace-metrics.js +5 -6
  145. package/dist/sdk/trace-metrics.js.map +1 -1
  146. package/dist/sdk/trace-processor.d.ts +11 -3
  147. package/dist/sdk/trace-processor.d.ts.map +1 -1
  148. package/dist/sdk/trace-processor.js +17 -9
  149. package/dist/sdk/trace-processor.js.map +1 -1
  150. package/dist/tsconfig.tsbuildinfo +1 -1888
  151. package/package.json +32 -20
  152. package/src/cli.ts +205 -152
  153. package/src/common_types.ts +192 -34
  154. package/src/config.ts +2 -5
  155. package/src/core/expect.ts +58 -24
  156. package/src/core/gatherer.ts +59 -24
  157. package/src/core/index.ts +36 -15
  158. package/src/core/logger.ts +1 -12
  159. package/src/core/runner.ts +215 -152
  160. package/src/dsl/journey.ts +37 -6
  161. package/src/dsl/monitor.ts +88 -0
  162. package/src/dsl/step.ts +9 -2
  163. package/src/formatter/javascript.ts +367 -0
  164. package/src/generator/index.ts +316 -0
  165. package/src/generator/utils.ts +80 -0
  166. package/src/helpers.ts +132 -12
  167. package/src/index.ts +22 -22
  168. package/src/loader.ts +171 -0
  169. package/src/locations/index.ts +108 -0
  170. package/src/locations/public-locations.ts +38 -0
  171. package/src/options.ts +211 -0
  172. package/src/plugins/browser-console.ts +30 -8
  173. package/src/plugins/network.ts +208 -267
  174. package/src/plugins/performance.ts +6 -22
  175. package/src/plugins/plugin-manager.ts +49 -31
  176. package/src/plugins/tracing.ts +8 -9
  177. package/src/push/bundler.ts +100 -0
  178. package/src/push/index.ts +202 -0
  179. package/src/push/monitor.ts +96 -0
  180. package/src/push/plugin.ts +119 -0
  181. package/src/push/request.ts +103 -0
  182. package/src/reporters/base.ts +63 -52
  183. package/src/reporters/index.ts +26 -3
  184. package/src/reporters/json.ts +203 -206
  185. package/src/reporters/junit.ts +98 -93
  186. package/src/sdk/lh-trace-processor.ts +132 -68
  187. package/src/sdk/trace-metrics.ts +10 -6
  188. package/src/sdk/trace-processor.ts +28 -13
  189. package/templates/.github/workflows/run-synthetics.yml +26 -0
  190. package/templates/README.md +21 -0
  191. package/templates/journeys/advanced-example-helpers.ts +54 -0
  192. package/templates/journeys/advanced-example.journey.ts +43 -0
  193. package/templates/journeys/example.journey.ts +18 -0
  194. package/templates/synthetics.config.ts +27 -0
  195. package/CHANGELOG.md +0 -102
  196. package/NOTICE.txt +0 -221
  197. package/dist/parse_args.d.ts.map +0 -1
  198. package/dist/parse_args.js +0 -89
  199. package/dist/parse_args.js.map +0 -1
  200. package/dist/reporters/reporter.d.ts.map +0 -1
  201. package/dist/reporters/reporter.js.map +0 -1
  202. package/src/parse_args.ts +0 -127
@@ -0,0 +1,316 @@
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 { progress, removeTrailingSlash, write as stdWrite } from '../helpers';
33
+ import {
34
+ getPackageManager,
35
+ replaceTemplates,
36
+ runCommand,
37
+ cloudIDToKibanaURL,
38
+ } from './utils';
39
+ import { formatLocations, getLocations, groupLocations } from '../locations';
40
+
41
+ // Templates that are required for setting up new synthetics project
42
+ const templateDir = join(__dirname, '..', '..', 'templates');
43
+
44
+ export type ProjectSettings = {
45
+ url: string;
46
+ space: string;
47
+ project: string;
48
+ };
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
+ '.github/workflows/run-synthetics.yml',
62
+ 'README.md',
63
+ ];
64
+ export const SETTINGS_PATH = '.synthetics/project.json';
65
+ export const CONFIG_PATH = 'synthetics.config.ts';
66
+
67
+ // Files to be overriden by default if the project is initialized multiple times
68
+ const DEFAULT_OVERRIDES = [SETTINGS_PATH, CONFIG_PATH];
69
+
70
+ export class Generator {
71
+ pkgManager = 'npm';
72
+ constructor(public projectDir: string) {}
73
+
74
+ async directory() {
75
+ progress(
76
+ `Initializing Synthetics project in '${
77
+ relative(process.cwd(), this.projectDir) || '.'
78
+ }'`
79
+ );
80
+ if (!existsSync(this.projectDir)) {
81
+ await mkdir(this.projectDir);
82
+ }
83
+ }
84
+
85
+ async questions() {
86
+ if (process.env.TEST_QUESTIONS) {
87
+ return JSON.parse(process.env.TEST_QUESTIONS);
88
+ }
89
+
90
+ const { onCloud } = await prompt<{ onCloud: string }>({
91
+ type: 'confirm',
92
+ name: 'onCloud',
93
+ initial: 'y',
94
+ message: 'Do you use Elastic Cloud',
95
+ });
96
+ const url = await new Input({
97
+ header: onCloud
98
+ ? yellow(
99
+ 'Get cloud.id from your deployment https://www.elastic.co/guide/en/cloud/current/ec-cloud-id.html'
100
+ )
101
+ : '',
102
+ message: onCloud
103
+ ? 'What is your cloud.id'
104
+ : 'What is the url of your Kibana instance',
105
+ name: 'url',
106
+ required: true,
107
+ result(value) {
108
+ return onCloud ? cloudIDToKibanaURL(value) : value;
109
+ },
110
+ }).run();
111
+
112
+ const auth = await new Input({
113
+ name: 'auth',
114
+ header: yellow(
115
+ `Generate API key from Kibana ${removeTrailingSlash(
116
+ url
117
+ )}/app/uptime/manage-monitors/all`
118
+ ),
119
+ required: true,
120
+ message: 'What is your API key',
121
+ }).run();
122
+
123
+ const allLocations = await getLocations({ url, auth });
124
+ const locChoices = formatLocations(allLocations);
125
+ if (locChoices.length === 0) {
126
+ // TODO - Add link to docs
127
+ throw 'Follow the docs to set up your first private locations - <link>';
128
+ }
129
+
130
+ const monitorQues = [
131
+ {
132
+ type: 'select',
133
+ name: 'locations',
134
+ hint: '(Use <space> to select, <return> to submit)',
135
+ message: 'Select the locations where you want to run monitors',
136
+ choices: locChoices,
137
+ multiple: true,
138
+ validate(value) {
139
+ return value.length === 0 ? `Select at least one option.` : true;
140
+ },
141
+ },
142
+ {
143
+ type: 'numeral',
144
+ name: 'schedule',
145
+ message: 'Set default schedule in minutes for all monitors',
146
+ initial: 10,
147
+ },
148
+ {
149
+ type: 'input',
150
+ name: 'project',
151
+ message: 'Choose project id to logically group monitors',
152
+ initial: basename(this.projectDir),
153
+ },
154
+ {
155
+ type: 'input',
156
+ name: 'space',
157
+ message: 'Choose the target Kibana space',
158
+ initial: 'default',
159
+ },
160
+ ];
161
+
162
+ // Split and group private and public locations from the answered list.
163
+ const answers = await prompt<PromptOptions>(monitorQues);
164
+ const { locations, privateLocations } = groupLocations(answers.locations);
165
+ return { ...answers, url, locations, privateLocations };
166
+ }
167
+
168
+ async files(answers: PromptOptions) {
169
+ const fileMap = new Map<string, string>();
170
+
171
+ // Setup project.json
172
+ const projectJSON = {
173
+ url: answers.url,
174
+ space: answers.space,
175
+ project: answers.project,
176
+ };
177
+ fileMap.set(SETTINGS_PATH, JSON.stringify(projectJSON, null, 2) + '\n');
178
+
179
+ // Setup Synthetics config file
180
+ fileMap.set(
181
+ CONFIG_PATH,
182
+ replaceTemplates(
183
+ await readFile(join(templateDir, CONFIG_PATH), 'utf-8'),
184
+ answers
185
+ )
186
+ );
187
+
188
+ // Setup non-templated files
189
+ Promise.all(
190
+ REGULAR_FILES_PATH.map(async file => {
191
+ fileMap.set(file, await readFile(join(templateDir, file), 'utf-8'));
192
+ })
193
+ ).catch(e => {
194
+ throw e;
195
+ });
196
+
197
+ // Create files
198
+ for (const [relativePath, content] of fileMap) {
199
+ await this.createFile(relativePath, content);
200
+ }
201
+ }
202
+
203
+ async createFile(relativePath: string, content: string, override = false) {
204
+ const absolutePath = join(this.projectDir, relativePath);
205
+
206
+ if (
207
+ !override &&
208
+ !DEFAULT_OVERRIDES.includes(relativePath) &&
209
+ existsSync(absolutePath)
210
+ ) {
211
+ const { override } = await prompt<{ override: boolean }>({
212
+ type: 'confirm',
213
+ name: 'override',
214
+ message: `File ${relativePath} already exists. Override it?`,
215
+ initial: false,
216
+ });
217
+ if (!override) return;
218
+ }
219
+
220
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
221
+ await mkdir(dirname(absolutePath), { recursive: true });
222
+ await writeFile(absolutePath, content, 'utf-8');
223
+ }
224
+
225
+ async package() {
226
+ this.pkgManager = await getPackageManager(this.projectDir);
227
+ const commands = new Map<string, string>();
228
+ commands.set(
229
+ `Setting up project using ${this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'}`,
230
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
231
+ );
232
+
233
+ const pkgName = '@elastic/synthetics';
234
+ commands.set(
235
+ `Installing @elastic/synthetics library`,
236
+ this.pkgManager == 'yarn'
237
+ ? `yarn add -dev ${pkgName} --silent`
238
+ : `npm i -d ${pkgName} --quiet`
239
+ );
240
+
241
+ // Execute commands
242
+ for (const [name, command] of commands) {
243
+ progress(`${name}...`);
244
+ execSync(command, {
245
+ stdio: 'inherit',
246
+ cwd: this.projectDir,
247
+ });
248
+ }
249
+ }
250
+
251
+ async patchPkgJSON() {
252
+ const filename = 'package.json';
253
+ const pkgJSON = JSON.parse(
254
+ await readFile(join(this.projectDir, filename), 'utf-8')
255
+ );
256
+
257
+ if (!pkgJSON.scripts) {
258
+ pkgJSON.scripts = {};
259
+ }
260
+ // Add test command
261
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
262
+
263
+ // Add push command
264
+ pkgJSON.scripts.push = `npx @elastic/synthetics push --auth $SYNTHETICS_API_KEY`;
265
+
266
+ await this.createFile(
267
+ filename,
268
+ JSON.stringify(pkgJSON, null, 2) + '\n',
269
+ true
270
+ );
271
+ }
272
+
273
+ async patchGitIgnore() {
274
+ const gitIgnorePath = join(this.projectDir, '.gitignore');
275
+ let gitIgnore = '';
276
+ if (existsSync(gitIgnorePath)) {
277
+ const contents = await readFile(gitIgnorePath, 'utf-8');
278
+ gitIgnore += contents.trimEnd() + '\n';
279
+ }
280
+ if (!gitIgnore.includes('node_modules')) {
281
+ gitIgnore += 'node_modules/\n';
282
+ }
283
+ gitIgnore += '.synthetics/\n';
284
+ await writeFile(gitIgnorePath, gitIgnore, 'utf-8');
285
+ }
286
+
287
+ banner() {
288
+ stdWrite(
289
+ bold(`
290
+ All set, you can run below commands inside: ${this.projectDir}:
291
+
292
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
293
+
294
+ Push monitors to Kibana: ${cyan(
295
+ 'SYNTHETICS_API_KEY=<value> ' + runCommand(this.pkgManager, 'push')
296
+ )}
297
+
298
+ ${yellow(
299
+ 'Make sure to configure the SYNTHETICS_API_KEY before pushing monitors to Kibana.'
300
+ )}
301
+
302
+ Visit https://www.elastic.co/guide/en/observability/current/synthetic-run-tests.html to learn more.
303
+ `)
304
+ );
305
+ }
306
+
307
+ async setup() {
308
+ await this.directory();
309
+ const answers = await this.questions();
310
+ await this.package();
311
+ await this.files(answers);
312
+ await this.patchPkgJSON();
313
+ await this.patchGitIgnore();
314
+ this.banner();
315
+ }
316
+ }
@@ -0,0 +1,80 @@
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
+ .map(f => `'${f}'`);
51
+ }
52
+ if (typeof finalValue == 'number') {
53
+ return Number(finalValue);
54
+ }
55
+ return finalValue;
56
+ });
57
+ }
58
+ return input;
59
+ }
60
+
61
+ export function cloudIDToKibanaURL(id: string) {
62
+ const ID_SEPARATOR = ':';
63
+ const VALUE_SEPARATOR = '$';
64
+ // Ignore values before the separator
65
+ const index = id.lastIndexOf(ID_SEPARATOR);
66
+ if (index >= 0) {
67
+ id = id.substring(index + 1);
68
+ }
69
+
70
+ // Decode the base64 string
71
+ const decoded = Buffer.from(id, 'base64').toString();
72
+ const words = decoded.split(VALUE_SEPARATOR);
73
+
74
+ // construct the kibana and ES urls from decoded value
75
+ const [host, port = '443'] = words[0].split(ID_SEPARATOR);
76
+ const [kibanaId, kibanaPort = port] = words[2].split(ID_SEPARATOR);
77
+ const kibanaURL = `https://${kibanaId}.${host}:${kibanaPort}`;
78
+
79
+ return kibanaURL;
80
+ }
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 } 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 '@cspotcode/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,15 +46,25 @@ 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
 
62
+ export function generateUniqueId() {
63
+ return `${Date.now() + Math.floor(Math.random() * 1e13)}`;
64
+ }
65
+
51
66
  export function generateTempPath() {
52
- return join(os.tmpdir(), `synthetics-${process.hrtime().toString()}`);
67
+ return join(os.tmpdir(), `synthetics-${generateUniqueId()}`);
53
68
  }
54
69
 
55
70
  /**
@@ -155,11 +170,11 @@ export async function totalist(
155
170
  pre = ''
156
171
  ) {
157
172
  dir = resolve('.', dir);
158
- await readAsync(dir).then(arr => {
173
+ await readdir(dir).then(arr => {
159
174
  return Promise.all(
160
175
  arr.map(str => {
161
176
  const abs = join(dir, str);
162
- return statAsync(abs).then(stats =>
177
+ return lstat(abs).then(stats =>
163
178
  stats.isDirectory()
164
179
  ? totalist(abs, callback, join(pre, str))
165
180
  : callback(join(pre, str), abs)
@@ -232,13 +247,118 @@ export function formatError(error: Error) {
232
247
  }
233
248
 
234
249
  const cwd = process.cwd();
250
+ /**
251
+ * All the settings that are related to the Synthetics is stored
252
+ * under this directory
253
+ * Examples: Screenshots, Project setup
254
+ */
255
+ export const SYNTHETICS_PATH = join(cwd, '.synthetics');
235
256
  /**
236
257
  * Synthetics cache path that is based on the process id to make sure
237
258
  * each process does not modify the caching layer used by other process
238
259
  * once we move to executing journeys in parallel
239
260
  */
240
- export const CACHE_PATH = join(cwd, '.synthetics', process.pid.toString());
261
+ export const CACHE_PATH = join(SYNTHETICS_PATH, process.pid.toString());
241
262
 
242
263
  export function getDurationInUs(duration: number) {
243
264
  return Math.trunc(duration * 1e6);
244
265
  }
266
+
267
+ export function megabitsToBytes(megabytes: number) {
268
+ return (megabytes * 1024 * 1024) / 8;
269
+ }
270
+
271
+ export const DEFAULT_THROTTLING_OPTIONS: ThrottlingOptions = {
272
+ download: 5,
273
+ upload: 3,
274
+ latency: 20,
275
+ };
276
+
277
+ /**
278
+ * Transforms the CLI throttling arguments in to format
279
+ * expected by Chrome devtools protocol NetworkConditions
280
+ */
281
+ export function getNetworkConditions(
282
+ throttlingOpts: ThrottlingOptions
283
+ ): NetworkConditions {
284
+ return {
285
+ downloadThroughput: megabitsToBytes(throttlingOpts.download),
286
+ uploadThroughput: megabitsToBytes(throttlingOpts.upload), // Devtools CDP expects format to be in bytes/second
287
+ latency: throttlingOpts.latency, // milliseconds,
288
+ offline: false,
289
+ };
290
+ }
291
+
292
+ const dstackTraceLimit = 10;
293
+
294
+ // Uses the V8 Stacktrace API to get the function location
295
+ // information - https://v8.dev/docs/stack-trace-api#customizing-stack-traces
296
+ export function wrapFnWithLocation<A extends unknown[], R>(
297
+ func: (location: Location, ...args: A) => R
298
+ ): (...args: A) => R {
299
+ return (...args) => {
300
+ const _prepareStackTrace = Error.prepareStackTrace;
301
+ Error.prepareStackTrace = (_, stackFrames) => {
302
+ // Deafult CallSite would not map to the original transpiled source
303
+ // from ts-node properly, So we wrap it with the library that knows
304
+ // how to retrive those source-map for the transpiled code
305
+ const frame: NodeJS.CallSite = sourceMapSupport.wrapCallSite(
306
+ stackFrames[1]
307
+ );
308
+ return {
309
+ file: frame.getFileName(),
310
+ line: frame.getLineNumber(),
311
+ column: frame.getColumnNumber(),
312
+ };
313
+ };
314
+ Error.stackTraceLimit = 2;
315
+ const obj: { stack: Location } = {} as any;
316
+ Error.captureStackTrace(obj);
317
+ const location = obj.stack;
318
+ Error.stackTraceLimit = dstackTraceLimit;
319
+ Error.prepareStackTrace = _prepareStackTrace;
320
+ return func(location, ...args);
321
+ };
322
+ }
323
+
324
+ // Safely parse ND JSON (Newline delimitted JSON) chunks
325
+ export function safeNDJSONParse(chunks: string[]) {
326
+ // chunks may not be at proper newline boundaries, so we make sure everything is split
327
+ // on proper newlines
328
+ chunks = Array.isArray(chunks) ? chunks : [chunks];
329
+ const lines = chunks.join('\n').split(/\r?\n/);
330
+ return lines
331
+ .filter(l => l.match(/\S/)) // remove blank lines
332
+ .map(line => {
333
+ try {
334
+ return JSON.parse(line);
335
+ } catch (e) {
336
+ throw `Error ${e} could not parse data '${line}'`;
337
+ }
338
+ });
339
+ }
340
+
341
+ // Console helpers
342
+ export function write(message: string) {
343
+ process.stderr.write(message + '\n');
344
+ }
345
+
346
+ export function progress(message: string) {
347
+ write(cyan(bold(`${symbols.progress} ${message}`)));
348
+ }
349
+
350
+ export function error(message: string) {
351
+ write(red(message));
352
+ }
353
+
354
+ export function done(message: string) {
355
+ write(bold(green(`${symbols['succeeded']} ${message}`)));
356
+ }
357
+
358
+ export function aborted(message: string) {
359
+ write(bold(yellow(`${symbols['warning']} ${message}`)));
360
+ }
361
+
362
+ export function removeTrailingSlash(url: string) {
363
+ return url.replace(/\/+$/, '');
364
+ }
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';