@api-client/core 0.6.19 → 0.6.23

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 (51) hide show
  1. package/build/browser.d.ts +2 -0
  2. package/build/browser.js +2 -0
  3. package/build/browser.js.map +1 -1
  4. package/build/index.d.ts +2 -0
  5. package/build/index.js +2 -0
  6. package/build/index.js.map +1 -1
  7. package/build/legacy.d.ts +39 -0
  8. package/build/legacy.js +40 -0
  9. package/build/legacy.js.map +1 -0
  10. package/build/src/mocking/lib/Url.js +1 -1
  11. package/build/src/models/AuthorizationData.d.ts +2 -0
  12. package/build/src/models/AuthorizationData.js +10 -3
  13. package/build/src/models/AuthorizationData.js.map +1 -1
  14. package/build/src/models/ClientCertificate.js +1 -1
  15. package/build/src/models/ClientCertificate.js.map +1 -1
  16. package/build/src/models/HostRule.d.ts +8 -0
  17. package/build/src/models/HostRule.js +10 -1
  18. package/build/src/models/HostRule.js.map +1 -1
  19. package/build/src/models/HttpProject.js +3 -0
  20. package/build/src/models/HttpProject.js.map +1 -1
  21. package/build/src/models/Url.d.ts +4 -4
  22. package/build/src/models/Url.js +6 -6
  23. package/build/src/models/Url.js.map +1 -1
  24. package/build/src/models/arc/ArcHttpRequest.d.ts +39 -0
  25. package/build/src/models/arc/ArcHttpRequest.js +106 -0
  26. package/build/src/models/arc/ArcHttpRequest.js.map +1 -0
  27. package/build/src/models/arc/ArcProject.d.ts +628 -0
  28. package/build/src/models/arc/ArcProject.js +1273 -0
  29. package/build/src/models/arc/ArcProject.js.map +1 -0
  30. package/build/src/models/legacy/DataExport.d.ts +5 -0
  31. package/build/src/models/transformers/ArcPouchTransformer.d.ts +0 -1
  32. package/build/src/models/transformers/ArcPouchTransformer.js +8 -7
  33. package/build/src/models/transformers/ArcPouchTransformer.js.map +1 -1
  34. package/build/src/models/transformers/LegacyDataExportToApiProject.js +1 -0
  35. package/build/src/models/transformers/LegacyDataExportToApiProject.js.map +1 -1
  36. package/build/src/models/transformers/LegacyExportProcessor.js.map +1 -1
  37. package/legacy.ts +41 -0
  38. package/package.json +3 -3
  39. package/src/mocking/lib/Url.ts +1 -1
  40. package/src/models/AuthorizationData.ts +10 -2
  41. package/src/models/ClientCertificate.ts +2 -2
  42. package/src/models/HostRule.ts +17 -1
  43. package/src/models/HttpProject.ts +3 -0
  44. package/src/models/Url.ts +10 -10
  45. package/src/models/arc/ArcHttpRequest.ts +121 -0
  46. package/src/models/arc/ArcProject.ts +1638 -0
  47. package/src/models/arc/readme.md +3 -0
  48. package/src/models/legacy/DataExport.ts +5 -0
  49. package/src/models/transformers/ArcPouchTransformer.ts +8 -7
  50. package/src/models/transformers/LegacyDataExportToApiProject.ts +1 -0
  51. package/src/models/transformers/LegacyExportProcessor.ts +1 -0
