@api-client/core 0.3.1 → 0.3.4

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 (183) hide show
  1. package/build/browser.d.ts +1 -1
  2. package/build/index.d.ts +2 -2
  3. package/build/index.js.map +1 -1
  4. package/build/src/models/Backend.d.ts +22 -0
  5. package/build/src/runtime/store/StoreSdk.d.ts +192 -12
  6. package/build/src/runtime/store/StoreSdk.js +592 -53
  7. package/build/src/runtime/store/StoreSdk.js.map +1 -1
  8. package/package.json +3 -1
  9. package/src/data/DataReader.ts +11 -0
  10. package/src/data/DataUtils.ts +108 -0
  11. package/src/data/JmesparthReader.ts +26 -0
  12. package/src/data/Json2Xml.ts +190 -0
  13. package/src/data/JsonReader.ts +41 -0
  14. package/src/data/PayloadPointer.ts +48 -0
  15. package/src/data/RequestDataExtractor.ts +133 -0
  16. package/src/data/UrlEncodedReader.ts +20 -0
  17. package/src/data/XmlReader.ts +103 -0
  18. package/src/events/BaseEvents.ts +259 -0
  19. package/src/events/CustomEvent.ts +27 -0
  20. package/src/events/EventTypes.ts +19 -0
  21. package/src/events/Events.ts +19 -0
  22. package/src/events/authorization/AuthorizationEventTypes.ts +22 -0
  23. package/src/events/authorization/AuthorizationEvents.ts +61 -0
  24. package/src/events/cookies/CookieEventTypes.ts +13 -0
  25. package/src/events/cookies/CookieEvents.ts +157 -0
  26. package/src/events/encryption/EncryptionEventTypes.ts +4 -0
  27. package/src/events/encryption/EncryptionEvents.ts +51 -0
  28. package/src/events/environment/EnvironmentEventTypes.ts +3 -0
  29. package/src/events/environment/EnvironmentEvents.ts +24 -0
  30. package/src/events/models/ClientCertificateEvents.ts +87 -0
  31. package/src/events/models/ModelEventTypes.ts +47 -0
  32. package/src/events/models/ModelEvents.ts +7 -0
  33. package/src/events/models/ProjectEvents.ts +331 -0
  34. package/src/events/process/ProcessEventTypes.ts +5 -0
  35. package/src/events/process/ProcessEvents.ts +76 -0
  36. package/src/events/readme.md +22 -0
  37. package/src/events/reporting/ReportingEventTypes.ts +3 -0
  38. package/src/events/reporting/ReportingEvents.ts +28 -0
  39. package/src/events/telemetry/TelemetryEventTypes.ts +10 -0
  40. package/src/events/telemetry/TelemetryEvents.ts +156 -0
  41. package/src/lib/cookies/Cookie.ts +312 -0
  42. package/src/lib/cookies/Cookies.ts +326 -0
  43. package/src/lib/cookies/Utils.ts +168 -0
  44. package/src/lib/headers/Headers.ts +219 -0
  45. package/src/lib/logging/DefaultLogger.ts +19 -0
  46. package/src/lib/logging/DummyLogger.ts +21 -0
  47. package/src/lib/logging/Logger.ts +16 -0
  48. package/src/lib/transformers/PayloadSerializer.ts +332 -0
  49. package/src/lib/transformers/Utils.ts +18 -0
  50. package/src/lib/uuid.ts +40 -0
  51. package/src/mocking/LegacyInterfaces.ts +52 -0
  52. package/src/mocking/LegacyMock.ts +37 -0
  53. package/src/mocking/legacy/Authorization.ts +39 -0
  54. package/src/mocking/legacy/Certificates.ts +145 -0
  55. package/src/mocking/legacy/Cookies.ts +51 -0
  56. package/src/mocking/legacy/HostRules.ts +43 -0
  57. package/src/mocking/legacy/Http.ts +236 -0
  58. package/src/mocking/legacy/HttpResponse.ts +106 -0
  59. package/src/mocking/legacy/RestApi.ts +68 -0
  60. package/src/mocking/legacy/Urls.ts +44 -0
  61. package/src/mocking/legacy/Variables.ts +53 -0
  62. package/src/models/ArcResponse.ts +166 -0
  63. package/src/models/Authorization.ts +481 -0
  64. package/src/models/AuthorizationData.ts +60 -0
  65. package/src/models/Backend.ts +107 -0
  66. package/src/models/ClientCertificate.ts +68 -0
  67. package/src/models/Environment.ts +279 -0
  68. package/src/models/ErrorResponse.ts +101 -0
  69. package/src/models/HistoryIndex.ts +76 -0
  70. package/src/models/HistoryRequest.ts +28 -0
  71. package/src/models/HostRule.ts +163 -0
  72. package/src/models/HttpCookie.ts +285 -0
  73. package/src/models/HttpProject.ts +1294 -0
  74. package/src/models/HttpProjectListItem.ts +23 -0
  75. package/src/models/HttpRequest.ts +124 -0
  76. package/src/models/HttpResponse.ts +143 -0
  77. package/src/models/License.ts +113 -0
  78. package/src/models/ProjectDefinitionProperty.ts +40 -0
  79. package/src/models/ProjectFolder.ts +439 -0
  80. package/src/models/ProjectItem.ts +135 -0
  81. package/src/models/ProjectParent.ts +113 -0
  82. package/src/models/ProjectRequest.ts +277 -0
  83. package/src/models/ProjectSchema.ts +202 -0
  84. package/src/models/Property.ts +423 -0
  85. package/src/models/Provider.ts +98 -0
  86. package/src/models/README.md +20 -0
  87. package/src/models/Request.ts +452 -0
  88. package/src/models/RequestActions.ts +163 -0
  89. package/src/models/RequestAuthorization.ts +115 -0
  90. package/src/models/RequestConfig.ts +317 -0
  91. package/src/models/RequestLog.ts +159 -0
  92. package/src/models/RequestTime.ts +108 -0
  93. package/src/models/RequestUiMeta.ts +258 -0
  94. package/src/models/RequestsSize.ts +65 -0
  95. package/src/models/ResponseAuthorization.ts +104 -0
  96. package/src/models/ResponseRedirect.ts +158 -0
  97. package/src/models/RevisionInfo.ts +37 -0
  98. package/src/models/SentRequest.ts +125 -0
  99. package/src/models/SerializablePayload.ts +68 -0
  100. package/src/models/Server.ts +153 -0
  101. package/src/models/Thing.ts +110 -0
  102. package/src/models/Url.ts +90 -0
  103. package/src/models/User.ts +120 -0
  104. package/src/models/WebApi.ts +234 -0
  105. package/src/models/WebApiIndex.ts +122 -0
  106. package/src/models/Workspace.ts +182 -0
  107. package/src/models/actions/Action.ts +213 -0
  108. package/src/models/actions/ActionView.ts +40 -0
  109. package/src/models/actions/Condition.ts +207 -0
  110. package/src/models/actions/ConditionView.ts +42 -0
  111. package/src/models/actions/Enums.ts +29 -0
  112. package/src/models/actions/RunnableAction.ts +144 -0
  113. package/src/models/actions/runnable/DeleteCookieAction.ts +113 -0
  114. package/src/models/actions/runnable/Runnable.ts +9 -0
  115. package/src/models/actions/runnable/SetCookieAction.ts +216 -0
  116. package/src/models/actions/runnable/SetVariableAction.ts +81 -0
  117. package/src/models/legacy/DataExport.ts +172 -0
  118. package/src/models/legacy/Normalizer.ts +110 -0
  119. package/src/models/legacy/actions/Actions.ts +269 -0
  120. package/src/models/legacy/authorization/Authorization.ts +572 -0
  121. package/src/models/legacy/models/ApiTypes.ts +202 -0
  122. package/src/models/legacy/models/ArcLegacyProject.ts +39 -0
  123. package/src/models/legacy/models/AuthData.ts +17 -0
  124. package/src/models/legacy/models/ClientCertificate.ts +95 -0
  125. package/src/models/legacy/models/Cookies.ts +52 -0
  126. package/src/models/legacy/models/HostRule.ts +35 -0
  127. package/src/models/legacy/models/RestApi.ts +49 -0
  128. package/src/models/legacy/models/UrlHistory.ts +37 -0
  129. package/src/models/legacy/models/Variable.ts +43 -0
  130. package/src/models/legacy/models/base.d.ts +95 -0
  131. package/src/models/legacy/request/ArcRequest.ts +405 -0
  132. package/src/models/legacy/request/ArcResponse.ts +177 -0
  133. package/src/models/legacy/request/HistoryData.ts +47 -0
  134. package/src/models/legacy/request/Legacy.ts +45 -0
  135. package/src/models/legacy/request/RequestBody.ts +87 -0
  136. package/src/models/transformers/ArcDexieTransformer.ts +323 -0
  137. package/src/models/transformers/ArcLegacyNormalizer.ts +85 -0
  138. package/src/models/transformers/ArcLegacyTransformer.ts +200 -0
  139. package/src/models/transformers/ArcPouchTransformer.ts +184 -0
  140. package/src/models/transformers/BaseTransformer.ts +116 -0
  141. package/src/models/transformers/ImportUtils.ts +141 -0
  142. package/src/models/transformers/LegacyDataExportToApiProject.ts +76 -0
  143. package/src/models/transformers/LegacyExportProcessor.ts +252 -0
  144. package/src/models/transformers/PostmanBackupTransformer.ts +306 -0
  145. package/src/models/transformers/PostmanDataTransformer.ts +50 -0
  146. package/src/models/transformers/PostmanTransformer.ts +106 -0
  147. package/src/models/transformers/PostmanV21Transformer.ts +311 -0
  148. package/src/models/transformers/PostmanV2Transformer.ts +308 -0
  149. package/src/models/transformers/har.ts +865 -0
  150. package/src/runtime/actions/ActionRunner.ts +83 -0
  151. package/src/runtime/actions/ConditionRunner.ts +194 -0
  152. package/src/runtime/actions/RunnableCondition.ts +57 -0
  153. package/src/runtime/actions/runnable/ActionRunnable.ts +19 -0
  154. package/src/runtime/actions/runnable/DeleteCookieRunnable.ts +39 -0
  155. package/src/runtime/actions/runnable/SetCookieRunnable.ts +92 -0
  156. package/src/runtime/actions/runnable/SetVariableRunnable.ts +53 -0
  157. package/src/runtime/http-engine/ArcEngine.ts +1064 -0
  158. package/src/runtime/http-engine/Errors.ts +13 -0
  159. package/src/runtime/http-engine/FormData.ts +85 -0
  160. package/src/runtime/http-engine/HttpEngine.ts +874 -0
  161. package/src/runtime/http-engine/HttpErrorCodes.ts +270 -0
  162. package/src/runtime/http-engine/NodeEngine.ts +787 -0
  163. package/src/runtime/http-engine/NodeEngineDirect.ts +476 -0
  164. package/src/runtime/http-engine/PayloadSupport.ts +84 -0
  165. package/src/runtime/http-engine/RequestUtils.ts +164 -0
  166. package/src/runtime/http-engine/ntlm/Des.ts +345 -0
  167. package/src/runtime/http-engine/ntlm/MD4.ts +135 -0
  168. package/src/runtime/http-engine/ntlm/NtlmAuth.ts +186 -0
  169. package/src/runtime/http-engine/ntlm/NtlmMessage.ts +57 -0
  170. package/src/runtime/modules/BasicAuthCache.ts +133 -0
  171. package/src/runtime/modules/ExecutionResponse.ts +4 -0
  172. package/src/runtime/modules/ModulesRegistry.ts +136 -0
  173. package/src/runtime/modules/RequestAuthorization.ts +110 -0
  174. package/src/runtime/modules/RequestCookies.ts +145 -0
  175. package/src/runtime/node/ProjectRunner.ts +275 -0
  176. package/src/runtime/node/RequestFactory.ts +422 -0
  177. package/src/runtime/node/VariablesStore.ts +25 -0
  178. package/src/runtime/store/StoreSdk.ts +838 -0
  179. package/src/runtime/variables/Cache.ts +53 -0
  180. package/src/runtime/variables/EvalFunctions.ts +132 -0
  181. package/src/runtime/variables/ProjectVariables.ts +6 -0
  182. package/src/runtime/variables/VariablesProcessor.ts +543 -0
  183. package/src/runtime/variables/VariablesTokenizer.ts +55 -0
