@api-client/core 0.3.5 → 0.3.8

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 (84) hide show
  1. package/build/browser.d.ts +5 -0
  2. package/build/browser.js +14 -0
  3. package/build/browser.js.map +1 -1
  4. package/build/index.d.ts +13 -1
  5. package/build/index.js +25 -1
  6. package/build/index.js.map +1 -1
  7. package/build/src/lib/calculators/DataCalculator.d.ts +27 -0
  8. package/build/src/lib/calculators/DataCalculator.js +88 -0
  9. package/build/src/lib/calculators/DataCalculator.js.map +1 -0
  10. package/build/src/lib/fs/Fs.d.ts +52 -0
  11. package/build/src/lib/fs/Fs.js +245 -0
  12. package/build/src/lib/fs/Fs.js.map +1 -0
  13. package/build/src/lib/parsers/UrlEncoder.d.ts +51 -0
  14. package/build/src/lib/parsers/UrlEncoder.js +74 -0
  15. package/build/src/lib/parsers/UrlEncoder.js.map +1 -0
  16. package/build/src/lib/parsers/UrlParser.d.ts +104 -0
  17. package/build/src/lib/parsers/UrlParser.js +189 -0
  18. package/build/src/lib/parsers/UrlParser.js.map +1 -0
  19. package/build/src/lib/parsers/UrlValueParser.d.ts +92 -0
  20. package/build/src/lib/parsers/UrlValueParser.js +172 -0
  21. package/build/src/lib/parsers/UrlValueParser.js.map +1 -0
  22. package/build/src/lib/timers/Timers.d.ts +5 -0
  23. package/build/src/lib/timers/Timers.js +10 -0
  24. package/build/src/lib/timers/Timers.js.map +1 -0
  25. package/build/src/mocking/ProjectMock.d.ts +13 -0
  26. package/build/src/mocking/ProjectMock.js +16 -0
  27. package/build/src/mocking/ProjectMock.js.map +1 -0
  28. package/build/src/mocking/lib/Request.d.ts +32 -0
  29. package/build/src/mocking/lib/Request.js +63 -0
  30. package/build/src/mocking/lib/Request.js.map +1 -0
  31. package/build/src/mocking/lib/Response.d.ts +33 -0
  32. package/build/src/mocking/lib/Response.js +79 -0
  33. package/build/src/mocking/lib/Response.js.map +1 -0
  34. package/build/src/runtime/node/BaseRunner.d.ts +21 -0
  35. package/build/src/runtime/node/BaseRunner.js +27 -0
  36. package/build/src/runtime/node/BaseRunner.js.map +1 -0
  37. package/build/src/runtime/node/ProjectParallelRunner.d.ts +81 -0
  38. package/build/src/runtime/node/ProjectParallelRunner.js +173 -0
  39. package/build/src/runtime/node/ProjectParallelRunner.js.map +1 -0
  40. package/build/src/runtime/node/ProjectRequestRunner.d.ts +125 -0
  41. package/build/src/runtime/node/ProjectRequestRunner.js +185 -0
  42. package/build/src/runtime/node/ProjectRequestRunner.js.map +1 -0
  43. package/build/src/runtime/node/ProjectRunner.d.ts +164 -62
  44. package/build/src/runtime/node/ProjectRunner.js +191 -146
  45. package/build/src/runtime/node/ProjectRunner.js.map +1 -1
  46. package/build/src/runtime/node/ProjectRunnerWorker.d.ts +1 -0
  47. package/build/src/runtime/node/ProjectRunnerWorker.js +58 -0
  48. package/build/src/runtime/node/ProjectRunnerWorker.js.map +1 -0
  49. package/build/src/runtime/node/ProjectSerialRunner.d.ts +11 -0
  50. package/build/src/runtime/node/ProjectSerialRunner.js +34 -0
  51. package/build/src/runtime/node/ProjectSerialRunner.js.map +1 -0
  52. package/build/src/runtime/reporters/ProjectRunCliReporter.d.ts +7 -0
  53. package/build/src/runtime/reporters/ProjectRunCliReporter.js +73 -0
  54. package/build/src/runtime/reporters/ProjectRunCliReporter.js.map +1 -0
  55. package/build/src/runtime/reporters/Reporter.d.ts +62 -0
  56. package/build/src/runtime/reporters/Reporter.js +98 -0
  57. package/build/src/runtime/reporters/Reporter.js.map +1 -0
  58. package/build/src/testing/TestCliHelper.d.ts +29 -0
  59. package/build/src/testing/TestCliHelper.js +80 -0
  60. package/build/src/testing/TestCliHelper.js.map +1 -0
  61. package/build/src/testing/getPort.d.ts +52 -0
  62. package/build/src/testing/getPort.js +169 -0
  63. package/build/src/testing/getPort.js.map +1 -0
  64. package/package.json +3 -2
  65. package/src/lib/calculators/DataCalculator.ts +91 -0
  66. package/src/lib/fs/Fs.ts +258 -0
  67. package/src/lib/parsers/UrlEncoder.ts +74 -0
  68. package/src/lib/parsers/UrlParser.ts +201 -0
  69. package/src/lib/parsers/UrlValueParser.ts +211 -0
  70. package/src/lib/timers/Timers.ts +9 -0
  71. package/src/mocking/LegacyInterfaces.ts +1 -1
  72. package/src/mocking/ProjectMock.ts +20 -0
  73. package/src/mocking/lib/Request.ts +85 -0
  74. package/src/mocking/lib/Response.ts +101 -0
  75. package/src/runtime/node/BaseRunner.ts +29 -0
  76. package/src/runtime/node/ProjectParallelRunner.ts +234 -0
  77. package/src/runtime/node/ProjectRequestRunner.ts +281 -0
  78. package/src/runtime/node/ProjectRunner.ts +279 -186
  79. package/src/runtime/node/ProjectRunnerWorker.ts +62 -0
  80. package/src/runtime/node/ProjectSerialRunner.ts +36 -0
  81. package/src/runtime/reporters/ProjectRunCliReporter.ts +79 -0
  82. package/src/runtime/reporters/Reporter.ts +142 -0
  83. package/src/testing/TestCliHelper.ts +87 -0
  84. package/src/testing/getPort.ts +212 -0
