@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,87 @@
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 {
28
+ ThrottlingOptions,
29
+ Location,
30
+ ScreenshotOptions,
31
+ Params,
32
+ PlaywrightOptions,
33
+ } from '../common_types';
34
+ import { LocationsMap } from './locations';
35
+
36
+ export type SyntheticsLocationsType = keyof typeof LocationsMap;
37
+ export const SyntheticsLocations = Object.keys(
38
+ LocationsMap
39
+ ) as SyntheticsLocationsType[];
40
+
41
+ export type MonitorConfig = {
42
+ id?: string;
43
+ name?: string;
44
+ tags?: string[];
45
+ schedule?: number;
46
+ enabled?: boolean;
47
+ locations?: SyntheticsLocationsType[];
48
+ throttling?: ThrottlingOptions;
49
+ screenshot?: ScreenshotOptions;
50
+ params?: Params;
51
+ playwrightOptions?: PlaywrightOptions;
52
+ };
53
+
54
+ type MonitorFilter = {
55
+ match: string;
56
+ tags?: string[];
57
+ };
58
+
59
+ export class Monitor {
60
+ source?: Location;
61
+ filter: MonitorFilter;
62
+ constructor(public config: MonitorConfig = {}) {}
63
+ /**
64
+ * Treat the creation time config with `monitor.use` as source of truth by
65
+ * merging the values coming from CLI and Synthetics config file
66
+ */
67
+ update(globalOpts: MonitorConfig = {}) {
68
+ this.config = merge(globalOpts, this.config, {
69
+ arrayMerge(target, source) {
70
+ return [...new Set(source)];
71
+ },
72
+ });
73
+ }
74
+
75
+ setSource(source: Location) {
76
+ this.source = source;
77
+ }
78
+ /**
79
+ * If journey files are colocated within the same file during
80
+ * push command, when we invoke synthetics from HB we rely on
81
+ * this filter for running that specific journey alone instead of
82
+ * all journeys on the file
83
+ */
84
+ setFilter(filter: MonitorFilter) {
85
+ this.filter = filter;
86
+ }
87
+ }
package/src/dsl/step.ts CHANGED
@@ -23,16 +23,23 @@
23
23
  *
24
24
  */
25
25
 
26
- import { VoidCallback } from '../common_types';
26
+ import { Location, VoidCallback } from '../common_types';
27
27
 