@@ -0,0 +1,1638 @@
1
+ /* eslint-disable no-param-reassign */
2
+ /* eslint-disable class-methods-use-this */
3
+ /* eslint-disable @typescript-eslint/no-this-alias */
4
+ /* eslint-disable max-classes-per-file */
5
+ // import { ARCHistoryRequest, ARCSavedRequest } from "@api-client/core/build/legacy.js";
6
+
7
+ import v4 from "../../lib/uuid.js";
8
+ import { HttpRequest, IHttpRequest } from "../HttpRequest.js";
9
+ import { IRequest, Request } from "../Request.js";
10
+ import { IThing, Thing } from "../Thing.js";
11
+ import { ARCHistoryRequest, ARCSavedRequest } from "../legacy/request/ArcRequest.js";
12
+ import { ARCProject } from "../legacy/models/ArcLegacyProject.js";
13
+
14
+ export const ArcProjectKind = 'ARC#HttpProject';
15
+ export const ArcProjectFolderKind = 'ARC#HttpProjectFolder';
16
+ export const ArcProjectRequestKind = 'ARC#HttpProjectRequest';
17
+
18
+ export interface IArcRequestCloneOptions {
19
+ /**
20
+ * By default it revalidates (re-creates) keys in the request.
21
+ * Set this to true to not make any changes to the keys.
22
+ */
23
+ withoutRevalidate?: boolean;
24
+ /**
25
+ * By default it attaches the request to the same parent as the original request.
26
+ * Set this to `true` when moving a request between projects to prevent adding the request to the project.
27
+ * Note, the request still have a reference to the original project. You need to update the `project` property.
28
+ */
29
+ withoutAttach?: boolean;
30
+ }
31
+
32
+ export interface IArcFolderAddOptions {
33
+ /**
34
+ * Optionally the position at which to add the request into the list of items.
35
+ */
36
+ index?: number;
37
+ }
38
+
39
+ export interface IArcFolderCloneOptions {
40
+ /**
41
+ * By default it clones the folder with all requests in it.
42
+ * Set this to `true` to skip copying the requests along with the folder.
43
+ */
44
+ withoutRequests?: boolean;
45
+ /**
46
+ * By default it clones the folder with all folders in it.
47
+ * Set this to `true` to skip copying the folders along with the folder.
48
+ */
49
+ withoutFolders?: boolean;
50
+ /**
51
+ * The target project where to put the copied folder.
52
+ * When the target project is not the same as the source project then the folder
53
+ * is put into the project root rather than the parent folder (as it would when cloning
54
+ * a folder inside the same project).
55
+ */
56
+ targetProject?: ArcProject;
57
+ /**
58
+ * The **key** of the target folder.
59
+ *
60
+ * By default it clones the folder to its parent unless the clone is attached to another project.
61
+ * When the target folder is set then it places the clone under the passed target folder.
62
+ */
63
+ targetFolder?: string;
64
+ }
65
+
66
+ export interface IArcFolderCreateOptions {
67
+ /**
68
+ * Ignores the operation when the folder with the same name already exists.
69
+ * This command can be used used to ensure that the folder exists.
70
+ */
71
+ skipExisting?: boolean;
72
+ /**
73
+ * The id of the parent folder. When not set it adds the folder to the project root.
74
+ */
75
+ parent?: string;
76
+ /**
77
+ * Optionally the position at which to add the folder into the list of items.
78
+ */
79
+ index?: number;
80
+ }
81
+
82
+ export interface IArcFolderSearchOptions {
83
+ /**
84
+ * When set it searches for a folder using keys only.
85
+ * By default it searches for a key and the name.
86
+ */
87
+ keyOnly?: boolean;
88
+ }
89
+
90
+ export interface IArcFolderDeleteOptions {
91
+ /**
92
+ * When set it won't throw an error when the folder is not found in the project.
93
+ */
94
+ safe?: boolean;
95
+ }
96
+
97
+ export interface IArcRequestAddOptions {
98
+ /**
99
+ * The id of the parent folder. When not set it adds the request to the project root.
100
+ */
101
+ parent?: string;
102
+ /**
103
+ * Optionally the position at which to add the request into the list of items.
104
+ */
105
+ index?: number;
106
+ }
107
+
108
+ export interface IArcRequestSearchOptions {
109
+ /**
110
+ * When set it searches for a request using keys only.
111
+ * By default it searches for a key and the name.
112
+ */
113
+ keyOnly?: boolean;
114
+ }
115
+
116
+ export interface IArcRequestDeleteOptions {
117
+ /**
118
+ * When set it won't throw an error when the request is not found in the project.
119
+ */
120
+ safe?: boolean;
121
+ }
122
+
123
+ export interface IArcProjectMoveOptions {
124
+ /**
125
+ * The position at which to insert the object in the destination. BY default it adds the object at the end.
126
+ */
127
+ index?: number;
128
+ /**
129
+ * The name or the key of the parent folder to move the item into.
130
+ * When not set it moves the item to the project's root.
131
+ */
132
+ parent?: string;
133
+ }
134
+
135
+ export interface IArcFolderListOptions {
136
+ /**
137
+ * Folder name or key to list folders for.
138
+ */
139
+ folder?: string;
140
+ }
141
+
142
+ export interface IArcProjectCloneOptions {
143
+ /**
144
+ * By default it revalidates (re-creates) keys in the request.
145
+ * Set this to true to not make any changes to the keys.
146
+ */
147
+ withoutRevalidate?: boolean;
148
+ }
149
+
150
+ export interface IArcProjectRequest extends IRequest {
151
+ kind: typeof ArcProjectRequestKind;
152
+ key: string;
153
+ }
154
+
155
+ export interface IArcProjectItem {
156
+ kind: typeof ArcProjectFolderKind | typeof ArcProjectRequestKind;
157
+ key: string;
158
+ }
159
+
160
+ export interface IArcProjectDefinitions {
161
+ /**
162
+ * The list of all folders defined in the project.
163
+ */
164
+ folders?: IProjectParent[];
165
+ /**
166
+ * The list of all requests defined in the project.
167
+ */
168
+ requests?: IArcProjectRequest[];
169
+ }
170
+
171
+ export interface ArcProjectDefinitions {
172
+ /**
173
+ * The list of all folders defined in the project.
174
+ */
175
+ folders: ArcProjectFolder[];
176
+ /**
177
+ * The list of all requests defined in the project.
178
+ */
179
+ requests: ArcProjectRequest[];
180
+ }
181
+
182
+ export interface IArcProject extends IProjectParent {
183
+ definitions: IArcProjectDefinitions;
184
+ }
185
+
186
+ export interface IProjectParent {
187
+ key: string;
188
+ /**
189
+ * The auto-generated key for the folder object.
190
+ * For the project root this is the same as the `_id`.
191
+ */
192
+ kind: typeof ArcProjectKind | typeof ArcProjectFolderKind;
193
+ /**
194
+ * Folder meta
195
+ */
196
+ info: IThing;
197
+ /**
198
+ * The list of items in the folder.
199
+ * It is an ordered list of requests and folders.
200
+ * The actual definition is kept in the root's `definitions`.
201
+ */
202
+ items: IArcProjectItem[];
203
+ /**
204
+ * Timestamp when the project was last updated.
205
+ */
206
+ updated?: number;
207
+ /**
208
+ * Timestamp when the project was created.
209
+ */
210
+ created?: number;
211
+ }
212
+
213
+ export class ArcProjectRequest extends Request {
214
+ kind = ArcProjectRequestKind;
215
+
216
+ /**
217
+ * The identifier of the request.
218
+ */
219
+ key = '';
220
+
221
+ /**
222
+ * A reference to the top level project object.
223
+ */
224
+ project: ArcProject;
225
+
226
+ /**
227
+ * Creates a project request from an URL.
228
+ * This does not manipulate the project.
229
+ *
230
+ * @param url The Request URL. This is required.
231
+ * @param project The parent project.
232
+ */
233
+ static fromUrl(url: string, project?: ArcProject): ArcProjectRequest {
234
+ if (!project) {
235
+ throw new Error(`The project is required.`);
236
+ }
237
+ const now: number = Date.now();
238
+ const request = new ArcProjectRequest(project, {
239
+ key: v4(),
240
+ kind: ArcProjectRequestKind,
241
+ created: now,
242
+ updated: now,
243
+ expects: HttpRequest.fromBaseValues({ url, method: 'GET' }).toJSON(),
244
+ info: Thing.fromName(url).toJSON(),
245
+ });
246
+ return request;
247
+ }
248
+
249
+ /**
250
+ * Creates a project request from a name.
251
+ * This does not manipulate the project.
252
+ *
253
+ * @param name The Request name.
254
+ * @param project The parent project.This is required.
255
+ */
256
+ static fromName(name: string, project?: ArcProject): ArcProjectRequest {
257
+ if (!project) {
258
+ throw new Error(`The project is required.`);
259
+ }
260
+ const now: number = Date.now();
261
+ const request = new ArcProjectRequest(project, {
262
+ key: v4(),
263
+ kind: ArcProjectRequestKind,
264
+ created: now,
265
+ updated: now,
266
+ expects: new HttpRequest().toJSON(),
267
+ info: Thing.fromName(name).toJSON(),
268
+ });
269
+ return request;
270
+ }
271
+
272
+ /**
273
+ * Creates a project request from an HttpRequest definition.
274
+ * This does not manipulate the project.
275
+ *
276
+ * @param project The parent project This is required.
277
+ * @param info The request data.
278
+ */
279
+ static fromHttpRequest(info: IHttpRequest, project?: ArcProject): ArcProjectRequest {
280
+ if (!project) {
281
+ throw new Error(`The project is required.`);
282
+ }
283
+ const now: number = Date.now();
284
+ const request = new ArcProjectRequest(project, {
285
+ key: v4(),
286
+ kind: ArcProjectRequestKind,
287
+ created: now,
288
+ updated: now,
289
+ expects: HttpRequest.fromBaseValues({ method: info.method, url: info.url, headers: info.headers, payload: info.payload }).toJSON(),
290
+ info: Thing.fromName(info.url).toJSON(),
291
+ });
292
+ return request;
293
+ }
294
+
295
+ /**
296
+ * Creates a project request for a schema of a Request.
297
+ */
298
+ static fromRequest(request: IRequest, project: ArcProject): ArcProjectRequest {
299
+ const key = v4();
300
+ const init: IArcProjectRequest = { ...request, key, kind: ArcProjectRequestKind };
301
+ const result = new ArcProjectRequest(project, init);
302
+ return result;
303
+ }
304
+
305
+ constructor(project: ArcProject, input?: string | IArcProjectRequest) {
306
+ super(input);
307
+ this.project = project;
308
+
309
+ let init: IArcProjectRequest | undefined;
310
+ if (typeof input === 'string') {
311
+ init = JSON.parse(input);
312
+ } else if (typeof input === 'object') {
313
+ init = input;
314
+ }
315
+ if (init) {
316
+ this.key = init.key || v4();
317
+ }
318
+ this.kind = ArcProjectRequestKind;
319
+ }
320
+
321
+ new(init: IArcProjectRequest): void {
322
+ super.new(init);
323
+
324
+ const { key = v4() } = init;
325
+ this.key = key;
326
+ this.kind = ArcProjectRequestKind;
327
+ }
328
+
329
+ toJSON(): IArcProjectRequest {
330
+ const request = super.toJSON();
331
+ const result: IArcProjectRequest = { ...request, key: this.key, kind: ArcProjectRequestKind };
332
+ return result;
333
+ }
334
+
335
+ /**
336
+ * @returns The instance of the ArcProject or a ArcProjectFolder that is a closes parent of this instance.
337
+ */
338
+ getParent(): ArcProjectFolder | ArcProject | undefined {
339
+ const { project, key } = this;
340
+ return project.findParent(key);
341
+ }
342
+
343
+ /**
344
+ * @returns A reference to the parent folder or the top-level HTTP project.
345
+ */
346
+ getProject(): ArcProject {
347
+ return this.project;
348
+ }
349
+
350
+ /**
351
+ * Removes this request from the project.
352
+ */
353
+ remove(): void {
354
+ this.project.removeRequest(this.key);
355
+ }
356
+
357
+ /**
358
+ * Makes a copy of this request.
359
+ * By default it attaches the copied request to the same parent.
360
+ * Use the options dictionary to control this behavior.
361
+ */
362
+ clone(opts: IArcRequestCloneOptions = {}): ArcProjectRequest {
363
+ const copy = new ArcProjectRequest(this.project, this.toJSON());
364
+ if (!opts.withoutRevalidate) {
365
+ copy.key = v4();
366
+ }
367
+ if (!opts.withoutAttach) {
368
+ // if the parent is the project then add the request to the project.
369
+ const parent = this.getParent();
370
+ if (parent) {
371
+ parent.addRequest(copy);
372
+ }
373
+ }
374
+ return copy;
375
+ }
376
+
377
+ /**
378
+ * The static version of the `clone()` method.
379
+ *
380
+ * @param request The request schema to clone.
381
+ * @param project The project to add the request to.
382
+ * @param opts Optional options.
383
+ * @returns The copied request.
384
+ */
385
+ static clone(request: IArcProjectRequest, project: ArcProject, opts: IArcRequestCloneOptions = {}): ArcProjectRequest {
386
+ const obj = new ArcProjectRequest(project, request);
387
+ return obj.clone(opts);
388
+ }
389
+ }
390
+
391
+ export class ArcProjectItem {
392
+ /**
393
+ * The kind of the item.
394
+ */
395
+ kind: typeof ArcProjectFolderKind | typeof ArcProjectRequestKind = ArcProjectRequestKind;
396
+
397
+ /**
398
+ * The identifier of the object in the `definitions` array of the project.
399
+ */
400
+ key = '';
401
+
402
+ /**
403
+ * A reference to the top level project object.
404
+ */
405
+ project: ArcProject;
406
+
407
+ /**
408
+ * Checks whether the input is a definition of a project item.
409
+ */
410
+ static isProjectItem(input: unknown): boolean {
411
+ const typed = input as IArcProjectItem;
412
+ if (!input || ![ArcProjectFolderKind, ArcProjectRequestKind].includes(typed.kind)) {
413
+ return false;
414
+ }
415
+ return true;
416
+ }
417
+
418
+ /**
419
+ * @return An instance that represents a request item
420
+ */
421
+ static projectRequest(project: ArcProject, key: string): ArcProjectItem {
422
+ const item = new ArcProjectItem(project, {
423
+ kind: ArcProjectRequestKind,
424
+ key,
425
+ });
426
+ return item;
427
+ }
428
+
429
+ /**
430
+ * @return An instance that represents a folder item
431
+ */
432
+ static projectFolder(project: ArcProject, key: string): ArcProjectItem {
433
+ const item = new ArcProjectItem(project, {
434
+ kind: ArcProjectFolderKind,
435
+ key,
436
+ });
437
+ return item;
438
+ }
439
+
440
+ /**
441
+ * @param project The top-most project.
442
+ * @param input The project item definition used to restore the state.
443
+ */
444
+ constructor(project: ArcProject, input: string | IArcProjectItem) {
445
+ this.project = project;
446
+ let init: IArcProjectItem;
447
+ if (typeof input === 'string') {
448
+ if (input === 'http-request') {
449
+ init = {
450
+ kind: ArcProjectRequestKind,
451
+ key: '',
452
+ };
453
+ } else if (input === 'folder') {
454
+ init = {
455
+ kind: ArcProjectFolderKind,
456
+ key: '',
457
+ };
458
+ } else {
459
+ init = JSON.parse(input);
460
+ }
461
+ } else if (typeof input === 'object') {
462
+ init = input;
463
+ } else {
464
+ throw new Error('Specify the type of the item.');
465
+ }
466
+ this.new(init);
467
+ }
468
+
469
+ /**
470
+ * Creates a new project item clearing anything that is so far defined.
471
+ *
472
+ * Note, this throws an error when the project item is not a project item.
473
+ */
474
+ new(init: IArcProjectItem): void {
475
+ if (!ArcProjectItem.isProjectItem(init)) {
476
+ throw new Error(`Not a project item.`);
477
+ }
478
+ const { kind, key } = init;
479
+ this.kind = kind;
480
+ this.key = key;
481
+ }
482
+
483
+ toJSON(): IArcProjectItem {
484
+ const result: IArcProjectItem = {
485
+ kind: this.kind,
486
+ key: this.key,
487
+ };
488
+ return result;
489
+ }
490
+
491
+ /**
492
+ * @returns The instance of the definition associated with this item.
493
+ */
494
+ getItem(): ArcProjectFolder | ArcProjectRequest | undefined {
495
+ const { project, key, kind } = this;
496
+ const { definitions } = project;
497
+ if (kind === ArcProjectRequestKind) {
498
+ return definitions.requests.find(i => i.key === key);
499
+ }
500
+ if (kind === ArcProjectFolderKind) {
501
+ return definitions.folders.find(i => i.key === key);
502
+ }
503
+ return undefined;
504
+ }
505
+
506
+ /**
507
+ * @returns The instance of the ArcProject or a ArcProjectFolder that is a closest parent of this item.
508
+ */
509
+ getParent(): ArcProjectFolder | ArcProject | undefined {
510
+ const { project, key } = this;
511
+ return project.findParent(key);
512
+ }
513
+ }
514
+
515
+ export abstract class ArcProjectParent {
516
+ /**
517
+ * The auto-generated key for the folder object.
518
+ * For the project root this is the same as the `_id`.
519
+ */
520
+ kind: typeof ArcProjectKind | typeof ArcProjectFolderKind;
521
+
522
+ /**
523
+ * The key of the project / folder.
524
+ */
525
+ key = '';
526
+
527
+ /**
528
+ * The basic information about the project / folder.
529
+ */
530
+ info: Thing = Thing.fromName('');
531
+
532
+ /**
533
+ * The list of items in the folder.
534
+ * It is an ordered list of requests and folders.
535
+ * The actual definition is kept in the root's `definitions`.
536
+ */
537
+ items: ArcProjectItem[] = [];
538
+
539
+ /**
540
+ * Timestamp when the project was last updated.
541
+ */
542
+ updated: number = Date.now();
543
+
544
+ /**
545
+ * Timestamp when the project was created.
546
+ */
547
+ created: number = Date.now();
548
+
549
+ constructor(kind: typeof ArcProjectKind | typeof ArcProjectFolderKind, input?: string | IProjectParent) {
550
+ this.kind = kind;
551
+
552
+ let init: IProjectParent;
553
+ if (typeof input === 'string') {
554
+ init = JSON.parse(input);
555
+ } else if (typeof input === 'object') {
556
+ init = input;
557
+ } else {
558
+ const now: number = Date.now();
559
+ init = {
560
+ kind,
561
+ created: now,
562
+ updated: now,
563
+ items: [],
564
+ key: v4(),
565
+ info: Thing.fromName('New folder').toJSON(),
566
+ };
567
+ }
568
+ this.new(init);
569
+ }
570
+
571
+ /**
572
+ * Creates a new project folder clearing anything that is so far defined.
573
+ *
574
+ * Note, this throws an error when the project folder is not a project folder.
575
+ */
576
+ new(init: IProjectParent): void {
577
+ const { key = v4(), created = Date.now(), updated = Date.now(), items, info, kind } = init;
578
+ this.kind = kind;
579
+ this.key = key;
580
+ this.created = created;
581
+ this.updated = updated;
582
+ this.setItems(items);
583
+ if (info) {
584
+ this.info = new Thing(info);
585
+ } else {
586
+ this.info = Thing.fromName('New folder');
587
+ }
588
+ }
589
+
590
+ abstract setItems(items?: IArcProjectItem[]): void;
591
+
592
+ /**
593
+ * Lists items (not the actual definitions!) that are folders.
594
+ */
595
+ listFolderItems(): ArcProjectItem[] {
596
+ const { items = [] } = this;
597
+ return items.filter(i => i.kind === ArcProjectFolderKind);
598
+ }
599
+
600
+ /**
601
+ * Lists items (not the actual definitions!) that are requests.
602
+ */
603
+ listRequestItems(): ArcProjectItem[] {
604
+ const { items = [] } = this;
605
+ return items.filter(i => i.kind === ArcProjectRequestKind);
606
+ }
607
+ }
608
+
609
+ export class ArcProjectFolder extends ArcProjectParent {
610
+
611
+ project: ArcProject;
612
+
613
+ /**
614
+ * Creates a new ArcProjectFolder object from a name.
615
+ * @param project The top-most project.
616
+ * @param name The name to set.
617
+ */
618
+ static fromName(project: ArcProject, name = 'New folder'): ArcProjectFolder {
619
+ const now = Date.now();
620
+ const key = v4();
621
+ const info = Thing.fromName(name);
622
+ const definition = new ArcProjectFolder(project, {
623
+ key,
624
+ created: now,
625
+ updated: now,
626
+ items: [],
627
+ kind: ArcProjectFolderKind,
628
+ info: info.toJSON(),
629
+ });
630
+ return definition;
631
+ }
632
+
633
+ constructor(project: ArcProject, input?: string | IProjectParent) {
634
+ super(ArcProjectFolderKind, input);
635
+ this.project = project;
636
+
637
+ let init: IProjectParent | undefined;
638
+ if (typeof input === 'string') {
639
+ init = JSON.parse(input);
640
+ } else if (typeof input === 'object') {
641
+ init = input;
642
+ }
643
+ if (init) {
644
+ this.key = init.key || v4();
645
+ }
646
+ this.kind = ArcProjectFolderKind;
647
+ }
648
+
649
+ toJSON(): IProjectParent {
650
+ const result: IProjectParent = {
651
+ kind: ArcProjectFolderKind,
652
+ info: this.info.toJSON(),
653
+ key: this.key,
654
+ created: this.created,
655
+ updated: this.updated,
656
+ items: [],
657
+ };
658
+ if (Array.isArray(this.items)) {
659
+ result.items = this.items.map(i => i.toJSON());
660
+ }
661
+ return result;
662
+ }
663
+
664
+ setItems(items?: IArcProjectItem[]): void {
665
+ if (Array.isArray(items)) {
666
+ this.items = items.map(i => new ArcProjectItem(this.project, i));
667
+ } else {
668
+ this.items = [];
669
+ }
670
+ }
671
+
672
+ /**
673
+ * Appends an instance of a folder to a project.
674
+ *
675
+ * @param folder The folder to add to this project.
676
+ * @returns The added folder.
677
+ */
678
+ addFolder(folder: ArcProjectFolder): ArcProjectFolder;
679
+
680
+ /**
681
+ * Appends new folder to a project from a full folder schema.
682
+ * This is primarily used to insert a folder on the client side
683
+ * after a folder was created in the store.
684
+ *
685
+ * @param folder The folder schema to add to this project.
686
+ * @returns The added folder.
687
+ */
688
+ addFolder(folder: IProjectParent): ArcProjectFolder;
689
+
690
+ /**
691
+ * Appends a new folder to the project or a sub-folder.
692
+ *
693
+ * @param name The name to set. Optional.
694
+ * @returns The newly inserted folder. If the folder already existed it returns its instance.
695
+ */
696
+ addFolder(name?: string): ArcProjectFolder;
697
+
698
+ /**
699
+ * Appends a new folder to the folder. It updates the project to add the request definition.
700
+ * @param name The name to set. Optional.
701
+ * @returns The key of newly inserted folder.
702
+ */
703
+ addFolder(name: string | IProjectParent | ArcProjectFolder | undefined): ArcProjectFolder {
704
+ return this.project.addFolder(name as ArcProjectFolder, { parent: this.key });
705
+ }
706
+
707
+ /**
708
+ * Adds a request to the project or a sub-folder.
709
+ *
710
+ * @param url The URL of the request.
711
+ * @param opts The request add options.
712
+ * @returns The inserted into the definitions request.
713
+ */
714
+ addRequest(url: string, opts?: IArcFolderAddOptions): ArcProjectRequest;
715
+
716
+ /**
717
+ * Adds a request to the project or a sub-folder.
718
+ *
719
+ * @param request The request to add.
720
+ * @param opts The request add options.
721
+ * @returns The inserted into the definitions request.
722
+ */
723
+ addRequest(request: IArcProjectRequest | ArcProjectRequest, opts?: IArcFolderAddOptions): ArcProjectRequest;
724
+
725
+ /**
726
+ * Appends a new request to the folder. It updates the project to add the request definition.
727
+ * @param request The request to append to the folder.
728
+ * @returns The key of newly inserted request.
729
+ */
730
+ addRequest(request: IArcProjectRequest | ArcProjectRequest | string, opts: IArcFolderAddOptions = {}): ArcProjectRequest {
731
+ const addOptions = { parent: this.key, ...opts };
732
+ if (typeof request === 'string') {
733
+ return this.project.addRequest(request, addOptions);
734
+ }
735
+ return this.project.addRequest(request, addOptions);
736
+ }
737
+
738
+ /**
739
+ * @returns The instance of the ArcProject or a ArcProjectFolder that is a closes parent of this instance.
740
+ */
741
+ getParent(): ArcProjectFolder | ArcProject | undefined {
742
+ const { project, key } = this;
743
+ return project.findParent(key);
744
+ }
745
+
746
+ /**
747
+ * @returns A reference to the parent folder or the top-level HTTP project.
748
+ */
749
+ getProject(): ArcProject {
750
+ return this.project;
751
+ }
752
+
753
+ /**
754
+ * Removes this folder from the project.
755
+ */
756
+ remove(): void {
757
+ this.project.removeFolder(this.key);
758
+ }
759
+
760
+ /**
761
+ * Makes a copy of this folder.
762
+ * By default it attaches the copied folder to the same parent.
763
+ * It also, by default, copies requests declared in this folder.
764
+ *
765
+ * Use the options dictionary to control these behaviors.
766
+ *
767
+ * @param opts Cloning options
768
+ */
769
+ clone(opts: IArcFolderCloneOptions = {}): ArcProjectFolder {
770
+ const { targetProject = this.project, targetFolder } = opts;
771
+ const copy = new ArcProjectFolder(targetProject, this.toJSON());
772
+ copy.key = v4();
773
+
774
+ const extProject = targetProject !== this.project;
775
+ if (extProject) {
776
+ if (targetFolder) {
777
+ const parent = targetProject.findFolder(targetFolder, { keyOnly: true });
778
+ if (!parent) {
779
+ throw new Error(`The target project does not contain the folder ${targetFolder}`);
780
+ }
781
+ parent.addFolder(copy);
782
+ } else {
783
+ targetProject.addFolder(copy);
784
+ }
785
+ } else {
786
+ const parent = targetFolder ? this.project.findFolder(targetFolder, { keyOnly: true }) : this.getParent();
787
+ if (parent) {
788
+ parent.addFolder(copy);
789
+ } else {
790
+ throw new Error(`Unable to locate a parent of the folder.`);
791
+ }
792
+ }
793
+ // removes all items. Depending on the passed option we re-add them next.
794
+ copy.items = [];
795
+
796
+ if (!opts.withoutRequests) {
797
+ this.cloneRequests(copy, this.project);
798
+ }
799
+ if (!opts.withoutFolders) {
800
+ this.cloneSubFolders(copy, this.project, !opts.withoutRequests);
801
+ }
802
+ return copy;
803
+ }
804
+
805
+ /**
806
+ * Clones the current requests to the target folder.
807
+ *
808
+ * @param folder The target folder into which to put the requests. The folder has to have the target project attached to it.
809
+ * @param project The originating project where the definitions are stored
810
+ */
811
+ protected cloneRequests(folder: ArcProjectFolder, project: ArcProject): void {
812
+ const requests = this.items.filter(i => i.kind === ArcProjectRequestKind);
813
+ requests.forEach(r => {
814
+ const request = project.findRequest(r.key, { keyOnly: true });
815
+ if (!request) {
816
+ // Should we throw an error here?
817
+ // CONS:
818
+ // - It's not really related to the operation. It means there is an inconsistency in the project. That's the role of the project class.
819
+ // - Ignoring this would allow us to make a copy that is error free.
820
+ // - The error may occur in a situation when the user does not expect it (giving the nature of the error)
821
+ // Pros:
822
+ // - There's an inconsistency in the project definition that should be reported back to the UI for the user to inspect
823
+ return;
824
+ }
825
+ const copy = request.clone({ withoutAttach: true });
826
+ copy.project = folder.getProject();
827
+ folder.addRequest(copy);
828
+ });
829
+ }
830
+
831
+ /**
832
+ * Clones the sub-folders to the target folder.
833
+ *
834
+ * @param folder The target folder into which to put the sub-folders. The folder has to have the target project attached to it.
835
+ * @param project The originating project where the definitions are stored
836
+ * @param withRequests Whether to clone requests with the folder.
837
+ */
838
+ protected cloneSubFolders(folder: ArcProjectFolder, project: ArcProject, withRequests = true): void {
839
+ const folders = this.items.filter(i => i.kind === ArcProjectFolderKind);
840
+ folders.forEach(f => {
841
+ const definition = project.findFolder(f.key, { keyOnly: true });
842
+ if (!definition) {
843
+ return;
844
+ }
845
+ const copy = new ArcProjectFolder(folder.getProject(), definition.toJSON());
846
+ copy.key = v4();
847
+ copy.items = [];
848
+ folder.addFolder(copy);
849
+ if (withRequests) {
850
+ definition.cloneRequests(copy, project);
851
+ }
852
+ definition.cloneSubFolders(copy, project, withRequests);
853
+ });
854
+ }
855
+
856
+ /**
857
+ * Lists folders in this folder.
858
+ */
859
+ listFolders(): ArcProjectFolder[] {
860
+ return this.project.listFolders({ folder: this.key });
861
+ }
862
+
863
+ /**
864
+ * Lists requests in this folder.
865
+ */
866
+ listRequests(): ArcProjectRequest[] {
867
+ return this.project.listRequests(this.key);
868
+ }
869
+
870
+ /**
871
+ * Adds a request to the project that has been created for a previous version of ARC.
872
+ *
873
+ * @param legacy The legacy request definition.
874
+ * @returns The created project request.
875
+ */
876
+ async addLegacyRequest(legacy: ARCSavedRequest | ARCHistoryRequest): Promise<ArcProjectRequest> {
877
+ const request = await Request.fromLegacy(legacy);
878
+ const projectRequest = ArcProjectRequest.fromRequest(request.toJSON(), this.project);
879
+ return this.addRequest(projectRequest);
880
+ }
881
+ }
882
+
883
+ export class ArcProject extends ArcProjectParent {
884
+ /**
885
+ * Timestamp when the project was last updated.
886
+ */
887
+ updated: number = Date.now();
888
+
889
+ /**
890
+ * Timestamp when the project was created.
891
+ */
892
+ created: number = Date.now();
893
+
894
+ definitions: ArcProjectDefinitions;
895
+
896
+ /**
897
+ * Creates a new ARC project from a name.
898
+ * @param name The name to set.
899
+ */
900
+ static fromName(name: string): ArcProject {
901
+ const project = new ArcProject();
902
+ const info = Thing.fromName(name);
903
+ project.info = info;
904
+ return project;
905
+ }
906
+
907
+ /**
908
+ * Creates an HTTP project instance from ARC's legacy project definition.
909
+ *
910
+ * Note, the `requests` should be processed and the payload restored to it's original value.
911
+ */
912
+ static async fromLegacyProject(project: ARCProject, requests: ARCSavedRequest[]): Promise<ArcProject> {
913
+ const { name = 'Unnamed project', description, requests: ids } = project;
914
+ const result = ArcProject.fromName(name);
915
+ if (project._id) {
916
+ result.key = project._id;
917
+ }
918
+ if (description) {
919
+ result.info.description = description;
920
+ }
921
+ if (Array.isArray(ids) && ids.length) {
922
+ const promises = ids.map(async (id) => {
923
+ const old = requests.find((item) => item._id === id);
924
+ if (!old) {
925
+ return;
926
+ }
927
+ const request = await Request.fromLegacy(old);
928
+ const projectRequest = ArcProjectRequest.fromRequest(request.toJSON(), result);
929
+ if (old._id) {
930
+ projectRequest.key = old._id;
931
+ }
932
+ result.addRequest(projectRequest);
933
+ });
934
+ await Promise.allSettled(promises);
935
+ }
936
+ return result;
937
+ }
938
+
939
+ constructor(input?: string | IArcProject) {
940
+ super(ArcProjectKind);
941
+ this.definitions = {
942
+ folders: [],
943
+ requests: [],
944
+ };
945
+ let init: IArcProject;
946
+ if (typeof input === 'string') {
947
+ init = JSON.parse(input);
948
+ } else if (typeof input === 'object') {
949
+ init = input;
950
+ if (!init.kind) {
951
+ init.kind = ArcProjectKind;
952
+ }
953
+ } else {
954
+ init = {
955
+ kind: ArcProjectKind,
956
+ key: v4(),
957
+ definitions: {},
958
+ items: [],
959
+ info: Thing.fromName('').toJSON(),
960
+ }
961
+ }
962
+ this.new(init);
963
+ }
964
+
965
+ new(init: IArcProject): void {
966
+ if (!init || !init.items) {
967
+ throw new Error(`Not a project.`);
968
+ }
969
+ const { key = v4(), definitions = {}, items, info, created = Date.now(), updated = Date.now() } = init;
970
+ this.key = key;
971
+ this.created = created;
972
+ this.updated = updated;
973
+ if (info) {
974
+ this.info = new Thing(info);
975
+ } else {
976
+ this.info = Thing.fromName('');
977
+ }
978
+ this.setItems(items);
979
+ this.definitions = {
980
+ folders: [],
981
+ requests: [],
982
+ };
983
+ if (Array.isArray(definitions.requests)) {
984
+ this.definitions.requests = definitions.requests.map(i => {
985
+ const instance = new ArcProjectRequest(this, i);
986
+ return instance;
987
+ });
988
+ }
989
+ if (Array.isArray(definitions.folders)) {
990
+ this.definitions.folders = definitions.folders.map(i => {
991
+ const instance = new ArcProjectFolder(this, i);
992
+ return instance;
993
+ });
994
+ }
995
+ }
996
+
997
+ toJSON(): IArcProject {
998
+ const result: IArcProject = {
999
+ kind: ArcProjectKind,
1000
+ key: this.key,
1001
+ definitions: {},
1002
+ items: [],
1003
+ info: this.info.toJSON(),
1004
+ };
1005
+ if (Array.isArray(this.definitions.requests) && this.definitions.requests.length) {
1006
+ result.definitions.requests = this.definitions.requests.map(i => i.toJSON());
1007
+ }
1008
+ if (Array.isArray(this.definitions.folders) && this.definitions.folders.length) {
1009
+ result.definitions.folders = this.definitions.folders.map(i => i.toJSON());
1010
+ }
1011
+ if (Array.isArray(this.items) && this.items.length) {
1012
+ result.items = this.items.map(i => i.toJSON());
1013
+ }
1014
+ return result;
1015
+ }
1016
+
1017
+ setItems(items?: IArcProjectItem[]): void {
1018
+ if (Array.isArray(items)) {
1019
+ this.items = items.map(i => new ArcProjectItem(this, i));
1020
+ } else {
1021
+ this.items = [];
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Finds a parent of a definition.
1027
+ *
1028
+ * @param key The key of the definition.
1029
+ * @returns The parent or undefine when not found.
1030
+ */
1031
+ findParent(key: string): ArcProjectFolder | ArcProject | undefined {
1032
+ const { definitions, items = [] } = this;
1033
+ const projectItemsIndex = items.findIndex(i => i.key === key);
1034
+ if (projectItemsIndex > -1) {
1035
+ return this;
1036
+ }
1037
+ const definition = definitions.folders.find(i => i.items.some(item => item.key === key));
1038
+ if (definition) {
1039
+ return definition;
1040
+ }
1041
+ return undefined;
1042
+ }
1043
+
1044
+ /**
1045
+ * Appends an instance of a folder to a project.
1046
+ *
1047
+ * @param folder The folder to add to this project.
1048
+ * @param opts Optional folder add options.
1049
+ * @returns The added folder.
1050
+ */
1051
+ addFolder(folder: ArcProjectFolder, opts?: IArcFolderCreateOptions): ArcProjectFolder;
1052
+
1053
+ /**
1054
+ * Appends new folder to a project from a full folder schema.
1055
+ * This is primarily used to insert a folder on the client side
1056
+ * after a folder was created in the store.
1057
+ *
1058
+ * @param folder The folder schema to add to this project.
1059
+ * @param opts Optional folder add options.
1060
+ * @returns The added folder.
1061
+ */
1062
+ addFolder(folder: IProjectParent, opts?: IArcFolderCreateOptions): ArcProjectFolder;
1063
+
1064
+ /**
1065
+ * Appends a new folder to the project or a sub-folder.
1066
+ *
1067
+ * @param name The name to set. Optional.
1068
+ * @param opts Folder create options.
1069
+ * @returns The newly inserted folder. If the folder already existed it returns its instance.
1070
+ */
1071
+ addFolder(name?: string, opts?: IArcFolderCreateOptions): ArcProjectFolder;
1072
+
1073
+ /**
1074
+ * Appends a new folder to the project or a sub-folder.
1075
+ *
1076
+ * Passing the folder schema as the fist argument is primarily used to insert a folder on the client side
1077
+ * after a folder was created in the store.
1078
+ *
1079
+ * @param init The name or a folder schema. When not set a default name is assumed.
1080
+ * @param opts Folder create options.
1081
+ * @returns The newly inserted folder. If the folder already existed it returns its instance.
1082
+ */
1083
+ addFolder(init: string | IProjectParent | ArcProjectFolder = 'New Folder', opts: IArcFolderCreateOptions = {}): ArcProjectFolder {
1084
+ if (!Array.isArray(this.items)) {
1085
+ this.items = [];
1086
+ }
1087
+ if (!Array.isArray(this.definitions.folders)) {
1088
+ this.definitions.folders = [];
1089
+ }
1090
+ const { skipExisting, parent } = opts;
1091
+ let root: ArcProjectFolder | ArcProject;
1092
+ if (parent) {
1093
+ const rootCandidate = this.findFolder(parent);
1094
+ if (!rootCandidate) {
1095
+ throw new Error(`Unable to find the parent folder ${parent}`);
1096
+ }
1097
+ root = rootCandidate;
1098
+ } else {
1099
+ root = this;
1100
+ }
1101
+ let definition: ArcProjectFolder;
1102
+ if (typeof init === 'string') {
1103
+ definition = ArcProjectFolder.fromName(this, init);
1104
+ } else if (init instanceof ArcProjectFolder) {
1105
+ definition = init;
1106
+ } else {
1107
+ definition = new ArcProjectFolder(this, init);
1108
+ }
1109
+ if (skipExisting) {
1110
+ const folders = root.listFolderItems();
1111
+ for (const item of folders) {
1112
+ const existing = this.findFolder(item.key, { keyOnly: true });
1113
+ if (existing && existing.info.name === definition.info.name) {
1114
+ return existing;
1115
+ }
1116
+ }
1117
+ }
1118
+
1119
+ this.definitions.folders.push(definition);
1120
+ const item = ArcProjectItem.projectFolder(this, definition.key);
1121
+ if (!Array.isArray(root.items)) {
1122
+ root.items = [];
1123
+ }
1124
+ if (typeof opts.index === 'number') {
1125
+ root.items.splice(opts.index, 0, item);
1126
+ } else {
1127
+ root.items.push(item);
1128
+ }
1129
+ return definition;
1130
+ }
1131
+
1132
+ /**
1133
+ * Searches for a folder in the structure.
1134
+ *
1135
+ * @param nameOrKey The name or the key of the folder.
1136
+ * @param opts Optional search options.
1137
+ * @returns Found project folder or undefined.
1138
+ */
1139
+ findFolder(nameOrKey: string, opts: IArcFolderSearchOptions = {}): ArcProjectFolder | undefined {
1140
+ const { definitions } = this;
1141
+ const item = definitions.folders.find((i) => {
1142
+ if (i.kind !== ArcProjectFolderKind) {
1143
+ return false;
1144
+ }
1145
+ const folder = (i as ArcProjectFolder);
1146
+ if (folder.key === nameOrKey) {
1147
+ return true;
1148
+ }
1149
+ if (opts.keyOnly) {
1150
+ return false;
1151
+ }
1152
+ return !!folder.info && folder.info.name === nameOrKey;
1153
+ });
1154
+ if (item) {
1155
+ return item as ArcProjectFolder;
1156
+ }
1157
+ return undefined;
1158
+ }
1159
+
1160
+ /**
1161
+ * Removes a folder from the project.
1162
+ * @param key The folder key. It ignores the name when searching to the folder to avoid ambiguity.
1163
+ * @param opts Folder remove options.
1164
+ * @returns The removed folder definition or undefined when not removed.
1165
+ */
1166
+ removeFolder(key: string, opts: IArcFolderDeleteOptions = {}): ArcProjectFolder | undefined {
1167
+ const { definitions } = this;
1168
+ const folder = this.findFolder(key, { keyOnly: true });
1169
+ if (!folder) {
1170
+ if (opts.safe) {
1171
+ return undefined;
1172
+ }
1173
+ throw new Error(`Unable to find the folder ${key}`);
1174
+ }
1175
+ const parent = this.findParent(key);
1176
+ if (!parent) {
1177
+ if (opts.safe) {
1178
+ return undefined;
1179
+ }
1180
+ throw new Error(`Unable to find a parent of the folder ${key}`);
1181
+ }
1182
+
1183
+ const requests = folder.listRequests();
1184
+ requests.forEach(r => r.remove());
1185
+ const folders = folder.listFolders();
1186
+ folders.forEach(f => f.remove());
1187
+
1188
+ const itemIndex = parent.items.findIndex(i => i.key === key);
1189
+ const definitionIndex = definitions.folders.findIndex(i => i.key === key);
1190
+ definitions.folders.splice(definitionIndex, 1);
1191
+ if (itemIndex >= 0) {
1192
+ parent.items.splice(itemIndex, 1);
1193
+ }
1194
+ return folder;
1195
+ }
1196
+
1197
+ /**
1198
+ * Moves a folder between folders and the project or between items inside a folder or a project
1199
+ *
1200
+ * Note, when the `parent` option is not specified it moved the folder to the project's root.
1201
+ *
1202
+ * @param key The key of the request to move.
1203
+ * @param opts The moving options.
1204
+ */
1205
+ moveFolder(key: string, opts: IArcProjectMoveOptions = {}): void {
1206
+ const { index, parent } = opts;
1207
+ const movedFolder = this.findFolder(key);
1208
+ if (!movedFolder) {
1209
+ throw new Error(`Unable to locate the folder ${key}`);
1210
+ }
1211
+ const parentFolder = this.findParent(key);
1212
+ if (!parentFolder) {
1213
+ throw new Error(`Unable to locate a parent of the folder ${key}`);
1214
+ }
1215
+ if (parent) {
1216
+ // check if moving a folder into another folder that is a child of the moved folder.
1217
+ if (this.hasChild(parent, key)) {
1218
+ throw new RangeError(`Unable to move a folder to its child.`);
1219
+ }
1220
+ }
1221
+ const target = parent ? this.findFolder(parent) : this;
1222
+ if (!target) {
1223
+ throw new Error(`Unable to locate the new parent folder ${parent}`);
1224
+ }
1225
+ const hasIndex = typeof index === 'number';
1226
+ if (hasIndex) {
1227
+ // comparing to the `.length` and not `.length - 1` in case we are adding at the end.
1228
+ const maxIndex = Math.max(target.items.length, 0);
1229
+ if (index > maxIndex) {
1230
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
1231
+ }
1232
+ }
1233
+
1234
+ const itemIndex = parentFolder.items.findIndex(i => i.key === key);
1235
+ const item = parentFolder.items.splice(itemIndex, 1)[0];
1236
+
1237
+ if (hasIndex && target.items.length > index) {
1238
+ target.items.splice(index, 0, item);
1239
+ } else {
1240
+ target.items.push(item);
1241
+ }
1242
+ }
1243
+
1244
+ /**
1245
+ * Checks whether a folder has a child (anywhere down the structure).
1246
+ *
1247
+ * @param child The **key** of the child.
1248
+ * @param folder The **key** of the folder. When not set it searches from the project root.
1249
+ * @returns True when the child is located somewhere down the structure.
1250
+ */
1251
+ hasChild(child: string, folder?: string): boolean {
1252
+ const target = folder ? this.findFolder(folder) : this;
1253
+ if (!target) {
1254
+ throw new Error(`Unable to locate the folder ${folder}`);
1255
+ }
1256
+ const { items = [] } = target;
1257
+ for (const item of items) {
1258
+ if (item.key === child) {
1259
+ return true;
1260
+ }
1261
+ if (item.kind === ArcProjectFolderKind) {
1262
+ const hasChild = this.hasChild(child, item.key);
1263
+ if (hasChild) {
1264
+ return true;
1265
+ }
1266
+ }
1267
+ }
1268
+ return false;
1269
+ }
1270
+
1271
+ /**
1272
+ * Adds a request to the project or a sub-folder.
1273
+ *
1274
+ * @param url The URL of the request.
1275
+ * @param opts The request add options.
1276
+ * @returns The inserted into the definitions request.
1277
+ */
1278
+ addRequest(url: string, opts?: IArcRequestAddOptions): ArcProjectRequest;
1279
+
1280
+ /**
1281
+ * Adds a request to the project or a sub-folder.
1282
+ *
1283
+ * @param request The request to add.
1284
+ * @param opts The request add options.
1285
+ * @returns The inserted into the definitions request.
1286
+ */
1287
+ addRequest(request: IArcProjectRequest | ArcProjectRequest, opts?: IArcRequestAddOptions): ArcProjectRequest;
1288
+
1289
+ /**
1290
+ * Adds a request to the project or a sub-folder.
1291
+ * @param request The request to add.
1292
+ * @param opts Thew request add options.
1293
+ * @returns The inserted into the definitions request.
1294
+ */
1295
+ addRequest(request: IArcProjectRequest | ArcProjectRequest | string, opts: IArcRequestAddOptions = {}): ArcProjectRequest {
1296
+ if (!Array.isArray(this.definitions.requests)) {
1297
+ this.definitions.requests = [];
1298
+ }
1299
+
1300
+ // the request can be already added to the project as the same method is used to refresh a request after
1301
+ // a store update. From the system perspective it is the same event.
1302
+
1303
+ if (typeof request === 'object' && request.key) {
1304
+ const existing = this.definitions.requests.find(i => i.key === request.key);
1305
+ if (existing) {
1306
+ existing.new(request as IArcProjectRequest);
1307
+ return existing;
1308
+ }
1309
+ }
1310
+
1311
+ // if we got here, it means that we are adding a new request object to the project.
1312
+
1313
+ let finalRequest;
1314
+ if (typeof request === 'string') {
1315
+ finalRequest = ArcProjectRequest.fromUrl(request, this);
1316
+ } else if (request instanceof ArcProjectRequest) {
1317
+ finalRequest = request;
1318
+ finalRequest.project = this;
1319
+ } else {
1320
+ finalRequest = new ArcProjectRequest(this, request);
1321
+ }
1322
+ if (!finalRequest.key) {
1323
+ finalRequest.key = v4();
1324
+ }
1325
+
1326
+ let root: ArcProjectFolder | ArcProject;
1327
+ if (opts.parent) {
1328
+ const rootCandidate = this.findFolder(opts.parent);
1329
+ if (!rootCandidate) {
1330
+ throw new Error(`Unable to find the parent folder ${opts.parent}.`);
1331
+ }
1332
+ root = rootCandidate;
1333
+ } else {
1334
+ root = this;
1335
+ }
1336
+
1337
+ if (!Array.isArray(root.items)) {
1338
+ root.items = [];
1339
+ }
1340
+
1341
+ if (typeof opts.index === 'number') {
1342
+ const maxIndex = Math.max(root.items.length - 1, 0);
1343
+ if (opts.index > maxIndex) {
1344
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
1345
+ }
1346
+ }
1347
+
1348
+ this.definitions.requests.push(finalRequest);
1349
+ const item = ArcProjectItem.projectRequest(this, finalRequest.key);
1350
+
1351
+ if (typeof opts.index === 'number') {
1352
+ root.items.splice(opts.index, 0, item);
1353
+ } else {
1354
+ root.items.push(item);
1355
+ }
1356
+ return finalRequest;
1357
+ }
1358
+
1359
+ /**
1360
+ * Adds a request to the project that has been created for a previous version of ARC.
1361
+ *
1362
+ * @param legacy The legacy request definition.
1363
+ * @returns The created project request.
1364
+ */
1365
+ async addLegacyRequest(legacy: ARCSavedRequest | ARCHistoryRequest): Promise<ArcProjectRequest> {
1366
+ const request = await Request.fromLegacy(legacy);
1367
+ const projectRequest = ArcProjectRequest.fromRequest(request.toJSON(), this);
1368
+ return this.addRequest(projectRequest);
1369
+ }
1370
+
1371
+ /**
1372
+ * Searches for a request in the project.
1373
+ *
1374
+ * @param nameOrKey The name or the key of the request.
1375
+ * @param opts Optional search options.
1376
+ * @returns Found project request or undefined.
1377
+ */
1378
+ findRequest(nameOrKey: string, opts: IArcRequestSearchOptions = {}): ArcProjectRequest | undefined {
1379
+ const { definitions } = this;
1380
+ const item = definitions.requests.find((request) => {
1381
+ if (request.key === nameOrKey) {
1382
+ return true;
1383
+ }
1384
+ if (opts.keyOnly) {
1385
+ return false;
1386
+ }
1387
+ return !!request.info && request.info.name === nameOrKey;
1388
+ });
1389
+ if (item) {
1390
+ return item as ArcProjectRequest;
1391
+ }
1392
+ return undefined;
1393
+ }
1394
+
1395
+ /**
1396
+ * Removes a request from the project.
1397
+ *
1398
+ * @param key The request key. It ignores the name when searching to the request to avoid ambiguity.
1399
+ * @param opts Request remove options.
1400
+ * @returns The removed request definition or undefined when not removed.
1401
+ */
1402
+ removeRequest(key: string, opts: IArcRequestDeleteOptions = {}): ArcProjectRequest | undefined {
1403
+ const { definitions } = this;
1404
+ const request = this.findRequest(key, { keyOnly: true });
1405
+ if (!request) {
1406
+ if (opts.safe) {
1407
+ return undefined;
1408
+ }
1409
+ throw new Error(`Unable to find the request ${key}`);
1410
+ }
1411
+ const parent = this.findParent(key);
1412
+ if (!parent) {
1413
+ if (opts.safe) {
1414
+ return undefined;
1415
+ }
1416
+ throw new Error(`Unable to find a parent of the request ${key}`);
1417
+ }
1418
+ const itemIndex = parent.items.findIndex(i => i.key === key);
1419
+ const definitionIndex = definitions.requests.findIndex(i => i.key === key);
1420
+ definitions.requests.splice(definitionIndex, 1);
1421
+ if (itemIndex >= 0) {
1422
+ parent.items.splice(itemIndex, 1);
1423
+ }
1424
+ return request;
1425
+ }
1426
+
1427
+ /**
1428
+ * Moves a request between folders and the project or between items inside a folder or a project.
1429
+ *
1430
+ * Note, when the `parent` option is not specified it moved the request to the project's root.
1431
+ *
1432
+ * @param key The key of the request to move.
1433
+ * @param opts The moving options.
1434
+ */
1435
+ moveRequest(key: string, opts: IArcProjectMoveOptions = {}): void {
1436
+ const { index, parent } = opts;
1437
+ const request = this.findRequest(key);
1438
+ if (!request) {
1439
+ throw new Error(`Unable to locate the request ${key}`);
1440
+ }
1441
+ const parentFolder = this.findParent(key);
1442
+ if (!parentFolder) {
1443
+ throw new Error(`Unable to locate a parent of the request ${key}`);
1444
+ }
1445
+ const target = parent ? this.findFolder(parent) : this;
1446
+ if (!target) {
1447
+ throw new Error(`Unable to locate the new parent folder ${parent}`);
1448
+ }
1449
+ const hasIndex = typeof index === 'number';
1450
+ if (hasIndex) {
1451
+ // comparing to the `.length` and not `.length - 1` in case we are adding at the end.
1452
+ const maxIndex = Math.max(target.items.length, 0);
1453
+ if (index > maxIndex) {
1454
+ throw new RangeError(`Index out of bounds. Maximum index is ${maxIndex}.`);
1455
+ }
1456
+ }
1457
+
1458
+ const itemIndex = parentFolder.items.findIndex(i => i.key === key);
1459
+ const item = parentFolder.items.splice(itemIndex, 1)[0];
1460
+
1461
+ if (hasIndex && target.items.length > index) {
1462
+ target.items.splice(index, 0, item);
1463
+ } else {
1464
+ target.items.push(item);
1465
+ }
1466
+ }
1467
+
1468
+ /**
1469
+ * Lists items (not the actual definitions!) that are folders.
1470
+ */
1471
+ listFolderItems(): ArcProjectItem[] {
1472
+ const { items = [] } = this;
1473
+ return items.filter(i => i.kind === ArcProjectFolderKind);
1474
+ }
1475
+
1476
+ /**
1477
+ * Lists items (not the actual definitions!) that are requests.
1478
+ */
1479
+ listRequestItems(): ArcProjectItem[] {
1480
+ const { items = [] } = this;
1481
+ return items.filter(i => i.kind === ArcProjectRequestKind);
1482
+ }
1483
+
1484
+ /**
1485
+ * Lists folders from the project or a sub-folder.
1486
+ * @param opts Folder listing options.
1487
+ */
1488
+ listFolders(opts: IArcFolderListOptions = {}): ArcProjectFolder[] {
1489
+ let root;
1490
+ if (opts.folder) {
1491
+ const parent = this.findFolder(opts.folder);
1492
+ if (!parent) {
1493
+ throw new Error(`Unable to find the folder ${opts.folder}.`);
1494
+ }
1495
+ root = parent;
1496
+ } else {
1497
+ root = this;
1498
+ }
1499
+ const items = root.listFolderItems();
1500
+ const result: ArcProjectFolder[] = [];
1501
+ const { definitions } = this;
1502
+ items.forEach((i) => {
1503
+ const definition = definitions.folders.find(d => i.key === d.key);
1504
+ if (definition) {
1505
+ result.push(definition);
1506
+ }
1507
+ });
1508
+ return result;
1509
+ }
1510
+
1511
+ /**
1512
+ * Lists requests in this project or a sub-folder.
1513
+ * @param folder The optional folder name or the key to list requests for.
1514
+ */
1515
+ listRequests(folder?: string): ArcProjectRequest[] {
1516
+ let root;
1517
+ if (folder) {
1518
+ const parent = this.findFolder(folder);
1519
+ if (!parent) {
1520
+ throw new Error(`Unable to find the folder ${folder}.`);
1521
+ }
1522
+ root = parent;
1523
+ } else {
1524
+ root = this;
1525
+ }
1526
+ const items = root.listRequestItems();
1527
+ const result: ArcProjectRequest[] = [];
1528
+ const { definitions } = this;
1529
+ items.forEach((i) => {
1530
+ const definition = definitions.requests.find(d => i.key === d.key);
1531
+ if (definition) {
1532
+ result.push(definition);
1533
+ }
1534
+ });
1535
+ return result;
1536
+ }
1537
+
1538
+ /**
1539
+ * Lists definitions for the `items` of the project or a folder.
1540
+ * @param folder Optionally the folder name to list the definitions for.
1541
+ */
1542
+ listDefinitions(folder?: string): (ArcProjectFolder | ArcProjectRequest)[] {
1543
+ let root;
1544
+ if (folder) {
1545
+ const parent = this.findFolder(folder);
1546
+ if (!parent) {
1547
+ throw new Error(`Unable to find the folder ${folder}`);
1548
+ }
1549
+ root = parent;
1550
+ } else {
1551
+ root = this;
1552
+ }
1553
+ const result: (ArcProjectFolder | ArcProjectRequest)[] = [];
1554
+ const { items = [] } = root;
1555
+ const { definitions } = this;
1556
+ items.forEach((item) => {
1557
+ let definition: ArcProjectFolder | ArcProjectRequest | undefined;
1558
+ if (item.kind === ArcProjectFolderKind) {
1559
+ definition = definitions.folders.find(d => item.key === d.key);
1560
+ } else if (item.kind === ArcProjectRequestKind) {
1561
+ definition = definitions.requests.find(d => item.key === d.key);
1562
+ }
1563
+ if (definition) {
1564
+ result.push(definition);
1565
+ }
1566
+ });
1567
+ return result;
1568
+ }
1569
+
1570
+ /**
1571
+ * @returns On the project level this always returns undefined.
1572
+ */
1573
+ getParent(): ArcProjectFolder | ArcProject | undefined {
1574
+ return undefined;
1575
+ }
1576
+
1577
+ getProject(): ArcProject {
1578
+ return this;
1579
+ }
1580
+
1581
+ /**
1582
+ * Makes a copy of this project.
1583
+ */
1584
+ clone(opts: IArcProjectCloneOptions = {}): ArcProject {
1585
+ const copy = new ArcProject(this.toJSON());
1586
+ if (!opts.withoutRevalidate) {
1587
+ copy.key = v4();
1588
+ ArcProject.regenerateKeys(copy);
1589
+ }
1590
+ return copy;
1591
+ }
1592
+
1593
+ static clone(project: IArcProject, opts: IArcProjectCloneOptions = {}): ArcProject {
1594
+ const obj = new ArcProject(project);
1595
+ return obj.clone(opts);
1596
+ }
1597
+
1598
+ /**
1599
+ * Re-generates keys in the project, taking care of the references.
1600
+ *
1601
+ * Note, this changes the project properties. Make a copy of the project before calling this.
1602
+ *
1603
+ * @param src The project instance to re-generate keys for.
1604
+ */
1605
+ static regenerateKeys(src: ArcProject): void {
1606
+ const { items = [], definitions } = src;
1607
+ // create a flat list of all "items" in the project and all folders.
1608
+ let flatItems = [...items];
1609
+ (definitions.folders || []).forEach((folder) => {
1610
+ if (Array.isArray(folder.items) && folder.items.length) {
1611
+ flatItems = flatItems.concat(folder.items);
1612
+ }
1613
+ });
1614
+ (definitions.folders || []).forEach((folder) => {
1615
+ // if (Array.isArray(folder.environments) && folder.environments.length) {
1616
+ // withEnvironments.push(folder);
1617
+ // }
1618
+ const oldKey = folder.key;
1619
+ const indexObject = flatItems.find(i => i.key === oldKey);
1620
+ if (!indexObject) {
1621
+ return;
1622
+ }
1623
+ const newKey = v4();
1624
+ indexObject.key = newKey;
1625
+ folder.key = newKey;
1626
+ });
1627
+ (definitions.requests || []).forEach((request) => {
1628
+ const oldKey = request.key;
1629
+ const indexObject = flatItems.find(i => i.key === oldKey);
1630
+ if (!indexObject) {
1631
+ return;
1632
+ }
1633
+ const newKey = v4();
1634
+ indexObject.key = newKey;
1635
+ request.key = newKey;
1636
+ });
1637
+ }
1638
+ }