@@ -0,0 +1,1294 @@
1
+ import { ProjectParent } from './ProjectParent.js';
2
+ import { IProjectDefinitionProperty } from './ProjectDefinitionProperty.js';
3
+ import { Environment, IEnvironment } from './Environment.js';
4
+ import { License, ILicense } from './License.js';
5
+ import { Provider, IProvider } from './Provider.js';
6
+ import { IThing, Thing, Kind as ThingKind } from './Thing.js';
7
+ import { ProjectItem, IProjectItem } from './ProjectItem.js';
8
+ import { IProjectFolder, ProjectFolder, Kind as ProjectFolderKind } from './ProjectFolder.js';
9
+ import { IProjectRequest, ProjectRequest, Kind as ProjectRequestKind } from './ProjectRequest.js';
10
+ import { ProjectSchema, IProjectSchema } from './ProjectSchema.js';
11
+ import { Request } from './Request.js';
12
+ import v4 from '../lib/uuid.js';
13
+ import { ARCSavedRequest, ARCHistoryRequest } from './legacy/request/ArcRequest.js';
14
+ import { ArcLegacyProject, ARCProject } from './legacy/models/ArcLegacyProject.js';
15
+ import { PostmanDataTransformer } from './transformers/PostmanDataTransformer.js';
16
+
17
+ export type HttpProjectKind = 'ARC#HttpProject';
18
+ export const Kind = 'ARC#HttpProject';
19
+
20
+ /**
21
+ * A list of options to initialize a project in various situations.
22
+ */
23
+ export interface IProjectInitOptions {
24
+ /**
25
+ * The name of the project.
26
+ */
27
+ name: string;
28
+ }
29
+
30
+ export interface IFolderCreateOptions {
31
+ /**
32
+ * Ignores the operation when the folder with the same name already exists.
33
+ * This command can be used used to ensure that the folder exists.
34
+ */
35
+ skipExisting?: boolean;
36
+ /**
37
+ * The id of the parent folder. When not set it adds the folder to the project root.
38
+ */
39
+ parent?: string;
40
+ /**
41
+ * Optionally the position at which to add the folder into the list of items.
42
+ */
43
+ index?: number;
44
+ }
45
+
46
+ export interface IFolderSearchOptions {
47
+ /**
48
+ * When set it searches for a folder using keys only.
49
+ * By default it searches for a key and the name.
50
+ */
51
+ keyOnly?: boolean;
52
+ }
53
+
54
+ export interface IFolderDeleteOptions {
55
+ /**
56
+ * When set it won't throw an error when the folder is not found in the project.
57
+ */
58
+ safe?: boolean;
59
+ }
60
+
61
+ export interface IRequestAddOptions {
62
+ /**
63
+ * The id of the parent folder. When not set it adds the request to the project root.
64
+ */
65
+ parent?: string;
66
+ /**
67
+ * Optionally the position at which to add the request into the list of items.
68
+ */
69
+ index?: number;
70
+ }
71
+
72
+ export interface IRequestSearchOptions {
73
+ /**
74
+ * When set it searches for a request using keys only.
75
+ * By default it searches for a key and the name.
76
+ */
77
+ keyOnly?: boolean;
78
+ }
79
+
80
+ export interface IRequestDeleteOptions {
81
+ /**
82
+ * When set it won't throw an error when the request is not found in the project.
83
+ */
84
+ safe?: boolean;
85
+ }
86
+
87
+ export interface IProjectMoveOptions {
88
+ /**
89
+ * The position at which to insert the object in the destination. BY default it adds the object at the end.
90
+ */
91
+ index?: number;
92
+ /**
93
+ * The name or the key of the parent folder to move the item into.
94
+ * When not set it moves the item to the project's root.
95
+ */
96
+ parent?: string;
97
+ }
98
+
99
+ export interface IReadEnvironmentOptions {
100
+ /**
101
+ * The name or the key of the environment to select.
102
+ *
103
+ * When the name is not specified it selects:
104
+ * - the first environment from the project, if any
105
+ * - any parent folder's first environment to the requested folder, if any (if folderKey is set)
106
+ * - the requested folder's first environment, if any (if folderKey is set)
107
+ */
108
+ nameOrKey?: string;
109
+ /**
110
+ * The key of the folder to collect the environments for.
111
+ */
112
+ folderKey?: string;
113
+ }
114
+
115
+ /**
116
+ * The object stored as a list index for the projects.
117
+ * This is used to list projects in the store and in the UI.
118
+ */
119
+ export interface IHttpProjectIndex {
120
+ key: string;
121
+ name: string;
122
+ version?: string;
123
+ }
124
+
125
+ export interface IProjectCloneOptions {
126
+ /**
127
+ * By default it revalidates (re-creates) keys in the request.
128
+ * Set this to true to not make any changes to the keys.
129
+ */
130
+ withoutRevalidate?: boolean;
131
+ }
132
+
133
+ export interface IFolderListOptions {
134
+ /**
135
+ * Folder name or key to list folders for.
136
+ */
137
+ folder?: string;
138
+ }
139
+
140
+ export interface ISchemaAddOptions {
141
+ /**
142
+ * Optionally the position at which to add the schema into the list of schemas.
143
+ */
144
+ index?: number;
145
+ }
146
+
147
+ export interface IProjectRequestIterator {
148
+ /**
149
+ * The parent folder key or name. Sets the starting point to iterate over the requests.
150
+ */
151
+ parent?: string
152
+ /**
153
+ * When set it includes requests in the current folder and sub-folder according to the order
154
+ * defined in the folder.
155
+ */
156
+ recursive?: boolean;
157
+ /**
158
+ * Limits the number of requests to include in the iterator.
159
+ * It is an array of request keys or names.
160
+ */
161
+ requests?: string[];
162
+ /**
163
+ * The opposite of the `requests`. The list of names or keys of requests or folders to ignore.
164
+ * Note, ignore is tested before the `requests`.
165
+ */
166
+ ignore?: string[];
167
+ }
168
+
169
+ /**
170
+ * The new definition of a project in ARC.
171
+ * Note, this is not the same as future `ApiProject` which is reserved for building APIs
172
+ * using RAML or OAS.
173
+ */
174
+ export interface IHttpProject extends IProjectDefinitionProperty {
175
+ kind: HttpProjectKind;
176
+ /**
177
+ * The license information for this HTTP project.
178
+ */
179
+ license?: ILicense;
180
+ /**
181
+ * The basic information about the project.
182
+ */
183
+ info: IThing;
184
+ /**
185
+ * Information about project provider.
186
+ */
187
+ provider?: IProvider;
188
+ /**
189
+ * The ordered list of HTTP requests / folders in the projects.
190
+ * The UI uses this to manipulate the view without changing the definitions.
191
+ */
192
+ items: IProjectItem[];
193
+ /**
194
+ * The project definitions.
195
+ * This is where all the data are stored.
196
+ */
197
+ definitions: IHttpProjectDefinitions;
198
+ /**
199
+ * The list of environment keys to apply to the project.
200
+ * Each key references an environment in the `definitions.environments` array.
201
+ */
202
+ environments?: string[];
203
+ }
204
+
205
+ export interface IHttpProjectDefinitions {
206
+ requests?: IProjectRequest[];
207
+ folders?: IProjectFolder[];
208
+ schemas?: IProjectSchema[];
209
+ environments?: IEnvironment[];
210
+ }
211
+
212
+ interface HttpProjectDefinitions {
213
+ requests: ProjectRequest[];
214
+ folders: ProjectFolder[];
215
+ schemas: ProjectSchema[];
216
+ environments: Environment[];
217
+ }
218
+
219
+ /**
220
+ * An instance of an HttpProject.
221
+ */
222
+ export class HttpProject extends ProjectParent {
223
+ kind = Kind;
224
+ private initEnvironments?: Environment[];
225
+ /**
226
+ * The license information for this HTTP project.
227
+ */
228
+ license?: License;
229
+ /**
230
+ * Information about project provider.
231
+ */
232
+ provider?: Provider;
233
+ /**
234
+ * The list of all requests stored in this project.
235
+ * Note, this is not used to visualized the request in the UI.
236
+ * This is just the source of data.
237
+ * The `items` property is used to build the view.
238
+ */
239
+ definitions: HttpProjectDefinitions = HttpProject.defaultDefinitions();
240
+
241
+ static defaultDefinitions(): HttpProjectDefinitions {
242
+ return { environments: [], folders: [], requests: [], schemas: [] };
243
+ }
244
+
245
+ /**
246
+ * Creates a new HTTP project from a name.
247
+ * @param {string} name The name to set.
248
+ */
249
+ static fromName(name: string): HttpProject {
250
+ const project = new HttpProject();
251
+ const info = Thing.fromName(name);
252
+ project.info = info;
253
+ return project;
254
+ }
255
+
256
+ /**
257
+ * Creates an HTTP project instance from ARC's legacy project definition.
258
+ */
259
+ static async fromLegacy(project: ArcLegacyProject, requests: ARCSavedRequest[]): Promise<HttpProject> {
260
+ const { name = 'Unnamed project', description, requests: ids } = project;
261
+ const typedLegacyDb = project as ARCProject;
262
+ const result = HttpProject.fromName(name);
263
+ if (typedLegacyDb._id) {
264
+ result.key = typedLegacyDb._id;
265
+ }
266
+ if (description) {
267
+ result.info.description = description;
268
+ }
269
+ if (Array.isArray(ids) && ids.length) {
270
+ const promises = ids.map(async (id) => {
271
+ const old = requests.find((item) => item._id === id);
272
+ if (!old) {
273
+ return;
274
+ }
275
+ const request = await Request.fromLegacy(old);
276
+ const projectRequest = ProjectRequest.fromRequest(request.toJSON(), result);
277
+ if (old._id) {
278
+ projectRequest.key = old._id;
279
+ }
280
+ result.addRequest(projectRequest);
281
+ });
282
+ await Promise.allSettled(promises);
283
+ }
284
+ return result;
285
+ }
286
+
287
+ /**
288
+ * Creates an HTTP project from a Postman collection
289
+ * @param init The postman collection object or a string that can be parsed to one.
290
+ */
291
+ static async fromPostman(init: any): Promise<HttpProject> {
292
+ const result = await PostmanDataTransformer.transform(init);
293
+ if (Array.isArray(result) && result.length > 1) {
294
+ throw new Error(`Unable to process postman data. It contains multiple collections.`);
295
+ }
296
+ const project = Array.isArray(result) ? result[0] : result;
297
+ return project;
298
+ }
299
+
300
+ /**
301
+ * Creates a new project from a set of options.
302
+ */
303
+ static fromInitOptions(init: IProjectInitOptions): HttpProject {
304
+ const { name = 'Unnamed project' } = init;
305
+ return HttpProject.fromName(name);
306
+ }
307
+
308
+ /**
309
+ * @param input The project definition used to restore the state.
310
+ * @param environments Optional list of environments to use with this project. It overrides environments stored in the project definition.
311
+ */
312
+ constructor(input?: string | IHttpProject, environments?: IEnvironment[]) {
313
+ super();
314
+ if (Array.isArray(environments)) {
315
+ this.initEnvironments = environments.map(i => new Environment(i));
316
+ }
317
+ let init: IHttpProject;
318
+ if (typeof input === 'string') {
319
+ init = JSON.parse(input);
320
+ } else if (typeof input === 'object') {
321
+ init = input;
322
+ if (!init.kind) {
323
+ init.kind = Kind;
324
+ }
325
+ } else {
326
+ init = {
327
+ kind: Kind,
328
+ key: v4(),
329
+ definitions: {},
330
+ items: [],
331
+ info: {
332
+ kind: ThingKind,
333
+ name: '',
334
+ },
335
+ }
336
+ }
337
+ this.new(init);
338
+ }
339
+
340
+ /**
341
+ * Creates a new project definition clearing anything that is so far defined.
342
+ *
343
+ * Note, this throws an error when the project is not an ARC project.
344
+ */
345
+ new(init: IHttpProject): void {
346
+ if (!init || !init.definitions || !init.items) {
347
+ throw new Error(`Not an ARC project.`);
348
+ }
349
+ const { key = v4(), definitions = {}, items, info, license, provider, environments } = init;
350
+ this.key = key;
351
+ this.environments = [];
352
+ if (Array.isArray(environments)) {
353
+ this.environments = environments;
354
+ }
355
+ if (license) {
356
+ this.license = new License(license);
357
+ } else {
358
+ this.license = undefined;
359
+ }
360
+ if (provider) {
361
+ this.provider = new Provider(provider);
362
+ } else {
363
+ this.provider = undefined;
364
+ }
365
+ if (info) {
366
+ this.info = new Thing(info);
367
+ } else {
368
+ this.info = new Thing({ kind: ThingKind, name: '' });
369
+ }
370
+ this.items = [];
371
+ if (Array.isArray(items)) {
372
+ this.items = items.map(i => new ProjectItem(this, i));
373
+ }
374
+ this.definitions = HttpProject.defaultDefinitions();
375
+ if (Array.isArray(definitions.environments)) {
376
+ this.definitions.environments = definitions.environments.map(i => new Environment(i));
377
+ }
378
+ if (Array.isArray(definitions.requests)) {
379
+ this.definitions.requests = definitions.requests.map(i => {
380
+ const instance = new ProjectRequest(this, i);
381
+ instance.attachedCallback();
382
+ return instance;
383
+ });
384
+ }
385
+ if (Array.isArray(definitions.folders)) {
386
+ this.definitions.folders = definitions.folders.map(i => {
387
+ const instance = new ProjectFolder(this, i);
388
+ instance.attachedCallback();
389
+ return instance;
390
+ });
391
+ }
392
+ if (Array.isArray(definitions.schemas)) {
393
+ this.definitions.schemas = definitions.schemas.map(i => new ProjectSchema(i));
394
+ }
395
+ }
396
+
397
+ toJSON(): IHttpProject {
398
+ const result: IHttpProject = {
399
+ kind: Kind,
400
+ key: this.key,
401
+ definitions: {},
402
+ environments: [],
403
+ items: [],
404
+ info: this.info.toJSON(),
405
+ };
406
+ if (Array.isArray(this.definitions.environments) && this.definitions.environments.length) {
407
+ result.definitions.environments = this.definitions.environments.map(i => i.toJSON());
408
+ }
409
+ if (Array.isArray(this.definitions.requests) && this.definitions.requests.length) {
410
+ result.definitions.requests = this.definitions.requests.map(i => i.toJSON());
411
+ }
412
+ if (Array.isArray(this.definitions.folders) && this.definitions.folders.length) {
413
+ result.definitions.folders = this.definitions.folders.map(i => i.toJSON());
414
+ }
415
+ if (Array.isArray(this.definitions.schemas) && this.definitions.schemas.length) {
416
+ result.definitions.schemas = this.definitions.schemas.map(i => i.toJSON());
417
+ }
418
+ if (Array.isArray(this.environments) && this.environments.length) {
419
+ result.environments = this.environments;
420
+ }
421
+ if (Array.isArray(this.items) && this.items.length) {
422
+ result.items = this.items.map(i => i.toJSON());
423
+ }
424
+ if (this.provider) {
425
+ result.provider = this.provider.toJSON();
426
+ }
427
+ if (this.license) {
428
+ result.license = this.license.toJSON();
429
+ }
430
+ return result;
431
+ }
432
+
433
+ /**
434
+ * @returns JSON representation of the project
435
+ */
436
+ toString(): string {
437
+ return JSON.stringify(this);
438
+ }
439
+
440
+ /**
441
+ * Finds a parent of a definition.
442
+ *
443
+ * @param key The key of the definition.
444
+ * @returns The parent or undefine when not found.
445
+ */
446
+ findParent(key: string): ProjectFolder | HttpProject | undefined {
447
+ const { definitions, items = [] } = this;
448
+ const projectItemsIndex = items.findIndex(i => i.key === key);
449
+ if (projectItemsIndex > -1) {
450
+ return this;
451
+ }
452
+ const definition = definitions.folders.find(i => i.items.some(item => item.key === key));
453
+ if (definition) {
454
+ return definition;
455
+ }
456
+ return undefined;
457
+ }
458
+
459
+ /**
460
+ * Appends an instance of a folder to a project.
461
+ *
462
+ * @param folder The folder to add to this project.
463
+ * @param opts Optional folder add options.
464
+ * @returns The added folder.
465
+ */
466
+ addFolder(folder: ProjectFolder, opts?: IFolderCreateOptions): ProjectFolder;
467
+
468
+ /**
469
+ * Appends new folder to a project from a full folder schema.
470
+ * This is primarily used to insert a folder on the client side
471
+ * after a folder was created in the store.
472
+ *
473
+ * @param folder The folder schema to add to this project.
474
+ * @param opts Optional folder add options.
475
+ * @returns The added folder.
476
+ */
477
+ addFolder(folder: IProjectFolder, opts?: IFolderCreateOptions): ProjectFolder;
478
+
479
+ /**
480
+ * Appends a new folder to the project or a sub-folder.
481
+ *
482
+ * @param name The name to set. Optional.
483
+ * @param opts Folder create options.
484
+ * @returns The newly inserted folder. If the folder already existed it returns its instance.
485
+ */
486
+ addFolder(name?: string, opts?: IFolderCreateOptions): ProjectFolder;
487
+
488
+ /**
489
+ * Appends a new folder to the project or a sub-folder.
490
+ *
491
+ * Passing the folder schema as the fist argument is primarily used to insert a folder on the client side
492
+ * after a folder was created in the store.
493
+ *
494
+ * @param init The name or a folder schema. When not set a default name is assumed.
495
+ * @param opts Folder create options.
496
+ * @returns The newly inserted folder. If the folder already existed it returns its instance.
497
+ */
498
+ addFolder(init: string | IProjectFolder | ProjectFolder = ProjectFolder.defaultName, opts: IFolderCreateOptions = {}): ProjectFolder {
499
+ if (!Array.isArray(this.items)) {
500
+ this.items = [];
501
+ }
502
+ if (!Array.isArray(this.definitions.folders)) {
503
+ this.definitions.folders = [];
504
+ }
505
+ const { skipExisting, parent } = opts;
506
+ let root: ProjectFolder | HttpProject;
507
+ if (parent) {
508
+ const rootCandidate = this.findFolder(parent);
509
+ if (!rootCandidate) {
510
+ throw new Error(`Unable to find the parent folder ${parent}`);
511
+ }
512
+ root = rootCandidate;
513
+ } else {
514
+ root = this;
515
+ }
516
+ let definition: ProjectFolder;
517
+ if (typeof init === 'string') {
518
+ definition = ProjectFolder.fromName(this, init);
519
+ } else if (init instanceof ProjectFolder) {
520
+ definition = init;
521
+ } else {
522
+ definition = new ProjectFolder(this, init);
523
+ }
524
+ if (skipExisting) {
525
+ const folders = root.listFolderItems();
526
+ for (const item of folders) {
527
+ const existing = this.findFolder(item.key, { keyOnly: true });
528
+ if (existing && existing.info.name === definition.info.name) {
529
+ return existing;
530
+ }
531
+ }
532
+ }
533
+
534
+ this.definitions.folders.push(definition);
535
+ const item = ProjectItem.projectFolder(this, definition.key);
536
+ if (!Array.isArray(root.items)) {
537
+ root.items = [];
538
+ }
539
+ if (typeof opts.index === 'number') {
540
+ root.items.splice(opts.index, 0, item);
541
+ } else {
542
+ root.items.push(item);
543
+ }
544
+ definition.attachedCallback();
545
+ return definition;
546
+ }
547
+
548
+ /**
549
+ * Searches for a folder in the structure.
550
+ *
551
+ * @param nameOrKey The name or the key of the folder.
552
+ * @param opts Optional search options.
553
+ * @returns Found project folder or undefined.
554
+ */
555
+ findFolder(nameOrKey: string, opts: IFolderSearchOptions = {}): ProjectFolder | undefined {
556
+ const { definitions } = this;
557
+ const item = definitions.folders.find((i) => {
558
+ if (i.kind !== ProjectFolderKind) {
559
+ return false;
560
+ }
561
+ const folder = (i as ProjectFolder);
562
+ if (folder.key === nameOrKey) {
563
+ return true;
564
+ }
565
+ if (opts.keyOnly) {
566
+ return false;
567
+ }
568
+ return !!folder.info && folder.info.name === nameOrKey;
569
+ });
570
+ if (item) {
571
+ return item as ProjectFolder;
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Removes a folder from the project.
577
+ * @param key The folder key. It ignores the name when searching to the folder to avoid ambiguity.
578
+ * @param opts Folder remove options.
579
+ * @returns The removed folder definition or undefined when not removed.
580
+ */
581
+ removeFolder(key: string, opts: IFolderDeleteOptions = {}): ProjectFolder | undefined {
582
+ const { definitions } = this;
583
+ const folder = this.findFolder(key, { keyOnly: true });
584
+ if (!folder) {
585
+ if (opts.safe) {
586
+ return undefined;
587
+ }
588
+ throw new Error(`Unable to find the folder ${key}`);
589
+ }
590
+ const parent = this.findParent(key);
591
+ if (!parent) {
592
+ if (opts.safe) {
593
+ return undefined;
594
+ }
595
+ throw new Error(`Unable to find a parent of the folder ${key}`);
596
+ }
597
+
598
+ const requests = folder.listRequests();
599
+ requests.forEach(r => r.remove());
600
+ const folders = folder.listFolders();
601
+ folders.forEach(f => f.remove());
602
+
603
+ const itemIndex = parent.items.findIndex(i => i.key === key);
604
+ const definitionIndex = definitions.folders.findIndex(i => i.key === key);
605
+ definitions.folders.splice(definitionIndex, 1);
606
+ folder.detachedCallback();
607
+ if (itemIndex >= 0) {
608
+ parent.items.splice(itemIndex, 1);
609
+ }
610
+ return folder;
611
+ }
612
+
613
+ /**
614
+ * Moves a folder between folders and the project or between items inside a folder or a project
615
+ *
616
+ * Note, when the `parent` option is not specified it moved the folder to the project's root.
617
+ *
618
+ * @param key The key of the request to move.
619
+ * @param opts The moving options.
620
+ */
621
+ moveFolder(key: string, opts: IProjectMoveOptions = {}): void {
622
+ const { index, parent } = opts;
623
+ const movedFolder = this.findFolder(key);
624
+ if (!movedFolder) {
625
+ throw new Error(`Unable to locate the folder ${key}`);
626
+ }
627
+ const parentFolder = this.findParent(key);
628
+ if (!parentFolder) {
629
+ throw new Error(`Unable to locate a parent of the folder ${key}`);
630
+ }
631
+ if (parent) {
632
+ // check if moving a folder into another folder that is a child of the moved folder.
633
+ if (this.hasChild(parent, key)) {
634
+ throw new RangeError(`Unable to move a folder to its child.`);
635
+ }
636
+ }
637
+ const target = parent ? this.findFolder(parent) : this;
638
+ if (!target) {
639
+ throw new Error(`Unable to locate the new parent folder ${parent}`);
640
+ }
641
+ const hasIndex = typeof index === 'number';
642
+ if (hasIndex) {
643
+ // comparing to the `.length` and not `.length - 1` in case we are adding at the end.
644
+ const maxIndex = Math.max(target.items.length, 0);
645
+ if (index > maxIndex) {
646
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
647
+ }
648
+ }
649
+
650
+ const itemIndex = parentFolder.items.findIndex(i => i.key === key);
651
+ const item = parentFolder.items.splice(itemIndex, 1)[0];
652
+ movedFolder.detachedCallback();
653
+
654
+ if (hasIndex && target.items.length > index) {
655
+ target.items.splice(index, 0, item);
656
+ } else {
657
+ target.items.push(item);
658
+ }
659
+ movedFolder.attachedCallback();
660
+ }
661
+
662
+ /**
663
+ * Checks whether a folder has a child (anywhere down the structure).
664
+ *
665
+ * @param child The **key** of the child.
666
+ * @param folder The **key** of the folder. When not set it searches from the project root.
667
+ * @returns True when the child is located somewhere down the structure.
668
+ */
669
+ hasChild(child: string, folder?: string): boolean {
670
+ const target = folder ? this.findFolder(folder) : this;
671
+ if (!target) {
672
+ throw new Error(`Unable to locate the folder ${folder}`);
673
+ }
674
+ const { items = [] } = target;
675
+ for (const item of items) {
676
+ if (item.key === child) {
677
+ return true;
678
+ }
679
+ if (item.kind === ProjectFolderKind) {
680
+ const hasChild = this.hasChild(child, item.key);
681
+ if (hasChild) {
682
+ return true;
683
+ }
684
+ }
685
+ }
686
+ return false;
687
+ }
688
+
689
+ /**
690
+ * Adds a request to the project or a sub-folder.
691
+ *
692
+ * @param url The URL of the request.
693
+ * @param opts The request add options.
694
+ * @returns The inserted into the definitions request.
695
+ */
696
+ addRequest(url: string, opts?: IRequestAddOptions): ProjectRequest;
697
+
698
+ /**
699
+ * Adds a request to the project or a sub-folder.
700
+ *
701
+ * @param request The request to add.
702
+ * @param opts The request add options.
703
+ * @returns The inserted into the definitions request.
704
+ */
705
+ addRequest(request: IProjectRequest | ProjectRequest, opts?: IRequestAddOptions): ProjectRequest;
706
+
707
+ /**
708
+ * Adds a request to the project or a sub-folder.
709
+ * @param request The request to add.
710
+ * @param opts Thew request add options.
711
+ * @returns The inserted into the definitions request.
712
+ */
713
+ addRequest(request: IProjectRequest | ProjectRequest | string, opts: IRequestAddOptions = {}): ProjectRequest {
714
+ if (!Array.isArray(this.definitions.requests)) {
715
+ this.definitions.requests = [];
716
+ }
717
+
718
+ // the request can be already added to the project as the same method is used to refresh a request after
719
+ // a store update. From the system perspective it is the same event.
720
+
721
+ if (typeof request === 'object' && request.key) {
722
+ const existing = this.definitions.requests.find(i => i.key === request.key);
723
+ if (existing) {
724
+ existing.new(request as IProjectRequest);
725
+ return existing;
726
+ }
727
+ }
728
+
729
+ // if we got here, it means that we are adding a new request object to the project.
730
+
731
+ let finalRequest;
732
+ if (typeof request === 'string') {
733
+ finalRequest = ProjectRequest.fromUrl(request, this);
734
+ } else if (request instanceof ProjectRequest) {
735
+ finalRequest = request;
736
+ if (finalRequest.project && finalRequest.project !== this) {
737
+ finalRequest.detachedCallback();
738
+ }
739
+ finalRequest.project = this;
740
+ } else {
741
+ finalRequest = new ProjectRequest(this, request);
742
+ }
743
+ if (!finalRequest.key) {
744
+ finalRequest.key = v4();
745
+ }
746
+
747
+ let root: ProjectFolder | HttpProject;
748
+ if (opts.parent) {
749
+ const rootCandidate = this.findFolder(opts.parent);
750
+ if (!rootCandidate) {
751
+ throw new Error(`Unable to find the parent folder ${opts.parent}.`);
752
+ }
753
+ root = rootCandidate;
754
+ } else {
755
+ root = this;
756
+ }
757
+
758
+ if (!Array.isArray(root.items)) {
759
+ root.items = [];
760
+ }
761
+
762
+ if (typeof opts.index === 'number') {
763
+ const maxIndex = Math.max(root.items.length - 1, 0);
764
+ if (opts.index > maxIndex) {
765
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
766
+ }
767
+ }
768
+
769
+ this.definitions.requests.push(finalRequest);
770
+ const item = ProjectItem.projectRequest(this, finalRequest.key);
771
+
772
+ if (typeof opts.index === 'number') {
773
+ root.items.splice(opts.index, 0, item);
774
+ } else {
775
+ root.items.push(item);
776
+ }
777
+ finalRequest.attachedCallback();
778
+ return finalRequest;
779
+ }
780
+
781
+ /**
782
+ * Adds a request to the project that has been created for a previous version of ARC.
783
+ *
784
+ * @param legacy The legacy request definition.
785
+ * @returns The created project request.
786
+ */
787
+ async addLegacyRequest(legacy: ARCSavedRequest | ARCHistoryRequest): Promise<ProjectRequest> {
788
+ const request = await Request.fromLegacy(legacy);
789
+ const projectRequest = ProjectRequest.fromRequest(request.toJSON(), this);
790
+ return this.addRequest(projectRequest);
791
+ }
792
+
793
+ /**
794
+ * Searches for a request in the project.
795
+ *
796
+ * @param nameOrKey The name or the key of the request.
797
+ * @param opts Optional search options.
798
+ * @returns Found project request or undefined.
799
+ */
800
+ findRequest(nameOrKey: string, opts: IRequestSearchOptions = {}): ProjectRequest | undefined {
801
+ const { definitions } = this;
802
+ const item = definitions.requests.find((request) => {
803
+ if (request.key === nameOrKey) {
804
+ return true;
805
+ }
806
+ if (opts.keyOnly) {
807
+ return false;
808
+ }
809
+ return !!request.info && request.info.name === nameOrKey;
810
+ });
811
+ if (item) {
812
+ return item as ProjectRequest;
813
+ }
814
+ return undefined;
815
+ }
816
+
817
+ /**
818
+ * Removes a request from the project.
819
+ *
820
+ * @param key The request key. It ignores the name when searching to the request to avoid ambiguity.
821
+ * @param opts Request remove options.
822
+ * @returns The removed request definition or undefined when not removed.
823
+ */
824
+ removeRequest(key: string, opts: IRequestDeleteOptions = {}): ProjectRequest | undefined {
825
+ const { definitions } = this;
826
+ const request = this.findRequest(key, { keyOnly: true });
827
+ if (!request) {
828
+ if (opts.safe) {
829
+ return undefined;
830
+ }
831
+ throw new Error(`Unable to find the request ${key}`);
832
+ }
833
+ const parent = this.findParent(key);
834
+ if (!parent) {
835
+ if (opts.safe) {
836
+ return undefined;
837
+ }
838
+ throw new Error(`Unable to find a parent of the request ${key}`);
839
+ }
840
+ const itemIndex = parent.items.findIndex(i => i.key === key);
841
+ const definitionIndex = definitions.requests.findIndex(i => i.key === key);
842
+ definitions.requests.splice(definitionIndex, 1);
843
+ request.detachedCallback();
844
+ if (itemIndex >= 0) {
845
+ parent.items.splice(itemIndex, 1);
846
+ }
847
+ return request;
848
+ }
849
+
850
+ /**
851
+ * Moves a request between folders and the project or between items inside a folder or a project.
852
+ *
853
+ * Note, when the `parent` option is not specified it moved the request to the project's root.
854
+ *
855
+ * @param key The key of the request to move.
856
+ * @param opts The moving options.
857
+ */
858
+ moveRequest(key: string, opts: IProjectMoveOptions = {}): void {
859
+ const { index, parent } = opts;
860
+ const request = this.findRequest(key);
861
+ if (!request) {
862
+ throw new Error(`Unable to locate the request ${key}`);
863
+ }
864
+ const parentFolder = this.findParent(key);
865
+ if (!parentFolder) {
866
+ throw new Error(`Unable to locate a parent of the request ${key}`);
867
+ }
868
+ const target = parent ? this.findFolder(parent) : this;
869
+ if (!target) {
870
+ throw new Error(`Unable to locate the new parent folder ${parent}`);
871
+ }
872
+ const hasIndex = typeof index === 'number';
873
+ if (hasIndex) {
874
+ // comparing to the `.length` and not `.length - 1` in case we are adding at the end.
875
+ const maxIndex = Math.max(target.items.length, 0);
876
+ if (index > maxIndex) {
877
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
878
+ }
879
+ }
880
+
881
+ const itemIndex = parentFolder.items.findIndex(i => i.key === key);
882
+ const item = parentFolder.items.splice(itemIndex, 1)[0];
883
+ request.detachedCallback();
884
+
885
+ if (hasIndex && target.items.length > index) {
886
+ target.items.splice(index, 0, item);
887
+ } else {
888
+ target.items.push(item);
889
+ }
890
+ request.attachedCallback();
891
+ }
892
+
893
+ /**
894
+ * Lists items (not the actual definitions!) that are folders.
895
+ */
896
+ listFolderItems(): ProjectItem[] {
897
+ const { items = [] } = this;
898
+ return items.filter(i => i.kind === ProjectFolderKind);
899
+ }
900
+
901
+ /**
902
+ * Lists items (not the actual definitions!) that are requests.
903
+ */
904
+ listRequestItems(): ProjectItem[] {
905
+ const { items = [] } = this;
906
+ return items.filter(i => i.kind === ProjectRequestKind);
907
+ }
908
+
909
+ /**
910
+ * Lists folders from the project or a sub-folder.
911
+ * @param opts Folder listing options.
912
+ */
913
+ listFolders(opts: IFolderListOptions = {}): ProjectFolder[] {
914
+ let root;
915
+ if (opts.folder) {
916
+ const parent = this.findFolder(opts.folder);
917
+ if (!parent) {
918
+ throw new Error(`Unable to find the folder ${opts.folder}.`);
919
+ }
920
+ root = parent;
921
+ } else {
922
+ root = this;
923
+ }
924
+ const items = root.listFolderItems();
925
+ const result: ProjectFolder[] = [];
926
+ const { definitions } = this;
927
+ items.forEach((i) => {
928
+ const definition = definitions.folders.find(d => i.key === d.key);
929
+ if (definition) {
930
+ result.push(definition);
931
+ }
932
+ });
933
+ return result;
934
+ }
935
+
936
+ /**
937
+ * Lists requests in this project or a sub-folder.
938
+ * @param folder The optional folder name or the key to list requests for.
939
+ */
940
+ listRequests(folder?: string): ProjectRequest[] {
941
+ let root;
942
+ if (folder) {
943
+ const parent = this.findFolder(folder);
944
+ if (!parent) {
945
+ throw new Error(`Unable to find the folder ${folder}.`);
946
+ }
947
+ root = parent;
948
+ } else {
949
+ root = this;
950
+ }
951
+ const items = root.listRequestItems();
952
+ const result: ProjectRequest[] = [];
953
+ const { definitions } = this;
954
+ items.forEach((i) => {
955
+ const definition = definitions.requests.find(d => i.key === d.key);
956
+ if (definition) {
957
+ result.push(definition);
958
+ }
959
+ });
960
+ return result;
961
+ }
962
+
963
+ /**
964
+ * Lists definitions for the `items` of the project or a folder.
965
+ * @param folder Optionally the folder name to list the definitions for.
966
+ */
967
+ listDefinitions(folder?: string): (ProjectFolder | ProjectRequest | Environment)[] {
968
+ let root;
969
+ if (folder) {
970
+ const parent = this.findFolder(folder);
971
+ if (!parent) {
972
+ throw new Error(`Unable to find the folder ${folder}`);
973
+ }
974
+ root = parent;
975
+ } else {
976
+ root = this;
977
+ }
978
+ const result: (ProjectFolder | ProjectRequest | Environment)[] = [];
979
+ const { items = [] } = root;
980
+ const { definitions } = this;
981
+ items.forEach((item) => {
982
+ let definition: ProjectFolder | ProjectRequest | undefined;
983
+ if (item.kind === ProjectFolderKind) {
984
+ definition = definitions.folders.find(d => item.key === d.key);
985
+ } else if (item.kind === ProjectRequestKind) {
986
+ definition = definitions.requests.find(d => item.key === d.key);
987
+ }
988
+ if (definition) {
989
+ result.push(definition);
990
+ }
991
+ });
992
+ if (Array.isArray(root.environments)) {
993
+ root.environments.map((id) => {
994
+ const definition = definitions.environments.find(d => d.key === id);
995
+ if (definition) {
996
+ result.push(definition);
997
+ }
998
+ });
999
+ }
1000
+ return result;
1001
+ }
1002
+
1003
+ /**
1004
+ * Makes sure the license information exists.
1005
+ * @returns The set license.
1006
+ */
1007
+ ensureLicense(): License {
1008
+ if (!this.license) {
1009
+ this.license = new License();
1010
+ }
1011
+ return this.license;
1012
+ }
1013
+
1014
+ /**
1015
+ * Makes sure the Provider information exists.
1016
+ * @returns The set provider.
1017
+ */
1018
+ ensureProvider(): Provider {
1019
+ if (!this.provider) {
1020
+ this.provider = new Provider();
1021
+ }
1022
+ return this.provider;
1023
+ }
1024
+
1025
+ /**
1026
+ * @returns On the project level this always returns undefined.
1027
+ */
1028
+ getParent(): ProjectFolder | HttpProject | undefined {
1029
+ return undefined;
1030
+ }
1031
+
1032
+ attachedCallback(): void {
1033
+ // ...
1034
+ }
1035
+
1036
+ detachedCallback(): void {
1037
+ // ...
1038
+ }
1039
+
1040
+ getProject(): HttpProject {
1041
+ return this;
1042
+ }
1043
+
1044
+ /**
1045
+ * Reads the list of environments from then selected folder up to the project environments.
1046
+ * It stops going up in the project structure when selected environment has the `encapsulated`
1047
+ * property set to true.
1048
+ * The environments are ordered from the top-most level to the selected folder.
1049
+ *
1050
+ * @param opts The environment read options
1051
+ */
1052
+ async readEnvironments(opts: IReadEnvironmentOptions = {}): Promise<Environment[]> {
1053
+ const result: Environment[] = [];
1054
+ const { folderKey, nameOrKey } = opts;
1055
+
1056
+ const root = folderKey ? this.findFolder(folderKey, { keyOnly: true }) : this;
1057
+ if (!root) {
1058
+ return result;
1059
+ }
1060
+
1061
+ let current: HttpProject | ProjectFolder | undefined = root;
1062
+ while (current) {
1063
+ const environments = current.getEnvironments();
1064
+ if (environments.length) {
1065
+ const selected = nameOrKey ? environments.find(i => i.key === nameOrKey || i.info.name === nameOrKey) : environments[0];
1066
+ if (selected) {
1067
+ result.push(selected);
1068
+ if (selected.encapsulated) {
1069
+ break;
1070
+ }
1071
+ }
1072
+ }
1073
+ current = current.getParent();
1074
+ }
1075
+
1076
+ return result.reverse();
1077
+ }
1078
+
1079
+ /**
1080
+ * Makes a copy of this project.
1081
+ */
1082
+ clone(opts: IProjectCloneOptions = {}): HttpProject {
1083
+ const copy = new HttpProject(this.toJSON());
1084
+ if (!opts.withoutRevalidate) {
1085
+ copy.key = v4();
1086
+ HttpProject.regenerateKeys(copy);
1087
+ }
1088
+ return copy;
1089
+ }
1090
+
1091
+ static clone(project: IHttpProject, opts: IProjectCloneOptions = {}): HttpProject {
1092
+ const obj = new HttpProject(project);
1093
+ return obj.clone(opts);
1094
+ }
1095
+
1096
+ /**
1097
+ * Re-generates keys in the project, taking care of the references.
1098
+ *
1099
+ * Note, this changes the project properties. Make a copy of the project before calling this.
1100
+ *
1101
+ * @param src The project instance to re-generate keys for.
1102
+ */
1103
+ static regenerateKeys(src: HttpProject): void {
1104
+ const { items = [], definitions } = src;
1105
+ // create a flat list of all "items" in the project and all folders.
1106
+ let flatItems = [...items];
1107
+ (definitions.folders || []).forEach((folder) => {
1108
+ if (Array.isArray(folder.items) && folder.items.length) {
1109
+ flatItems = flatItems.concat(folder.items);
1110
+ }
1111
+ });
1112
+ const withEnvironments: (HttpProject | ProjectFolder)[] = [];
1113
+ if (Array.isArray(src.environments) && src.environments.length) {
1114
+ withEnvironments.push(src);
1115
+ }
1116
+ (definitions.folders || []).forEach((folder) => {
1117
+ if (Array.isArray(folder.environments) && folder.environments.length) {
1118
+ withEnvironments.push(folder);
1119
+ }
1120
+ const oldKey = folder.key;
1121
+ const indexObject = flatItems.find(i => i.key === oldKey);
1122
+ if (!indexObject) {
1123
+ return;
1124
+ }
1125
+ const newKey = v4();
1126
+ indexObject.key = newKey;
1127
+ folder.key = newKey;
1128
+ });
1129
+ (definitions.requests || []).forEach((request) => {
1130
+ const oldKey = request.key;
1131
+ const indexObject = flatItems.find(i => i.key === oldKey);
1132
+ if (!indexObject) {
1133
+ return;
1134
+ }
1135
+ const newKey = v4();
1136
+ indexObject.key = newKey;
1137
+ request.key = newKey;
1138
+ });
1139
+ (definitions.schemas || []).forEach((schema) => {
1140
+ schema.key = v4();
1141
+ });
1142
+ (definitions.environments || []).forEach((environment) => {
1143
+ // project or folder that has the environment.
1144
+ const parent = withEnvironments.find(item => item.environments.includes(environment.key));
1145
+ const oldKey = environment.key;
1146
+ const newKey = v4();
1147
+ environment.key = newKey;
1148
+ if (parent) {
1149
+ const index = parent.environments.indexOf(oldKey);
1150
+ parent.environments[index] = newKey;
1151
+ }
1152
+ });
1153
+ }
1154
+
1155
+ /**
1156
+ * Adds an empty schema to the project.
1157
+ *
1158
+ * @param name The name of the schema
1159
+ * @param opts The schema add options.
1160
+ * @returns The inserted into the schemas schema.
1161
+ */
1162
+ addSchema(url: string, opts?: ISchemaAddOptions): ProjectSchema;
1163
+
1164
+ /**
1165
+ * Adds a schema to the project.
1166
+ *
1167
+ * @param schema The schema to add.
1168
+ * @param opts The schema add options.
1169
+ * @returns The inserted into the schemas schema.
1170
+ */
1171
+ addSchema(schema: IProjectSchema | ProjectSchema, opts?: ISchemaAddOptions): ProjectSchema;
1172
+
1173
+ /**
1174
+ * Adds a request to the project or a sub-folder.
1175
+ * @param schema The schema to add.
1176
+ * @param opts Thew schema add options.
1177
+ * @returns The inserted into the schemas schema.
1178
+ */
1179
+ addSchema(schema: IProjectSchema | ProjectSchema | string, opts: ISchemaAddOptions = {}): ProjectSchema {
1180
+ if (!Array.isArray(this.definitions.schemas)) {
1181
+ this.definitions.schemas = [];
1182
+ }
1183
+
1184
+ // this renews existing schema
1185
+ if (typeof schema === 'object' && schema.key) {
1186
+ const existing = this.definitions.schemas.find(i => i.key === schema.key) as ProjectSchema | undefined;
1187
+ if (existing) {
1188
+ existing.new(schema as IProjectSchema);
1189
+ return existing;
1190
+ }
1191
+ }
1192
+
1193
+ let finalSchema: ProjectSchema;
1194
+ if (typeof schema === 'string') {
1195
+ finalSchema = ProjectSchema.fromName(schema);
1196
+ } else if (schema instanceof ProjectSchema) {
1197
+ finalSchema = schema;
1198
+ } else {
1199
+ finalSchema = new ProjectSchema(schema);
1200
+ }
1201
+ if (!finalSchema.key) {
1202
+ finalSchema.key = v4();
1203
+ }
1204
+ const { index } = opts;
1205
+ const hasIndex = typeof index === 'number';
1206
+ if (hasIndex && this.definitions.schemas.length > index) {
1207
+ // comparing to the `.length` and not `.length - 1` in case we are adding at the end.
1208
+ const maxIndex = Math.max(this.definitions.schemas.length, 0);
1209
+ if (index > maxIndex) {
1210
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
1211
+ }
1212
+ this.definitions.schemas.splice(index, 0, finalSchema);
1213
+ } else {
1214
+ this.definitions.schemas.push(finalSchema);
1215
+ }
1216
+ return finalSchema;
1217
+ }
1218
+
1219
+ /**
1220
+ * @returns The current list of schemas in the project.
1221
+ */
1222
+ listSchemas(): ProjectSchema[] {
1223
+ if (!Array.isArray(this.definitions.schemas)) {
1224
+ return [];
1225
+ }
1226
+ return this.definitions.schemas;
1227
+ }
1228
+
1229
+ getEnvironments(): Environment[] {
1230
+ if (Array.isArray(this.initEnvironments)) {
1231
+ return this.initEnvironments;
1232
+ }
1233
+ return super.getEnvironments();
1234
+ }
1235
+
1236
+ /**
1237
+ * Iterates over requests in the project,
1238
+ */
1239
+ * requestIterator(opts: IProjectRequestIterator = {}): Generator<ProjectRequest> {
1240
+ const { definitions } = this;
1241
+ const { ignore=[], parent, recursive, requests=[] } = opts;
1242
+ const root = parent ? this.findFolder(parent) : this;
1243
+ if (!root) {
1244
+ throw new Error(`The parent folder not found: ${parent}.`);
1245
+ }
1246
+ const items = root.items;
1247
+ if (!items || !items.length) {
1248
+ return;
1249
+ }
1250
+ for (const item of items) {
1251
+ if (ignore.includes(item.key)) {
1252
+ continue;
1253
+ }
1254
+ if (item.kind === ProjectRequestKind) {
1255
+ const request = definitions.requests.find(i => i.key === item.key);
1256
+ if (!request) {
1257
+ continue;
1258
+ }
1259
+ const name = request.info.name || '';
1260
+ if (ignore.includes(name)) {
1261
+ continue;
1262
+ }
1263
+ if (requests.length && !requests.includes(item.key) && !requests.includes(name)) {
1264
+ continue;
1265
+ }
1266
+ yield request;
1267
+ } else if (recursive && item.kind === ProjectFolderKind) {
1268
+ const folder = definitions.folders.find(i => i.key === item.key);
1269
+ if (!folder) {
1270
+ continue;
1271
+ }
1272
+ const name = folder.info.name || '';
1273
+ if (ignore.includes(name)) {
1274
+ continue;
1275
+ }
1276
+ const it = this.requestIterator({
1277
+ parent: item.key,
1278
+ recursive,
1279
+ ignore,
1280
+ requests,
1281
+ });
1282
+ for (const request of it) {
1283
+ yield request;
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ [Symbol.iterator](): Generator<ProjectRequest> {
1290
+ return this.requestIterator({
1291
+ recursive: true,
1292
+ });
1293
+ }
1294
+ }