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

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 (189) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +99 -162
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +156 -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/gatherer.d.ts +4 -8
  13. package/dist/core/gatherer.d.ts.map +1 -1
  14. package/dist/core/gatherer.js +46 -14
  15. package/dist/core/gatherer.js.map +1 -1
  16. package/dist/core/index.d.ts +5 -1
  17. package/dist/core/index.d.ts.map +1 -1
  18. package/dist/core/index.js +23 -11
  19. package/dist/core/index.js.map +1 -1
  20. package/dist/core/logger.d.ts +0 -1
  21. package/dist/core/logger.d.ts.map +1 -1
  22. package/dist/core/logger.js +3 -16
  23. package/dist/core/logger.js.map +1 -1
  24. package/dist/core/runner.d.ts +21 -65
  25. package/dist/core/runner.d.ts.map +1 -1
  26. package/dist/core/runner.js +211 -93
  27. package/dist/core/runner.js.map +1 -1
  28. package/dist/dsl/journey.d.ts +7 -3
  29. package/dist/dsl/journey.d.ts.map +1 -1
  30. package/dist/dsl/journey.js +22 -6
  31. package/dist/dsl/journey.js.map +1 -1
  32. package/{src/reporters/reporter.ts → dist/dsl/locations.d.ts} +12 -10
  33. package/dist/dsl/locations.d.ts.map +1 -0
  34. package/dist/dsl/locations.js +41 -0
  35. package/dist/dsl/locations.js.map +1 -0
  36. package/dist/dsl/monitor.d.ts +65 -0
  37. package/dist/dsl/monitor.d.ts.map +1 -0
  38. package/dist/dsl/monitor.js +63 -0
  39. package/dist/dsl/monitor.js.map +1 -0
  40. package/dist/dsl/step.d.ts +3 -2
  41. package/dist/dsl/step.d.ts.map +1 -1
  42. package/dist/dsl/step.js +2 -1
  43. package/dist/dsl/step.js.map +1 -1
  44. package/dist/formatter/javascript.d.ts +98 -0
  45. package/dist/formatter/javascript.d.ts.map +1 -0
  46. package/dist/formatter/javascript.js +295 -0
  47. package/dist/formatter/javascript.js.map +1 -0
  48. package/dist/generator/index.d.ts +21 -0
  49. package/dist/generator/index.d.ts.map +1 -0
  50. package/dist/generator/index.js +169 -0
  51. package/dist/generator/index.js.map +1 -0
  52. package/dist/{reporters/reporter.d.ts → generator/utils.d.ts} +4 -9
  53. package/dist/generator/utils.d.ts.map +1 -0
  54. package/dist/generator/utils.js +57 -0
  55. package/dist/generator/utils.js.map +1 -0
  56. package/dist/helpers.d.ts +20 -1
  57. package/dist/helpers.d.ts.map +1 -1
  58. package/dist/helpers.js +98 -18
  59. package/dist/helpers.js.map +1 -1
  60. package/dist/index.d.ts +5 -6
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +5 -26
  63. package/dist/index.js.map +1 -1
  64. package/dist/{parse_args.d.ts → loader.d.ts} +2 -5
  65. package/dist/loader.d.ts.map +1 -0
  66. package/dist/loader.js +144 -0
  67. package/dist/loader.js.map +1 -0
  68. package/dist/options.d.ts +34 -0
  69. package/dist/options.d.ts.map +1 -0
  70. package/dist/options.js +162 -0
  71. package/dist/options.js.map +1 -0
  72. package/dist/plugins/browser-console.d.ts +5 -4
  73. package/dist/plugins/browser-console.d.ts.map +1 -1
  74. package/dist/plugins/browser-console.js +27 -8
  75. package/dist/plugins/browser-console.js.map +1 -1
  76. package/dist/plugins/network.d.ts +20 -33
  77. package/dist/plugins/network.d.ts.map +1 -1
  78. package/dist/plugins/network.js +173 -214
  79. package/dist/plugins/network.js.map +1 -1
  80. package/dist/plugins/performance.d.ts +4 -19
  81. package/dist/plugins/performance.d.ts.map +1 -1
  82. package/dist/plugins/performance.js +5 -5
  83. package/dist/plugins/performance.js.map +1 -1
  84. package/dist/plugins/plugin-manager.d.ts +9 -5
  85. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  86. package/dist/plugins/plugin-manager.js +44 -29
  87. package/dist/plugins/plugin-manager.js.map +1 -1
  88. package/dist/plugins/tracing.d.ts +6 -6
  89. package/dist/plugins/tracing.d.ts.map +1 -1
  90. package/dist/plugins/tracing.js +8 -7
  91. package/dist/plugins/tracing.js.map +1 -1
  92. package/dist/push/bundler.d.ts +34 -0
  93. package/dist/push/bundler.d.ts.map +1 -0
  94. package/dist/push/bundler.js +114 -0
  95. package/dist/push/bundler.js.map +1 -0
  96. package/dist/{reporters/reporter.js → push/index.d.ts} +4 -3
  97. package/dist/push/index.d.ts.map +1 -0
  98. package/dist/push/index.js +55 -0
  99. package/dist/push/index.js.map +1 -0
  100. package/dist/push/monitor.d.ts +32 -0
  101. package/dist/push/monitor.d.ts.map +1 -0
  102. package/dist/push/monitor.js +62 -0
  103. package/dist/push/monitor.js.map +1 -0
  104. package/dist/push/plugin.d.ts +33 -0
  105. package/dist/push/plugin.d.ts.map +1 -0
  106. package/dist/push/plugin.js +124 -0
  107. package/dist/push/plugin.js.map +1 -0
  108. package/dist/push/request.d.ts +42 -0
  109. package/dist/push/request.d.ts.map +1 -0
  110. package/dist/push/request.js +84 -0
  111. package/dist/push/request.js.map +1 -0
  112. package/dist/reporters/base.d.ts +14 -6
  113. package/dist/reporters/base.d.ts.map +1 -1
  114. package/dist/reporters/base.js +54 -48
  115. package/dist/reporters/base.js.map +1 -1
  116. package/dist/reporters/index.d.ts +18 -8
  117. package/dist/reporters/index.d.ts.map +1 -1
  118. package/dist/reporters/index.js.map +1 -1
  119. package/dist/reporters/json.d.ts +18 -67
  120. package/dist/reporters/json.d.ts.map +1 -1
  121. package/dist/reporters/json.js +153 -175
  122. package/dist/reporters/json.js.map +1 -1
  123. package/dist/reporters/junit.d.ts +7 -1
  124. package/dist/reporters/junit.d.ts.map +1 -1
  125. package/dist/reporters/junit.js +94 -89
  126. package/dist/reporters/junit.js.map +1 -1
  127. package/dist/sdk/lh-trace-processor.d.ts +35 -9
  128. package/dist/sdk/lh-trace-processor.d.ts.map +1 -1
  129. package/dist/sdk/lh-trace-processor.js +114 -53
  130. package/dist/sdk/lh-trace-processor.js.map +1 -1
  131. package/dist/sdk/trace-metrics.d.ts +4 -4
  132. package/dist/sdk/trace-metrics.d.ts.map +1 -1
  133. package/dist/sdk/trace-metrics.js +5 -6
  134. package/dist/sdk/trace-metrics.js.map +1 -1
  135. package/dist/sdk/trace-processor.d.ts +11 -3
  136. package/dist/sdk/trace-processor.d.ts.map +1 -1
  137. package/dist/sdk/trace-processor.js +17 -9
  138. package/dist/sdk/trace-processor.js.map +1 -1
  139. package/dist/tsconfig.tsbuildinfo +1 -1888
  140. package/package.json +31 -19
  141. package/src/cli.ts +187 -154
  142. package/src/common_types.ts +188 -34
  143. package/src/config.ts +2 -5
  144. package/src/core/gatherer.ts +55 -27
  145. package/src/core/index.ts +36 -15
  146. package/src/core/logger.ts +1 -12
  147. package/src/core/runner.ts +216 -152
  148. package/src/dsl/journey.ts +29 -5
  149. package/src/dsl/locations.ts +38 -0
  150. package/src/dsl/monitor.ts +87 -0
  151. package/src/dsl/step.ts +9 -2
  152. package/src/formatter/javascript.ts +367 -0
  153. package/src/generator/index.ts +212 -0
  154. package/src/generator/utils.ts +54 -0
  155. package/src/helpers.ts +106 -10
  156. package/src/index.ts +21 -22
  157. package/src/loader.ts +162 -0
  158. package/src/options.ts +173 -0
  159. package/src/plugins/browser-console.ts +30 -8
  160. package/src/plugins/network.ts +208 -267
  161. package/src/plugins/performance.ts +6 -22
  162. package/src/plugins/plugin-manager.ts +49 -31
  163. package/src/plugins/tracing.ts +8 -9
  164. package/src/push/bundler.ts +95 -0
  165. package/src/push/index.ts +59 -0
  166. package/src/push/monitor.ts +68 -0
  167. package/src/push/plugin.ts +114 -0
  168. package/src/push/request.ts +111 -0
  169. package/src/reporters/base.ts +63 -52
  170. package/src/reporters/index.ts +26 -3
  171. package/src/reporters/json.ts +203 -206
  172. package/src/reporters/junit.ts +98 -93
  173. package/src/sdk/lh-trace-processor.ts +132 -68
  174. package/src/sdk/trace-metrics.ts +10 -6
  175. package/src/sdk/trace-processor.ts +28 -13
  176. package/templates/.github/workflows/run-synthetics.yml +26 -0
  177. package/templates/README.md +21 -0
  178. package/templates/journeys/advanced-example-helpers.ts +54 -0
  179. package/templates/journeys/advanced-example.journey.ts +43 -0
  180. package/templates/journeys/example.journey.ts +18 -0
  181. package/templates/synthetics.config.ts +26 -0
  182. package/CHANGELOG.md +0 -102
  183. package/NOTICE.txt +0 -221
  184. package/dist/parse_args.d.ts.map +0 -1
  185. package/dist/parse_args.js +0 -89
  186. package/dist/parse_args.js.map +0 -1
  187. package/dist/reporters/reporter.d.ts.map +0 -1
  188. package/dist/reporters/reporter.js.map +0 -1
  189. package/src/parse_args.ts +0 -127