28
28
  export class Step {
29
29
  name: string;
30
30
  index: number;
31
31
  callback: VoidCallback;
32
+ location?: Location;
32
33
 
33
- constructor(name: string, index: number, callback: VoidCallback) {
34
+ constructor(
35
+ name: string,
36
+ index: number,
37
+ callback: VoidCallback,
38
+ location: Location
39
+ ) {
34
40
  this.name = name;
35
41
  this.index = index;
36
42
  this.callback = callback;
43
+ this.location = location;
37
44
  }
38
45
  }
@@ -0,0 +1,367 @@
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
+ JavaScriptLanguageGenerator,
28
+ JavaScriptFormatter,
29
+ } from 'playwright-core/lib/server/supplements/recorder/javascript';
30
+
31
+ export type Step = {
32
+ actions: ActionInContext[];
33
+ name?: string;
34
+ };
35
+
36
+ export type Steps = Step[];
37
+
38
+ export type ActionInContext = {
39
+ pageAlias: string;
40
+ frameName?: string;
41
+ frameUrl: string;
42
+ isMainFrame: boolean;
43
+ action: Action;
44
+ committed?: boolean;
45
+ modified?: boolean;
46
+ title?: string;
47
+ };
48
+
49
+ export type Action = {
50
+ name: string;
51
+ selector?: string;
52
+ url?: string;
53
+ key?: string;
54
+ signals: Signal[];
55
+ modifiers?: number;
56
+ button?: 'left' | 'middle' | 'right';
57
+ clickCount?: number;
58
+ text?: string;
59
+ value?: string;
60
+ isAssert?: boolean;
61
+ command?: string;
62
+ files?: string[];
63
+ options?: string[];
64
+ };
65
+
66
+ export type Signal = {
67
+ name: string;
68
+ url?: string;
69
+ isAsync?: boolean;
70
+ popupAlias?: string;
71
+ downloadAlias?: string;
72
+ dialogAlias?: string;
73
+ };
74
+
75
+ export class SyntheticsGenerator extends JavaScriptLanguageGenerator {
76
+ private previousContext: ActionInContext;
77
+ private insideStep: boolean;
78
+
79
+ constructor(private isSuite: boolean) {
80
+ super(true);
81
+ this.insideStep = false;
82
+ this.previousContext = undefined;
83
+ }
84
+
85
+ /**
86
+ * Generate code for an action.
87
+ * @param actionInContext The action to create code for.
88
+ * @returns the strings generated for the action.
89
+ */
90
+ generateAction(actionInContext: ActionInContext) {
91
+ const { action, pageAlias } = actionInContext;
92
+ if (action.name === 'openPage') {
93
+ return '';
94
+ }
95
+ // Don't cleanup page object managed by Synthetics
96
+ const isCleanUp = action.name === 'closePage' && pageAlias === 'page';
97
+ if (isCleanUp) {
98
+ return '';
99
+ }
100
+
101
+ const stepIndent = this.insideStep ? 2 : 0;
102
+ const offset = this.isSuite ? 2 + stepIndent : 0 + stepIndent;
103
+ const formatter = new JavaScriptFormatter(offset);
104
+
105
+ const subject = actionInContext.isMainFrame
106
+ ? pageAlias
107
+ : actionInContext.frameName
108
+ ? `${pageAlias}.frame(${formatObject({
109
+ name: actionInContext.frameName,
110
+ })})`
111
+ : `${pageAlias}.frame(${formatObject({
112
+ url: actionInContext.frameUrl,
113
+ })})`;
114
+
115
+ const signals = toSignalMap(action);
116
+
117
+ if (signals.dialog) {
118
+ formatter.add(` ${pageAlias}.once('dialog', dialog => {
119
+ console.log(\`Dialog message: $\{dialog.message()}\`);
120
+ dialog.dismiss().catch(() => {});
121
+ });`);
122
+ }
123
+
124
+ const emitPromiseAll =
125
+ signals.waitForNavigation || signals.popup || signals.download;
126
+ if (emitPromiseAll) {
127
+ // Generate either await Promise.all([]) or
128
+ // const [popup1] = await Promise.all([]).
129
+ let leftHandSide = '';
130
+ if (signals.popup)
131
+ leftHandSide = `const [${signals.popup.popupAlias}] = `;
132
+ else if (signals.download) leftHandSide = `const [download] = `;
133
+ formatter.add(`${leftHandSide}await Promise.all([`);
134
+ }
135
+
136
+ // Popup signals.
137
+ if (signals.popup) formatter.add(`${pageAlias}.waitForEvent('popup'),`);
138
+
139
+ // Navigation signal.
140
+ if (signals.waitForNavigation)
141
+ formatter.add(
142
+ `${pageAlias}.waitForNavigation(/*{ url: ${quote(
143
+ signals.waitForNavigation.url
144
+ )} }*/),`
145
+ );
146
+
147
+ // Download signals.
148
+ if (signals.download)
149
+ formatter.add(`${pageAlias}.waitForEvent('download'),`);
150
+
151
+ const prefix =
152
+ signals.popup || signals.waitForNavigation || signals.download
153
+ ? ''
154
+ : 'await ';
155
+ const actionCall = super._generateActionCall(action);
156
+ // Add assertion from Synthetics.
157
+ const isAssert = action.name === 'assert' && action.isAssert;
158
+
159
+ if (!isAssert) {
160
+ const suffix = signals.waitForNavigation || emitPromiseAll ? '' : ';';
161
+ formatter.add(`${prefix}${subject}.${actionCall}${suffix}`);
162
+
163
+ if (emitPromiseAll) {
164
+ formatter.add(`]);`);
165
+ } else if (signals.assertNavigation) {
166
+ formatter.add(
167
+ ` expect(${pageAlias}.url()).toBe(${quote(
168
+ signals.assertNavigation.url
169
+ )});`
170
+ );
171
+ }
172
+ } else if (action.command) {
173
+ formatter.add(toAssertCall(pageAlias, action));
174
+ }
175
+
176
+ this.previousContext = actionInContext;
177
+ return formatter.format();
178
+ }
179
+
180
+ isNewStep(actioninContext: ActionInContext) {
181
+ const { action, frameUrl } = actioninContext;
182
+ if (action.name === 'navigate') {
183
+ return true;
184
+ } else if (action.name === 'click') {
185
+ return (
186
+ this.previousContext?.frameUrl === frameUrl && action.signals.length > 0
187
+ );
188
+ }
189
+ return false;
190
+ }
191
+
192
+ generateStepStart(name) {
193
+ this.insideStep = true;
194
+ const formatter = new JavaScriptFormatter(this.isSuite ? 2 : 0);
195
+ formatter.add(`step(${quote(name)}, async () => {`);
196
+ return formatter.format();
197
+ }
198
+
199
+ generateStepEnd() {
200
+ if (!this.insideStep) {
201
+ return '';
202
+ }
203
+ this.insideStep = false;
204
+ const formatter = new JavaScriptFormatter(this.isSuite ? 2 : 0);
205
+ formatter.add(`});`);
206
+ return formatter.format();
207
+ }
208
+
209
+ generateHeader() {
210
+ const formatter = new JavaScriptFormatter(0);
211
+ formatter.add(`
212
+ const { journey, step, expect } = require('@elastic/synthetics');
213
+
214
+ journey('Recorded journey', async ({ page, context }) => {`);
215
+ return formatter.format();
216
+ }
217
+
218
+ generateFooter() {
219
+ return `});`;
220
+ }
221
+
222
+ /**
223
+ * Generates JavaScript code from a custom set of steps and nested actions.
224
+ *
225
+ * This function makes no assumptions about where steps should be created,
226
+ * and instead follows the step definitions the caller has defined.
227
+ * @param steps IR to use for code generation
228
+ * @returns a list of the code strings outputted by the generator
229
+ */
230
+ generateFromSteps(steps: Steps): string {
231
+ const text = [];
232
+ if (this.isSuite) {
233
+ text.push(this.generateHeader());
234
+ }
235
+ for (const step of steps) {
236
+ if (step.actions.length === 0)
237
+ throw Error('Cannot process an empty step');
238
+ text.push(
239
+ this.generateStepStart(
240
+ step.name ??
241
+ step.actions[0].title ??
242
+ actionTitle(step.actions[0].action)
243
+ )
244
+ );
245
+
246
+ for (const action of step.actions) {
247
+ const actionText = this.generateAction(action);
248
+ if (actionText.length) text.push(actionText);
249
+ }
250
+
251
+ text.push(this.generateStepEnd());
252
+ }
253
+ if (this.isSuite) {
254
+ text.push(this.generateFooter());
255
+ }
256
+ return text.filter(s => !!s).join('\n');
257
+ }
258
+ }
259
+
260
+ // TODO: Replace once Playwright releases new version
261
+ export function quote(text: string, char = "'") {
262
+ const stringified = JSON.stringify(text);
263
+ const escapedText = stringified
264
+ .substring(1, stringified.length - 1)
265
+ .replace(/\\"/g, '"');
266
+ if (char === "'") return char + escapedText.replace(/[']/g, "\\'") + char;
267
+ if (char === '"') return char + escapedText.replace(/["]/g, '\\"') + char;
268
+ if (char === '`') return char + escapedText.replace(/[`]/g, '`') + char;
269
+ throw new Error('Invalid escape char');
270
+ }
271
+
272
+ function toSignalMap(action) {
273
+ let waitForNavigation;
274
+ let assertNavigation;
275
+ let popup;
276
+ let download;
277
+ let dialog;
278
+ for (const signal of action.signals) {
279
+ if (signal.name === 'navigation' && signal.isAsync)
280
+ waitForNavigation = signal;
281
+ else if (signal.name === 'navigation' && !signal.isAsync)
282
+ assertNavigation = signal;
283
+ else if (signal.name === 'popup') popup = signal;
284
+ else if (signal.name === 'download') download = signal;
285
+ else if (signal.name === 'dialog') dialog = signal;
286
+ }
287
+ return {
288
+ waitForNavigation,
289
+ assertNavigation,
290
+ popup,
291
+ download,
292
+ dialog,
293
+ };
294
+ }
295
+
296
+ function toAssertCall(pageAlias, action) {
297
+ const { command, selector, value } = action;
298
+ switch (command) {
299
+ case 'textContent':
300
+ case 'innerText':
301
+ return `expect(await ${pageAlias}.${command}(${quote(
302
+ selector
303
+ )})).toMatch(${quote(value)});`;
304
+ case 'isVisible':
305
+ case 'isHidden':
306
+ case 'isChecked':
307
+ case 'isEditable':
308
+ case 'isEnabled':
309
+ case 'isDisabled':
310
+ return `expect(await ${pageAlias}.${command}(${quote(
311
+ selector
312
+ )})).toBeTruthy();`;
313
+ }
314
+ }
315
+
316
+ function formatObject(value, indent = ' ') {
317
+ if (typeof value === 'string') return quote(value);
318
+ if (Array.isArray(value))
319
+ return `[${value.map(o => formatObject(o)).join(', ')}]`;
320
+ if (typeof value === 'object') {
321
+ const keys = Object.keys(value);
322
+ if (!keys.length) return '{}';
323
+ const tokens = [];
324
+ for (const key of keys) tokens.push(`${key}: ${formatObject(value[key])}`);
325
+ return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`;
326
+ }
327
+ return String(value);
328
+ }
329
+
330
+ /**
331
+ * Generates an appropriate title string based on the action type/data.
332
+ * @param action Playwright action IR
333
+ * @returns title string
334
+ */
335
+ export function actionTitle(action: Action) {
336
+ switch (action.name) {
337
+ case 'openPage':
338
+ return `Open new page`;
339
+ case 'closePage':
340
+ return `Close page`;
341
+ case 'check':
342
+ return `Check ${action.selector}`;
343
+ case 'uncheck':
344
+ return `Uncheck ${action.selector}`;
345
+ case 'click': {
346
+ if (action.clickCount === 1) return `Click ${action.selector}`;
347
+ if (action.clickCount === 2) return `Double click ${action.selector}`;
348
+ if (action.clickCount === 3) return `Triple click ${action.selector}`;
349
+ return `${action.clickCount}× click`;
350
+ }
351
+ case 'fill':
352
+ return `Fill ${action.selector}`;
353
+ case 'setInputFiles':
354
+ if (action.files.length === 0) return `Clear selected files`;
355
+ else return `Upload ${action.files.join(', ')}`;
356
+ case 'navigate':
357
+ return `Go to ${action.url}`;
358
+ case 'press':
359
+ return (
360
+ `Press ${action.key}` + (action.modifiers ? ' with modifiers' : '')
361
+ );
362
+ case 'select':
363
+ return `Select ${action.options.join(', ')}`;
364
+ case 'assert':
365
+ return `Assert ${action.selector} ${action.command}`;
366
+ }
367
+ }
@@ -0,0 +1,212 @@
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
+ import { prompt } from 'enquirer';
31
+ import { SyntheticsLocations } from '../dsl/monitor';
32
+ import { progress, write as stdWrite } from '../helpers';
33
+ import { getPackageManager, replaceTemplates, runCommand } from './utils';
34
+
35
+ // Templates that are required for setting up new
36
+ // synthetics project
37
+ const templateDir = join(__dirname, '..', '..', 'templates');
38
+
39
+ type PromptOptions = {
40
+ locations: string;
41
+ schedule: number;
42
+ };
43
+
44
+ // exported for testing
45
+ export const regularFiles = [
46
+ '.github/workflows/run-synthetics.yml',
47
+ 'README.md',
48
+ 'journeys/example.journey.ts',
49
+ 'journeys/advanced-example.journey.ts',
50
+ 'journeys/advanced-example-helpers.ts',
51
+ ];
52
+
53
+ export class Generator {
54
+ pkgManager = 'npm';
55
+ constructor(public projectDir: string) {}
56
+
57
+ async directory() {
58
+ if (!existsSync(this.projectDir)) {
59
+ await mkdir(this.projectDir);
60
+ }
61
+ }
62
+
63
+ async questions() {
64
+ if (process.env.TEST_QUESTIONS) {
65
+ return JSON.parse(process.env.TEST_QUESTIONS);
66
+ }
67
+ const question = [
68
+ {
69
+ type: 'select',
70
+ name: 'locations',
71
+ message: 'Select the default location where you want to run monitors.',
72
+ choices: SyntheticsLocations,
73
+ },
74
+ {
75
+ type: 'numeral',
76
+ name: 'schedule',
77
+ message: 'Set default schedule in minutes for all monitors',
78
+ initial: 10,
79
+ },
80
+ ];
81
+ return await prompt<PromptOptions>(question);
82
+ }
83
+
84
+ async files(answers: PromptOptions) {
85
+ const fileMap = new Map<string, string>();
86
+ // Setup Synthetics config file
87
+ const configFile = 'synthetics.config.ts';
88
+ fileMap.set(
89
+ configFile,
90
+ replaceTemplates(
91
+ await readFile(join(templateDir, configFile), 'utf-8'),
92
+ answers
93
+ )
94
+ );
95
+
96
+ // Setup non-templated files
97
+ Promise.all(
98
+ regularFiles.map(async fn => {
99
+ fileMap.set(fn, await readFile(join(templateDir, fn), 'utf-8'));
100
+ })
101
+ ).catch(e => {
102
+ throw e;
103
+ });
104
+
105
+ // Create files
106
+ for (const [relativePath, content] of fileMap) {
107
+ await this.createFile(relativePath, content);
108
+ }
109
+ }
110
+
111
+ async createFile(relativePath: string, content: string, override = false) {
112
+ const absolutePath = join(this.projectDir, relativePath);
113
+ if (override || !existsSync(absolutePath)) {
114
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
115
+ await mkdir(dirname(absolutePath), { recursive: true });
116
+ await writeFile(absolutePath, content, 'utf-8');
117
+ }
118
+ }
119
+
120
+ async package() {
121
+ this.pkgManager = await getPackageManager(this.projectDir);
122
+ const commands = new Map<string, string>();
123
+ commands.set(
124
+ `Initializing Synthetics project using ${
125
+ this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'
126
+ }`,
127
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
128
+ );
129
+
130
+ const pkgName = '@elastic/synthetics';
131
+ commands.set(
132
+ `Installing @elastic/synthetics library`,
133
+ this.pkgManager == 'yarn'
134
+ ? `yarn add -dev ${pkgName}`
135
+ : `npm i -d ${pkgName}`
136
+ );
137
+
138
+ // Execute commands
139
+ for (const [name, command] of commands) {
140
+ progress(`${name}...`);
141
+ execSync(command, {
142
+ stdio: 'inherit',
143
+ cwd: this.projectDir,
144
+ });
145
+ }
146
+ }
147
+
148
+ async patchPkgJSON() {
149
+ const filename = 'package.json';
150
+ const pkgJSON = JSON.parse(
151
+ await readFile(join(this.projectDir, filename), 'utf-8')
152
+ );
153
+
154
+ if (!pkgJSON.scripts) {
155
+ pkgJSON.scripts = {};
156
+ }
157
+ // Add test command
158
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
159
+
160
+ // Add push command
161
+ const project = basename(this.projectDir);
162
+ pkgJSON.scripts.push = `npx @elastic/synthetics push journeys --project ${project} --url http://localhost:5601 --auth apiKey`;
163
+
164
+ await this.createFile(
165
+ filename,
166
+ JSON.stringify(pkgJSON, null, 2) + '\n',
167
+ true
168
+ );
169
+ }
170
+
171
+ async patchGitIgnore() {
172
+ const gitIgnorePath = join(this.projectDir, '.gitignore');
173
+ let gitIgnore = '';
174
+ if (existsSync(gitIgnorePath)) {
175
+ const contents = await readFile(gitIgnorePath, 'utf-8');
176
+ gitIgnore += contents.trimEnd() + '\n';
177
+ }
178
+ if (!gitIgnore.includes('node_modules')) {
179
+ gitIgnore += 'node_modules/\n';
180
+ }
181
+ gitIgnore += '.synthetics/\n';
182
+ await writeFile(gitIgnorePath, gitIgnore, 'utf-8');
183
+ }
184
+
185
+ banner() {
186
+ stdWrite(
187
+ bold(`
188
+ All set, you can run below commands inside: ${this.projectDir}:
189
+
190
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
191
+
192
+ Push monitors to Kibana: ${cyan(runCommand(this.pkgManager, 'push'))}
193
+
194
+ ${yellow(
195
+ 'Make sure to update the Kibana url and api keys before pushing monitors to Kibana.'
196
+ )}
197
+
198
+ Visit https://www.elastic.co/guide/en/observability/current/synthetic-run-tests.html to learn more.
199
+ `)
200
+ );
201
+ }
202
+
203
+ async setup() {
204
+ await this.directory();
205
+ const answers = await this.questions();
206
+ await this.package();
207
+ await this.files(answers);
208
+ await this.patchPkgJSON();
209
+ await this.patchGitIgnore();
210
+ this.banner();
211
+ }
212
+ }