@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
@@ -23,7 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { PluginOutput } from '../common_types';
26
+ import { PluginOutput, Driver } from '../common_types';
27
27
  import {
28
28
  BrowserConsole,
29
29
  NetworkManager,
@@ -31,7 +31,6 @@ import {
31
31
  Tracing,
32
32
  TraceOptions,
33
33
  } from './';
34
- import { Driver } from '../core/gatherer';
35
34
  import { Step } from '../dsl';
36
35
 
37
36
  type PluginType = 'network' | 'trace' | 'performance' | 'browserconsole';
@@ -39,59 +38,78 @@ type Plugin = NetworkManager | Tracing | PerformanceManager | BrowserConsole;
39
38
  type PluginOptions = TraceOptions;
40
39
 
41
40
  export class PluginManager {
42
- protected plugins = new Map<string, Plugin>();
43
-
41
+ protected plugins = new Map<PluginType, Plugin>();
42
+ public PLUGIN_TYPES: Array<PluginType> = [
43
+ 'network',
44
+ 'trace',
45
+ 'performance',
46
+ 'browserconsole',
47
+ ];
44
48
  constructor(private driver: Driver) {}
45
49
 
46
- async start(type: PluginType, options?: PluginOptions) {
50
+ register(type: PluginType, options: PluginOptions) {
47
51
  let instance: Plugin;
48
52
  switch (type) {
49
53
  case 'network':
50
- instance = new NetworkManager();
51
- await instance.start(this.driver.client);
54
+ instance = new NetworkManager(this.driver);
52
55
  break;
53
56
  case 'trace':
54
- instance = new Tracing(options);
55
- await instance.start(this.driver.client);
57
+ instance = new Tracing(this.driver, options);
56
58
  break;
57
59
  case 'performance':
58
- instance = new PerformanceManager(this.driver.client);
59
- instance.start();
60
+ instance = new PerformanceManager(this.driver);
60
61
  break;
61
62
  case 'browserconsole':
62
- instance = new BrowserConsole(this.driver.page);
63
- instance.start();
63
+ instance = new BrowserConsole(this.driver);
64
64
  break;
65
65
  }
66
+ instance && this.plugins.set(type, instance);
67
+ return instance;
68
+ }
69
+
70
+ registerAll(options: PluginOptions) {
71
+ for (const type of this.PLUGIN_TYPES) {
72
+ this.register(type, options);
73
+ }
74
+ }
75
+
76
+ unregisterAll() {
77
+ for (const type of this.PLUGIN_TYPES) {
78
+ this.plugins.delete(type);
79
+ }
80
+ }
81
+
82
+ async stop(type: PluginType) {
83
+ const instance = this.plugins.get(type);
84
+ if (instance) {
85
+ return await instance.stop();
86
+ }
87
+ return {};
88
+ }
66
89
 
67
- this.plugins.set(instance.constructor.name, instance);
90
+ async start(type: PluginType) {
91
+ const instance = this.plugins.get(type);
92
+ instance && (await instance.start());
68
93
  return instance;
69
94
  }
70
95
 
71
- get<T extends Plugin>(Type: new (...args: any[]) => T): T {
72
- return this.plugins.get(Type.name) as T;
96
+ get(type: PluginType) {
97
+ return this.plugins.get(type);
73
98
  }
74
99
 
75
100
  onStep(step: Step) {
76
- this.get(BrowserConsole) && (this.get(BrowserConsole)._currentStep = step);
77
- this.get(NetworkManager) && (this.get(NetworkManager)._currentStep = step);
101
+ (this.get('browserconsole') as BrowserConsole)._currentStep = step;
102
+ (this.get('network') as NetworkManager)._currentStep = step;
78
103
  }
79
104
 
80
- async output(): Promise<PluginOutput> {
105
+ async output() {
81
106
  const data: PluginOutput = {};
82
- try {
83
- for (const [, plugin] of this.plugins) {
84
- if (plugin instanceof NetworkManager) {
85
- data.networkinfo = plugin.stop();
86
- } else if (plugin instanceof Tracing) {
87
- const result = await plugin.stop(this.driver.client);
88
- Object.assign(data, { ...result });
89
- } else if (plugin instanceof BrowserConsole) {
90
- data.browserconsole = plugin.stop();
91
- }
107
+ for (const [, plugin] of this.plugins) {
108
+ if (plugin instanceof NetworkManager) {
109
+ data.networkinfo = await plugin.stop();
110
+ } else if (plugin instanceof BrowserConsole) {
111
+ data.browserconsole = plugin.stop();
92
112
  }
93
- } catch (e) {
94
- console.error('Error capturing data', e.message);
95
113
  }
96
114
  return data;
97
115
  }
@@ -23,8 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { CDPSession } from 'playwright-chromium';
27
- import { PluginOutput } from '../common_types';
26
+ import { Driver, PluginOutput } from '../common_types';
28
27
  import { Filmstrips } from '../sdk/trace-metrics';
29
28
  import { TraceEvent, TraceProcessor } from '../sdk/trace-processor';
30
29
 
@@ -38,9 +37,9 @@ export type TraceOptions = {
38
37
  * https://chromedevtools.github.io/devtools-protocol/tot/Tracing/
39
38
  */
40
39
  export class Tracing {
41
- constructor(public options: TraceOptions) {}
40
+ constructor(private driver: Driver, private options: TraceOptions) {}
42
41
 
43
- async start(client: CDPSession) {
42
+ async start() {
44
43
  const includedCategories = [
45
44
  // exclude all default categories
46
45
  '-*',
@@ -63,21 +62,21 @@ export class Tracing {
63
62
  'disabled-by-default-devtools.timeline'
64
63
  );
65
64
  }
66
- await client.send('Tracing.start', {
65
+ await this.driver.client.send('Tracing.start', {
67
66
  /**
68
67
  * Using `ReportEvents` makes gathering trace events
69
68
  * much faster as opposed to using `ReturnAsStream` mode
70
69
  */
71
70
  transferMode: 'ReportEvents',
72
- traceConfig: {
73
- includedCategories,
74
- },
71
+ categories: includedCategories.join(','),
72
+ options: 'sampling-frequency=10000', // 1000 is default
75
73
  });
76
74
  }
77
75
 
78
- async stop(client: CDPSession) {
76
+ async stop() {
79
77
  const events = [];
80
78
  const collectListener = payload => events.push(...payload.value);
79
+ const { client } = this.driver;
81
80
  client.on('Tracing.dataCollected', collectListener);
82
81
 
83
82
  const [traceEvents] = await Promise.all([
@@ -0,0 +1,95 @@
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 path from 'path';
27
+ import { unlink, readFile } from 'fs/promises';
28
+ import { createWriteStream } from 'fs';
29
+ import * as esbuild from 'esbuild';
30
+ import archiver from 'archiver';
31
+ import { commonOptions, MultiAssetPlugin, PluginData } from './plugin';
32
+
33
+ function relativeToCwd(entry: string) {
34
+ return path.relative(process.cwd(), entry);
35
+ }
36
+
37
+ export class Bundler {
38
+ moduleMap = new Map<string, string>();
39
+ constructor() {}
40
+
41
+ async prepare(absPath: string) {
42
+ const addToMap = (data: PluginData) => {
43
+ this.moduleMap.set(data.path, data.contents);
44
+ };
45
+
46
+ const options: esbuild.BuildOptions = {
47
+ ...commonOptions(),
48
+ ...{
49
+ entryPoints: {
50
+ [absPath]: absPath,
51
+ },
52
+ plugins: [MultiAssetPlugin(addToMap)],
53
+ },
54
+ };
55
+ const result = await esbuild.build(options);
56
+ if (result.errors.length > 0) {
57
+ throw result.errors;
58
+ }
59
+ this.moduleMap.set(absPath, result.outputFiles[0].text);
60
+ }
61
+
62
+ async zip(outputPath: string) {
63
+ return new Promise((fulfill, reject) => {
64
+ const output = createWriteStream(outputPath);
65
+ const archive = archiver('zip', {
66
+ zlib: { level: 9 },
67
+ });
68
+ archive.on('error', err => reject(err));
69
+ output.on('close', fulfill);
70
+ archive.pipe(output);
71
+ for (const [path, content] of this.moduleMap.entries()) {
72
+ const relativePath = relativeToCwd(path);
73
+ archive.append(content, { name: relativePath });
74
+ }
75
+ archive.finalize();
76
+ });
77
+ }
78
+
79
+ async build(entry: string, output: string) {
80
+ await this.prepare(entry);
81
+ await this.zip(output);
82
+ const data = await this.encode(output);
83
+ await this.cleanup(output);
84
+ return data;
85
+ }
86
+
87
+ async encode(outputPath: string) {
88
+ return await readFile(outputPath, 'base64');
89
+ }
90
+
91
+ async cleanup(outputPath: string) {
92
+ this.moduleMap = new Map<string, string>();
93
+ await unlink(outputPath);
94
+ }
95
+ }
@@ -0,0 +1,59 @@
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 {
27
+ createMonitors,
28
+ ok,
29
+ formatAPIError,
30
+ formatFailedMonitors,
31
+ formatNotFoundError,
32
+ } from './request';
33
+ import { Monitor } from '../dsl/monitor';
34
+ import { PushOptions } from '../common_types';
35
+ import { buildMonitorSchema } from './monitor';
36
+ import { progress, error, done } from '../helpers';
37
+
38
+ export async function push(monitors: Monitor[], options: PushOptions) {
39
+ progress(`preparing all monitors`);
40
+ const schemas = await buildMonitorSchema(monitors);
41
+ try {
42
+ progress(`creating all monitors`);
43
+ const { body, statusCode } = await createMonitors(schemas, options);
44
+ if (statusCode === 404) {
45
+ throw formatNotFoundError(await body.text());
46
+ }
47
+ if (!ok(statusCode)) {
48
+ const { error, message } = await body.json();
49
+ throw formatAPIError(statusCode, error, message);
50
+ }
51
+ const { failedMonitors } = await body.json();
52
+ if (failedMonitors.length > 0) {
53
+ throw formatFailedMonitors(failedMonitors);
54
+ }
55
+ done('Pushed');
56
+ } catch (e) {
57
+ error(e);
58
+ }
59
+ }
@@ -0,0 +1,68 @@
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 { mkdir } from 'fs/promises';
27
+ import { join } from 'path';
28
+ import { Bundler } from './bundler';
29
+ import { CACHE_PATH } from '../helpers';
30
+ import { LocationsMap } from '../dsl/locations';
31
+ import { Monitor, MonitorConfig } from '../dsl/monitor';
32
+
33
+ export type MonitorSchema = Omit<MonitorConfig, 'locations'> & {
34
+ content: string;
35
+ locations: string[];
36
+ filter: Monitor['filter'];
37
+ };
38
+
39
+ function translateLocation(locations: MonitorConfig['locations']) {
40
+ return locations.map(loc => LocationsMap[loc]).filter(Boolean);
41
+ }
42
+
43
+ export async function buildMonitorSchema(monitors: Monitor[]) {
44
+ if (monitors.length == 0) {
45
+ throw new Error('No Monitors found');
46
+ }
47
+ /**
48
+ * Set up the bundle artifacts path which can be used to
49
+ * create the bundles required for uploading journeys
50
+ */
51
+ const bundlePath = join(CACHE_PATH, 'bundles');
52
+ await mkdir(bundlePath, { recursive: true });
53
+ const bundler = new Bundler();
54
+ const schemas: MonitorSchema[] = [];
55
+
56
+ for (const monitor of monitors) {
57
+ const { source, config, filter } = monitor;
58
+ const outPath = join(bundlePath, config.name + '.zip');
59
+ const content = await bundler.build(source.file, outPath);
60
+ schemas.push({
61
+ ...config,
62
+ content,
63
+ locations: translateLocation(config.locations),
64
+ filter: filter,
65
+ });
66
+ }
67
+ return schemas;
68
+ }
@@ -0,0 +1,114 @@
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 path from 'path';
27
+ import fs from 'fs/promises';
28
+ import * as esbuild from 'esbuild';
29
+
30
+ export function commonOptions(): esbuild.BuildOptions {
31
+ return {
32
+ bundle: true,
33
+ external: ['node_modules', '@elastic/synthetics'],
34
+ minify: false,
35
+ platform: 'node',
36
+ logLevel: 'silent',
37
+ format: 'esm',
38
+ write: false,
39
+ outExtension: {
40
+ '.js': '.js',
41
+ },
42
+ };
43
+ }
44
+
45
+ export type PluginData = {
46
+ path: string;
47
+ contents: string;
48
+ };
49
+ export type PluginCallback = (data: PluginData) => void;
50
+
51
+ export function MultiAssetPlugin(callback: PluginCallback): esbuild.Plugin {
52
+ const isBare = (str: string) => {
53
+ if (str.startsWith('/') || str.startsWith('./') || str.startsWith('../')) {
54
+ return true;
55
+ }
56
+ return false;
57
+ };
58
+
59
+ return {
60
+ name: 'esbuild-multiasset-plugin',
61
+ setup(build) {
62
+ build.onResolve({ filter: /.*?/ }, async args => {
63
+ // External and other packages need be marked external to
64
+ // be removed from the bundle
65
+ if (
66
+ build.initialOptions.external?.includes(args.path) ||
67
+ !isBare(args.path)
68
+ ) {
69
+ return {
70
+ external: true,
71
+ };
72
+ }
73
+
74
+ if (args.kind === 'entry-point') {
75
+ return {
76
+ path: args.path,
77
+ namespace: 'asset',
78
+ };
79
+ }
80
+
81
+ // If the modules are resolved locally, then
82
+ // use the imported path to get full path
83
+ const entryPath =
84
+ path.join(path.dirname(args.importer), args.path) +
85
+ path.extname(args.importer);
86
+ // Spin off another build to copy over the imported modules without bundling
87
+ const result = await esbuild.build({
88
+ ...commonOptions(),
89
+ entryPoints: {
90
+ [entryPath]: entryPath,
91
+ },
92
+ bundle: false,
93
+ external: [],
94
+ });
95
+
96
+ callback({
97
+ path: entryPath,
98
+ contents: result.outputFiles[0].text,
99
+ });
100
+
101
+ return {
102
+ errors: result.errors,
103
+ external: true,
104
+ };
105
+ });
106
+
107
+ build.onLoad({ filter: /.*?/, namespace: 'asset' }, async args => {
108
+ const contents = await fs.readFile(args.path, 'utf-8');
109
+ callback({ path: args.path, contents });
110
+ return { contents };
111
+ });
112
+ },
113
+ };
114
+ }
@@ -0,0 +1,111 @@
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 { bold } from 'kleur/colors';
27
+ import { request } from 'undici';
28
+ import { PushOptions } from '../common_types';
29
+ import { indent, symbols } from '../helpers';
30
+ import { MonitorSchema } from './monitor';
31
+
32
+ /* eslint-disable @typescript-eslint/no-var-requires */
33
+ const { version } = require('../../package.json');
34
+
35
+ export type APISchema = {
36
+ project: string;
37
+ keep_stale: boolean;
38
+ monitors: MonitorSchema[];
39
+ };
40
+
41
+ function getAPIUrl(options: PushOptions) {
42
+ // remove trialing / as well
43
+ return (
44
+ options.url.replace(/\/+$/, '') +
45
+ `/s/${options.space}/api/synthetics/service/project/monitors`
46
+ );
47
+ }
48
+
49
+ export function ok(statusCode: number) {
50
+ return statusCode >= 200 && statusCode <= 299;
51
+ }
52
+
53
+ export async function createMonitors(
54
+ monitors: MonitorSchema[],
55
+ options: PushOptions
56
+ ) {
57
+ const schema: APISchema = {
58
+ project: options.project,
59
+ keep_stale: false,
60
+ monitors,
61
+ };
62
+
63
+ return await request(getAPIUrl(options), {
64
+ method: 'PUT',
65
+ body: JSON.stringify(schema),
66
+ headers: {
67
+ authorization: `ApiKey ${options.auth}`,
68
+ 'content-type': 'application/json',
69
+ 'user-agent': `Elastic/Synthetics ${version}`,
70
+ 'kbn-xsrf': 'true',
71
+ },
72
+ });
73
+ }
74
+
75
+ export type APIMonitorError = {
76
+ id?: string;
77
+ reason: string;
78
+ details: string;
79
+ };
80
+
81
+ export function formatNotFoundError(message: string) {
82
+ return bold(
83
+ `${symbols['failed']} Please check your kibana url and try again - 404:${message}`
84
+ );
85
+ }
86
+
87
+ export function formatAPIError(
88
+ statuCode: number,
89
+ error: string,
90
+ message: string
91
+ ) {
92
+ let outer = bold(`${symbols['failed']} Error\n`);
93
+ let inner = bold(
94
+ `${symbols['failed']} monitor creation failed - ${statuCode}:${error}\n`
95
+ );
96
+ inner += indent(message, ' ');
97
+ outer += indent(inner);
98
+ return outer;
99
+ }
100
+
101
+ export function formatFailedMonitors(errors: APIMonitorError[]) {
102
+ let outer = bold(`${symbols['failed']} Error\n`);
103
+ for (const error of errors) {
104
+ const monitorId = error.id ? `: monitor(${error.id})` : '';
105
+ let inner = bold(`> ${error.reason}${monitorId}\n`);
106
+ inner += indent(error.details, ' ');
107
+ outer += indent(inner) + '\n';
108
+ outer += '\n';
109
+ }
110
+ return outer;
111
+ }