@@ -1,71 +1,94 @@
1
- import { EventEmitter } from 'events';
2
- import { Environment } from '../../models/Environment.js';
1
+ import { SerializableError } from '../../models/SerializableError.js';
2
+ import { HttpProject } from '../../models/HttpProject.js';
3
+ import { ProjectFolder } from '../../models/ProjectFolder.js';
4
+ import { Environment, IEnvironment } from '../../models/Environment.js';
5
+ import { DummyLogger } from '../../lib/logging/DummyLogger.js';
3
6
  import { Logger } from '../../lib/logging/Logger.js';
4
- import { IRequestLog, RequestLog } from '../../models/RequestLog.js';
5
- import { Property } from '../../models/Property.js';
6
- import { ProjectFolder, Kind as ProjectFolderKind } from '../../models/ProjectFolder.js';
7
- import { ProjectRequest } from '../../models/ProjectRequest.js';
7
+ import { IRequestLog } from '../../models/RequestLog.js';
8
8
  import { IHttpRequest } from '../../models/HttpRequest.js';
9
- import { HttpProject, IProjectRequestIterator } from '../../models/HttpProject.js';
10
- import { SentRequest } from '../..//models/SentRequest.js';
11
- import { ErrorResponse } from '../../models/ErrorResponse.js';
12
- import { VariablesStore } from './VariablesStore.js';
13
- import { VariablesProcessor } from '../variables/VariablesProcessor.js';
14
- import { RequestFactory } from './RequestFactory.js';
15
- import { EventTypes } from '../../events/EventTypes.js';
9
+ import { ProjectRequestRunner } from './ProjectRequestRunner.js';
10
+ import { IProjectExecutionIteration, IProjectExecutionLog } from '../reporters/Reporter.js';
11
+ import { pathExists, readJson } from '../../lib/fs/Fs.js';
12
+ import { BaseRunner } from './BaseRunner.js';
16
13
 