@@ -0,0 +1,54 @@
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, literals: Record<string, any>) {
44
+ for (const key in literals) {
45
+ const finalValue = literals[key];
46
+ input = input.replace(new RegExp(`'{{` + key + `}}'`, 'g'), () => {
47
+ if (typeof finalValue == 'number') {
48
+ return Number(finalValue);
49
+ }
50
+ return finalValue;
51
+ });
52
+ }
53
+ return input;
54
+ }
package/src/helpers.ts CHANGED
@@ -23,16 +23,28 @@
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
30
  import { promisify } from 'util';
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';
40
+
41
+ const lstatAsync = promisify(fs.lstat);
42
+ const readdirAsync = promisify(fs.readdir);
43
+
44
+ export const readFileAsync = promisify(fs.readFile);
45
+ export const writeFileAsync = promisify(fs.writeFile);
46
+ export const mkdirAsync = promisify(fs.mkdir);
33
47
 
34
- const statAsync = promisify(fs.lstat);
35
- const readAsync = promisify(fs.readdir);
36
48
  const SEPARATOR = '\n';
37
49
 
38
50
  export function noop() {}
@@ -41,15 +53,25 @@ export function indent(lines: string, tab = ' ') {
41
53
  return lines.replace(/^/gm, tab);
42
54
  }
