@vcd/sdk 15.0.7 → 17.0.0

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 (38) hide show
  1. package/{esm2020 → esm2022}/client/client/api.result.service.mjs +4 -4
  2. package/esm2022/client/client/logging.interceptor.mjs +44 -0
  3. package/esm2022/client/client/request.headers.interceptor.mjs +100 -0
  4. package/esm2022/client/client/response.normalization.interceptor.mjs +59 -0
  5. package/esm2022/client/client/vcd.api.client.mjs +603 -0
  6. package/{esm2020 → esm2022}/client/client/vcd.http.client.mjs +6 -6
  7. package/esm2022/client/client/vcd.transfer.client.mjs +166 -0
  8. package/esm2022/client/query/filter.builder.mjs +195 -0
  9. package/esm2022/client/query/query.builder.mjs +79 -0
  10. package/esm2022/common/container-hooks.mjs +85 -0
  11. package/{esm2020 → esm2022}/main.mjs +7 -7
  12. package/{fesm2020 → fesm2022}/vcd-sdk.mjs +54 -54
  13. package/{fesm2020 → fesm2022}/vcd-sdk.mjs.map +1 -1
  14. package/open_source_license_vcd_ui_sdk_17.0.0_ga.txt +393 -0
  15. package/package.json +8 -14
  16. package/VMware-vcd_ui_sdk-15.0.7-ODP.tar.gz +0 -0
  17. package/esm2020/client/client/logging.interceptor.mjs +0 -44
  18. package/esm2020/client/client/request.headers.interceptor.mjs +0 -100
  19. package/esm2020/client/client/response.normalization.interceptor.mjs +0 -59
  20. package/esm2020/client/client/vcd.api.client.mjs +0 -603
  21. package/esm2020/client/client/vcd.transfer.client.mjs +0 -166
  22. package/esm2020/client/query/filter.builder.mjs +0 -195
  23. package/esm2020/client/query/query.builder.mjs +0 -79
  24. package/esm2020/common/container-hooks.mjs +0 -85
  25. package/fesm2015/vcd-sdk.mjs +0 -1505
  26. package/fesm2015/vcd-sdk.mjs.map +0 -1
  27. package/open_source_license_@vcdsdk_15.0.7_GA.txt +0 -22623
  28. /package/{esm2020 → esm2022}/client/client/constants.mjs +0 -0
  29. /package/{esm2020 → esm2022}/client/client/index.mjs +0 -0
  30. /package/{esm2020 → esm2022}/client/client/types.mjs +0 -0
  31. /package/{esm2020 → esm2022}/client/index.mjs +0 -0
  32. /package/{esm2020 → esm2022}/client/openapi.mjs +0 -0
  33. /package/{esm2020 → esm2022}/client/query/index.mjs +0 -0
  34. /package/{esm2020 → esm2022}/common/index.mjs +0 -0
  35. /package/{esm2020 → esm2022}/core/index.mjs +0 -0
  36. /package/{esm2020 → esm2022}/core/plugin.module.mjs +0 -0
  37. /package/{esm2020 → esm2022}/public-api.mjs +0 -0
  38. /package/{esm2020 → esm2022}/vcd-sdk.mjs +0 -0
