@api-client/core 0.3.4 → 0.3.7

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