43
55
 
56
+ /**
57
+ * Disable unicode symbols for windows, the underlying
58
+ * FS stream has a known issue in windows
59
+ */
60
+ const NO_UTF8_SUPPORT = process.platform === 'win32';
44
61
  export const symbols = {
45
- warning: yellow('⚠'),
62
+ warning: yellow(NO_UTF8_SUPPORT ? '!' : '⚠'),
46
63
  skipped: cyan('-'),
47
- succeeded: green('✓'),
48
- failed: red('✖'),
64
+ progress: cyan('>'),
65
+ succeeded: green(NO_UTF8_SUPPORT ? 'ok' : '✓'),
66
+ failed: red(NO_UTF8_SUPPORT ? 'x' : '✖'),
49
67
  };
50
68
 
69
+ export function generateUniqueId() {
70
+ return `${Date.now() + Math.floor(Math.random() * 1e13)}`;
71
+ }
72
+
51
73
  export function generateTempPath() {
52
- return join(os.tmpdir(), `synthetics-${process.hrtime().toString()}`);
74
+ return join(os.tmpdir(), `synthetics-${generateUniqueId()}`);
53
75
  }
54
76
 
55
77
  /**
@@ -155,11 +177,11 @@ export async function totalist(
155
177
  pre = ''
156
178
  ) {
157
179
  dir = resolve('.', dir);
158
- await readAsync(dir).then(arr => {
180
+ await readdirAsync(dir).then(arr => {
159
181
  return Promise.all(
160
182
  arr.map(str => {
161
183
  const abs = join(dir, str);
162
- return statAsync(abs).then(stats =>
184
+ return lstatAsync(abs).then(stats =>
163
185
  stats.isDirectory()
164
186
  ? totalist(abs, callback, join(pre, str))
165
187
  : callback(join(pre, str), abs)
@@ -242,3 +264,77 @@ export const CACHE_PATH = join(cwd, '.synthetics', process.pid.toString());
242
264
  export function getDurationInUs(duration: number) {
243
265
  return Math.trunc(duration * 1e6);
244
266
  }
267
+
268
+ export function megabitsToBytes(megabytes: number) {
269
+ return (megabytes * 1024 * 1024) / 8;
270
+ }
271
+
272
+ export const DEFAULT_THROTTLING_OPTIONS: ThrottlingOptions = {
273
+ download: 5,
274
+ upload: 3,
275
+ latency: 20,
276
+ };
277
+
278
+ /**
279
+ * Transforms the CLI throttling arguments in to format
280
+ * expected by Chrome devtools protocol NetworkConditions
281
+ */
282
+ export function getNetworkConditions(
283
+ throttlingOpts: ThrottlingOptions
284
+ ): NetworkConditions {
285
+ return {
286
+ downloadThroughput: megabitsToBytes(throttlingOpts.download),
287
+ uploadThroughput: megabitsToBytes(throttlingOpts.upload), // Devtools CDP expects format to be in bytes/second
288
+ latency: throttlingOpts.latency, // milliseconds,
289
+ offline: false,
290
+ };
291
+ }
292
+
293
+ const dstackTraceLimit = 10;
294
+
295
+ // Uses the V8 Stacktrace API to get the function location
296
+ // information - https://v8.dev/docs/stack-trace-api#customizing-stack-traces
297
+ export function wrapFnWithLocation<A extends unknown[], R>(
298
+ func: (location: Location, ...args: A) => R
299
+ ): (...args: A) => R {
300
+ return (...args) => {
301
+ const _prepareStackTrace = Error.prepareStackTrace;
302
+ Error.prepareStackTrace = (_, stackFrames) => {
303
+ // Deafult CallSite would not map to the original transpiled source
304
+ // from ts-node properly, So we wrap it with the library that knows
305
+ // how to retrive those source-map for the transpiled code
306
+ const frame: NodeJS.CallSite = sourceMapSupport.wrapCallSite(
307
+ stackFrames[1]
308
+ );
309
+ return {
310
+ file: frame.getFileName(),
311
+ line: frame.getLineNumber(),
312
+ column: frame.getColumnNumber(),
313
+ };
314
+ };
315
+ Error.stackTraceLimit = 2;
316
+ const obj: { stack: Location } = {} as any;
317
+ Error.captureStackTrace(obj);
318
+ const location = obj.stack;
319
+ Error.stackTraceLimit = dstackTraceLimit;
320
+ Error.prepareStackTrace = _prepareStackTrace;
321
+ return func(location, ...args);
322
+ };
323
+ }
324
+
325
+ // Console helpers
326
+ export function write(message: string) {
327
+ process.stderr.write(message + '\n');
328
+ }
329
+
330
+ export function progress(message: string) {
331
+ write(cyan(bold(`${symbols.progress} ${message}`)));
332
+ }
333
+
334
+ export function error(message: string) {
335
+ write(red(message));
336
+ }
337
+
338
+ export function done(message: string) {
339
+ write(bold(green(`${symbols['succeeded']} ${message}`)));
340
+ }
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
@@ -70,3 +59,13 @@ export type {
70
59
  */
71
60
  export type { default as Runner } from './core/runner';
72
61
  export type { Reporter, ReporterOptions } from './reporters';
62
+
63
+ export type { SyntheticsConfig } from './common_types';
64
+ export type {
65
+ Action,
66
+ ActionInContext,
67
+ Signal,
68
+ Step,
69
+ Steps,
70
+ actionTitle,
71
+ } from './formatter/javascript';
package/src/loader.ts ADDED
@@ -0,0 +1,162 @@
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 { stdin, cwd } from 'process';
27
+ import { resolve } from 'path';
28
+ import { CliArgs } from './common_types';
29
+ import { step, journey } from './core';
30
+ import { log } from './core/logger';
31
+ import { expect } from './core/expect';
32
+ import {
33
+ isDepInstalled,
34
+ isDirectory,
35
+ totalist,
36
+ findPkgJsonByTraversing,
37
+ } from './helpers';
38
+
39
+ const resolvedCwd = cwd();
40
+
41
+ export async function loadTestFiles(options: CliArgs, args: string[]) {
42
+ /**
43
+ * Transform `.ts` files out of the box by invoking
44
+ * the `ts-node` via `transpile-only` mode that compiles
45
+ * TS files without doing any extensive type checks.
46
+ *
47
+ * We must register `ts-node` _before_ loading inline
48
+ * scripts too because otherwise we will not be able to
49
+ * require `.ts` configuration files.
50
+ */
51
+ /* eslint-disable-next-line @typescript-eslint/no-var-requires */
52
+ require('ts-node').register({
53
+ transpileOnly: true,
54
+ compilerOptions: {
55
+ esModuleInterop: true,
56
+ allowJs: true,
57
+ target: 'es2020',
58
+ },
59
+ });
60
+
61
+ /**
62
+ * Preload modules before running the tests
63
+ */
64
+ const modules = [].concat(options.require || []).filter(Boolean);
65
+ for (const name of modules) {
66
+ if (isDepInstalled(name)) {
67
+ require(name);
68
+ } else {
69
+ throw new Error(`cannot find module '${name}'`);
70
+ }
71
+ }
72
+
73
+ if (options.inline) {
74
+ const source = await readStdin();
75
+ loadInlineScript(source);
76
+ return;
77
+ }
78
+ /**
79
+ * Handle piped files by reading the STDIN
80
+ * ex: ls example/suites/*.js | npx @elastic/synthetics
81
+ */
82
+ const files =
83
+ args.length > 0 ? args : (await readStdin()).split('\n').filter(Boolean);
84
+ const suites = await prepareSuites(files, options.pattern);
85
+ requireSuites(suites);
86
+ }
87
+
88
+ const loadInlineScript = source => {
89
+ const scriptFn = new Function(
90
+ 'step',
91
+ 'page',
92
+ 'context',
93
+ 'browser',
94
+ 'params',
95
+ 'expect',
96
+ source
97
+ );
98
+ journey('inline', ({ page, context, browser, params }) => {
99
+ scriptFn.apply(null, [step, page, context, browser, params, expect]);
100
+ });
101
+ };
102
+
103
+ /**
104
+ * Read the input from STDIN and run it as inline journey
105
+ */
106
+ async function readStdin() {
107
+ const chunks = [];
108
+ stdin.resume();
109
+ stdin.setEncoding('utf-8');
110
+ for await (const chunk of stdin) {
111
+ chunks.push(chunk);
112
+ }
113
+ return chunks.join();
114
+ }
115
+
116
+ function requireSuites(suites: Iterable<string>) {
117
+ for (const suite of suites) {
118
+ require(suite);
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Handle both directory and files that are passed through TTY
124
+ * and add them to suites
125
+ */
126
+ async function prepareSuites(inputs: string[], filePattern?: string) {
127
+ const suites = new Set<string>();
128
+ const addSuite = absPath => {
129
+ log(`Processing file: ${absPath}`);
130
+ suites.add(require.resolve(absPath));
131
+ };
132
+ /**
133
+ * Match all files inside the directory with the
134
+ * .journey.{mjs|cjs|js|ts) extensions
135
+ */
136
+ const pattern = filePattern
137
+ ? new RegExp(filePattern, 'i')
138
+ : /.+\.journey\.([mc]js|[jt]s?)$/;
139
+ /**
140
+ * Ignore node_modules by default when running suites
141
+ */
142
+ const ignored = /node_modules/i;
143
+
144
+ for (const input of inputs) {
145
+ const absPath = resolve(resolvedCwd, input);
146
+ /**
147
+ * Validate for package.json file before running
148
+ * the suites
149
+ */
150
+ findPkgJsonByTraversing(absPath, resolvedCwd);
151
+ if (isDirectory(absPath)) {
152
+ await totalist(absPath, (rel, abs) => {
153
+ if (pattern.test(rel) && !ignored.test(rel)) {
154
+ addSuite(abs);
155
+ }
156
+ });
157
+ } else {
158
+ addSuite(absPath);
159
+ }
160
+ }
161
+ return suites.values();
162
+ }
package/src/options.ts ADDED
@@ -0,0 +1,173 @@
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 merge from 'deepmerge';
27
+ import { readConfig } from './config';
28
+ import { getNetworkConditions, DEFAULT_THROTTLING_OPTIONS } from './helpers';
29
+ import type { CliArgs, RunOptions, ThrottlingOptions } from './common_types';
30
+
31
+ /**
32
+ * Set debug based on DEBUG ENV and -d flags
33
+ * namespace - synthetics
34
+ */
35
+ const namespace = 'synthetics';
36
+ if (process.env.DEBUG && process.env.DEBUG.includes(namespace)) {
37
+ process.env.DEBUG = '1';
38
+ }
39
+
40
+ export function normalizeOptions(cliArgs: CliArgs): RunOptions {
41
+ const options: RunOptions = {
42
+ ...cliArgs,
43
+ environment: process.env['NODE_ENV'] || 'development',
44
+ };
45
+ /**
46
+ * Group all events that can be consumed by heartbeat and
47
+ * eventually by the Synthetics UI.
48
+ */
49
+ if (cliArgs.richEvents) {
50
+ options.reporter = cliArgs.reporter ?? 'json';
51
+ options.ssblocks = true;
52
+ options.network = true;
53
+ options.trace = true;
54
+ options.quietExitCode = true;
55
+ }
56
+
57
+ if (cliArgs.capability) {
58
+ const supportedCapabilities = [
59
+ 'trace',
60
+ 'network',
61
+ 'filmstrips',
62
+ 'metrics',
63
+ 'ssblocks',
64
+ ];
65
+ /**
66
+ * trace - record chrome trace events(LCP, FCP, CLS, etc.) for all journeys
67
+ * network - capture network information for all journeys
68
+ * filmstrips - record detailed filmstrips for all journeys
69
+ * metrics - capture performance metrics (DOM Nodes, Heap size, etc.) for each step
70
+ * ssblocks - Dedupes the screenshots in to blocks to save storage space
71
+ */
72
+ for (const flag of cliArgs.capability) {
73
+ if (supportedCapabilities.includes(flag)) {
74
+ options[flag] = true;
75
+ } else {
76
+ console.warn(
77
+ `Missing capability "${flag}", current supported capabilities are ${supportedCapabilities.join(
78
+ ', '
79
+ )}`
80
+ );
81
+ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Validate and read synthetics config file
87
+ * based on the environment
88
+ */
89
+ const config =
90
+ cliArgs.config || !cliArgs.inline
91
+ ? readConfig(options.environment, cliArgs.config)
92
+ : {};
93
+
94
+ /**
95
+ * Order of preference for options that are used while running are
96
+ * 1. Local options configured via Runner API
97
+ * 2. CLI flags
98
+ * 3. Configuration file
99
+ */
100
+ options.params = Object.freeze(merge(config.params, cliArgs.params || {}));
101
+
102
+ /**
103
+ * Merge playwright options from CLI and Synthetics config
104
+ * and prefer individual options over other option
105
+ */
106
+ const playwrightOpts = merge(
107
+ config.playwrightOptions,
108
+ cliArgs.playwrightOptions || {}
109
+ );
110
+ options.playwrightOptions = {
111
+ ...playwrightOpts,
112
+ headless: cliArgs.headless,
113
+ chromiumSandbox: cliArgs.sandbox ?? playwrightOpts?.chromiumSandbox,
114
+ ignoreHTTPSErrors:
115
+ cliArgs.ignoreHttpsErrors ?? playwrightOpts?.ignoreHTTPSErrors,
116
+ };
117
+
118
+ /**
119
+ * Get the default monitor config from synthetics.config.ts file
120
+ */
121
+ const monitor = config.monitor;
122
+ if (cliArgs.throttling) {
123
+ const throttleConfig = merge.all([
124
+ DEFAULT_THROTTLING_OPTIONS,
125
+ monitor?.throttling || {},
126
+ cliArgs.throttling as ThrottlingOptions,
127
+ ]);
128
+ options.throttling = throttleConfig;
129
+ options.networkConditions = getNetworkConditions(throttleConfig);
130
+ } else {
131
+ /**
132
+ * Do not apply throttling when `--no-throttling` flag is passed
133
+ */
134
+ options.throttling = {};
135
+ }
136
+
137
+ options.schedule = cliArgs.schedule ?? monitor?.schedule;
138
+ options.locations = cliArgs.locations ?? monitor?.locations;
139
+
140
+ return options;
141
+ }
142
+
143
+ /**
144
+ * Parses the throttling CLI settings and also
145
+ * adapts to the format to keep the backwards compatability
146
+ * - Accepts old format `<5d/3u/20l>`
147
+ * - Processess new format otherwise `{download: 5, upload: 3, latency: 20}`
148
+ */
149
+ export function parseThrottling(value: string, prev?: string) {
150
+ const THROTTLING_REGEX = /([0-9]{1,}u)|([0-9]{1,}d)|([0-9]{1,}l)/gm;
151
+ if (THROTTLING_REGEX.test(value)) {
152
+ const throttling: ThrottlingOptions = {};
153
+ const conditions = value.split('/');
154
+
155
+ conditions.forEach(condition => {
156
+ const setting = condition.slice(0, condition.length - 1);
157
+ const token = condition.slice(-1);
158
+ switch (token) {
159
+ case 'd':
160
+ throttling.download = Number(setting);
161
+ break;
162
+ case 'u':
163
+ throttling.upload = Number(setting);
164
+ break;
165
+ case 'l':
166
+ throttling.latency = Number(setting);
167
+ break;
168
+ }
169
+ });
170
+ return throttling;
171
+ }
172
+ return JSON.parse(value || prev);
173
+ }
@@ -23,8 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { Page } from 'playwright-chromium';
27
- import { BrowserMessage } from '../common_types';
26
+ import { BrowserMessage, Driver } from '../common_types';
28
27
  import { Step } from '../dsl';
29
28
  import { getTimestamp } from '../helpers';
30
29
 
@@ -34,6 +33,8 @@ export class BrowserConsole {
34
33
  private messages: BrowserMessage[] = [];
35
34
  _currentStep: Partial<Step> = null;
36
35
 
36
+ constructor(private driver: Driver) {}
37
+
37
38
  private consoleEventListener = msg => {
38
39
  if (!this._currentStep) {
39
40
  return;
@@ -47,20 +48,41 @@ export class BrowserConsole {
47
48
  type,
48
49
  step: { name, index },
49
50
  });
50
- if (this.messages.length > defaultMessageLimit) {
51
- this.messages.splice(0, 1);
52
- }
51
+
52
+ this.enforceMessagesLimit();
53
+ }
54
+ };
55
+
56
+ private pageErrorEventListener = (error: Error) => {
57
+ if (!this._currentStep) {
58
+ return;
53
59
  }
60
+ const { name, index } = this._currentStep;
61
+ this.messages.push({
62
+ timestamp: getTimestamp(),
63
+ text: error.message,
64
+ type: 'error',
65
+ step: { name, index },
66
+ error,
67
+ });
68
+
69
+ this.enforceMessagesLimit();
54
70
  };
55
71
 
56
- constructor(private page: Page) {}
72
+ private enforceMessagesLimit() {
73
+ if (this.messages.length > defaultMessageLimit) {
74
+ this.messages.splice(0, 1);
75
+ }
76
+ }
57
77
 
58
78
  start() {
59
- this.page.on('console', this.consoleEventListener);
79
+ this.driver.page.on('console', this.consoleEventListener);
80
+ this.driver.page.on('pageerror', this.pageErrorEventListener);
60
81
  }
61
82
 
62
83
  stop() {
63
- this.page.off('console', this.consoleEventListener);
84
+ this.driver.page.off('console', this.consoleEventListener);
85
+ this.driver.page.off('pageerror', this.pageErrorEventListener);
64
86
  return this.messages;
65
87
  }
66
88
  }