17
- export interface ProjectRunnerOptions {
14
+ type ProjectParent = HttpProject | ProjectFolder;
15
+
16
+ export interface IProjectRunnerOptions {
18
17
  /**
19
- * When provided it overrides any project / folder defined environment.
18
+ * The environment to use.
19
+ * This can be a name or the key of the environment located under the parent or root.
20
+ * It can also be a path to the environment definition. If the file exists it is used. Otherwise it tried to
21
+ * find the environment in the project.
20
22
  */
21
- environment?: Environment;
23
+ environment?: string;
22
24
  /**
23
- * Additional variables to pass to the selected environment.
24
- * This can be use to pass system variables, when needed.
25
- *
26
- * To use system variables tou can use `init.variables = process.env`;
25
+ * The parent folder to execute.
27
26
  */
28
- variables?: Record<string, string>;
27
+ parent?: string;
29
28
  /**
30
- * Overrides the default logger (console).
29
+ * The names or the keys of requests to execute.
30
+ * This can be used to limit the number of requests.
31
31
  */
32
- logger?: Logger;
32
+ request?: string[];
33
33
  /**
34
- * The event target to use.
35
- * By default it creates its own target.
34
+ * The number of times the execution should be repeated.
35
+ * Default to 1.
36
36
  */
37
- eventTarget?: EventTarget;
38
- }
39
-
40
- export interface ProjectRunnerRunOptions extends IProjectRequestIterator {
41
- }
42
-
43
- export interface RunResult {
37
+ iterations?: number;
44
38
  /**
45
- * The key of the request from the HttpProject that was executed.
39
+ * The number of milliseconds to wait between each iteration.
40
+ * Default to the next frame (vary from 1 to tens of milliseconds).
46
41
  */
47
- key: string;
42
+ iterationDelay?: number;
48
43
  /**
49
- * The key of parent folder of the executed request.
44
+ * When set it performs parallel execution for each iteration.
45
+ * The number of executions at the same time depends on the number of processor cores
46
+ * available on the current machine. The maximum of the parallel execution
47
+ * is the number of available cores. When the `iterations` number is higher
48
+ * then the "rest" is added to the iterations per each core.
50
49
  */
51
- parent?: string;
50
+ parallel?: boolean;
52
51
  /**
53
- * Set when a fatal error occurred so the request couldn't be executed.
54
- * This is not the same as error reported during a request. The log's response can still be IResponseError.
52
+ * When set it includes requests in the current folder and sub-folder according to the order
53
+ * defined in the folder.
55
54
  */
56
- error?: boolean;
55
+ recursive?: boolean;
57
56
  /**
58
- * The error message. Always set when the `error` is `true`.
57
+ * The opposite of the `requests`. The list of names or keys of requests or folders to ignore.
58
+ * Note, ignore is tested before the `requests`.
59
59
  */
60
- errorMessage?: string;
60
+ ignore?: string[];
61
+ /**
62
+ * The logger to use with the request factory.
63
+ * When not set it uses the dummy logger (no output).
64
+ */
65
+ logger?: Logger;
61
66
  /**
62
- * The request log.
63
- * Always set when the `error` is `false`.
67
+ * When true it copies all system variables to the execution environment.
68
+ * When an array of strings, only takes system variables that are listed in the array.
69
+ * When a map, it uses this map as a list of variables.
70
+ * When not set it does not read system variables.
64
71
  */
65
- log?: IRequestLog;
72
+ variables?: boolean | string[] | Record<string, string>;
66
73
  }
67
74
 
68
75
  export interface ProjectRunner {
76
+ /**
77
+ * Event dispatched when an iteration is about to start.
78
+ */
79
+ on(event: 'before-iteration', listener: (index: number, iterated: boolean) => void): this;
80
+ /**
81
+ * Event dispatched when an iteration finished.
82
+ */
83
+ on(event: 'after-iteration', listener: (index: number, iterated: boolean) => void): this;
84
+ /**
85
+ * Event dispatched before the iteration is going to sleep for the set period of time.
86
+ */
87
+ on(event: 'before-sleep', listener: () => void): this;
88
+ /**
89
+ * Event dispatched after the iteration is woke up.
90
+ */
91
+ on(event: 'after-sleep', listener: () => void): this;
69
92
  /**
70
93
  * The request object is prepared and about to be sent to the HTTP engine
71
94
  */
@@ -78,6 +101,22 @@ export interface ProjectRunner {
78
101
  * There was a general error during the request
79
102
  */
80
103
  on(event: 'error', listener: (key: string, log: IRequestLog, message: string) => void): this;
104
+ /**
105
+ * Event dispatched when an iteration is about to start.
106
+ */
107
+ once(event: 'before-iteration', listener: (index: number, iterated: boolean) => void): this;
108
+ /**
109
+ * Event dispatched when an iteration finished.
110
+ */
111
+ once(event: 'after-iteration', listener: (index: number, iterated: boolean) => void): this;
112
+ /**
113
+ * Event dispatched before the iteration is going to sleep for the set period of time.
114
+ */
115
+ once(event: 'before-sleep', listener: () => void): this;
116
+ /**
117
+ * Event dispatched after the iteration is woke up.
118
+ */
119
+ once(event: 'after-sleep', listener: () => void): this;
81
120
  /**
82
121
  * The request object is prepared and about to be sent to the HTTP engine
83
122
  */
@@ -93,189 +132,243 @@ export interface ProjectRunner {
93
132
  }
94
133
 
95
134
  /**
96
- * Runs requests in a project.
97
- * Developers can run the entire project with the `recursive` flag set. They can also
98
- * set the starting point with the `parent` options.
135
+ * A class to be extended to run an entire API Project for the given configuration options.
99
136
  *
100
- * Requests are executed in order defined in the folder.
137
+ * The main purpose of this class (and its children) is to iterate over requests
138
+ * in the project and execute them one-by-one.
139
+ *
140
+ * Implementations allow to execute the requests in a serial model or in parallel mode, where
141
+ * a separate workers are created to run the same HTTP requests in each worker.
142
+ *
143
+ * This class generates a run report which other programs can use to build all kinds of UIs
144
+ * around the data collected during the run.
101
145
  */
102
- export class ProjectRunner extends EventEmitter {
103
- eventTarget: EventTarget;
104
- logger?: Logger;
105
- project: HttpProject;
106
-
107
- protected masterEnvironment?: Environment;
108
- protected extraVariables?: Record<string, string>;
109
-
146
+ export abstract class ProjectRunner extends BaseRunner {
147
+ /**
148
+ * The HTTP project to run requests from.
149
+ */
150
+ project?: HttpProject;
151
+ /**
152
+ * The execution options for the project.
153
+ */
154
+ options?: IProjectRunnerOptions;
155
+ /**
156
+ * The root object (project or a folder) where the program starts iterating over the requests.
157
+ */
158
+ root?: ProjectParent;
159
+ /**
160
+ * The selected environment to apply to the requests.
161
+ */
162
+ environment?: Environment;
163
+ /**
164
+ * The events target instance for events dispatched by the request factory.
165
+ */
166
+ target = new EventTarget();
167
+ /**
168
+ * This is used with `--iterations`. The index of the current iteration.
169
+ */
170
+ protected index = 0;
171
+ /**
172
+ * The currently executed iteration loop.
173
+ */
174
+ protected currentIteration?: IProjectExecutionIteration;
175
+ /**
176
+ * The number of remaining iterations to run.
177
+ */
178
+ protected remaining = 1;
179
+ /**
180
+ * Whether the configuration allows iterations (the parallel mode).
181
+ */
182
+ protected hasIterations = false;
110
183
  /**
111
- * The variables processor instance.
184
+ * When set it won't amit any event.
185
+ * This can be used in a background worker when events are never handled.
112
186
  */
113
- protected variablesProcessor = new VariablesProcessor();
187
+ noEmit = false;
114
188
 
115
- constructor(project: HttpProject, opts: ProjectRunnerOptions = {}) {
189
+ constructor() {
116
190
  super();
117
- this.project = project;
118
- this.logger = opts.logger;
119
- this.eventTarget = opts.eventTarget || new EventTarget();
120
- this.masterEnvironment = opts.environment;
121
- this.extraVariables = opts.variables;
191
+ this._requestHandler = this._requestHandler.bind(this);
192
+ this._responseHandler = this._responseHandler.bind(this);
193
+ this._errorHandler = this._errorHandler.bind(this);
122
194
  }
123
195
 
124
196
  /**
125
- * Runs the request from the project root or a specified folder.
126
- * @param options Run options.
127
- * @returns A promise with the run result.
128
- */
129
- async run(options?: ProjectRunnerRunOptions): Promise<RunResult[]> {
130
- const { project } = this;
131
- const executed: RunResult[] = [];
132
- for (const request of project.requestIterator(options)) {
133
- const parent = request.getParent() || project;
134
- let variables: Record<string, string>;
135
- if (VariablesStore.has(parent)) {
136
- variables = VariablesStore.get(parent);
137
- } else {
138
- variables = await this.getVariables(parent);
139
- VariablesStore.set(parent, variables);
140
- }
141
- const info = await this.execute(request, variables);
142
- executed.push(info);
197
+ * A required step before running the project.
198
+ * It configures the execution context. It may throw an error when configuration is not valid.
199
+ */
200
+ async configure(project: HttpProject, opts: IProjectRunnerOptions = {}): Promise<void> {
201
+ this.project = project;
202
+ this.options = opts || {};
203
+ if (typeof this.options.iterations === 'number' && this.options.iterations >= 0) {
204
+ this.remaining = this.options.iterations;
143
205
  }
144
- return executed;
206
+ this.hasIterations = this.remaining > 1;
207
+
208
+ const root = opts.parent ? project.findFolder(opts.parent) : project;
209
+ if (!root) {
210
+ throw new Error(`Unable to locate the folder: ${opts.parent}`);
211
+ }
212
+ this.root = root;
213
+ this.environment = await this.getEnvironment();
145
214
  }
146
215
 
147
- protected async execute(request: ProjectRequest, variables: Record<string, string>): Promise<RunResult> {
148
- const config = request.getConfig();
149
- const factory = new RequestFactory(this.eventTarget);
216
+ /**
217
+ * Executes the requests in the project.
218
+ * @returns The execution log created by calling the `createReport()` function.
219
+ */
220
+ abstract execute(): Promise<IProjectExecutionLog>;
150
221
 
151
- factory.variables = variables;
152
- if (request.authorization) {
153
- factory.authorization = request.authorization.map(i => i.toJSON());
154
- }
155
- if (request.actions) {
156
- factory.actions = request.actions.toJSON();
222
+ /**
223
+ * Creates the report of the execution.
224
+ */
225
+ protected async createReport(): Promise<IProjectExecutionLog> {
226
+ const log: IProjectExecutionLog = {
227
+ started: this.startTime as number,
228
+ ended: this.endTime as number,
229
+ iterations: this.executed,
230
+ };
231
+ return log;
232
+ }
233
+
234
+ /**
235
+ * Reads the environment data to use with the execution.
236
+ * If the configured environment is a location of a file
237
+ * it is read as API Client's environment and used in the execution.
238
+ * Otherwise it searches for the environment in the list of the defined
239
+ * environments by the name of the key.
240
+ *
241
+ * It throws when the environment cannot be found or when the file contents is invalid.
242
+ */
243
+ protected async getEnvironment(): Promise<Environment | undefined> {
244
+ const { options } = this;
245
+ if (!options) {
246
+ throw new Error(`Run configure() first.`);
157
247
  }
158
- if (request.clientCertificate) {
159
- factory.certificates = [request.clientCertificate];
248
+ if (!options.environment) {
249
+ return;
160
250
  }
161
- if (config.enabled !== false) {
162
- factory.config = config.toJSON();
251
+ const fileExists = await pathExists(options.environment);
252
+ if (fileExists) {
253
+ const contents = await readJson(options.environment);
254
+ return new Environment(contents as IEnvironment);
163
255
  }
164
- if (this.logger) {
165
- factory.logger = this.logger;
256
+ const root = this.root as ProjectParent;
257
+ const envs = root.getEnvironments();
258
+ const env = envs.find(i => i.key === options.environment || i.info.name === options.environment);
259
+ if (!env) {
260
+ throw new SerializableError(`The environment cannot be found: ${options.environment}.`, 'EENVNOTFOUND');
166
261
  }
167
- const info: RunResult = {
168
- key: request.key,
169
- };
170
- const requestData = request.expects.toJSON();
171
- requestData.url = this.prepareRequestUrl(requestData.url, variables);
262
+ return env;
263
+ }
172
264
 
173
- function variableHandler(e: CustomEvent): void {
174
- if (e.defaultPrevented) {
175
- return;
176
- }
177
- const { name, value } = e.detail;
178
- variables[name] = value;
179
- e.preventDefault();
180
- e.detail.result = Promise.resolve();
265
+ /**
266
+ * Runs the requests from the project as configured.
267
+ */
268
+ protected async executeIteration(): Promise<void> {
269
+ const { environment, project, options, hasIterations, index, noEmit } = this;
270
+ if (!options || !project) {
271
+ throw new Error(`Run configure() first.`);
181
272
  }
182
-
183
- this.eventTarget.addEventListener(EventTypes.Environment.set, variableHandler as any);
184
-
273
+ if (!noEmit) {
274
+ this.emit('before-iteration', index, hasIterations);
275
+ }
276
+
277
+ const runner = new ProjectRequestRunner(project, {
278
+ environment,
279
+ logger: options.logger ? options.logger : new DummyLogger(),
280
+ eventTarget: this.target,
281
+ variables: this.getSystemVariables(),
282
+ });
283
+
284
+ runner.on('request', this._requestHandler);
285
+ runner.on('response', this._responseHandler);
286
+ runner.on('error', this._errorHandler);
287
+ this.currentIteration = {
288
+ index: this.index,
289
+ executed: [],
290
+ };
185
291
  try {
186
- // Below replaces the single call to the `run()` function of the factory to
187
- // report via the events a request object that has evaluated with the Jexl library.
188
- const requestCopy = await factory.processRequestVariables(requestData);
189
- this.emit('request', request.key, { ...requestCopy });
190
- await factory.processRequestLogic(requestCopy);
191
- const result = await factory.executeRequest(requestCopy);
192
- await factory.processResponse(result);
193
- request.setLog(result);
194
- info.log = result;
195
- this.emit('response', request.key, { ...result });
292
+ await runner.run({
293
+ parent: options.parent,
294
+ requests: options.request,
295
+ ignore: options.ignore,
296
+ recursive: options.recursive
297
+ });
196
298
  } catch (e) {
197
299
  const cause = e as Error;
198
- info.error = true;
199
- info.errorMessage = cause.message;
200
- const sent = new SentRequest({ ...requestData, startTime: 0, endTime: 0, });
201
- const response = ErrorResponse.fromError(info.errorMessage);
202
- const log = RequestLog.fromRequestResponse(sent.toJSON(), response.toJSON()).toJSON();
203
- this.emit('error', request.key, log, info.errorMessage);
300
+ console.error(e);
301
+ this.currentIteration.error = cause.message || 'Unknown error ocurred';
302
+ // ...
204
303
  }
205
-
206
- this.eventTarget.removeEventListener(EventTypes.Environment.set, variableHandler as any);
207
- return info;
208
- }
209
-
210
- protected async getVariables(parent: HttpProject | ProjectFolder): Promise<Record<string, string>> {
211
- if (this.masterEnvironment) {
212
- return this.applyVariables([this.masterEnvironment]);
304
+ this.executed.push(this.currentIteration);
305
+ if (!noEmit) {
306
+ this.emit('after-iteration', index, hasIterations);
213
307
  }
214
- return this.createEnvironment(parent);
215
308
  }
216
309
 
217
- protected async createEnvironment(parent: HttpProject | ProjectFolder): Promise<Record<string, string>> {
218
- const envs = await this.readEnvironments(parent);
219
- return this.applyVariables(envs);
310
+ /**
311
+ * Retargets the "request" event from the factory.
312
+ */
313
+ protected _requestHandler(key: string, request: IHttpRequest): void {
314
+ if (!this.noEmit) {
315
+ this.emit('request', key, request);
316
+ }
220
317
  }
221
318
 
222
319
  /**
223
- * Reads the list of the environments to apply to this runtime.
320
+ * Retargets the "response" event from the factory.
224
321
  */
225
- protected async readEnvironments(parent: HttpProject | ProjectFolder): Promise<Environment[]> {
226
- const folderKey = parent.kind === ProjectFolderKind ? (parent as ProjectFolder).key : undefined;
227
- return this.project.readEnvironments({ folderKey });
322
+ protected _responseHandler(key: string, log: IRequestLog): void {
323
+ this.currentIteration?.executed.push(log);
324
+ if (!this.noEmit) {
325
+ this.emit('response', key, log);
326
+ }
228
327
  }
229
328
 
230
329
  /**
231
- * Reads the variables and the base URI from the passed environments.
330
+ * Retargets the "error" event from the factory.
232
331
  */
233
- protected async applyVariables(environments: Environment[]): Promise<Record<string, string>> {
234
- let baseUri = '';
235
- const variables: Property[] = [];
236
- environments.forEach((environment) => {
237
- const { server, variables: envVariables } = environment;
238
- if (server) {
239
- baseUri = server.readUri();
240
- }
241
- if (envVariables.length) {
242
- envVariables.forEach((item) => {
243
- const defined = variables.findIndex(i => i.name === item.name);
244
- if (defined >= 0) {
245
- variables[defined] = item;
246
- } else {
247
- variables.push(item);
248
- }
249
- });
250
- }
251
- });
252
- const { extraVariables } = this;
253
- const ctx = VariablesProcessor.createContextFromProperties(variables);
254
- if (extraVariables) {
255
- Object.keys(extraVariables).forEach((key) => {
256
- ctx[key] = extraVariables[key];
257
- });
332
+ protected _errorHandler(key: string, log: IRequestLog, message: string): void {
333
+ this.currentIteration?.executed.push(log);
334
+ if (!this.noEmit) {
335
+ this.emit('error', key, log, message);
258
336
  }
259
- // the `baseUri` is reserved and always set to the environment's `baseUri`.
260
- ctx.baseUri = baseUri || '';
261
- return this.variablesProcessor.buildContext(ctx);
262
337
  }
263
338
 
264
339
  /**
265
- * When defined it applies the serve's base URI to relative URLs.
266
- * @param currentUrl The URL to process.
340
+ * @returns Reads the system variables based on the library configuration.
267
341
  */
268
- protected prepareRequestUrl(currentUrl: string, variables: Record<string, string>): string {
269
- const { baseUri } = variables;
270
- if (!baseUri) {
271
- return currentUrl;
342
+ protected getSystemVariables(): Record<string, string> {
343
+ const result: Record<string, string> = {};
344
+ const { options } = this;
345
+ if (!options) {
346
+ return result;
347
+ }
348
+ const { variables } = options;
349
+ if (typeof variables === 'undefined') {
350
+ return result;
272
351
  }
273
- if (currentUrl.startsWith('http:') || currentUrl.startsWith('https:')) {
274
- return currentUrl;
352
+ if (typeof variables === 'boolean') {
353
+ return variables ? this._readSystemVariables() : result;
275
354
  }
276
- if (currentUrl.startsWith('/')) {
277
- return `${baseUri}${currentUrl}`;
355
+ if (Array.isArray(variables)) {
356
+ return this._readSystemVariables(variables);
278
357
  }
279
- return `${baseUri}/${currentUrl}`;
358
+ return variables;
359
+ }
360
+
361
+ private _readSystemVariables(names?: string[]): Record<string, string> {
362
+ const result: Record<string, string> = {};
363
+ Object.keys(process.env).forEach((key) => {
364
+ if (names && !names.includes(key)) {
365
+ return;
366
+ }
367
+ const value = process.env[key];
368
+ if (value) {
369
+ result[key] = value;
370
+ }
371
+ });
372
+ return result;
280
373
  }
281
374
  }
@@ -0,0 +1,62 @@
1
+ /* eslint-disable no-unused-vars */
2
+ import process from 'process';
3
+ import cluster from 'cluster';
4
+ import { HttpProject } from '../../models/HttpProject.js';
5
+ import { IProjectExecutionLog } from '../reporters/Reporter.js';
6
+ import { IWorkerMessage, IProjectParallelWorkerOptions } from './ProjectParallelRunner.js';
7
+ import { sleep } from '../../lib/timers/Timers.js';
8
+ import { ProjectRunner } from './ProjectRunner.js';
9
+
10
+ class ProjectExeWorker extends ProjectRunner {
11
+ initialize(): void {
12
+ if (cluster.isPrimary) {
13
+ throw new Error(`This file should not be called directly.`);
14
+ }
15
+ process.send!({ cmd: 'online' });
16
+ process.on('message', this.messageHandler.bind(this));
17
+ }
18
+
19
+ messageHandler(message: IWorkerMessage): void {
20
+ switch (message.cmd) {
21
+ case 'run': this.run(message.data as IProjectParallelWorkerOptions); break;
22
+ }
23
+ }
24
+
25
+ async run(options: IProjectParallelWorkerOptions): Promise<void> {
26
+ try {
27
+ await this.configure(new HttpProject(options.project), options);
28
+ await this.execute();
29
+ } catch (e) {
30
+ const cause = e as Error;
31
+ process.send!({ cmd: 'error', data: cause.message });
32
+ }
33
+ }
34
+
35
+ async execute(): Promise<IProjectExecutionLog> {
36
+ const { root } = this;
37
+ if (!root) {
38
+ throw new Error(`The project runner is not configured.`);
39
+ }
40
+ function unhandledRejection(): void {}
41
+ process.on('unhandledRejection', unhandledRejection);
42
+ this.startTime = Date.now();
43
+ while (this.remaining > 0) {
44
+ this.remaining--;
45
+ await this.executeIteration();
46
+ this.index++;
47
+ if (this.remaining && this.options?.iterationDelay) {
48
+ await sleep(this.options.iterationDelay);
49
+ }
50
+ }
51
+ process.off('unhandledRejection', unhandledRejection);
52
+ this.endTime = Date.now();
53
+
54
+ const log = await this.createReport();
55
+ process.send!({ cmd: 'result', data: log.iterations });
56
+ return log;
57
+ }
58
+ }
59
+
60
+ const instance = new ProjectExeWorker();
61
+ instance.noEmit = true;
62
+ instance.initialize();
@@ -0,0 +1,36 @@
1
+ import { SerializableError } from '../../models/SerializableError.js';
2
+ import { sleep } from '../../lib/timers/Timers.js';
3
+ import { ProjectRunner } from './ProjectRunner.js';
4
+ import { IProjectExecutionLog } from '../reporters/Reporter.js';
5
+
6
+ /**
7
+ * Project runner that runs the requests in the project one-by-one.
8
+ */
9
+ export class ProjectSerialRunner extends ProjectRunner {
10
+ /**
11
+ * Executes the requests in the project.
12
+ */
13
+ async execute(): Promise<IProjectExecutionLog> {
14
+ const { root } = this;
15
+ if (!root) {
16
+ throw new SerializableError(`The project runner is not configured.`, 'ECONFIGURE');
17
+ }
18
+
19
+ this.startTime = Date.now();
20
+ while (this.remaining > 0) {
21
+ this.remaining--;
22
+ await this.executeIteration();
23
+ this.index++;
24
+ if (this.remaining && this.options?.iterationDelay) {
25
+ this.emit('before-sleep');
26
+ await sleep(this.options.iterationDelay);
27
+ this.emit('after-sleep');
28
+ } else {
29
+ await sleep(0);
30
+ }
31
+ }
32
+
33
+ this.endTime = Date.now();
34
+ return this.createReport();
35
+ }
36
+ }