@@ -1,1505 +0,0 @@
1
- import * as i1 from '@angular/common/http';
2
- import { HttpResponse, HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
3
- import * as i0 from '@angular/core';
4
- import { Injectable, InjectionToken, Optional, Inject, NgModule } from '@angular/core';
5
- import { CommonModule } from '@angular/common';
6
- import { tap, finalize, map, catchError, switchMap, retry, flatMap, skipWhile, share, concatMap, filter, withLatestFrom } from 'rxjs/operators';
7
- import { Observable, throwError, BehaviorSubject, of, ReplaySubject, merge } from 'rxjs';
8
- import { TaskType } from '@vcd/bindings/vcloud/api/rest/schema_v1_5';
9
-
10
- // tslint:disable:variable-name
11
- // tslint:disable-next-line:no-namespace
12
- var Query;
13
- (function (Query) {
14
- class Builder {
15
- constructor() {
16
- this._format = Format.ID_RECORDS;
17
- this._links = true;
18
- this._pageSize = 25;
19
- }
20
- static getBuilder() {
21
- return new Builder();
22
- }
23
- static ofType(type) {
24
- const qb = new Builder();
25
- qb._type = type;
26
- return qb;
27
- }
28
- format(format) {
29
- this._format = format;
30
- return this;
31
- }
32
- links(links) {
33
- this._links = links;
34
- return this;
35
- }
36
- pageSize(pageSize) {
37
- this._pageSize = pageSize;
38
- return this;
39
- }
40
- fields(...fields) {
41
- this._fields = fields;
42
- return this;
43
- }
44
- filter(filter) {
45
- this._filter = filter;
46
- return this;
47
- }
48
- sort(...sort) {
49
- this._sort = sort;
50
- return this;
51
- }
52
- get() {
53
- let query = `?type=${this._type}&format=${this._format}&links=${this._links}&pageSize=${this._pageSize}`;
54
- if (this._fields && this._fields.length > 0) {
55
- query += `&fields=${this._fields.join(',')}`;
56
- }
57
- if (this._filter) {
58
- query += `&filter=${this._filter}`;
59
- }
60
- if (this._sort) {
61
- this._sort.forEach(s => {
62
- query += `&${s.reverse ? 'sortDesc' : 'sortAsc'}=${s.field}`;
63
- });
64
- }
65
- return query;
66
- }
67
- getCloudAPI() {
68
- let query = `?pageSize=${this._pageSize}`;
69
- if (this._filter) {
70
- query += `&filter=${this._filter}`;
71
- }
72
- if (this._sort) {
73
- this._sort.forEach(s => {
74
- query += `&${s.reverse ? 'sortDesc' : 'sortAsc'}=${s.field}`;
75
- });
76
- }
77
- return query;
78
- }
79
- }
80
- Query.Builder = Builder;
81
- class Format {
82
- }
83
- Format.ID_RECORDS = 'idrecords';
84
- Format.RECORDS = 'records';
85
- Format.REFERENCES = 'references';
86
- Query.Format = Format;
87
- })(Query || (Query = {}));
88
-
89
- // tslint:disable-next-line:no-namespace
90
- var Filter;
91
- (function (Filter) {
92
- class Operators {
93
- }
94
- Operators.OR = ',';
95
- Operators.AND = ';';
96
- Operators.GT = '=gt=';
97
- Operators.GE = '=ge=';
98
- Operators.LT = '=lt=';
99
- Operators.LE = '=le=';
100
- Operators.EQ = '==';
101
- Operators.NEQ = '!=';
102
- /**
103
- * Collection of strategies for wilcard string matching.
104
- */
105
- class MatchMode {
106
- }
107
- /**
108
- * Match the start of a string.
109
- */
110
- MatchMode.START = 'START';
111
- /**
112
- * Match the end of a string.
113
- */
114
- MatchMode.END = 'END';
115
- /**
116
- * Match anywhere in the string.
117
- */
118
- MatchMode.ANYWHERE = 'ANYWHERE';
119
- Filter.MatchMode = MatchMode;
120
- class BuilderChain {
121
- constructor(parent) {
122
- this.result = '';
123
- this.parent = parent;
124
- }
125
- query() {
126
- return this.buildPartial();
127
- }
128
- // tslint:disable-next-line:max-line-length
129
- and(condition1, condition2, conditionN) {
130
- if (!condition1) {
131
- return this.simpleAnd();
132
- }
133
- this.result += '(' + condition1.buildPartial() + Operators.AND + condition2.buildPartial();
134
- if (conditionN && conditionN.length) {
135
- conditionN.forEach((condition) => {
136
- this.result += Operators.AND + condition.buildPartial();
137
- });
138
- }
139
- this.result += ')';
140
- return this;
141
- }
142
- simpleAnd() {
143
- if (this.currentCompositeOp === Operators.OR || this.parent && this.parent.currentCompositeOp === Operators.OR) {
144
- if (this.parent) {
145
- this.parent.result = '(' + this.parent.result;
146
- this.result += ')';
147
- }
148
- else {
149
- this.wrap();
150
- }
151
- this.currentCompositeOp = Operators.AND;
152
- }
153
- this.result += Operators.AND;
154
- return this;
155
- }
156
- // tslint:disable-next-line:max-line-length
157
- or(condition1, condition2, conditionN) {
158
- if (!condition1) {
159
- return this.simpleOr();
160
- }
161
- this.result += '(' + condition1.buildPartial() + Operators.OR + condition2.buildPartial();
162
- if (conditionN && conditionN.length) {
163
- conditionN.forEach((condition) => {
164
- this.result += Operators.OR + condition.buildPartial();
165
- });
166
- }
167
- this.result += ')';
168
- return this;
169
- }
170
- simpleOr() {
171
- if (this.currentCompositeOp === Operators.AND || (this.parent && this.parent.currentCompositeOp === Operators.AND)) {
172
- if (this.parent) {
173
- this.parent.result = '(' + this.parent.result;
174
- this.result += ')';
175
- }
176
- else {
177
- this.wrap();
178
- }
179
- this.currentCompositeOp = Operators.OR;
180
- }
181
- this.result += Operators.OR;
182
- return this;
183
- }
184
- wrap() {
185
- this.result = '(' + this.result + ')';
186
- this.currentCompositeOp = null;
187
- return this;
188
- }
189
- buildPartial() {
190
- return (this.parent) ? this.parent.buildPartial() + this.result : this.result;
191
- }
192
- is(property) {
193
- const builder = new BuilderChain(this);
194
- builder.result = property;
195
- return builder;
196
- }
197
- equalTo(value, ...moreValues) {
198
- return this.condition(Operators.EQ, value, ...moreValues);
199
- }
200
- notEqualTo(value) {
201
- return this.condition(Operators.NEQ, value);
202
- }
203
- lessThan(value) {
204
- return this.condition(Operators.LT, value);
205
- }
206
- lessOrEqualTo(value) {
207
- return this.condition(Operators.LE, value);
208
- }
209
- greaterThan(value) {
210
- return this.condition(Operators.GT, value);
211
- }
212
- greaterOrEqualTo(value) {
213
- return this.condition(Operators.GE, value);
214
- }
215
- like(value, mode = MatchMode.START) {
216
- let wildcardValue;
217
- switch (mode) {
218
- case MatchMode.START:
219
- wildcardValue = `${value}*`;
220
- break;
221
- case MatchMode.END:
222
- wildcardValue = `*${value}`;
223
- break;
224
- case MatchMode.ANYWHERE:
225
- wildcardValue = `*${value}*`;
226
- break;
227
- default:
228
- wildcardValue = value;
229
- break;
230
- }
231
- return this.condition(Operators.EQ, wildcardValue);
232
- }
233
- condition(operator, value, ...moreValues) {
234
- const name = this.result;
235
- this.result += operator + encodeURI(value);
236
- if (moreValues.length) {
237
- moreValues.forEach((next) => {
238
- this.result += ',' + name + operator + encodeURI(next);
239
- });
240
- this.currentCompositeOp = Operators.OR;
241
- }
242
- return this;
243
- }
244
- }
245
- /**
246
- * Builds a FIQL search condition using a fluent interface.
247
- */
248
- class Builder {
249
- /**
250
- * Create a simple property to be evaulated as a filter condition.
251
- *
252
- * @param property the name of the property
253
- * @returns a Property instance for defining a filter condition
254
- */
255
- is(property) {
256
- return new BuilderChain().is(property);
257
- }
258
- /**
259
- * Create a conjunction (AND) condition from existing conditions.
260
- *
261
- * @param condition1 first condition
262
- * @param condition2 second condition
263
- * @param conditionN any additional conditions
264
- * @returns an evaluatable filter condition
265
- */
266
- and(condition1, condition2, conditionN) {
267
- return new BuilderChain().and(condition1, condition2, conditionN);
268
- }
269
- /**
270
- * Create a disjunction (OR) condition from existing conditions.
271
- *
272
- * @param condition1 first condition
273
- * @param condition2 second condition
274
- * @param conditionN any additional conditions
275
- * @returns an evaluatable filter condition
276
- */
277
- or(condition1, condition2, conditionN) {
278
- return new BuilderChain().or(condition1, condition2, conditionN);
279
- }
280
- }
281
- Filter.Builder = Builder;
282
- })(Filter || (Filter = {}));
283
-
284
- // tslint:disable:variable-name
285
- class ApiResultService {
286
- constructor() {
287
- this._results = [];
288
- }
289
- get results() {
290
- return this._results;
291
- }
292
- add(result) {
293
- this._results = [result, ...this._results.slice(0, 99)];
294
- }
295
- clear() {
296
- this._results = [];
297
- }
298
- }
299
- ApiResultService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: ApiResultService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
300
- ApiResultService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: ApiResultService });
301
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: ApiResultService, decorators: [{
302
- type: Injectable
303
- }] });
304
- class ApiResult {
305
- get message() {
306
- return this._message;
307
- }
308
- get succeeded() {
309
- return this._succeeded;
310
- }
311
- get started() {
312
- return this._started;
313
- }
314
- get finished() {
315
- return this._finished;
316
- }
317
- constructor(message, succeeded, started, finished) {
318
- this._message = message;
319
- this._succeeded = succeeded;
320
- this._started = started;
321
- this._finished = finished;
322
- }
323
- }
324
-
325
- /**
326
- * This is the currently supported - albeit very minimal - public SDK.
327
- */
328
- // Bind straight into the hooks provided by the container.
329
- if (!window.System || !window.System.registry || !window.System.registry.get) {
330
- throw new Error('SystemJS registry not found');
331
- }
332
- let containerHooks = window.System.registry.get('@vcd/common');
333
- if (!containerHooks) {
334
- containerHooks = window.System.registry.get('@vcd-ui/common');
335
- }
336
- if (!containerHooks) {
337
- throw new Error('VCD UI container hooks not present in SystemJS registry');
338
- }
339
- /**
340
- * Wire in as a string. Gives the root URL for API access (for example, the load balancer URL
341
- * or the single-cell URL).
342
- */
343
- const API_ROOT_URL = containerHooks.API_ROOT_URL;
344
- /**
345
- * Wire in as a string. Gives the root URL for the legacy Flex application.
346
- */
347
- const FLEX_APP_URL = containerHooks.API_ROOT_URL;
348
- /**
349
- * Wire in as a string. Gives the current scope of the VCD-UI. As of current, this will be
350
- * either 'tenant' for the tenant portal, or 'service-provider' for the service-provider portal.
351
- */
352
- const SESSION_SCOPE = containerHooks.SESSION_SCOPE;
353
- /**
354
- * Wire in as a string. Gives the unique name (not the display name) of the current tenant
355
- * organization that the VCD-UI is being used for.
356
- */
357
- const SESSION_ORGANIZATION = containerHooks.SESSION_ORGANIZATION;
358
- /**
359
- * Wire in as a string. Gives the UUID identifier of the current tenant
360
- * organization that the VCD-UI is being used for.
361
- */
362
- const SESSION_ORG_ID = containerHooks.SESSION_ORG_ID ? containerHooks.SESSION_ORG_ID : '';
363
- /**
364
- * Wire in as a string. Gives the full root path for module assets (e.g. images, scripts, text files)
365
- *
366
- * ATTENTION!
367
- * Add || new InjectionToken to workaround the Angular security mechanics which prevent use of injection tokens
368
- * which potentially are not defiend. The same fix can be applied for the rest tokens if needed.
369
- */
370
- const EXTENSION_ASSET_URL = containerHooks.EXTENSION_ASSET_URL || new InjectionToken('EXTENSION_ASSET_URL');
371
- /**
372
- * Wire in as a string. Gives the Angular 2 route that the module is registered under.
373
- */
374
- const EXTENSION_ROUTE = containerHooks.EXTENSION_ROUTE;
375
- /**
376
- * Wire in as a boolean. True if running under the SDK, false if running in production.
377
- */
378
- const SDK_MODE = containerHooks.SDK_MODE;
379
- const ExtensionNavRegistrationAction = containerHooks.ExtensionNavRegistrationAction;
380
- const AuthTokenHolderService = containerHooks.AuthTokenHolderService;
381
- /**
382
- * Every component referenced by an entity action extension point must inherit from this.
383
- */
384
- // tslint:disable-next-line:class-name
385
- class _EntityActionExtensionComponent {
386
- }
387
- const EntityActionExtensionComponent = containerHooks.EntityActionExtensionComponent;
388
- // tslint:disable-next-line:class-name
389
- class _WizardExtensionComponent {
390
- }
391
- const WizardExtensionComponent = containerHooks.WizardExtensionComponent;
392
- // tslint:disable-next-line:class-name
393
- class _WizardExtensionWithValidationComponent extends _WizardExtensionComponent {
394
- }
395
- // tslint:disable-next-line:max-line-length
396
- const WizardExtensionWithValidationComponent = containerHooks.WizardExtensionWithValidationComponent;
397
- /**
398
- * Every component-based Extension Point that is renderd in Cloud Director UI Entity Details
399
- * must extend that class to obtain context about the Entity.
400
- *
401
- * See comments of the methods of the abstract class for more information.
402
- */
403
- // tslint:disable-next-line:class-name
404
- class _WizardExtensionWithContextComponent extends _WizardExtensionComponent {
405
- }
406
- // tslint:disable-next-line:max-line-length
407
- const WizardExtensionWithContextComponent = containerHooks.WizardExtensionWithContextComponent;
408
-
409
- class PluginModule {
410
- constructor(appStore) {
411
- this.appStore = appStore;
412
- }
413
- registerExtension(extension) {
414
- this.appStore.dispatch(new ExtensionNavRegistrationAction(extension));
415
- }
416
- }
417
- /**
418
- * Config object that is passed on VcdSdkModule init
419
- * using .forRoot() method. It can be used to store
420
- * configutration properties that are later used by the Services
421
- * provided.
422
- */
423
- class VcdSdkConfig {
424
- }
425
- /**
426
- * Use this token for injecting custom HttpInterceptor implementations inside the HttpClient
427
- */
428
- const VCD_HTTP_INTERCEPTORS = new InjectionToken("VCD_HTTP_INTERCEPTORS");
429
-
430
- // tslint:disable:variable-name
431
- class LoggingInterceptor {
432
- set enabled(enabled) {
433
- this._enabled = enabled;
434
- if (this._enabled && this._outputToConsole) {
435
- console.warn('API logging enabled but no provider found for ApiResultService. Results will be output to the console.');
436
- }
437
- }
438
- constructor(apiResultService) {
439
- this.apiResultService = apiResultService;
440
- this._enabled = false;
441
- this._outputToConsole = !this.apiResultService;
442
- }
443
- intercept(req, next) {
444
- if (!this._enabled) {
445
- return next.handle(req);
446
- }
447
- const started = new Date();
448
- let succeeded;
449
- return next.handle(req)
450
- .pipe(tap(event => succeeded = event instanceof HttpResponse ? true : false, error => succeeded = false), finalize(() => {
451
- if (this._outputToConsole) {
452
- console.log(`${req.method} ${req.urlWithParams} completed in ${Date.now() - started.getTime()} ms. Success: ${succeeded}`);
453
- }
454
- else {
455
- this.apiResultService.add(new ApiResult(`${req.method} ${req.urlWithParams}`, succeeded, started, new Date()));
456
- }
457
- }));
458
- }
459
- }
460
- LoggingInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: LoggingInterceptor, deps: [{ token: ApiResultService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
461
- LoggingInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: LoggingInterceptor });
462
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: LoggingInterceptor, decorators: [{
463
- type: Injectable
464
- }], ctorParameters: function () {
465
- return [{ type: ApiResultService, decorators: [{
466
- type: Optional
467
- }] }];
468
- } });
469
-
470
- /**
471
- * HTTP Headers
472
- */
473
- const HTTP_HEADERS = Object.freeze({
474
- Authorization: 'Authorization',
475
- etag: 'etag',
476
- // Angular is dealing with case sensitive links despite the specification
477
- // https://github.com/angular/angular/issues/6142
478
- link: 'link',
479
- Link: 'Link',
480
- x_vcloud_authorization: 'x-vcloud-authorization'
481
- });
482
-
483
- // tslint:disable:variable-name
484
- class RequestHeadersInterceptor {
485
- constructor() {
486
- this._enabled = true;
487
- this._version = '';
488
- this._authenticationHeader = HTTP_HEADERS.Authorization;
489
- }
490
- set enabled(_enabled) {
491
- this._enabled = _enabled;
492
- }
493
- set actAs(_actAs) {
494
- this._actAs = _actAs;
495
- }
496
- set actAsOrgName(_actAsOrgName) {
497
- this._actAsOrgName = _actAsOrgName;
498
- }
499
- get version() {
500
- return this._version;
501
- }
502
- set version(_version) {
503
- this._version = _version;
504
- }
505
- set authentication(_authentication) {
506
- this._authentication = _authentication;
507
- this._authenticationHeader = (this._authentication && this._authentication.length > 32) ?
508
- HTTP_HEADERS.Authorization : HTTP_HEADERS.x_vcloud_authorization;
509
- }
510
- intercept(req, next) {
511
- let headers = req.headers;
512
- if (!headers.has('Accept')) {
513
- headers = this.setAcceptHeader(headers);
514
- }
515
- if (!headers.has('Content-Type')) {
516
- headers = this.setContentTypeHeader(headers, req.url);
517
- }
518
- if (this._authentication && !headers.has(HTTP_HEADERS.Authorization)) {
519
- headers = headers.set(this._authenticationHeader, this._authentication);
520
- }
521
- /**
522
- * Covers the case where the User set the ActAs token himself
523
- */
524
- if (!headers.has('X-VMWARE-VCLOUD-TENANT-CONTEXT') && this._actAs) {
525
- headers = headers.set('X-VMWARE-VCLOUD-TENANT-CONTEXT', this._actAs);
526
- }
527
- /**
528
- * Covers the case where the User set the ActAs token himself
529
- */
530
- if (!headers.has('X-VMWARE-VCLOUD-AUTH-CONTEXT') && this._actAsOrgName) {
531
- headers = headers.set('X-VMWARE-VCLOUD-AUTH-CONTEXT', this._actAsOrgName);
532
- }
533
- const customReq = req.clone({
534
- headers
535
- });
536
- return next.handle(customReq).pipe(map((res) => {
537
- if (res instanceof HttpResponse) {
538
- if (!res.body || !res.headers) {
539
- return res;
540
- }
541
- if (res.headers.has(HTTP_HEADERS.link)) {
542
- res.body.link = parseHeaderHateoasLinks(res.headers.get(HTTP_HEADERS.link));
543
- }
544
- if (res.headers.has(HTTP_HEADERS.Link)) {
545
- res.body.link = parseHeaderHateoasLinks(res.headers.get(HTTP_HEADERS.Link));
546
- }
547
- if (res.headers.has(HTTP_HEADERS.etag)) {
548
- res.body.etag = res.headers.get(HTTP_HEADERS.etag);
549
- }
550
- }
551
- return res;
552
- }));
553
- }
554
- setAcceptHeader(headers) {
555
- const value = headers.get('_multisite');
556
- headers = headers.delete('_multisite');
557
- return headers.set('Accept', [
558
- `application/*+json;version=${this._version}${value ? `;multisite=${value}` : ''}`,
559
- `application/json;version=${this._version}${value ? `;multisite=${value}` : ''}`
560
- ]);
561
- }
562
- setContentTypeHeader(headers, url) {
563
- if (url.indexOf('cloudapi') > -1) {
564
- return headers.set('Content-Type', 'application/json');
565
- }
566
- else {
567
- return headers.set('Content-Type', 'application/*+json');
568
- }
569
- }
570
- }
571
- RequestHeadersInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: RequestHeadersInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
572
- RequestHeadersInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: RequestHeadersInterceptor });
573
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: RequestHeadersInterceptor, decorators: [{
574
- type: Injectable
575
- }] });
576
-
577
- // tslint:disable:jsdoc-format
578
- /**
579
- * An interceptor on the response chain that normalizes differences in
580
- * JSON payloads between vCloud Director version 9.1 and versions
581
- * greater than 9.1.
582
- *
583
- * In 9.1 (API version 30.0) the server serializes JSON and nests the payload in a value field:
584
- * ```
585
- {
586
- "name" : "{http://www.vmware.com/vcloud/versions}SupportedVersions",
587
- "declaredType" : "com.vmware.vcloud.api.rest.schema.versioning.SupportedVersionsType",
588
- "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
589
- "value" : {
590
- "versionInfo" : [],
591
- "any" : [],
592
- "otherAttributes" : {}
593
- }
594
- }
595
- ```
596
- *
597
- * That same request in API versions 31.0 and above is represented as:
598
- * ```
599
- {
600
- "versionInfo" : [],
601
- "any" : [],
602
- "otherAttributes" : {}
603
- }
604
- ```
605
- * This interceptor should process responses before any other interceptors that rely
606
- * on consistent API information.
607
- */
608
- class ResponseNormalizationInterceptor {
609
- intercept(req, next) {
610
- return next.handle(req).pipe(map(response => {
611
- // While this condition seems awfully specific, the alternative option of examining the 'Content-Type'
612
- // response header for 'version=30.0' proved to be an unreliable condition in at least one case;
613
- // returning the same JSON payload as API versions >= 31.0.
614
- if (response instanceof HttpResponse && response.body && response.body.value && response.body.declaredType && response.body.scope) {
615
- const body = response.body.value;
616
- if (response.body.declaredType === ResponseNormalizationInterceptor.QUERY_RESULT_TYPE) {
617
- body.record = body.record.map(record => record.value);
618
- }
619
- return response.clone({ body });
620
- }
621
- return response;
622
- }));
623
- }
624
- }
625
- ResponseNormalizationInterceptor.QUERY_RESULT_TYPE = 'com.vmware.vcloud.api.rest.schema_v1_5.QueryResultRecordsType';
626
- ResponseNormalizationInterceptor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: ResponseNormalizationInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
627
- ResponseNormalizationInterceptor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: ResponseNormalizationInterceptor });
628
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: ResponseNormalizationInterceptor, decorators: [{
629
- type: Injectable
630
- }] });
631
-
632
- /**
633
- * Angular's HttpInterceptorHandler is not publicly exposed. This is a clone of it.
634
- */
635
- class VcdHttpInterceptorHandler {
636
- constructor(next, interceptor) {
637
- this.next = next;
638
- this.interceptor = interceptor;
639
- }
640
- handle(req) {
641
- return this.interceptor.intercept(req, this.next);
642
- }
643
- }
644
- /**
645
- * This is a specialist subclass of HttpClient. The HttpClient that is defined/imported
646
- * by HttpClientModule is a singleton from the container, meaning that all extensions would
647
- * get the same one. We sub-class it so that each extension gets their own instance.
648
- * Extension consumers should inject this.
649
- * @see HttpClient
650
- */
651
- class VcdHttpClient extends HttpClient {
652
- /**
653
- * Create an HttpClient with the logging and header interceptors in the chain.
654
- * @param httpBackend backend (likely injected from HttpClientModule)
655
- * @param loggingInterceptor the logging interceptor
656
- * @param requestHeadersInterceptor the request header interceptor
657
- * @param responseNormalizationInterceptor
658
- * @param customInterceptors
659
- */
660
- constructor(httpBackend, loggingInterceptor, requestHeadersInterceptor, responseNormalizationInterceptor, customInterceptors) {
661
- const interceptors = [
662
- loggingInterceptor,
663
- requestHeadersInterceptor,
664
- responseNormalizationInterceptor,
665
- ...(customInterceptors !== null && customInterceptors !== void 0 ? customInterceptors : []),
666
- ];
667
- const chain = interceptors.reduceRight((next, interceptor) => new VcdHttpInterceptorHandler(next, interceptor), httpBackend);
668
- super(chain);
669
- this.customInterceptors = customInterceptors;
670
- this.loggingInterceptor = loggingInterceptor;
671
- this.requestHeadersInterceptor = requestHeadersInterceptor;
672
- }
673
- }
674
- VcdHttpClient.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdHttpClient, deps: [{ token: i1.HttpBackend }, { token: LoggingInterceptor }, { token: RequestHeadersInterceptor }, { token: ResponseNormalizationInterceptor }, { token: VCD_HTTP_INTERCEPTORS, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
675
- VcdHttpClient.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdHttpClient });
676
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdHttpClient, decorators: [{
677
- type: Injectable
678
- }], ctorParameters: function () {
679
- return [{ type: i1.HttpBackend }, { type: LoggingInterceptor }, { type: RequestHeadersInterceptor }, { type: ResponseNormalizationInterceptor }, { type: undefined, decorators: [{
680
- type: Optional
681
- }, {
682
- type: Inject,
683
- args: [VCD_HTTP_INTERCEPTORS]
684
- }] }];
685
- } });
686
-
687
- /**
688
- * Default chunk size is 50MiB. This is equal to the chunk size the VCD UI uses for library uploads.
689
- */
690
- const MAX_CHUNK_SIZE = 50 * 1024 * 1024;
691
- /**
692
- * How many times to retry a chunk upload.
693
- */
694
- const MAX_CHUNK_RETRY_COUNT = 5;
695
- /**
696
- * A special error thrown by the transfer client. It gives access to the causing error, and the final progress
697
- * before the error occurred.
698
- */
699
- class TransferError extends Error {
700
- constructor(message, originalError, lastProgress) {
701
- super(message);
702
- this.originalError = originalError;
703
- this.lastProgress = lastProgress;
704
- }
705
- }
706
- /**
707
- * This is used to upload files to a VCD API transfer URL. It is not suggested to create this class - instead
708
- * use the startTransfer method in VcdApiClient.
709
- */
710
- class VcdTransferClient {
711
- /**
712
- * Create a transfer client.
713
- * @param httpClient the http client to be used
714
- * @param transferUrl the URL to upload to
715
- */
716
- constructor(httpClient, transferUrl, maxChunkSize = MAX_CHUNK_SIZE, maxChunkRetryCount = MAX_CHUNK_RETRY_COUNT) {
717
- this.httpClient = httpClient;
718
- this.transferUrl = transferUrl;
719
- this.maxChunkSize = maxChunkSize;
720
- this.maxChunkRetryCount = maxChunkRetryCount;
721
- }
722
- /**
723
- * Upload data, optionally listening for progress updates.
724
- * @param source what to upload.
725
- * @param progressObserver (optional) this will get progress notifications during the upload
726
- * @returns fetails of the finished upload.
727
- * @throws TransferError when a chunk upload fails.
728
- */
729
- upload(source, progressObserver) {
730
- // Cache the client and url so they don't change from under us.
731
- const { httpClient, transferUrl, maxChunkSize, maxChunkRetryCount } = this;
732
- // Compute static information used through the upload.
733
- const filename = source.name || '<blob>';
734
- const totalChunks = Math.ceil(source.size / maxChunkSize);
735
- const totalBytes = source.size;
736
- const startTimeMs = new Date().getTime();
737
- let retryCount = 0;
738
- // This helper function creates a TransferProgress object for sending to the progressObserver.
739
- // It relies on the above static information, hence being nested.
740
- function createTransferProgress(retryNumber, rtryCount, chunksSent) {
741
- const chunksRemaining = totalChunks - chunksSent;
742
- const bytesSent = Math.min(chunksSent * maxChunkSize, totalBytes);
743
- const bytesRemaining = totalBytes - bytesSent;
744
- const percent = bytesSent / totalBytes * 100;
745
- const timeTakenMs = new Date().getTime() - startTimeMs;
746
- const estimatedTotalTimeMs = (bytesSent / bytesRemaining) * timeTakenMs;
747
- const estimatedTimeRemainingMs = Math.max(estimatedTotalTimeMs - timeTakenMs, 0);
748
- return {
749
- filename, transferUrl, retryNumber, retryCount: rtryCount,
750
- chunksSent, chunksRemaining, bytesSent, bytesRemaining,
751
- percent, timeTakenMs, estimatedTimeRemainingMs
752
- };
753
- }
754
- // This is the main chunk upload function
755
- function transferChunk(chunkIndex) {
756
- // Calculate chunk details.
757
- const chunkStart = chunkIndex * maxChunkSize;
758
- const chunkEnd = Math.min(chunkStart + maxChunkSize, totalBytes);
759
- const contentRangeHeader = `bytes ${chunkStart}-${chunkEnd - 1}/${totalBytes}`;
760
- // Dispatch progress
761
- if (progressObserver) {
762
- const progress = createTransferProgress(0, retryCount, chunkIndex);
763
- progressObserver.next(progress);
764
- }
765
- // Read in the chunk
766
- return Observable.create(observer => {
767
- const chunkSlice = source.slice(chunkStart, chunkEnd);
768
- const fileReader = new FileReader();
769
- fileReader.onerror = err => {
770
- observer.error(err);
771
- };
772
- fileReader.onabort = err => {
773
- observer.error(err);
774
- };
775
- fileReader.onload = () => {
776
- };
777
- fileReader.onloadend = () => {
778
- observer.next(fileReader.result);
779
- observer.complete();
780
- };
781
- return fileReader.readAsArrayBuffer(chunkSlice);
782
- // Transfer the chunk
783
- }).pipe(
784
- // Upon read error, abort the upload process. No point retrying read failures.
785
- catchError((e) => {
786
- // Abandon the upload and propagate a consumable error.
787
- const progress = createTransferProgress(0, retryCount, chunkIndex);
788
- return throwError(() => new TransferError('Read error', e, progress));
789
- }),
790
- // Upon successful read, transfer the chunk.
791
- switchMap((data) => {
792
- let retryNumber = 0;
793
- return httpClient.put(transferUrl, data, {
794
- headers: new HttpHeaders({
795
- 'Content-Range': contentRangeHeader
796
- }),
797
- responseType: 'text'
798
- }).pipe(
799
- // This is called upon any chunk upload failure.
800
- catchError((e) => {
801
- // Increase the total retry count.
802
- retryCount++;
803
- // Increase the current chunk retry number.
804
- retryNumber++;
805
- // Dispatch progress (the retry information has changed).
806
- if (progressObserver) {
807
- const progress = createTransferProgress(retryNumber, retryCount, chunkIndex);
808
- progressObserver.next(progress);
809
- }
810
- // Rethrow the error so that the "retry" call handles it.
811
- return throwError(() => e);
812
- }),
813
- // Retry the chunk upload up to the limit - this will run the entire chain again.
814
- retry(maxChunkRetryCount),
815
- // This is called when all retries for the chunk are exhausted.
816
- catchError((e) => {
817
- // Abandon the upload and propagate a consumable error.
818
- const progress = createTransferProgress(retryNumber, retryCount, chunkIndex);
819
- return throwError(() => new TransferError('Transfer error', e, progress));
820
- }));
821
- }));
822
- }
823
- // This creates the final transfer progress, dispatches it, and returns the transfer result.
824
- function finishUpload() {
825
- const transferProgress = createTransferProgress(0, retryCount, totalChunks);
826
- if (progressObserver) {
827
- progressObserver.next(transferProgress);
828
- progressObserver.complete();
829
- }
830
- const transferResult = {
831
- filename: transferProgress.filename,
832
- transferUrl: transferProgress.transferUrl,
833
- retryCount: transferProgress.retryCount,
834
- chunksSent: transferProgress.chunksSent,
835
- bytesSent: transferProgress.bytesSent,
836
- timeTakenMs: transferProgress.timeTakenMs
837
- };
838
- return transferResult;
839
- }
840
- // Upload all of the chunks
841
- let chain = transferChunk(0);
842
- for (let currentChunk = 1; currentChunk < totalChunks; currentChunk++) {
843
- chain = chain.pipe(flatMap(() => transferChunk(currentChunk)));
844
- }
845
- // Finish transfer
846
- return chain.pipe(map(finishUpload));
847
- }
848
- }
849
-
850
- class ClientError extends Error {
851
- constructor(message, type) {
852
- super(message);
853
- this.message = message;
854
- this.type = type;
855
- }
856
- }
857
- var ClientErrorType;
858
- (function (ClientErrorType) {
859
- ClientErrorType["HateoasLinkMissing"] = "HateoasLinkMissing";
860
- ClientErrorType["TaskLinkMissing"] = "TaskLinkMissing";
861
- })(ClientErrorType || (ClientErrorType = {}));
862
-
863
- const TRANSFER_LINK_REL = 'upload:default';
864
- const HATEOAS_HEADER = 'Link';
865
- // tslint:disable:variable-name
866
- /**
867
- * Parse out Link headers using a very lazily implemented pull parser
868
- * @param header '<url1>;name1="value1",name2="value2",<url2>;name3="value3,value4"'
869
- * @returns parsed link headers
870
- */
871
- function parseHeaderHateoasLinks(header) {
872
- const results = [];
873
- if (!header) {
874
- return results;
875
- }
876
- const headerFieldMappings = {
877
- href: 'href',
878
- model: 'type',
879
- title: 'id',
880
- rel: 'rel'
881
- };
882
- let tokenIndex = -1;
883
- function peek(token) {
884
- return header.indexOf(token, tokenIndex + 1);
885
- }
886
- function next(token) {
887
- const nextIndex = peek(token);
888
- if (nextIndex === -1) {
889
- throw new Error(JSON.stringify({ header, token, tokenIndex }));
890
- }
891
- tokenIndex = nextIndex;
892
- return tokenIndex;
893
- }
894
- while (peek('<') > -1) {
895
- try {
896
- const hrefStart = next('<');
897
- const hrefEnd = next('>');
898
- const href = header.substring(hrefStart + 1, hrefEnd);
899
- const result = { href, type: null, id: null, rel: null, vCloudExtension: [] };
900
- let comma = peek(',');
901
- let semicolon = peek(';');
902
- while ((semicolon > -1 && comma > -1 && semicolon < comma) || (semicolon > -1 && comma === -1)) {
903
- const nameStart = next(';');
904
- const nameEnd = next('=');
905
- const name = header.substring(nameStart + 1, nameEnd).trim().toLowerCase();
906
- const valueStart = next('"');
907
- const valueEnd = next('"');
908
- const value = header.substring(valueStart + 1, valueEnd);
909
- const mappedName = headerFieldMappings[name];
910
- if (mappedName) {
911
- // @ts-ignore
912
- result[mappedName] = decodeURIComponent(value);
913
- }
914
- comma = peek(',');
915
- semicolon = peek(';');
916
- }
917
- results.push(result);
918
- }
919
- catch (error) { // We will try the next one...
920
- console.log(error);
921
- }
922
- }
923
- return results;
924
- }
925
- var LinkRelType;
926
- (function (LinkRelType) {
927
- LinkRelType["add"] = "add";
928
- LinkRelType["remove"] = "remove";
929
- LinkRelType["edit"] = "edit";
930
- })(LinkRelType || (LinkRelType = {}));
931
- /**
932
- * A basic client for interacting with the VMware Cloud Director APIs.
933
- *
934
- * A VMware Cloud Director plugin can get a reference to this client by using angular injection.
935
- * ```
936
- * constructor(private vcdApi: VcdApiClient) {}
937
- * ```
938
- *
939
- * VcdApiClient reuses the authentication from the VCD platform so in general there is
940
- * no need of an explicit authentication/login.
941
- *
942
- * When dealing with the session management there are two APIs:
943
- * 1. Deprecated legacy API that is using the `api/session` endpoint and the corresponding models
944
- * 2. Newly added API that is using the `cloudapi` endpoint and the corresponding models
945
- *
946
- * Note that if a plugin performs an explicit cloud api authentication call through
947
- * {@link VcdApiClient#setCloudApiAuthentication} or {@link VcdApiClient#cloudApiLogin}
948
- * from that moment on the VcdApiClient uses only cloud api session management.
949
- * This means calls to {@link VcdApiClient#setAuthentication} or {@link VcdApiClient#login} have no effect.
950
- */
951
- class VcdApiClient {
952
- set baseUrl(_baseUrl) {
953
- this._baseUrl = _baseUrl;
954
- }
955
- get version() {
956
- return this.http.requestHeadersInterceptor.version;
957
- }
958
- constructor(http, injector, config) {
959
- var _a;
960
- this.http = http;
961
- this.injector = injector;
962
- this.config = config;
963
- /**
964
- * @deprecated Use {@link VcdApiClient#_cloudApiSession}
965
- */
966
- this._session = new BehaviorSubject(null);
967
- this._sessionObservable = this._session.asObservable()
968
- .pipe(skipWhile(session => !session));
969
- /**
970
- * CloudApi Session
971
- */
972
- this._cloudApiSession = new BehaviorSubject(null);
973
- this._cloudApiSessionObservable = this._cloudApiSession.asObservable()
974
- .pipe(skipWhile(session => !session));
975
- this._cloudApiSessionLinks = new BehaviorSubject([]);
976
- /**
977
- * This property determines if it is an explicit cloud api login.
978
- * In this case the old API (/api/session) should not be used at all.
979
- */
980
- this._isCloudApiLogin = false;
981
- this._baseUrl = this.injector.get(API_ROOT_URL);
982
- let negotiatedVersion;
983
- if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.apiVersion) {
984
- negotiatedVersion = of(this.config.apiVersion).pipe(map((version) => {
985
- this.setVersion(version);
986
- return version;
987
- }));
988
- }
989
- else {
990
- negotiatedVersion = this.http.get(`${this._baseUrl}/api/versions`).pipe(map(versions => this.negotiateVersion(versions)), tap(version => this.setVersion(version)));
991
- }
992
- this._negotiateVersion = negotiatedVersion.pipe(share({ connector: () => new ReplaySubject(1), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }));
993
- const tokenHolder = this.injector.get(AuthTokenHolderService, { token: '' });
994
- const token = tokenHolder.jwt ? `Bearer ${tokenHolder.jwt}` : tokenHolder.token;
995
- this._getSession = this.setAuthentication(token)
996
- .pipe(share({ connector: () => new ReplaySubject(1), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }));
997
- this._getCloudApiSession = this.setCloudApiAuthentication(token)
998
- .pipe(share({ connector: () => new ReplaySubject(1), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }));
999
- // This is not an explicit cloud api login
1000
- this._isCloudApiLogin = false;
1001
- }
1002
- negotiateVersion(serverVersions) {
1003
- const supportedVersions = serverVersions.versionInfo.map(versionInfo => versionInfo.version);
1004
- // Default API Version used is the Latest API Version in VMware Cloud Director
1005
- return supportedVersions[supportedVersions.length - 1];
1006
- }
1007
- /**
1008
- * The purpose of this function is to ensure that prior to sending any call to the backend
1009
- * the version has been set and the current session has been retrieved.
1010
- * Note that this is important during the automatic authentication that is done during the
1011
- * constructor initialization, when the plugin is not required to perform its own explicit authentication
1012
- * but rather the ones from the underlying framework is used.
1013
- */
1014
- validateRequestContext() {
1015
- return (this.version ? of(this.version) : this._negotiateVersion)
1016
- .pipe(
1017
- // In case of a cloud api login we are not interested in the /api/session session
1018
- concatMap(() => this._isCloudApiLogin ? of(null) : this._getSession), concatMap(() => this._getCloudApiSession
1019
- // In case of cloud api failure we do not want to prevent further execution
1020
- // for backward compatibility considerations since this may be a case
1021
- // when cloud api is not supported at all for the specified version
1022
- .pipe(catchError((e) => of(true)))), map(() => true));
1023
- }
1024
- /**
1025
- *
1026
- * For use cases wich solely depends on cloudapi without any backward compatibility
1027
- * there should be no dependence on the old /api endpoint at all
1028
- */
1029
- validateRequestContextCloudApiOnly() {
1030
- return (this.version ? of(this.version) : this._negotiateVersion).pipe(concatMap(() => this._getCloudApiSession));
1031
- }
1032
- setVersion(_version) {
1033
- this.http.requestHeadersInterceptor.version = _version;
1034
- return this;
1035
- }
1036
- /**
1037
- * Global configuration for the service, that allows a provider user to execute API requests
1038
- * in the scope of a specific tenant.
1039
- *
1040
- * If you want to execute single API request in scope of specific tenant you can do it
1041
- * by passing "X-VMWARE-VCLOUD-TENANT-CONTEXT" header to the specific API Request.
1042
- *
1043
- * This scoping is available to query-based API calls and to bulk GET calls in the
1044
- * /cloudapi space.
1045
- *
1046
- * @param actAs an entityRef of the tenant (organization) to scope subsequent calls to in
1047
- * the VcdApiClient, or null/no parameter to remove tenant-specific scoping
1048
- * @returns the current VcdApiClient instance (for chaining)
1049
- */
1050
- actAs(actAs = null) {
1051
- this.http.requestHeadersInterceptor.actAs = !actAs ? null : actAs.id;
1052
- this.http.requestHeadersInterceptor.actAsOrgName = !actAs ? null : actAs.name;
1053
- return this;
1054
- }
1055
- /**
1056
- * @deprecated Use {@link VcdApiClient#setCloudApiAuthentication}
1057
- *
1058
- * Sets the authentication token to use for the VcdApiClient.
1059
- *
1060
- * After setting the token, the client will get the current session
1061
- * information associated with the authenticated token.
1062
- *
1063
- * @param authentication the authentication string (to be used in either the 'Authorization'
1064
- * or 'x-vcloud-authorization' header)
1065
- * @returns the session associated with the authentication token
1066
- */
1067
- setAuthentication(authentication) {
1068
- if (this._isCloudApiLogin) {
1069
- return throwError('Only cloud api auth is allowed since it was already used');
1070
- }
1071
- this.http.requestHeadersInterceptor.authentication = authentication;
1072
- return this.http.get(`${this._baseUrl}/api/session`).pipe(tap(session => {
1073
- // automatically set actAs for provider in tenant scope
1074
- if (session.org === 'System' && this.injector.get(SESSION_SCOPE) === 'tenant') {
1075
- // Automatic actAs only works in versions >=9.5
1076
- try {
1077
- this.actAs({ id: this.injector.get(SESSION_ORG_ID) });
1078
- }
1079
- catch (e) {
1080
- console.warn('No SESSION_ORG_ID set in container. Automatic actAs is disabled.');
1081
- }
1082
- }
1083
- }), tap(session => this._session.next(session)));
1084
- }
1085
- /**
1086
- * Sets the authentication token to use for the VcdApiClient.
1087
- *
1088
- * After setting the token, the client will get the current session
1089
- * information associated with the authenticated token.
1090
- *
1091
- * @param authentication the authentication string (to be used in either the 'Authorization'
1092
- * or 'x-vcloud-authorization' header)
1093
- *
1094
- * @returns session observable associated with the authentication token
1095
- */
1096
- setCloudApiAuthentication(authentication) {
1097
- this.onBeforeCloudApiAuthentication();
1098
- return of(true)
1099
- .pipe(
1100
- // Set the authentication as part of the observable in order to ensure the caller has subscribed to the observable
1101
- tap(() => this.http.requestHeadersInterceptor.authentication = authentication), switchMap(() => this.http.get(`${this._baseUrl}/cloudapi/1.0.0/sessions/current`, { observe: 'response' })))
1102
- .pipe(this.onCloudApiAuthentication());
1103
- }
1104
- enableLogging() {
1105
- this.http.loggingInterceptor.enabled = true;
1106
- return this;
1107
- }
1108
- /**
1109
- * @deprecated Use {@link VcdApiClient#cloudApiLogin}
1110
- *
1111
- * Creates an authenticated session for the specified credential data.
1112
- *
1113
- * @param username the name of the user to authenticate
1114
- * @param tenant the organization the user belongs to
1115
- * @param password the password for the user
1116
- * @returns an authenticated session for the given credentials
1117
- */
1118
- login(username, tenant, password) {
1119
- if (this._isCloudApiLogin) {
1120
- return throwError('Only cloud api auth is allowed since it was already used');
1121
- }
1122
- const authString = btoa(`${username}@${tenant}:${password}`);
1123
- return this.http.post(`${this._baseUrl}/api/sessions`, null, {
1124
- observe: 'response',
1125
- headers: new HttpHeaders({ Authorization: `Basic ${authString}` })
1126
- })
1127
- .pipe(tap((response) =>
1128
- // tslint:disable-next-line:max-line-length
1129
- this.http.requestHeadersInterceptor.authentication = `${response.headers.get('x-vmware-vcloud-token-type')} ${response.headers.get('x-vmware-vcloud-access-token')}`), map(response => response.body), tap(session => this._session.next(session)));
1130
- }
1131
- /**
1132
- * Creates an authenticated session for the specified credential data using cloud api endpoint.
1133
- *
1134
- * @param username the name of the user to authenticate
1135
- * @param tenant the organization the user belongs to
1136
- * @param password the password for the user
1137
- * @returns an authenticated session for the given credentials
1138
- */
1139
- cloudApiLogin(username, tenant, password) {
1140
- this.onBeforeCloudApiAuthentication();
1141
- const authString = btoa(`${username}@${tenant}:${password}`);
1142
- let url = `${this._baseUrl}/cloudapi/1.0.0/sessions`;
1143
- if (tenant.toLowerCase() === 'system') {
1144
- url += '/provider';
1145
- }
1146
- return this.http.post(url, null, {
1147
- observe: 'response',
1148
- headers: new HttpHeaders({ [HTTP_HEADERS.Authorization]: `Basic ${authString}` })
1149
- }).pipe(tap((response) => {
1150
- // tslint:disable-next-line:max-line-length
1151
- const token = `${response.headers.get('x-vmware-vcloud-token-type')} ${response.headers.get('x-vmware-vcloud-access-token')}`;
1152
- this.http.requestHeadersInterceptor.authentication = token;
1153
- }), this.onCloudApiAuthentication());
1154
- }
1155
- /**
1156
- * It is necessary to know if an explicit cloud api auth request was done.
1157
- * This function handles this by setting the corresponding flags, properties etc.
1158
- */
1159
- onBeforeCloudApiAuthentication() {
1160
- // In case of an explicit cloud api auth request:
1161
- // Set the flag _isCloudApiLogin in order to know that explicit cloud api authentication is done
1162
- // This will help us skip code related to the old api, i.e. we should not allow explicit mix of both the api-s
1163
- this._isCloudApiLogin = true;
1164
- // In case of an explicit cloud api auth request:
1165
- // There is no need of _getCloudApiSession observable which is needed in the automatic login during the constructor initialization.
1166
- // The explicit cloud api auth request will retrieve the session.
1167
- this._getCloudApiSession = of(null);
1168
- }
1169
- /**
1170
- * Handle authentication.
1171
- * This includes getting HATEOAS links, setting the session, handling errors etc.
1172
- */
1173
- onCloudApiAuthentication() {
1174
- return (source) => source.pipe(tap((resp) => {
1175
- // Get HATEOAS links
1176
- try {
1177
- this.setCloudApiSessionLinks(parseHeaderHateoasLinks(resp.headers.get(HATEOAS_HEADER)));
1178
- }
1179
- catch (e) {
1180
- console.log('Error when parsing session HATEOAS links:', e);
1181
- }
1182
- }), map(resp => resp.body), tap((session) => {
1183
- // Clear previous actAs
1184
- this.actAs(null);
1185
- // automatically set actAs for provider in tenant scope
1186
- if (session.org && session.org.name === 'System' && this.injector.get(SESSION_SCOPE) === 'tenant') {
1187
- // Automatic actAs only works in versions >=9.5
1188
- try {
1189
- this.actAs({ id: this.injector.get(SESSION_ORG_ID) });
1190
- }
1191
- catch (e) {
1192
- console.warn('No SESSION_ORG_ID set in container. Automatic actAs is disabled.');
1193
- }
1194
- }
1195
- }), tap((session) => this._cloudApiSession.next(session)), catchError((e) => {
1196
- this.onCloudApiAuthenticationError();
1197
- return throwError(e);
1198
- }));
1199
- }
1200
- onCloudApiAuthenticationError() {
1201
- // Clear the authentication so that any subsequent backend calls are not authenticated
1202
- this.http.requestHeadersInterceptor.authentication = '';
1203
- // _getCloudApiSession is in the center of any backend call, nullify it in order not to prevent those calls
1204
- // since it is easier to troubleshoot failing backend rather than no call
1205
- this._getCloudApiSession = of(null);
1206
- // Clear the links
1207
- this._cloudApiSessionLinks.next([]);
1208
- // Clear the session
1209
- this._cloudApiSession.next(null);
1210
- }
1211
- setCloudApiSessionLinks(links) {
1212
- this._cloudApiAccessibleLocations = null;
1213
- this._cloudApiSessionLinks.next(links || []);
1214
- }
1215
- get(endpoint, options) {
1216
- return this.validateRequestContext().pipe(concatMap(() => this.http.get(this.buildEndpointUrl(endpoint), Object.assign({}, options))));
1217
- }
1218
- list(endpoint, queryBuilder, multisite, options) {
1219
- let url = this.buildEndpointUrl(endpoint);
1220
- if (queryBuilder) {
1221
- url = `${url}${queryBuilder.getCloudAPI()}`;
1222
- }
1223
- if (multisite) {
1224
- if (!options) {
1225
- return this.http.get(url, { headers: new HttpHeaders({ _multisite: this.parseMultisiteValue(multisite) }) });
1226
- }
1227
- else if (options === null || options === void 0 ? void 0 : options.headers) {
1228
- options.headers.append("_multisite", this.parseMultisiteValue(multisite));
1229
- return this.http.get(url, Object.assign({}, options));
1230
- }
1231
- }
1232
- return this.validateRequestContext().pipe(concatMap(() => this.http.get(url, Object.assign({}, options))));
1233
- }
1234
- createSync(endpoint, item, options) {
1235
- return this.validateRequestContext().pipe(concatMap(() => this.http.post(this.buildEndpointUrl(endpoint), item, Object.assign({}, options))));
1236
- }
1237
- createAsync(endpoint, item, options) {
1238
- return this.validateRequestContext().pipe(concatMap(() => this.http.post(this.buildEndpointUrl(endpoint), item, Object.assign(Object.assign({}, options), { observe: 'response' }))), concatMap(response => this.mapResponseToTask(response, 'POST')));
1239
- }
1240
- getTransferLink(endpoint, item, transferRel = TRANSFER_LINK_REL) {
1241
- return this.http
1242
- .post(this.buildEndpointUrl(endpoint), item, { observe: 'response' })
1243
- .pipe(map((res) => {
1244
- const headerLinks = res.headers.has(HATEOAS_HEADER)
1245
- ? parseHeaderHateoasLinks(res.headers.get(HATEOAS_HEADER))
1246
- : [];
1247
- const links = res.body ? (res.body.link || []) : [];
1248
- const link = [...headerLinks, ...links]
1249
- .find((l) => l.rel === transferRel);
1250
- if (!link) {
1251
- throw new ClientError(`Response from ${endpoint} did not contain a transfer link`, ClientErrorType.HateoasLinkMissing);
1252
- }
1253
- return link.href;
1254
- }));
1255
- }
1256
- startTransfer(endpoint, item, transferRel = TRANSFER_LINK_REL) {
1257
- return this.getTransferLink(endpoint, item, transferRel)
1258
- .pipe(map((transferUrl) => new VcdTransferClient(this.http, transferUrl)));
1259
- }
1260
- updateSync(endpoint, item, options) {
1261
- return this.validateRequestContext().pipe(concatMap(() => this.http.put(this.buildEndpointUrl(endpoint), item, Object.assign({}, options))));
1262
- }
1263
- updateAsync(endpoint, item, options) {
1264
- return this.validateRequestContext().pipe(concatMap(() => this.http.put(this.buildEndpointUrl(endpoint), item, Object.assign(Object.assign({}, options), { observe: 'response' }))), concatMap(response => this.mapResponseToTask(response, 'PUT')));
1265
- }
1266
- deleteSync(endpoint, options) {
1267
- return this.validateRequestContext().pipe(concatMap(() => this.http.delete(this.buildEndpointUrl(endpoint), Object.assign({}, options))));
1268
- }
1269
- deleteAsync(endpoint, options) {
1270
- return this.validateRequestContext().pipe(concatMap(() => this.http.delete(this.buildEndpointUrl(endpoint), Object.assign(Object.assign({}, options), { observe: 'response' }))), concatMap(response => this.mapResponseToTask(response, 'DELETE')));
1271
- }
1272
- mapResponseToTask(response, httpVerb) {
1273
- if (response.headers.has('Location') && response.status === 202) {
1274
- return this.http.get(response.headers.get('Location'));
1275
- }
1276
- else if (response.body && response.body.type.startsWith('application/vnd.vmware.vcloud.task+')) {
1277
- const task = Object.assign(new TaskType(), response.body);
1278
- return of(task);
1279
- }
1280
- return throwError(() => new ClientError(`An asynchronous request was made to [${httpVerb} ${response.url}], but no task was returned. The operation may still have been successful.`, ClientErrorType.TaskLinkMissing));
1281
- }
1282
- getEntity(entityRefOrUrn) {
1283
- const entityResolver = typeof entityRefOrUrn === 'string' ?
1284
- this.http.get(`${this._baseUrl}/api/entity/${entityRefOrUrn}`) :
1285
- this.http.get(`${this._baseUrl}/api/entity/urn:vcloud:${entityRefOrUrn.type}:${entityRefOrUrn.id}`);
1286
- return this.validateRequestContext().pipe(concatMap(() => entityResolver), concatMap(entity => this.http.get(`${entity.link[0].href}`)));
1287
- }
1288
- updateTask(task, options) {
1289
- return this.validateRequestContext().pipe(concatMap(() => this.http.get(task.href, Object.assign({}, options))));
1290
- }
1291
- isTaskComplete(task) {
1292
- return ['success', 'error', 'canceled', 'aborted'].indexOf(task.status) > -1;
1293
- }
1294
- removeItem(item, options) {
1295
- const link = this.findLink(item, 'remove', null);
1296
- if (!link) {
1297
- return throwError(() => new ClientError(`No 'remove' link for specified resource.`, ClientErrorType.HateoasLinkMissing));
1298
- }
1299
- return this.validateRequestContext().pipe(concatMap(() => this.http.delete(link.href, Object.assign({}, options))));
1300
- }
1301
- query(builder, multisite, options) {
1302
- return this.getQueryPage(`${this._baseUrl}/api/query${builder.get()}`, multisite, options);
1303
- }
1304
- firstPage(result, multisite, options) {
1305
- const link = this.findLink(result, 'firstPage', result.type);
1306
- if (!link) {
1307
- return throwError(() => new ClientError(`No 'firstPage' link for specified query.`, ClientErrorType.HateoasLinkMissing));
1308
- }
1309
- return this.getQueryPage(link.href, multisite, options);
1310
- }
1311
- hasFirstPage(result) {
1312
- return !!this.findLink(result, 'firstPage', result.type);
1313
- }
1314
- previousPage(result, multisite, options) {
1315
- const link = this.findLink(result, 'previousPage', result.type);
1316
- if (!link) {
1317
- return throwError(() => new ClientError(`No 'previousPage' link for specified query.`, ClientErrorType.HateoasLinkMissing));
1318
- }
1319
- return this.getQueryPage(link.href, multisite, options);
1320
- }
1321
- hasPreviousPage(result) {
1322
- return !!this.findLink(result, 'previousPage', result.type);
1323
- }
1324
- nextPage(result, multisite, options) {
1325
- const link = this.findLink(result, 'nextPage', result.type);
1326
- if (!link) {
1327
- return throwError(() => new ClientError(`No 'nextPage' link for specified query.`, ClientErrorType.HateoasLinkMissing));
1328
- }
1329
- return this.getQueryPage(link.href, multisite, options);
1330
- }
1331
- hasNextPage(result) {
1332
- return !!this.findLink(result, 'nextPage', result.type);
1333
- }
1334
- lastPage(result, multisite, options) {
1335
- const link = this.findLink(result, 'lastPage', result.type);
1336
- if (!link) {
1337
- return throwError(() => new ClientError(`No 'lastPage' link for specified query.`, ClientErrorType.HateoasLinkMissing));
1338
- }
1339
- return this.getQueryPage(link.href, multisite, options);
1340
- }
1341
- hasLastPage(result) {
1342
- return !!this.findLink(result, 'lastPage', result.type);
1343
- }
1344
- getQueryPage(href, multisite, options) {
1345
- if (multisite) {
1346
- if (!options) {
1347
- return this.http.get(href, { headers: new HttpHeaders({ _multisite: this.parseMultisiteValue(multisite) }) });
1348
- }
1349
- else if (options === null || options === void 0 ? void 0 : options.headers) {
1350
- options.headers.append("_multisite", this.parseMultisiteValue(multisite));
1351
- return this.http.get(href, Object.assign({}, options));
1352
- }
1353
- }
1354
- return this.validateRequestContext().pipe(concatMap(() => this.http.get(href, Object.assign({}, options))));
1355
- }
1356
- /**
1357
- * Use to perform action availability check before calling the API
1358
- * @param item - the navigable item (containing link collection)
1359
- * @param linkRelType - the link rel type, pass either LinkRelType or string
1360
- * @param entityRefType - the entity reference type
1361
- */
1362
- canPerformAction(item, linkRelType, entityRefType) {
1363
- return !!this.findLink(item, linkRelType, entityRefType);
1364
- }
1365
- findLink(item, rel, type) {
1366
- if (!item || !item.link) {
1367
- return undefined;
1368
- }
1369
- return item.link.find((link) => {
1370
- if (type) {
1371
- return link.rel.includes(rel) && link.type === type;
1372
- }
1373
- return link.rel.includes(rel);
1374
- });
1375
- }
1376
- parseMultisiteValue(multisite) {
1377
- return typeof multisite === 'boolean' ? (multisite ? 'global' : 'local') : multisite.map(site => site.locationId).join(',');
1378
- }
1379
- /**
1380
- * @deprecated Use cloudApiSession
1381
- */
1382
- get session() {
1383
- return this.validateRequestContext().pipe(concatMap(() => this._sessionObservable));
1384
- }
1385
- /**
1386
- * Get Session observable
1387
- */
1388
- get cloudApiSession() {
1389
- return this.validateRequestContextCloudApiOnly().pipe(concatMap(() => this._cloudApiSessionObservable));
1390
- }
1391
- get username() {
1392
- return merge(this.cloudApiSession.pipe(filter(() => this._isCloudApiLogin), map(session => session && session.user && session.user.name)), this.session.pipe(filter(() => !this._isCloudApiLogin), map(session => session && session.user)));
1393
- }
1394
- get organization() {
1395
- return merge(this.cloudApiSession.pipe(filter(() => this._isCloudApiLogin), map(session => session && session.org && session.org.name)), this.session.pipe(filter(() => !this._isCloudApiLogin), map(session => session && session.org)));
1396
- }
1397
- /**
1398
- * @deprecated Use cloudApiLocation
1399
- */
1400
- get location() {
1401
- return this.session.pipe(map(session => session.authorizedLocations.location.find(location => location.locationId === session.locationId)));
1402
- }
1403
- /**
1404
- * Gets the location corresponding to the current session
1405
- */
1406
- get cloudApiLocation() {
1407
- return this.cloudApiSession.pipe(switchMap(() => {
1408
- if (!this._cloudApiAccessibleLocations) {
1409
- // Ensure caching for getting AccessibleLocations
1410
- this._cloudApiAccessibleLocations = this._cloudApiSessionLinks
1411
- .pipe(
1412
- // Get the AccessibleLocations link
1413
- map((links) => this.findLink({ link: links }, 'down', 'AccessibleLocations')),
1414
- // Fetch AccessibleLocations from the backend
1415
- switchMap((link) => link ? this.http.get(link.href) : of(null)),
1416
- // Get the array with all locations (what if there are many pages)
1417
- map((accessibleLocations) => accessibleLocations && accessibleLocations.values))
1418
- .pipe(share({ connector: () => new ReplaySubject(1), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }));
1419
- }
1420
- return this._cloudApiAccessibleLocations;
1421
- }),
1422
- // Need to have the session in order to get its location
1423
- withLatestFrom(this.cloudApiSession),
1424
- // Find the location that corresponds to this session
1425
- map(([accessibleLocations, session]) => {
1426
- if (!accessibleLocations || !session) {
1427
- return null;
1428
- }
1429
- const sessionLocation = session.location;
1430
- if (!sessionLocation) {
1431
- return null;
1432
- }
1433
- return accessibleLocations.find(location => location.locationId === sessionLocation);
1434
- }));
1435
- }
1436
- getLocation(session) {
1437
- return session.authorizedLocations.location.find(location => location.locationId === session.locationId);
1438
- }
1439
- /**
1440
- * Build the endpoint url. If the provided endpoint is already an absolute URL, then return it as it is without
1441
- * any modifications, otherwise consider it as a relative one and prepend the baseUrl as defined by the host application.
1442
- */
1443
- buildEndpointUrl(endpoint) {
1444
- return endpoint.indexOf('://') > -1 ? endpoint : `${this._baseUrl}/${endpoint}`;
1445
- }
1446
- }
1447
- VcdApiClient.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdApiClient, deps: [{ token: VcdHttpClient }, { token: i0.Injector }, { token: VcdSdkConfig, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
1448
- VcdApiClient.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdApiClient });
1449
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdApiClient, decorators: [{
1450
- type: Injectable
1451
- }], ctorParameters: function () {
1452
- return [{ type: VcdHttpClient }, { type: i0.Injector }, { type: VcdSdkConfig, decorators: [{
1453
- type: Optional
1454
- }] }];
1455
- } });
1456
-
1457
- /**
1458
- * Extensions should import this module.
1459
- * They can then wire in SDK components as desired.
1460
- */
1461
- class VcdSdkModule {
1462
- static forRoot(config) {
1463
- return {
1464
- ngModule: VcdSdkModule,
1465
- providers: [
1466
- RequestHeadersInterceptor,
1467
- LoggingInterceptor,
1468
- ResponseNormalizationInterceptor,
1469
- VcdHttpClient,
1470
- VcdApiClient,
1471
- {
1472
- provide: VcdSdkConfig,
1473
- useValue: config || {}
1474
- },
1475
- ]
1476
- };
1477
- }
1478
- }
1479
- VcdSdkModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdSdkModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1480
- VcdSdkModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.0", ngImport: i0, type: VcdSdkModule, imports: [HttpClientModule,
1481
- CommonModule] });
1482
- VcdSdkModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdSdkModule, imports: [HttpClientModule,
1483
- CommonModule] });
1484
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.0", ngImport: i0, type: VcdSdkModule, decorators: [{
1485
- type: NgModule,
1486
- args: [{
1487
- imports: [
1488
- HttpClientModule,
1489
- CommonModule,
1490
- ],
1491
- declarations: [],
1492
- exports: [],
1493
- }]
1494
- }] });
1495
-
1496
- /*
1497
- * Public API Surface of sdk
1498
- */
1499
-
1500
- /**
1501
- * Generated bundle index. Do not edit.
1502
- */
1503
-
1504
- export { API_ROOT_URL, ApiResult, ApiResultService, AuthTokenHolderService, ClientError, ClientErrorType, EXTENSION_ASSET_URL, EXTENSION_ROUTE, EntityActionExtensionComponent, ExtensionNavRegistrationAction, FLEX_APP_URL, Filter, HATEOAS_HEADER, LinkRelType, LoggingInterceptor, MAX_CHUNK_RETRY_COUNT, MAX_CHUNK_SIZE, PluginModule, Query, RequestHeadersInterceptor, ResponseNormalizationInterceptor, SDK_MODE, SESSION_ORGANIZATION, SESSION_ORG_ID, SESSION_SCOPE, TRANSFER_LINK_REL, TransferError, VCD_HTTP_INTERCEPTORS, VcdApiClient, VcdHttpClient, VcdSdkConfig, VcdSdkModule, VcdTransferClient, WizardExtensionComponent, WizardExtensionWithContextComponent, WizardExtensionWithValidationComponent, _EntityActionExtensionComponent, _WizardExtensionComponent, _WizardExtensionWithContextComponent, _WizardExtensionWithValidationComponent, parseHeaderHateoasLinks };
1505
- //# sourceMappingURL=vcd-sdk.mjs.map