@platform-mesh/portal-ui-lib 0.72.1 → 0.74.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.
@@ -1,781 +1,730 @@
1
- import * as i0 from '@angular/core';
2
- import { inject, Injectable } from '@angular/core';
3
- import { LuigiCoreService, AuthService, ConfigService, EnvConfigService } from '@openmfp/portal-ui-lib';
4
- import { kcpRootOrgsPath, ALL_NAMESPACE, DOWNLOAD_KUBECONFIG_FROM_SECRET_REF_ACTION } from '@platform-mesh/portal-ui-lib/models';
5
- import { HttpHeaders, HttpClient } from '@angular/common/http';
6
- import { ApolloLink, Observable, split, InMemoryCache } from '@apollo/client/core';
7
- import { SetContextLink } from '@apollo/client/link/context';
8
- import { getMainDefinition } from '@apollo/client/utilities';
9
- import { Apollo, gql } from 'apollo-angular';
10
- import { HttpLink } from 'apollo-angular/http';
11
- import { print } from 'graphql';
12
- import { createClient } from 'graphql-sse';
13
- import { of, throwError, catchError as catchError$1, map as map$1, firstValueFrom } from 'rxjs';
14
- import { catchError, map, switchMap, shareReplay } from 'rxjs/operators';
15
- import { isNamespacedResource, getValueByPath, buildResourcePath, getResourceValueByJsonPath, stripTypename, buildGraphQLInputTypeName, decodeBase64, generateGraphQLFields } from '@platform-mesh/portal-ui-lib/utils';
16
- import * as gqlBuilder from 'gql-query-builder';
17
-
18
- class GatewayService {
19
- constructor() {
20
- this.luigiCoreService = inject(LuigiCoreService);
21
- }
22
- getGatewayUrl(nodeContext, readFromParentKcpPath = false) {
23
- const gatewayUrl = nodeContext.portalContext.crdGatewayApiUrl;
24
- const currentKcpPath = this.extractKcpPath(gatewayUrl);
25
- return gatewayUrl?.replace(currentKcpPath, this.resolveKcpPath(nodeContext, readFromParentKcpPath));
26
- }
27
- updateCrdGatewayUrlWithEntityPath(kcpPath) {
28
- const gatewayUrl = this.luigiCoreService.getGlobalContext().portalContext.crdGatewayApiUrl;
29
- const currentKcpPath = this.extractKcpPath(gatewayUrl);
30
- this.luigiCoreService.getGlobalContext().portalContext.crdGatewayApiUrl =
31
- gatewayUrl.replace(currentKcpPath, kcpPath);
32
- }
33
- resolveKcpPath(nodeContext, readFromParentKcpPath = false) {
34
- const gatewayUrl = nodeContext.portalContext.crdGatewayApiUrl;
35
- let kcpPath = this.extractKcpPath(gatewayUrl);
36
- if (nodeContext.kcpPath) {
37
- kcpPath = nodeContext.kcpPath;
38
- }
39
- if (readFromParentKcpPath) {
40
- const lastIndex = kcpPath.lastIndexOf(':');
41
- if (lastIndex !== -1) {
42
- kcpPath = kcpPath.slice(0, lastIndex);
43
- }
44
- }
45
- return kcpPath;
46
- }
47
- extractKcpPath(gatewayUrl) {
48
- return gatewayUrl.match(new RegExp(`(${kcpRootOrgsPath}[^/]*)`))?.[1] || '';
49
- }
50
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: GatewayService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
51
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: GatewayService, providedIn: 'root' }); }
52
- }
53
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: GatewayService, decorators: [{
54
- type: Injectable,
55
- args: [{ providedIn: 'root' }]
56
- }] });
57
-
58
- class SSELink extends ApolloLink {
59
- constructor(options) {
60
- super();
61
- this.client = createClient(options);
62
- }
63
- request(operation) {
64
- return new Observable((sink) => {
65
- return this.client.subscribe({ ...operation, query: print(operation.query) }, {
66
- next: sink.next.bind(sink),
67
- complete: sink.complete.bind(sink),
68
- error: sink.error.bind(sink),
69
- });
70
- });
71
- }
72
- }
1
+ import * as i0 from "@angular/core";
2
+ import { Injectable, inject } from "@angular/core";
3
+ import { AuthService, ConfigService, EnvConfigService, LuigiCoreService } from "@openmfp/portal-ui-lib";
4
+ import { ALL_NAMESPACE, DOWNLOAD_KUBECONFIG_FROM_SECRET_REF_ACTION, kcpRootOrgsPath } from "@platform-mesh/portal-ui-lib/models";
5
+ import { HttpClient, HttpHeaders } from "@angular/common/http";
6
+ import { ApolloLink, InMemoryCache, Observable, split } from "@apollo/client/core";
7
+ import { SetContextLink } from "@apollo/client/link/context";
8
+ import { getMainDefinition } from "@apollo/client/utilities";
9
+ import { Apollo, gql } from "apollo-angular";
10
+ import { HttpLink } from "apollo-angular/http";
11
+ import { print } from "graphql";
12
+ import { createClient } from "graphql-sse";
13
+ import { catchError, firstValueFrom, map, of, throwError } from "rxjs";
14
+ import { catchError as catchError$1, map as map$1, shareReplay, switchMap } from "rxjs/operators";
15
+ import { buildGraphQLInputTypeName, buildResourcePath, decodeBase64, generateGraphQLFields, getResourceValueByJsonPath, getValueByPath, isNamespacedResource, stripTypename } from "@platform-mesh/portal-ui-lib/utils";
16
+ import * as gqlBuilder from "gql-query-builder";
17
+ var GatewayService = class GatewayService {
18
+ constructor() {
19
+ this.luigiCoreService = inject(LuigiCoreService);
20
+ }
21
+ getGatewayUrl(nodeContext, readFromParentKcpPath = false) {
22
+ const gatewayUrl = nodeContext.portalContext.crdGatewayApiUrl;
23
+ const currentKcpPath = this.extractKcpPath(gatewayUrl);
24
+ return gatewayUrl?.replace(currentKcpPath, this.resolveKcpPath(nodeContext, readFromParentKcpPath));
25
+ }
26
+ updateCrdGatewayUrlWithEntityPath(kcpPath) {
27
+ const gatewayUrl = this.luigiCoreService.getGlobalContext().portalContext.crdGatewayApiUrl;
28
+ const currentKcpPath = this.extractKcpPath(gatewayUrl);
29
+ this.luigiCoreService.getGlobalContext().portalContext.crdGatewayApiUrl = gatewayUrl.replace(currentKcpPath, kcpPath);
30
+ }
31
+ resolveKcpPath(nodeContext, readFromParentKcpPath = false) {
32
+ const gatewayUrl = nodeContext.portalContext.crdGatewayApiUrl;
33
+ let kcpPath = this.extractKcpPath(gatewayUrl);
34
+ if (nodeContext.kcpPath) kcpPath = nodeContext.kcpPath;
35
+ if (readFromParentKcpPath) {
36
+ const lastIndex = kcpPath.lastIndexOf(":");
37
+ if (lastIndex !== -1) kcpPath = kcpPath.slice(0, lastIndex);
38
+ }
39
+ return kcpPath;
40
+ }
41
+ extractKcpPath(gatewayUrl) {
42
+ return gatewayUrl.match(new RegExp(`(${kcpRootOrgsPath}[^/]*)`))?.[1] || "";
43
+ }
44
+ static {
45
+ this.ɵfac = i0.ɵɵngDeclareFactory({
46
+ minVersion: "12.0.0",
47
+ version: "22.2.6",
48
+ ngImport: i0,
49
+ type: GatewayService,
50
+ deps: [],
51
+ target: i0.ɵɵFactoryTarget.Injectable
52
+ });
53
+ }
54
+ static {
55
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
56
+ minVersion: "12.0.0",
57
+ version: "22.2.6",
58
+ ngImport: i0,
59
+ type: GatewayService,
60
+ providedIn: "root"
61
+ });
62
+ }
63
+ };
64
+ i0.ɵɵngDeclareClassMetadata({
65
+ minVersion: "12.0.0",
66
+ version: "22.2.6",
67
+ ngImport: i0,
68
+ type: GatewayService,
69
+ decorators: [{
70
+ type: Injectable,
71
+ args: [{ providedIn: "root" }]
72
+ }]
73
+ });
74
+ var SSELink = class extends ApolloLink {
75
+ constructor(options) {
76
+ super();
77
+ this.client = createClient(options);
78
+ }
79
+ request(operation) {
80
+ return new Observable((sink) => {
81
+ return this.client.subscribe({
82
+ ...operation,
83
+ query: print(operation.query)
84
+ }, {
85
+ next: sink.next.bind(sink),
86
+ complete: sink.complete.bind(sink),
87
+ error: sink.error.bind(sink)
88
+ });
89
+ });
90
+ }
91
+ };
73
92
  const noopZone = {
74
- run: (fn) => fn(),
75
- runOutsideAngular: (fn) => fn(),
93
+ run: (fn) => fn(),
94
+ runOutsideAngular: (fn) => fn()
76
95
  };
77
- // Long enough for an in-flight boot refresh to land, short enough to be
78
- // invisible next to a reload.
79
96
  const AUTH_RETRY_DELAY_MS = 750;
80
97
  const isUnauthorized = (error) => {
81
- const err = error;
82
- return [
83
- err?.status,
84
- err?.statusCode,
85
- err?.networkError?.status,
86
- err?.networkError?.statusCode,
87
- ].includes(401);
98
+ const err = error;
99
+ return [
100
+ err?.status,
101
+ err?.statusCode,
102
+ err?.networkError?.status,
103
+ err?.networkError?.statusCode
104
+ ].includes(401);
88
105
  };
89
- class ApolloFactory {
90
- constructor() {
91
- this.httpLink = inject(HttpLink);
92
- this.gatewayService = inject(GatewayService);
93
- this.authService = inject(AuthService);
94
- this.luigiCoreService = inject(LuigiCoreService);
95
- this.apollo = (nodeContext, readFromParentKcpPath = false) => new Apollo(noopZone, this.createApolloOptions(nodeContext, readFromParentKcpPath));
96
- }
97
- /**
98
- * The token must be resolved per request, never captured at client
99
- * creation: a client built before the shell delivers the token would
100
- * otherwise send "Bearer undefined" for its whole lifetime (silent 401s,
101
- * empty views until a hard reload). Prefer live sources over the node
102
- * context, which is a mount-time snapshot: in web-component bundles the
103
- * injected AuthService belongs to a separate injector that never runs a
104
- * refresh, so the shell's Luigi auth store is the only value that tracks
105
- * the boot refresh and later scheduled refreshes.
106
- */
107
- resolveToken(nodeContext) {
108
- return (this.authService.getToken() ||
109
- this.resolveLuigiStoreToken() ||
110
- nodeContext.token);
111
- }
112
- // Web components run on the shell window; iframe-based MFEs have no
113
- // window.Luigi, so the service throws and we fall through to the node
114
- // context. LuigiCoreService wraps the same shell global (stateless), so
115
- // it is injector-safe for web-component bundles.
116
- resolveLuigiStoreToken() {
117
- try {
118
- return this.luigiCoreService.getAuthData()?.idToken;
119
- }
120
- catch {
121
- return undefined;
122
- }
123
- }
124
- /**
125
- * Retries an operation exactly once when the gateway answers 401. The
126
- * Authorization header is rebuilt by the context link on the retry, so a
127
- * request that raced ahead of token delivery (or whose token expired in
128
- * flight) heals itself instead of leaving the view empty until a manual
129
- * reload. 401 means the request was rejected before execution, so this
130
- * is safe for mutations too.
131
- */
132
- createAuthRetryLink() {
133
- return new ApolloLink((operation, forward) => {
134
- return new Observable((observer) => {
135
- let activeSub;
136
- let retryTimer;
137
- const attempt = (isRetry) => {
138
- // A retry replaces the failed subscription; release the previous
139
- // one explicitly instead of relying on the errored link having
140
- // closed it downstream.
141
- activeSub?.unsubscribe();
142
- activeSub = forward(operation).subscribe({
143
- next: observer.next.bind(observer),
144
- complete: observer.complete.bind(observer),
145
- error: (error) => {
146
- if (!isRetry && isUnauthorized(error)) {
147
- retryTimer = setTimeout(() => attempt(true), AUTH_RETRY_DELAY_MS);
148
- return;
149
- }
150
- observer.error(error);
151
- },
152
- });
153
- };
154
- attempt(false);
155
- return () => {
156
- if (retryTimer !== undefined) {
157
- clearTimeout(retryTimer);
158
- }
159
- activeSub?.unsubscribe();
160
- };
161
- });
162
- });
163
- }
164
- createApolloOptions(nodeContext, readFromParentKcpPath = false) {
165
- const contextLink = new SetContextLink((prevContext) => {
166
- const baseHeaders = prevContext.headers instanceof HttpHeaders
167
- ? prevContext.headers
168
- : new HttpHeaders(prevContext.headers ?? {});
169
- return {
170
- ...prevContext,
171
- uri: () => this.gatewayService.getGatewayUrl(nodeContext, readFromParentKcpPath),
172
- headers: baseHeaders
173
- .set('Authorization', `Bearer ${this.resolveToken(nodeContext)}`)
174
- .set('Accept', 'charset=utf-8'),
175
- };
176
- });
177
- const splitClient = split(({ query }) => {
178
- const definition = getMainDefinition(query);
179
- return (definition.kind === 'OperationDefinition' &&
180
- definition.operation === 'subscription');
181
- }, new SSELink({
182
- url: () => this.gatewayService.getGatewayUrl(nodeContext, readFromParentKcpPath),
183
- headers: () => ({
184
- Authorization: `Bearer ${this.resolveToken(nodeContext)}`,
185
- }),
186
- }), this.httpLink.create({}));
187
- // Retry sits outermost so a retry re-runs the context link and picks
188
- // up a freshly resolved token.
189
- const link = ApolloLink.from([
190
- this.createAuthRetryLink(),
191
- contextLink,
192
- splitClient,
193
- ]);
194
- const cache = new InMemoryCache();
195
- return {
196
- link,
197
- cache,
198
- };
199
- }
200
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ApolloFactory, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
201
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ApolloFactory, providedIn: 'root' }); }
202
- }
203
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ApolloFactory, decorators: [{
204
- type: Injectable,
205
- args: [{
206
- providedIn: 'root',
207
- }]
208
- }] });
209
-
210
- class InstancePermissionsService {
211
- constructor() {
212
- this.httpClient = inject(HttpClient);
213
- this.luigiCoreService = inject(LuigiCoreService);
214
- }
215
- requestChecks(nodeContext, permissionsDefinition, instances) {
216
- if (!permissionsDefinition?.entityActions.length || !instances.length) {
217
- return of([]);
218
- }
219
- const organization = nodeContext.organization;
220
- const accountPath = nodeContext.accountPath;
221
- const token = this.luigiCoreService.getAuthData()?.idToken;
222
- if (!organization || !token) {
223
- return of([]);
224
- }
225
- const checks = instances.map((instance) => ({
226
- resource: permissionsDefinition.resource,
227
- group: permissionsDefinition.group,
228
- name: instance.name,
229
- namespace: instance.namespace,
230
- actions: permissionsDefinition.entityActions,
231
- }));
232
- const body = {
233
- organization,
234
- accountPath,
235
- checks,
236
- };
237
- return this.httpClient
238
- .post('/rest/permissions/resource-check', body, { headers: { Authorization: `Bearer ${token}` } })
239
- .pipe(catchError(() => of([])));
240
- }
241
- checkInstance(nodeContext, permissionsDefinition, instance) {
242
- return this.requestChecks(nodeContext, permissionsDefinition, [instance]);
243
- }
244
- checkInstances(nodeContext, permissionsDefinition, instances) {
245
- return this.requestChecks(nodeContext, permissionsDefinition, instances);
246
- }
247
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: InstancePermissionsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
248
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: InstancePermissionsService, providedIn: 'root' }); }
249
- }
250
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: InstancePermissionsService, decorators: [{
251
- type: Injectable,
252
- args: [{ providedIn: 'root' }]
253
- }] });
254
-
255
- class ResourceService {
256
- constructor() {
257
- this.apolloFactory = inject(ApolloFactory);
258
- this.luigiCoreService = inject(LuigiCoreService);
259
- }
260
- read(resourceId, params, fieldsOrRawQuery, nodeContext, readFromParentKcpPath = true) {
261
- const isNamespaced = isNamespacedResource(nodeContext);
262
- const namespace = this.getNamespace(nodeContext);
263
- let query = this.resolveReadQuery(params, fieldsOrRawQuery, resourceId, isNamespaced ? namespace : undefined);
264
- query = this.parseGQLQuery(query);
265
- return this.apolloFactory
266
- .apollo(nodeContext, readFromParentKcpPath)
267
- .query({
268
- query,
269
- variables: {
270
- name: resourceId,
271
- ...(isNamespaced && {
272
- namespace: namespace,
273
- }),
274
- },
275
- })
276
- .pipe(map((res) => getValueByPath(res.data, buildResourcePath(params, '.'))));
277
- }
278
- resolveReadQuery(params, fieldsOrRawQuery, resourceId, namespace) {
279
- if (fieldsOrRawQuery instanceof Array) {
280
- const { entity, version, apiGroup } = params;
281
- const queryFields = [
282
- {
283
- operation: entity,
284
- variables: {
285
- name: { value: resourceId, type: 'String!' },
286
- ...(namespace && {
287
- namespace: { value: namespace, type: 'String' },
288
- }),
289
- },
290
- fields: fieldsOrRawQuery,
291
- },
292
- ];
293
- const queryOptions = this.calcQueryOptions(queryFields, [
294
- { operation: apiGroup },
295
- { operation: version },
296
- ]);
297
- return gqlBuilder.query(queryOptions).query;
298
- }
299
- else {
300
- return fieldsOrRawQuery;
301
- }
302
- }
303
- list(operation, fieldsOrRawQuery, nodeContext, options = {}) {
304
- const { readFromParentKcpPath = false, pagination, variables: extraVariables, } = options;
305
- const isNamespaced = isNamespacedResource(nodeContext);
306
- const variables = {
307
- ...(isNamespaced && {
308
- namespace: { type: 'String', value: this.getNamespace(nodeContext) },
309
- }),
310
- ...(pagination?.limit && {
311
- limit: { type: 'Int', value: pagination?.limit },
312
- }),
313
- ...(pagination?.continue && {
314
- continue: { type: 'String', value: pagination?.continue },
315
- }),
316
- ...extraVariables,
317
- };
318
- const resourceDefinition = nodeContext.resourceDefinition;
319
- if (!resourceDefinition) {
320
- return throwError(() => new Error('Resource definition is required'));
321
- }
322
- return fieldsOrRawQuery instanceof Array
323
- ? this.listWithFields(resourceDefinition, fieldsOrRawQuery, nodeContext, readFromParentKcpPath, variables)
324
- : this.listWithRawQuery(operation, fieldsOrRawQuery, nodeContext, readFromParentKcpPath, variables);
325
- }
326
- getResourceReadyStatus(resource, nodeContext) {
327
- const readyCondition = nodeContext.resourceDefinition?.readyCondition;
328
- if (readyCondition) {
329
- return getResourceValueByJsonPath(resource, readyCondition);
330
- }
331
- return true;
332
- }
333
- listWithFields(resourceDefinition, fields, nodeContext, readFromParentKcpPath, variables) {
334
- const { apiGroup, entityCollection, version } = resourceDefinition;
335
- const queryFields = [
336
- {
337
- operation: entityCollection,
338
- variables,
339
- fields: [
340
- 'resourceVersion',
341
- 'remainingItemCount',
342
- 'continue',
343
- { items: fields },
344
- ],
345
- },
346
- ];
347
- const queryOptions = this.calcQueryOptions(queryFields, [
348
- { operation: apiGroup },
349
- { operation: version },
350
- ]);
351
- const listQuery = gqlBuilder.query(queryOptions);
352
- const query = this.parseGQLQuery(listQuery.query);
353
- return this.apolloFactory
354
- .apollo(nodeContext, readFromParentKcpPath)
355
- .query({
356
- query,
357
- variables: listQuery.variables,
358
- })
359
- .pipe(map((res) => {
360
- const resourceListResult = getValueByPath(res.data, buildResourcePath({ apiGroup, version, entity: entityCollection }, '.'));
361
- if (!resourceListResult) {
362
- throw new Error('Resource list result not found');
363
- }
364
- return resourceListResult;
365
- }), map((resourceListResult) => {
366
- const processedResult = resourceListResult.items
367
- .map((resource) => ({
368
- ...resource,
369
- ready: this.getResourceReadyStatus(resource, nodeContext),
370
- }))
371
- .map((r) => ({
372
- ...r,
373
- id: this.getResourceId(r),
374
- isAvailable: this.isAvailable(r, resourceDefinition.availableWhenNotReady),
375
- accessibleName: this.getAccessibleName(r),
376
- }));
377
- return { ...resourceListResult, items: processedResult };
378
- }));
379
- }
380
- getResourceId(resource) {
381
- return `${resource.metadata.name}${resource.metadata.namespace ? '_' + resource.metadata.namespace : ''}`;
382
- }
383
- isAvailable(item, availableWhenNotReady = false) {
384
- return ((!!item.ready || availableWhenNotReady) &&
385
- !item.metadata?.deletionTimestamp);
386
- }
387
- getAccessibleName(item) {
388
- if (item.metadata?.deletionTimestamp) {
389
- return 'Resource is pending deletion';
390
- }
391
- else if (!item.ready) {
392
- return 'Resource is not ready';
393
- }
394
- return undefined;
395
- }
396
- listWithRawQuery(operation, rawQuery, nodeContext, readFromParentKcpPath, variables) {
397
- const query = this.parseGQLQuery(rawQuery);
398
- return this.apolloFactory
399
- .apollo(nodeContext, readFromParentKcpPath)
400
- .query({
401
- query,
402
- variables: this.normalizeGqlBuilderVariables(variables),
403
- })
404
- .pipe(map((res) => getValueByPath(res.data, operation) ?? []));
405
- }
406
- resourceChangeSubscription(operation, fields, nodeContext, resourceVersion, readFromParentKcpPath) {
407
- const isNamespaced = isNamespacedResource(nodeContext);
408
- const variables = {
409
- ...(isNamespaced && {
410
- namespace: { type: 'String', value: this.getNamespace(nodeContext) },
411
- }),
412
- };
413
- const lowerCaseOperation = operation.toLowerCase();
414
- const subscriptionQuery = gqlBuilder.subscription({
415
- operation: lowerCaseOperation,
416
- fields: ['type', { object: fields }],
417
- variables: {
418
- ...variables,
419
- resourceVersion: {
420
- type: 'String',
421
- value: resourceVersion,
422
- },
423
- },
424
- });
425
- const query = this.parseGQLQuery(subscriptionQuery.query);
426
- return this.apolloFactory
427
- .apollo(nodeContext, readFromParentKcpPath)
428
- .subscribe({
429
- query,
430
- variables: subscriptionQuery.variables,
431
- })
432
- .pipe(map((res) => {
433
- const resource = getValueByPath(res.data, lowerCaseOperation);
434
- if (resource) {
435
- resource.object.ready = this.getResourceReadyStatus(resource.object, nodeContext);
436
- resource.object.id = this.getResourceId(resource.object);
437
- resource.object.isAvailable = this.isAvailable(resource.object, nodeContext.resourceDefinition?.availableWhenNotReady);
438
- resource.object.accessibleName = this.getAccessibleName(resource.object);
439
- }
440
- return resource;
441
- }));
442
- }
443
- delete(resource, resourceDefinition, nodeContext, readFromParentKcpPath = false) {
444
- const isNamespaced = isNamespacedResource(nodeContext);
445
- const { apiGroup, entity, version } = resourceDefinition;
446
- const fields = [
447
- {
448
- operation: `delete${entity}`,
449
- variables: {
450
- name: { type: 'String!', value: resource.metadata.name },
451
- ...(isNamespaced && {
452
- namespace: {
453
- type: 'String',
454
- value: this.getNamespace(nodeContext),
455
- },
456
- }),
457
- },
458
- fields: [],
459
- },
460
- ];
461
- const queryOptions = this.calcQueryOptions(fields, [
462
- { operation: apiGroup },
463
- { operation: version },
464
- ]);
465
- const mutation = gqlBuilder.mutation(queryOptions);
466
- const query = this.parseGQLQuery(mutation.query);
467
- return this.apolloFactory
468
- .apollo(nodeContext, readFromParentKcpPath)
469
- .mutate({
470
- mutation: query,
471
- variables: mutation.variables,
472
- });
473
- }
474
- create(resource, resourceDefinition, nodeContext) {
475
- const isNamespaced = isNamespacedResource(nodeContext);
476
- const { apiGroup, entity, version } = resourceDefinition;
477
- const namespace = this.getNamespace(nodeContext, resource);
478
- const apollo = this.apolloFactory.apollo(nodeContext);
479
- return this.readInputTypeName(apollo, resourceDefinition).pipe(switchMap((inputTypeName) => {
480
- const mutationFields = [
481
- {
482
- operation: `create${entity}`,
483
- variables: {
484
- ...(isNamespaced && {
485
- namespace: { type: 'String', value: namespace },
486
- }),
487
- object: {
488
- type: `${inputTypeName}!`,
489
- value: resource,
490
- },
491
- },
492
- fields: ['__typename'],
493
- },
494
- ];
495
- const queryOptions = this.calcQueryOptions(mutationFields, [
496
- { operation: apiGroup },
497
- { operation: version },
498
- ]);
499
- const mutation = gqlBuilder.mutation(queryOptions);
500
- const query = this.parseGQLQuery(mutation.query);
501
- return apollo.mutate({
502
- mutation: query,
503
- fetchPolicy: 'no-cache',
504
- variables: mutation.variables,
505
- });
506
- }));
507
- }
508
- update(resource, resourceDefinition, nodeContext, readFromParentKcpPath = false, fields = ['__typename']) {
509
- const isNamespaced = isNamespacedResource(nodeContext);
510
- const { apiGroup, entity, version } = resourceDefinition;
511
- const namespace = this.getNamespace(nodeContext, resource);
512
- const cleanResource = stripTypename(resource);
513
- const apollo = this.apolloFactory.apollo(nodeContext, readFromParentKcpPath);
514
- return this.readInputTypeName(apollo, resourceDefinition).pipe(switchMap((inputTypeName) => {
515
- const mutationFields = [
516
- {
517
- operation: `update${entity}`,
518
- variables: {
519
- ...(isNamespaced && {
520
- namespace: { type: 'String', value: namespace },
521
- }),
522
- name: { type: 'String!', value: resource.metadata.name },
523
- object: {
524
- type: `${inputTypeName}!`,
525
- value: cleanResource,
526
- },
527
- },
528
- fields: fields,
529
- },
530
- ];
531
- const queryOptions = this.calcQueryOptions(mutationFields, [
532
- { operation: apiGroup },
533
- { operation: version },
534
- ]);
535
- const mutation = gqlBuilder.mutation(queryOptions);
536
- const query = this.parseGQLQuery(mutation.query);
537
- return apollo.mutate({
538
- mutation: query,
539
- fetchPolicy: 'no-cache',
540
- variables: mutation.variables,
541
- });
542
- }), map((res) => getValueByPath(res.data, buildResourcePath({ apiGroup, entity: `update${entity}`, version }, '.'))));
543
- }
544
- /**
545
- * Reads the `__typename` of the query type that holds the resource, e.g.
546
- * `{ network_api_foo_bar { v1alpha1 { __typename } } }`, and derives the
547
- * mutation input type name from it. The gateway generates the schema, so
548
- * its type names are the only source of truth.
549
- */
550
- readInputTypeName(apollo, resourceDefinition) {
551
- const { apiGroup, entity, version } = resourceDefinition;
552
- const selection = [apiGroup, version]
553
- .filter((field) => !!field)
554
- .reduceRight((inner, field) => `${field} { ${inner} }`, '__typename');
555
- return apollo
556
- .query({ query: this.parseGQLQuery(`query { ${selection} }`) })
557
- .pipe(map((res) => buildGraphQLInputTypeName(getValueByPath(res.data, buildResourcePath({ apiGroup, entity: '__typename', version }, '.')), entity)));
558
- }
559
- getNamespace(nodeContext, resource) {
560
- // namespaceId can carry the '-all-' sentinel when the portal forwards the
561
- // namespace selection; it is never a real namespace, so fall through.
562
- if (nodeContext.namespaceId && nodeContext.namespaceId !== ALL_NAMESPACE) {
563
- return nodeContext.namespaceId;
564
- }
565
- if (resource?.metadata?.namespace) {
566
- return resource.metadata.namespace;
567
- }
568
- const namespace = this.luigiCoreService
569
- .routing()
570
- .getSearchParams().namespace;
571
- if (namespace) {
572
- return namespace === ALL_NAMESPACE ? undefined : namespace;
573
- }
574
- return undefined;
575
- }
576
- normalizeGqlBuilderVariables(variables) {
577
- return Object.fromEntries(Object.entries(variables).map(([key, value]) => [key, value.value]));
578
- }
579
- calcQueryOptions(innerFields, wrappers) {
580
- const filteredWrappers = wrappers.filter((wrapper) => !!wrapper?.operation);
581
- if (filteredWrappers.length === 0) {
582
- const completeQuery = innerFields.pop();
583
- if (completeQuery && completeQuery.operation && completeQuery.fields) {
584
- return completeQuery;
585
- }
586
- throw new Error('At least one wrapper or inner fields is required');
587
- }
588
- let fields = innerFields;
589
- let nextWrapper = filteredWrappers.pop();
590
- filteredWrappers.forEach((wrapper) => {
591
- fields = [
592
- {
593
- operation: nextWrapper.operation,
594
- fields: innerFields,
595
- variables: nextWrapper.variables,
596
- },
597
- ];
598
- nextWrapper = wrapper;
599
- });
600
- return {
601
- operation: nextWrapper.operation,
602
- fields,
603
- variables: nextWrapper.variables,
604
- };
605
- }
606
- parseGQLQuery(query) {
607
- try {
608
- return gql `
106
+ var ApolloFactory = class ApolloFactory {
107
+ constructor() {
108
+ this.httpLink = inject(HttpLink);
109
+ this.gatewayService = inject(GatewayService);
110
+ this.authService = inject(AuthService);
111
+ this.luigiCoreService = inject(LuigiCoreService);
112
+ this.apollo = (nodeContext, readFromParentKcpPath = false) => new Apollo(noopZone, this.createApolloOptions(nodeContext, readFromParentKcpPath));
113
+ }
114
+ resolveToken(nodeContext) {
115
+ return this.authService.getToken() || this.resolveLuigiStoreToken() || nodeContext.token;
116
+ }
117
+ resolveLuigiStoreToken() {
118
+ try {
119
+ return this.luigiCoreService.getAuthData()?.idToken;
120
+ } catch {
121
+ return;
122
+ }
123
+ }
124
+ createAuthRetryLink() {
125
+ return new ApolloLink((operation, forward) => {
126
+ return new Observable((observer) => {
127
+ let activeSub;
128
+ let retryTimer;
129
+ const attempt = (isRetry) => {
130
+ activeSub?.unsubscribe();
131
+ activeSub = forward(operation).subscribe({
132
+ next: observer.next.bind(observer),
133
+ complete: observer.complete.bind(observer),
134
+ error: (error) => {
135
+ if (!isRetry && isUnauthorized(error)) {
136
+ retryTimer = setTimeout(() => attempt(true), AUTH_RETRY_DELAY_MS);
137
+ return;
138
+ }
139
+ observer.error(error);
140
+ }
141
+ });
142
+ };
143
+ attempt(false);
144
+ return () => {
145
+ if (retryTimer !== void 0) clearTimeout(retryTimer);
146
+ activeSub?.unsubscribe();
147
+ };
148
+ });
149
+ });
150
+ }
151
+ createApolloOptions(nodeContext, readFromParentKcpPath = false) {
152
+ const contextLink = new SetContextLink((prevContext) => {
153
+ const baseHeaders = prevContext.headers instanceof HttpHeaders ? prevContext.headers : new HttpHeaders(prevContext.headers ?? {});
154
+ return {
155
+ ...prevContext,
156
+ uri: () => this.gatewayService.getGatewayUrl(nodeContext, readFromParentKcpPath),
157
+ headers: baseHeaders.set("Authorization", `Bearer ${this.resolveToken(nodeContext)}`).set("Accept", "charset=utf-8")
158
+ };
159
+ });
160
+ const splitClient = split(({ query }) => {
161
+ const definition = getMainDefinition(query);
162
+ return definition.kind === "OperationDefinition" && definition.operation === "subscription";
163
+ }, new SSELink({
164
+ url: () => this.gatewayService.getGatewayUrl(nodeContext, readFromParentKcpPath),
165
+ headers: () => ({ Authorization: `Bearer ${this.resolveToken(nodeContext)}` })
166
+ }), this.httpLink.create({}));
167
+ return {
168
+ link: ApolloLink.from([
169
+ this.createAuthRetryLink(),
170
+ contextLink,
171
+ splitClient
172
+ ]),
173
+ cache: new InMemoryCache()
174
+ };
175
+ }
176
+ static {
177
+ this.ɵfac = i0.ɵɵngDeclareFactory({
178
+ minVersion: "12.0.0",
179
+ version: "22.2.6",
180
+ ngImport: i0,
181
+ type: ApolloFactory,
182
+ deps: [],
183
+ target: i0.ɵɵFactoryTarget.Injectable
184
+ });
185
+ }
186
+ static {
187
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
188
+ minVersion: "12.0.0",
189
+ version: "22.2.6",
190
+ ngImport: i0,
191
+ type: ApolloFactory,
192
+ providedIn: "root"
193
+ });
194
+ }
195
+ };
196
+ i0.ɵɵngDeclareClassMetadata({
197
+ minVersion: "12.0.0",
198
+ version: "22.2.6",
199
+ ngImport: i0,
200
+ type: ApolloFactory,
201
+ decorators: [{
202
+ type: Injectable,
203
+ args: [{ providedIn: "root" }]
204
+ }]
205
+ });
206
+ var InstancePermissionsService = class InstancePermissionsService {
207
+ constructor() {
208
+ this.httpClient = inject(HttpClient);
209
+ this.luigiCoreService = inject(LuigiCoreService);
210
+ }
211
+ requestChecks(nodeContext, permissionsDefinition, instances) {
212
+ if (!permissionsDefinition?.entityActions.length || !instances.length) return of([]);
213
+ const organization = nodeContext.organization;
214
+ const accountPath = nodeContext.accountPath;
215
+ const token = this.luigiCoreService.getAuthData()?.idToken;
216
+ if (!organization || !token) return of([]);
217
+ const body = {
218
+ organization,
219
+ accountPath,
220
+ checks: instances.map((instance) => ({
221
+ resource: permissionsDefinition.resource,
222
+ group: permissionsDefinition.group,
223
+ name: instance.name,
224
+ namespace: instance.namespace,
225
+ actions: permissionsDefinition.entityActions
226
+ }))
227
+ };
228
+ return this.httpClient.post("/rest/permissions/resource-check", body, { headers: { Authorization: `Bearer ${token}` } }).pipe(catchError$1(() => of([])));
229
+ }
230
+ checkInstance(nodeContext, permissionsDefinition, instance) {
231
+ return this.requestChecks(nodeContext, permissionsDefinition, [instance]);
232
+ }
233
+ checkInstances(nodeContext, permissionsDefinition, instances) {
234
+ return this.requestChecks(nodeContext, permissionsDefinition, instances);
235
+ }
236
+ static {
237
+ this.ɵfac = i0.ɵɵngDeclareFactory({
238
+ minVersion: "12.0.0",
239
+ version: "22.2.6",
240
+ ngImport: i0,
241
+ type: InstancePermissionsService,
242
+ deps: [],
243
+ target: i0.ɵɵFactoryTarget.Injectable
244
+ });
245
+ }
246
+ static {
247
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
248
+ minVersion: "12.0.0",
249
+ version: "22.2.6",
250
+ ngImport: i0,
251
+ type: InstancePermissionsService,
252
+ providedIn: "root"
253
+ });
254
+ }
255
+ };
256
+ i0.ɵɵngDeclareClassMetadata({
257
+ minVersion: "12.0.0",
258
+ version: "22.2.6",
259
+ ngImport: i0,
260
+ type: InstancePermissionsService,
261
+ decorators: [{
262
+ type: Injectable,
263
+ args: [{ providedIn: "root" }]
264
+ }]
265
+ });
266
+ var ResourceService = class ResourceService {
267
+ constructor() {
268
+ this.apolloFactory = inject(ApolloFactory);
269
+ this.luigiCoreService = inject(LuigiCoreService);
270
+ }
271
+ read(resourceId, params, fieldsOrRawQuery, nodeContext, readFromParentKcpPath = true) {
272
+ const isNamespaced = isNamespacedResource(nodeContext);
273
+ const namespace = this.getNamespace(nodeContext);
274
+ let query = this.resolveReadQuery(params, fieldsOrRawQuery, resourceId, isNamespaced ? namespace : void 0);
275
+ query = this.parseGQLQuery(query);
276
+ return this.apolloFactory.apollo(nodeContext, readFromParentKcpPath).query({
277
+ query,
278
+ variables: {
279
+ name: resourceId,
280
+ ...isNamespaced && { namespace }
281
+ }
282
+ }).pipe(map$1((res) => getValueByPath(res.data, buildResourcePath(params, "."))));
283
+ }
284
+ resolveReadQuery(params, fieldsOrRawQuery, resourceId, namespace) {
285
+ if (fieldsOrRawQuery instanceof Array) {
286
+ const { entity, version, apiGroup } = params;
287
+ const queryFields = [{
288
+ operation: entity,
289
+ variables: {
290
+ name: {
291
+ value: resourceId,
292
+ type: "String!"
293
+ },
294
+ ...namespace && { namespace: {
295
+ value: namespace,
296
+ type: "String"
297
+ } }
298
+ },
299
+ fields: fieldsOrRawQuery
300
+ }];
301
+ const queryOptions = this.calcQueryOptions(queryFields, [{ operation: apiGroup }, { operation: version }]);
302
+ return gqlBuilder.query(queryOptions).query;
303
+ } else return fieldsOrRawQuery;
304
+ }
305
+ list(operation, fieldsOrRawQuery, nodeContext, options = {}) {
306
+ const { readFromParentKcpPath = false, pagination, variables: extraVariables } = options;
307
+ const variables = {
308
+ ...isNamespacedResource(nodeContext) && { namespace: {
309
+ type: "String",
310
+ value: this.getNamespace(nodeContext)
311
+ } },
312
+ ...pagination?.limit && { limit: {
313
+ type: "Int",
314
+ value: pagination?.limit
315
+ } },
316
+ ...pagination?.continue && { continue: {
317
+ type: "String",
318
+ value: pagination?.continue
319
+ } },
320
+ ...extraVariables
321
+ };
322
+ const resourceDefinition = nodeContext.resourceDefinition;
323
+ if (!resourceDefinition) return throwError(() => /* @__PURE__ */ new Error("Resource definition is required"));
324
+ return fieldsOrRawQuery instanceof Array ? this.listWithFields(resourceDefinition, fieldsOrRawQuery, nodeContext, readFromParentKcpPath, variables) : this.listWithRawQuery(operation, fieldsOrRawQuery, nodeContext, readFromParentKcpPath, variables);
325
+ }
326
+ getResourceReadyStatus(resource, nodeContext) {
327
+ const readyCondition = nodeContext.resourceDefinition?.readyCondition;
328
+ if (readyCondition) return getResourceValueByJsonPath(resource, readyCondition);
329
+ return true;
330
+ }
331
+ listWithFields(resourceDefinition, fields, nodeContext, readFromParentKcpPath, variables) {
332
+ const { apiGroup, entityCollection, version } = resourceDefinition;
333
+ const queryFields = [{
334
+ operation: entityCollection,
335
+ variables,
336
+ fields: [
337
+ "resourceVersion",
338
+ "remainingItemCount",
339
+ "continue",
340
+ { items: fields }
341
+ ]
342
+ }];
343
+ const queryOptions = this.calcQueryOptions(queryFields, [{ operation: apiGroup }, { operation: version }]);
344
+ const listQuery = gqlBuilder.query(queryOptions);
345
+ const query = this.parseGQLQuery(listQuery.query);
346
+ return this.apolloFactory.apollo(nodeContext, readFromParentKcpPath).query({
347
+ query,
348
+ variables: listQuery.variables
349
+ }).pipe(map$1((res) => {
350
+ const resourceListResult = getValueByPath(res.data, buildResourcePath({
351
+ apiGroup,
352
+ version,
353
+ entity: entityCollection
354
+ }, "."));
355
+ if (!resourceListResult) throw new Error("Resource list result not found");
356
+ return resourceListResult;
357
+ }), map$1((resourceListResult) => {
358
+ const processedResult = resourceListResult.items.map((resource) => ({
359
+ ...resource,
360
+ ready: this.getResourceReadyStatus(resource, nodeContext)
361
+ })).map((r) => ({
362
+ ...r,
363
+ id: this.getResourceId(r),
364
+ isAvailable: this.isAvailable(r, resourceDefinition.availableWhenNotReady),
365
+ accessibleName: this.getAccessibleName(r)
366
+ }));
367
+ return {
368
+ ...resourceListResult,
369
+ items: processedResult
370
+ };
371
+ }));
372
+ }
373
+ getResourceId(resource) {
374
+ return `${resource.metadata.name}${resource.metadata.namespace ? "_" + resource.metadata.namespace : ""}`;
375
+ }
376
+ isAvailable(item, availableWhenNotReady = false) {
377
+ return (!!item.ready || availableWhenNotReady) && !item.metadata?.deletionTimestamp;
378
+ }
379
+ getAccessibleName(item) {
380
+ if (item.metadata?.deletionTimestamp) return "Resource is pending deletion";
381
+ else if (!item.ready) return "Resource is not ready";
382
+ }
383
+ listWithRawQuery(operation, rawQuery, nodeContext, readFromParentKcpPath, variables) {
384
+ const query = this.parseGQLQuery(rawQuery);
385
+ return this.apolloFactory.apollo(nodeContext, readFromParentKcpPath).query({
386
+ query,
387
+ variables: this.normalizeGqlBuilderVariables(variables)
388
+ }).pipe(map$1((res) => getValueByPath(res.data, operation) ?? []));
389
+ }
390
+ resourceChangeSubscription(operation, fields, nodeContext, resourceVersion, readFromParentKcpPath) {
391
+ const variables = { ...isNamespacedResource(nodeContext) && { namespace: {
392
+ type: "String",
393
+ value: this.getNamespace(nodeContext)
394
+ } } };
395
+ const lowerCaseOperation = operation.toLowerCase();
396
+ const subscriptionQuery = gqlBuilder.subscription({
397
+ operation: lowerCaseOperation,
398
+ fields: ["type", { object: fields }],
399
+ variables: {
400
+ ...variables,
401
+ resourceVersion: {
402
+ type: "String",
403
+ value: resourceVersion
404
+ }
405
+ }
406
+ });
407
+ const query = this.parseGQLQuery(subscriptionQuery.query);
408
+ return this.apolloFactory.apollo(nodeContext, readFromParentKcpPath).subscribe({
409
+ query,
410
+ variables: subscriptionQuery.variables
411
+ }).pipe(map$1((res) => {
412
+ const resource = getValueByPath(res.data, lowerCaseOperation);
413
+ if (resource) {
414
+ resource.object.ready = this.getResourceReadyStatus(resource.object, nodeContext);
415
+ resource.object.id = this.getResourceId(resource.object);
416
+ resource.object.isAvailable = this.isAvailable(resource.object, nodeContext.resourceDefinition?.availableWhenNotReady);
417
+ resource.object.accessibleName = this.getAccessibleName(resource.object);
418
+ }
419
+ return resource;
420
+ }));
421
+ }
422
+ delete(resource, resourceDefinition, nodeContext, readFromParentKcpPath = false) {
423
+ const isNamespaced = isNamespacedResource(nodeContext);
424
+ const { apiGroup, entity, version } = resourceDefinition;
425
+ const fields = [{
426
+ operation: `delete${entity}`,
427
+ variables: {
428
+ name: {
429
+ type: "String!",
430
+ value: resource.metadata.name
431
+ },
432
+ ...isNamespaced && { namespace: {
433
+ type: "String",
434
+ value: this.getNamespace(nodeContext)
435
+ } }
436
+ },
437
+ fields: []
438
+ }];
439
+ const queryOptions = this.calcQueryOptions(fields, [{ operation: apiGroup }, { operation: version }]);
440
+ const mutation = gqlBuilder.mutation(queryOptions);
441
+ const query = this.parseGQLQuery(mutation.query);
442
+ return this.apolloFactory.apollo(nodeContext, readFromParentKcpPath).mutate({
443
+ mutation: query,
444
+ variables: mutation.variables
445
+ });
446
+ }
447
+ create(resource, resourceDefinition, nodeContext) {
448
+ const isNamespaced = isNamespacedResource(nodeContext);
449
+ const { apiGroup, entity, version } = resourceDefinition;
450
+ const namespace = this.getNamespace(nodeContext, resource);
451
+ const apollo = this.apolloFactory.apollo(nodeContext);
452
+ return this.readInputTypeName(apollo, resourceDefinition).pipe(switchMap((inputTypeName) => {
453
+ const mutationFields = [{
454
+ operation: `create${entity}`,
455
+ variables: {
456
+ ...isNamespaced && { namespace: {
457
+ type: "String",
458
+ value: namespace
459
+ } },
460
+ object: {
461
+ type: `${inputTypeName}!`,
462
+ value: resource
463
+ }
464
+ },
465
+ fields: ["__typename"]
466
+ }];
467
+ const queryOptions = this.calcQueryOptions(mutationFields, [{ operation: apiGroup }, { operation: version }]);
468
+ const mutation = gqlBuilder.mutation(queryOptions);
469
+ const query = this.parseGQLQuery(mutation.query);
470
+ return apollo.mutate({
471
+ mutation: query,
472
+ fetchPolicy: "no-cache",
473
+ variables: mutation.variables
474
+ });
475
+ }));
476
+ }
477
+ update(resource, resourceDefinition, nodeContext, readFromParentKcpPath = false, fields = ["__typename"]) {
478
+ const isNamespaced = isNamespacedResource(nodeContext);
479
+ const { apiGroup, entity, version } = resourceDefinition;
480
+ const namespace = this.getNamespace(nodeContext, resource);
481
+ const cleanResource = stripTypename(resource);
482
+ const apollo = this.apolloFactory.apollo(nodeContext, readFromParentKcpPath);
483
+ return this.readInputTypeName(apollo, resourceDefinition).pipe(switchMap((inputTypeName) => {
484
+ const mutationFields = [{
485
+ operation: `update${entity}`,
486
+ variables: {
487
+ ...isNamespaced && { namespace: {
488
+ type: "String",
489
+ value: namespace
490
+ } },
491
+ name: {
492
+ type: "String!",
493
+ value: resource.metadata.name
494
+ },
495
+ object: {
496
+ type: `${inputTypeName}!`,
497
+ value: cleanResource
498
+ }
499
+ },
500
+ fields
501
+ }];
502
+ const queryOptions = this.calcQueryOptions(mutationFields, [{ operation: apiGroup }, { operation: version }]);
503
+ const mutation = gqlBuilder.mutation(queryOptions);
504
+ const query = this.parseGQLQuery(mutation.query);
505
+ return apollo.mutate({
506
+ mutation: query,
507
+ fetchPolicy: "no-cache",
508
+ variables: mutation.variables
509
+ });
510
+ }), map$1((res) => getValueByPath(res.data, buildResourcePath({
511
+ apiGroup,
512
+ entity: `update${entity}`,
513
+ version
514
+ }, "."))));
515
+ }
516
+ readInputTypeName(apollo, resourceDefinition) {
517
+ const { apiGroup, entity, version } = resourceDefinition;
518
+ const selection = [apiGroup, version].filter((field) => !!field).reduceRight((inner, field) => `${field} { ${inner} }`, "__typename");
519
+ return apollo.query({ query: this.parseGQLQuery(`query { ${selection} }`) }).pipe(map$1((res) => buildGraphQLInputTypeName(getValueByPath(res.data, buildResourcePath({
520
+ apiGroup,
521
+ entity: "__typename",
522
+ version
523
+ }, ".")), entity)));
524
+ }
525
+ getNamespace(nodeContext, resource) {
526
+ if (nodeContext.namespaceId && nodeContext.namespaceId !== ALL_NAMESPACE) return nodeContext.namespaceId;
527
+ if (resource?.metadata?.namespace) return resource.metadata.namespace;
528
+ const namespace = this.luigiCoreService.routing().getSearchParams().namespace;
529
+ if (namespace) return namespace === ALL_NAMESPACE ? void 0 : namespace;
530
+ }
531
+ normalizeGqlBuilderVariables(variables) {
532
+ return Object.fromEntries(Object.entries(variables).map(([key, value]) => [key, value.value]));
533
+ }
534
+ calcQueryOptions(innerFields, wrappers) {
535
+ const filteredWrappers = wrappers.filter((wrapper) => !!wrapper?.operation);
536
+ if (filteredWrappers.length === 0) {
537
+ const completeQuery = innerFields.pop();
538
+ if (completeQuery && completeQuery.operation && completeQuery.fields) return completeQuery;
539
+ throw new Error("At least one wrapper or inner fields is required");
540
+ }
541
+ let fields = innerFields;
542
+ let nextWrapper = filteredWrappers.pop();
543
+ filteredWrappers.forEach((wrapper) => {
544
+ fields = [{
545
+ operation: nextWrapper.operation,
546
+ fields: innerFields,
547
+ variables: nextWrapper.variables
548
+ }];
549
+ nextWrapper = wrapper;
550
+ });
551
+ return {
552
+ operation: nextWrapper.operation,
553
+ fields,
554
+ variables: nextWrapper.variables
555
+ };
556
+ }
557
+ parseGQLQuery(query) {
558
+ try {
559
+ return gql`
609
560
  ${query}
610
561
  `;
611
- }
612
- catch (error) {
613
- const message = error instanceof Error ? error.message : String(error);
614
- this.luigiCoreService.showAlert({
615
- text: `Could not parse gql query: <br/><br/> ${query} <br/><br/> ${message}`,
616
- type: 'error',
617
- });
618
- throw error;
619
- }
620
- }
621
- /**
622
- * Returns a {@link ReadResources}-shaped adapter over this service so that
623
- * consumers can swap implementations behind a feature toggle without depending
624
- * on the GraphQL-specific signatures of `list` / `resourceChangeSubscription`.
625
- */
626
- asReadResources() {
627
- return {
628
- list: (nodeContext, pagination, params) => {
629
- const operation = params.operation ??
630
- nodeContext.resourceDefinition?.entityCollection ??
631
- '';
632
- const fields = params.fields ??
633
- nodeContext.resourceDefinition?.ui?.listView?.fields ??
634
- [];
635
- const resourcePagination = {
636
- limit: pagination.limit,
637
- continue: pagination.cursor,
638
- };
639
- return this.list(operation, fields, nodeContext, {
640
- readFromParentKcpPath: params.readFromParentKcpPath ?? false,
641
- pagination: resourcePagination,
642
- }).pipe(map((result) => ({
643
- items: result?.items ?? [],
644
- nextCursor: result?.continue,
645
- remainingItemCount: result?.remainingItemCount,
646
- resourceVersion: result?.resourceVersion,
647
- })));
648
- },
649
- subscribe: (nodeContext, params) => {
650
- const operation = nodeContext.resourceDefinition?.entityCollection ?? '';
651
- const fields = Array.isArray(params.fields)
652
- ? params.fields
653
- : (nodeContext.resourceDefinition?.ui?.listView?.fields ??
654
- []);
655
- return this.resourceChangeSubscription(operation, fields, nodeContext, params.resourceVersion ?? '', params.readFromParentKcpPath ?? false);
656
- },
657
- };
658
- }
659
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ResourceService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
660
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ResourceService, providedIn: 'root' }); }
661
- }
662
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ResourceService, decorators: [{
663
- type: Injectable,
664
- args: [{
665
- providedIn: 'root',
666
- }]
667
- }] });
668
-
562
+ } catch (error) {
563
+ const message = error instanceof Error ? error.message : String(error);
564
+ this.luigiCoreService.showAlert({
565
+ text: `Could not parse gql query: <br/><br/> ${query} <br/><br/> ${message}`,
566
+ type: "error"
567
+ });
568
+ throw error;
569
+ }
570
+ }
571
+ asReadResources() {
572
+ return {
573
+ list: (nodeContext, pagination, params) => {
574
+ const operation = params.operation ?? nodeContext.resourceDefinition?.entityCollection ?? "";
575
+ const fields = params.fields ?? nodeContext.resourceDefinition?.ui?.listView?.fields ?? [];
576
+ const resourcePagination = {
577
+ limit: pagination.limit,
578
+ continue: pagination.cursor
579
+ };
580
+ return this.list(operation, fields, nodeContext, {
581
+ readFromParentKcpPath: params.readFromParentKcpPath ?? false,
582
+ pagination: resourcePagination
583
+ }).pipe(map$1((result) => ({
584
+ items: result?.items ?? [],
585
+ nextCursor: result?.continue,
586
+ remainingItemCount: result?.remainingItemCount,
587
+ resourceVersion: result?.resourceVersion
588
+ })));
589
+ },
590
+ subscribe: (nodeContext, params) => {
591
+ const operation = nodeContext.resourceDefinition?.entityCollection ?? "";
592
+ const fields = Array.isArray(params.fields) ? params.fields : nodeContext.resourceDefinition?.ui?.listView?.fields ?? [];
593
+ return this.resourceChangeSubscription(operation, fields, nodeContext, params.resourceVersion ?? "", params.readFromParentKcpPath ?? false);
594
+ }
595
+ };
596
+ }
597
+ static {
598
+ this.ɵfac = i0.ɵɵngDeclareFactory({
599
+ minVersion: "12.0.0",
600
+ version: "22.2.6",
601
+ ngImport: i0,
602
+ type: ResourceService,
603
+ deps: [],
604
+ target: i0.ɵɵFactoryTarget.Injectable
605
+ });
606
+ }
607
+ static {
608
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
609
+ minVersion: "12.0.0",
610
+ version: "22.2.6",
611
+ ngImport: i0,
612
+ type: ResourceService,
613
+ providedIn: "root"
614
+ });
615
+ }
616
+ };
617
+ i0.ɵɵngDeclareClassMetadata({
618
+ minVersion: "12.0.0",
619
+ version: "22.2.6",
620
+ ngImport: i0,
621
+ type: ResourceService,
622
+ decorators: [{
623
+ type: Injectable,
624
+ args: [{ providedIn: "root" }]
625
+ }]
626
+ });
669
627
  const SECRET_RESOURCE_DEFINITION = {
670
- version: 'v1',
671
- entity: 'Secret',
672
- entityCollection: 'Secrets',
673
- scope: 'Namespaced',
628
+ version: "v1",
629
+ entity: "Secret",
630
+ entityCollection: "Secrets",
631
+ scope: "Namespaced"
674
632
  };
675
- const DEFAULT_DATA_KEY = 'kubeconfig';
676
- const DEFAULT_FILENAME = 'kubeconfig.yaml';
633
+ const DEFAULT_DATA_KEY = "kubeconfig";
634
+ const DEFAULT_FILENAME = "kubeconfig.yaml";
677
635
  function isDownloadKubeconfigButtonSettings(buttonSettings) {
678
- return buttonSettings?.action === DOWNLOAD_KUBECONFIG_FROM_SECRET_REF_ACTION;
636
+ return buttonSettings?.action === DOWNLOAD_KUBECONFIG_FROM_SECRET_REF_ACTION;
679
637
  }
680
- class KubeconfigSecretService {
681
- constructor() {
682
- this.resourceService = inject(ResourceService);
683
- }
684
- /**
685
- * Fields the detail-view query has to read so the action can resolve its
686
- * Secret reference from the loaded resource.
687
- */
688
- secretReferenceQueryFields(buttonSettings) {
689
- if (!isDownloadKubeconfigButtonSettings(buttonSettings)) {
690
- return [];
691
- }
692
- const fields = [];
693
- const resourceProperty = this.readString(buttonSettings.resourceProperty);
694
- if (resourceProperty) {
695
- fields.push({ property: resourceProperty });
696
- }
697
- const namespaceProperty = this.readString(buttonSettings.namespaceProperty);
698
- if (namespaceProperty) {
699
- fields.push({ property: namespaceProperty });
700
- }
701
- return fields;
702
- }
703
- isSecretReferenceAvailable(buttonSettings, resource, context) {
704
- return (isDownloadKubeconfigButtonSettings(buttonSettings) &&
705
- this.resolveSecretReference(buttonSettings, resource, context) !==
706
- undefined);
707
- }
708
- readKubeconfig(buttonSettings, resource, context) {
709
- if (!isDownloadKubeconfigButtonSettings(buttonSettings)) {
710
- return throwError(() => new Error('Button is not a kubeconfig download action'));
711
- }
712
- const secretReference = this.resolveSecretReference(buttonSettings, resource, context);
713
- if (!secretReference) {
714
- return throwError(() => new Error('Kubeconfig Secret reference is not available'));
715
- }
716
- const dataKey = this.readString(buttonSettings.dataKey) ?? DEFAULT_DATA_KEY;
717
- const filename = this.readString(buttonSettings.filename) ?? DEFAULT_FILENAME;
718
- const secretContext = {
719
- ...context,
720
- namespaceId: secretReference.namespace,
721
- resourceDefinition: SECRET_RESOURCE_DEFINITION,
722
- };
723
- return this.resourceService
724
- .read(secretReference.name, SECRET_RESOURCE_DEFINITION, ['data'], secretContext, false)
725
- .pipe(catchError$1(() => throwError(() => new Error('Kubeconfig Secret could not be read'))), map$1((secret) => {
726
- const encodedKubeconfig = this.readString(secret?.data?.[dataKey]);
727
- if (!encodedKubeconfig) {
728
- throw new Error(`Kubeconfig data key "${dataKey}" is not available`);
729
- }
730
- return {
731
- contents: decodeBase64(encodedKubeconfig),
732
- filename,
733
- };
734
- }));
735
- }
736
- resolveSecretReference(buttonSettings, resource, context) {
737
- if (!resource) {
738
- return undefined;
739
- }
740
- try {
741
- const resourceProperty = this.readString(buttonSettings.resourceProperty);
742
- if (!resourceProperty) {
743
- return undefined;
744
- }
745
- const name = this.readString(getResourceValueByJsonPath(resource, {
746
- property: resourceProperty,
747
- }));
748
- const namespaceProperty = this.readString(buttonSettings.namespaceProperty);
749
- const namespace = namespaceProperty
750
- ? this.namespaceOf(getResourceValueByJsonPath(resource, {
751
- property: namespaceProperty,
752
- }))
753
- : (this.namespaceOf(resource.metadata?.namespace) ??
754
- this.namespaceOf(this.resourceService.getNamespace(context)));
755
- return name && namespace ? { name, namespace } : undefined;
756
- }
757
- catch {
758
- return undefined;
759
- }
760
- }
761
- namespaceOf(value) {
762
- const namespace = this.readString(value);
763
- return namespace && namespace !== ALL_NAMESPACE ? namespace : undefined;
764
- }
765
- readString(value) {
766
- return typeof value === 'string' && value.trim() ? value.trim() : undefined;
767
- }
768
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: KubeconfigSecretService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
769
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: KubeconfigSecretService, providedIn: 'root' }); }
770
- }
771
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: KubeconfigSecretService, decorators: [{
772
- type: Injectable,
773
- args: [{
774
- providedIn: 'root',
775
- }]
776
- }] });
777
-
778
- const accountInfoRead = gql `
638
+ var KubeconfigSecretService = class KubeconfigSecretService {
639
+ constructor() {
640
+ this.resourceService = inject(ResourceService);
641
+ }
642
+ secretReferenceQueryFields(buttonSettings) {
643
+ if (!isDownloadKubeconfigButtonSettings(buttonSettings)) return [];
644
+ const fields = [];
645
+ const resourceProperty = this.readString(buttonSettings.resourceProperty);
646
+ if (resourceProperty) fields.push({ property: resourceProperty });
647
+ const namespaceProperty = this.readString(buttonSettings.namespaceProperty);
648
+ if (namespaceProperty) fields.push({ property: namespaceProperty });
649
+ return fields;
650
+ }
651
+ isSecretReferenceAvailable(buttonSettings, resource, context) {
652
+ return isDownloadKubeconfigButtonSettings(buttonSettings) && this.resolveSecretReference(buttonSettings, resource, context) !== void 0;
653
+ }
654
+ readKubeconfig(buttonSettings, resource, context) {
655
+ if (!isDownloadKubeconfigButtonSettings(buttonSettings)) return throwError(() => /* @__PURE__ */ new Error("Button is not a kubeconfig download action"));
656
+ const secretReference = this.resolveSecretReference(buttonSettings, resource, context);
657
+ if (!secretReference) return throwError(() => /* @__PURE__ */ new Error("Kubeconfig Secret reference is not available"));
658
+ const dataKey = this.readString(buttonSettings.dataKey) ?? DEFAULT_DATA_KEY;
659
+ const filename = this.readString(buttonSettings.filename) ?? DEFAULT_FILENAME;
660
+ const secretContext = {
661
+ ...context,
662
+ namespaceId: secretReference.namespace,
663
+ resourceDefinition: SECRET_RESOURCE_DEFINITION
664
+ };
665
+ return this.resourceService.read(secretReference.name, SECRET_RESOURCE_DEFINITION, ["data"], secretContext, false).pipe(catchError(() => throwError(() => /* @__PURE__ */ new Error("Kubeconfig Secret could not be read"))), map((secret) => {
666
+ const encodedKubeconfig = this.readString(secret?.data?.[dataKey]);
667
+ if (!encodedKubeconfig) throw new Error(`Kubeconfig data key "${dataKey}" is not available`);
668
+ return {
669
+ contents: decodeBase64(encodedKubeconfig),
670
+ filename
671
+ };
672
+ }));
673
+ }
674
+ resolveSecretReference(buttonSettings, resource, context) {
675
+ if (!resource) return;
676
+ try {
677
+ const resourceProperty = this.readString(buttonSettings.resourceProperty);
678
+ if (!resourceProperty) return;
679
+ const name = this.readString(getResourceValueByJsonPath(resource, { property: resourceProperty }));
680
+ const namespaceProperty = this.readString(buttonSettings.namespaceProperty);
681
+ const namespace = namespaceProperty ? this.namespaceOf(getResourceValueByJsonPath(resource, { property: namespaceProperty })) : this.namespaceOf(resource.metadata?.namespace) ?? this.namespaceOf(this.resourceService.getNamespace(context));
682
+ return name && namespace ? {
683
+ name,
684
+ namespace
685
+ } : void 0;
686
+ } catch {
687
+ return;
688
+ }
689
+ }
690
+ namespaceOf(value) {
691
+ const namespace = this.readString(value);
692
+ return namespace && namespace !== ALL_NAMESPACE ? namespace : void 0;
693
+ }
694
+ readString(value) {
695
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
696
+ }
697
+ static {
698
+ this.ɵfac = i0.ɵɵngDeclareFactory({
699
+ minVersion: "12.0.0",
700
+ version: "22.2.6",
701
+ ngImport: i0,
702
+ type: KubeconfigSecretService,
703
+ deps: [],
704
+ target: i0.ɵɵFactoryTarget.Injectable
705
+ });
706
+ }
707
+ static {
708
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
709
+ minVersion: "12.0.0",
710
+ version: "22.2.6",
711
+ ngImport: i0,
712
+ type: KubeconfigSecretService,
713
+ providedIn: "root"
714
+ });
715
+ }
716
+ };
717
+ i0.ɵɵngDeclareClassMetadata({
718
+ minVersion: "12.0.0",
719
+ version: "22.2.6",
720
+ ngImport: i0,
721
+ type: KubeconfigSecretService,
722
+ decorators: [{
723
+ type: Injectable,
724
+ args: [{ providedIn: "root" }]
725
+ }]
726
+ });
727
+ const accountInfoRead = gql`
779
728
  {
780
729
  core_platform_mesh_io {
781
730
  v1alpha1 {
@@ -807,56 +756,67 @@ const accountInfoRead = gql `
807
756
  }
808
757
  }
809
758
  `;
810
-
811
- class AccountInfoService {
812
- constructor() {
813
- this.apolloFactory = inject(ApolloFactory);
814
- this.gatewayService = inject(GatewayService);
815
- this.readCache = new Map();
816
- }
817
- read(nodeContext) {
818
- const cacheKey = this.gatewayService.getGatewayUrl(nodeContext);
819
- const cachedRead = this.readCache.get(cacheKey);
820
- if (cachedRead) {
821
- return cachedRead;
822
- }
823
- const request$ = this.apolloFactory
824
- .apollo(nodeContext)
825
- .query({
826
- query: accountInfoRead,
827
- })
828
- .pipe(map((res) => {
829
- const rawAccountInfo = res.data.core_platform_mesh_io.v1alpha1.AccountInfo;
830
- const rawOidc = rawAccountInfo.spec.oidc;
831
- return {
832
- ...rawAccountInfo,
833
- spec: {
834
- ...rawAccountInfo.spec,
835
- oidc: rawOidc
836
- ? { ...rawOidc, clients: JSON.parse(rawOidc.clients) }
837
- : undefined,
838
- },
839
- };
840
- }), shareReplay(1), catchError((error) => {
841
- if (this.readCache.get(cacheKey) === request$) {
842
- this.readCache.delete(cacheKey);
843
- }
844
- return throwError(() => error);
845
- }));
846
- this.readCache.set(cacheKey, request$);
847
- return request$;
848
- }
849
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: AccountInfoService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
850
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: AccountInfoService, providedIn: 'root' }); }
851
- }
852
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: AccountInfoService, decorators: [{
853
- type: Injectable,
854
- args: [{
855
- providedIn: 'root',
856
- }]
857
- }] });
858
-
859
- const queryLoginCluster = gql `
759
+ var AccountInfoService = class AccountInfoService {
760
+ constructor() {
761
+ this.apolloFactory = inject(ApolloFactory);
762
+ this.gatewayService = inject(GatewayService);
763
+ this.readCache = /* @__PURE__ */ new Map();
764
+ }
765
+ read(nodeContext) {
766
+ const cacheKey = this.gatewayService.getGatewayUrl(nodeContext);
767
+ const cachedRead = this.readCache.get(cacheKey);
768
+ if (cachedRead) return cachedRead;
769
+ const request$ = this.apolloFactory.apollo(nodeContext).query({ query: accountInfoRead }).pipe(map$1((res) => {
770
+ const rawAccountInfo = res.data.core_platform_mesh_io.v1alpha1.AccountInfo;
771
+ const rawOidc = rawAccountInfo.spec.oidc;
772
+ return {
773
+ ...rawAccountInfo,
774
+ spec: {
775
+ ...rawAccountInfo.spec,
776
+ oidc: rawOidc ? {
777
+ ...rawOidc,
778
+ clients: JSON.parse(rawOidc.clients)
779
+ } : void 0
780
+ }
781
+ };
782
+ }), shareReplay(1), catchError$1((error) => {
783
+ if (this.readCache.get(cacheKey) === request$) this.readCache.delete(cacheKey);
784
+ return throwError(() => error);
785
+ }));
786
+ this.readCache.set(cacheKey, request$);
787
+ return request$;
788
+ }
789
+ static {
790
+ this.ɵfac = i0.ɵɵngDeclareFactory({
791
+ minVersion: "12.0.0",
792
+ version: "22.2.6",
793
+ ngImport: i0,
794
+ type: AccountInfoService,
795
+ deps: [],
796
+ target: i0.ɵɵFactoryTarget.Injectable
797
+ });
798
+ }
799
+ static {
800
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
801
+ minVersion: "12.0.0",
802
+ version: "22.2.6",
803
+ ngImport: i0,
804
+ type: AccountInfoService,
805
+ providedIn: "root"
806
+ });
807
+ }
808
+ };
809
+ i0.ɵɵngDeclareClassMetadata({
810
+ minVersion: "12.0.0",
811
+ version: "22.2.6",
812
+ ngImport: i0,
813
+ type: AccountInfoService,
814
+ decorators: [{
815
+ type: Injectable,
816
+ args: [{ providedIn: "root" }]
817
+ }]
818
+ });
819
+ const queryLoginCluster = gql`
860
820
  {
861
821
  core_kcp_io {
862
822
  v1alpha1 {
@@ -869,147 +829,213 @@ const queryLoginCluster = gql `
869
829
  }
870
830
  }
871
831
  `;
872
-
873
- class LogicalClusterService {
874
- constructor() {
875
- this.apolloFactory = inject(ApolloFactory);
876
- }
877
- read(nodeContext) {
878
- return this.apolloFactory
879
- .apollo(nodeContext)
880
- .query({
881
- query: queryLoginCluster,
882
- })
883
- .pipe(map((res) => res.data.core_kcp_io.v1alpha1.LogicalCluster));
884
- }
885
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: LogicalClusterService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
886
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: LogicalClusterService, providedIn: 'root' }); }
887
- }
888
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: LogicalClusterService, decorators: [{
889
- type: Injectable,
890
- args: [{
891
- providedIn: 'root',
892
- }]
893
- }] });
894
-
895
- class NamespaceService {
896
- constructor() {
897
- this.resourceService = inject(ResourceService);
898
- }
899
- list(nodeContext) {
900
- return this.resourceService
901
- .list('v1_namespaces', generateGraphQLFields([{ property: 'metadata.name' }]), {
902
- portalContext: {
903
- crdGatewayApiUrl: nodeContext.portalContext.crdGatewayApiUrl,
904
- },
905
- resourceDefinition: {
906
- version: 'v1',
907
- entityCollection: 'Namespaces',
908
- entity: 'Namespace',
909
- scope: 'Cluster',
910
- },
911
- kcpPath: nodeContext.kcpPath,
912
- token: nodeContext.token,
913
- })
914
- .pipe(map((result) => result.items.map((item) => item.metadata.name)));
915
- }
916
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: NamespaceService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
917
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: NamespaceService, providedIn: 'root' }); }
918
- }
919
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: NamespaceService, decorators: [{
920
- type: Injectable,
921
- args: [{
922
- providedIn: 'root',
923
- }]
924
- }] });
925
-
926
- class ErrorHandlerService {
927
- constructor() {
928
- this.luigiCoreService = inject(LuigiCoreService);
929
- }
930
- handleError(error, msg) {
931
- const message = error?.message || error?.errors?.map((e) => e.message).join('\n');
932
- this.luigiCoreService.showAlert({
933
- text: [msg, message].filter(Boolean).join('\n') ||
934
- 'An unknown error occurred',
935
- type: 'error',
936
- });
937
- console.error(error);
938
- }
939
- errorCode(error) {
940
- if (this.isUnauthorizedAccess(error)) {
941
- return 403;
942
- }
943
- return ([
944
- error?.statusCode,
945
- error?.status,
946
- error?.networkError?.statusCode,
947
- error?.networkError?.status,
948
- error?.response?.status,
949
- ].find(Boolean) ?? 500);
950
- }
951
- isUnauthorizedAccess(error) {
952
- return (!!error?.message?.toLowerCase().includes('forbidden') ||
953
- !!error?.message?.toLowerCase()?.includes('access denied'));
954
- }
955
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ErrorHandlerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
956
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ErrorHandlerService, providedIn: 'root' }); }
957
- }
958
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: ErrorHandlerService, decorators: [{
959
- type: Injectable,
960
- args: [{ providedIn: 'root' }]
961
- }] });
962
-
963
- class OrganizationReadyService {
964
- constructor() {
965
- this.configService = inject(ConfigService);
966
- this.envConfigService = inject(EnvConfigService);
967
- this.logicalClusterService = inject(LogicalClusterService);
968
- this.authService = inject(AuthService);
969
- this.isReady = false;
970
- }
971
- isOrganizationReady() {
972
- if (this.isReady) {
973
- return Promise.resolve(true);
974
- }
975
- this.pendingCheck ??= this.readOrganizationReady().finally(() => {
976
- this.pendingCheck = undefined;
977
- });
978
- return this.pendingCheck;
979
- }
980
- async readOrganizationReady() {
981
- const portalConfig = await this.configService.getPortalConfig();
982
- const { idpName } = await this.envConfigService.getEnvConfig();
983
- if (idpName === 'welcome') {
984
- return true;
985
- }
986
- try {
987
- const logicalCluster = await firstValueFrom(this.logicalClusterService.read({
988
- portalContext: {
989
- crdGatewayApiUrl: portalConfig.portalContext['crdGatewayApiUrl'],
990
- },
991
- token: this.authService.getToken(),
992
- accountId: idpName,
993
- }));
994
- this.isReady = logicalCluster.status.phase === 'Ready';
995
- return this.isReady;
996
- }
997
- catch (error) {
998
- console.error('Org check failed', error);
999
- return true;
1000
- }
1001
- }
1002
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: OrganizationReadyService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1003
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: OrganizationReadyService, providedIn: 'root' }); }
1004
- }
1005
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.2.1", ngImport: i0, type: OrganizationReadyService, decorators: [{
1006
- type: Injectable,
1007
- args: [{ providedIn: 'root' }]
1008
- }] });
1009
-
1010
- /**
1011
- * Generated bundle index. Do not edit.
1012
- */
1013
-
832
+ var LogicalClusterService = class LogicalClusterService {
833
+ constructor() {
834
+ this.apolloFactory = inject(ApolloFactory);
835
+ }
836
+ read(nodeContext) {
837
+ return this.apolloFactory.apollo(nodeContext).query({ query: queryLoginCluster }).pipe(map$1((res) => res.data.core_kcp_io.v1alpha1.LogicalCluster));
838
+ }
839
+ static {
840
+ this.ɵfac = i0.ɵɵngDeclareFactory({
841
+ minVersion: "12.0.0",
842
+ version: "22.2.6",
843
+ ngImport: i0,
844
+ type: LogicalClusterService,
845
+ deps: [],
846
+ target: i0.ɵɵFactoryTarget.Injectable
847
+ });
848
+ }
849
+ static {
850
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
851
+ minVersion: "12.0.0",
852
+ version: "22.2.6",
853
+ ngImport: i0,
854
+ type: LogicalClusterService,
855
+ providedIn: "root"
856
+ });
857
+ }
858
+ };
859
+ i0.ɵɵngDeclareClassMetadata({
860
+ minVersion: "12.0.0",
861
+ version: "22.2.6",
862
+ ngImport: i0,
863
+ type: LogicalClusterService,
864
+ decorators: [{
865
+ type: Injectable,
866
+ args: [{ providedIn: "root" }]
867
+ }]
868
+ });
869
+ var NamespaceService = class NamespaceService {
870
+ constructor() {
871
+ this.resourceService = inject(ResourceService);
872
+ }
873
+ list(nodeContext) {
874
+ return this.resourceService.list("v1_namespaces", generateGraphQLFields([{ property: "metadata.name" }]), {
875
+ portalContext: { crdGatewayApiUrl: nodeContext.portalContext.crdGatewayApiUrl },
876
+ resourceDefinition: {
877
+ version: "v1",
878
+ entityCollection: "Namespaces",
879
+ entity: "Namespace",
880
+ scope: "Cluster"
881
+ },
882
+ kcpPath: nodeContext.kcpPath,
883
+ token: nodeContext.token
884
+ }).pipe(map$1((result) => result.items.map((item) => item.metadata.name)));
885
+ }
886
+ static {
887
+ this.ɵfac = i0.ɵɵngDeclareFactory({
888
+ minVersion: "12.0.0",
889
+ version: "22.2.6",
890
+ ngImport: i0,
891
+ type: NamespaceService,
892
+ deps: [],
893
+ target: i0.ɵɵFactoryTarget.Injectable
894
+ });
895
+ }
896
+ static {
897
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
898
+ minVersion: "12.0.0",
899
+ version: "22.2.6",
900
+ ngImport: i0,
901
+ type: NamespaceService,
902
+ providedIn: "root"
903
+ });
904
+ }
905
+ };
906
+ i0.ɵɵngDeclareClassMetadata({
907
+ minVersion: "12.0.0",
908
+ version: "22.2.6",
909
+ ngImport: i0,
910
+ type: NamespaceService,
911
+ decorators: [{
912
+ type: Injectable,
913
+ args: [{ providedIn: "root" }]
914
+ }]
915
+ });
916
+ const FORBIDDEN_ERROR_CODE = 403;
917
+ var ErrorHandlerService = class ErrorHandlerService {
918
+ constructor() {
919
+ this.luigiCoreService = inject(LuigiCoreService);
920
+ }
921
+ handleError(error, msg) {
922
+ const message = error?.message || error?.errors?.map((e) => e.message).join("\n");
923
+ this.luigiCoreService.showAlert({
924
+ text: [msg, message].filter(Boolean).join("\n") || "An unknown error occurred",
925
+ type: "error"
926
+ });
927
+ console.error(error);
928
+ }
929
+ errorCode(error) {
930
+ if (this.isUnauthorizedAccess(error)) return FORBIDDEN_ERROR_CODE;
931
+ return [
932
+ error?.statusCode,
933
+ error?.status,
934
+ error?.networkError?.statusCode,
935
+ error?.networkError?.status,
936
+ error?.response?.status
937
+ ].find(Boolean) ?? 500;
938
+ }
939
+ navigateToErrorPageIfForbidden(code) {
940
+ if (code !== FORBIDDEN_ERROR_CODE) return false;
941
+ this.luigiCoreService.navigation().withOptions({ preventHistoryEntry: true }).navigate(`/error/${code}`);
942
+ return true;
943
+ }
944
+ isUnauthorizedAccess(error) {
945
+ return !!error?.message?.toLowerCase().includes("forbidden") || !!error?.message?.toLowerCase()?.includes("access denied");
946
+ }
947
+ static {
948
+ this.ɵfac = i0.ɵɵngDeclareFactory({
949
+ minVersion: "12.0.0",
950
+ version: "22.2.6",
951
+ ngImport: i0,
952
+ type: ErrorHandlerService,
953
+ deps: [],
954
+ target: i0.ɵɵFactoryTarget.Injectable
955
+ });
956
+ }
957
+ static {
958
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
959
+ minVersion: "12.0.0",
960
+ version: "22.2.6",
961
+ ngImport: i0,
962
+ type: ErrorHandlerService,
963
+ providedIn: "root"
964
+ });
965
+ }
966
+ };
967
+ i0.ɵɵngDeclareClassMetadata({
968
+ minVersion: "12.0.0",
969
+ version: "22.2.6",
970
+ ngImport: i0,
971
+ type: ErrorHandlerService,
972
+ decorators: [{
973
+ type: Injectable,
974
+ args: [{ providedIn: "root" }]
975
+ }]
976
+ });
977
+ var OrganizationReadyService = class OrganizationReadyService {
978
+ constructor() {
979
+ this.configService = inject(ConfigService);
980
+ this.envConfigService = inject(EnvConfigService);
981
+ this.logicalClusterService = inject(LogicalClusterService);
982
+ this.authService = inject(AuthService);
983
+ this.isReady = false;
984
+ }
985
+ isOrganizationReady() {
986
+ if (this.isReady) return Promise.resolve(true);
987
+ this.pendingCheck ??= this.readOrganizationReady().finally(() => {
988
+ this.pendingCheck = void 0;
989
+ });
990
+ return this.pendingCheck;
991
+ }
992
+ async readOrganizationReady() {
993
+ const portalConfig = await this.configService.getPortalConfig();
994
+ const { idpName } = await this.envConfigService.getEnvConfig();
995
+ if (idpName === "welcome") return true;
996
+ try {
997
+ const logicalCluster = await firstValueFrom(this.logicalClusterService.read({
998
+ portalContext: { crdGatewayApiUrl: portalConfig.portalContext["crdGatewayApiUrl"] },
999
+ token: this.authService.getToken(),
1000
+ accountId: idpName
1001
+ }));
1002
+ this.isReady = logicalCluster.status.phase === "Ready";
1003
+ return this.isReady;
1004
+ } catch (error) {
1005
+ console.error("Org check failed", error);
1006
+ return true;
1007
+ }
1008
+ }
1009
+ static {
1010
+ this.ɵfac = i0.ɵɵngDeclareFactory({
1011
+ minVersion: "12.0.0",
1012
+ version: "22.2.6",
1013
+ ngImport: i0,
1014
+ type: OrganizationReadyService,
1015
+ deps: [],
1016
+ target: i0.ɵɵFactoryTarget.Injectable
1017
+ });
1018
+ }
1019
+ static {
1020
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
1021
+ minVersion: "12.0.0",
1022
+ version: "22.2.6",
1023
+ ngImport: i0,
1024
+ type: OrganizationReadyService,
1025
+ providedIn: "root"
1026
+ });
1027
+ }
1028
+ };
1029
+ i0.ɵɵngDeclareClassMetadata({
1030
+ minVersion: "12.0.0",
1031
+ version: "22.2.6",
1032
+ ngImport: i0,
1033
+ type: OrganizationReadyService,
1034
+ decorators: [{
1035
+ type: Injectable,
1036
+ args: [{ providedIn: "root" }]
1037
+ }]
1038
+ });
1014
1039
  export { AccountInfoService, ApolloFactory, ErrorHandlerService, GatewayService, InstancePermissionsService, KubeconfigSecretService, LogicalClusterService, NamespaceService, OrganizationReadyService, ResourceService, isDownloadKubeconfigButtonSettings };
1015
- //# sourceMappingURL=platform-mesh-portal-ui-lib-services.mjs.map
1040
+
1041
+ //# sourceMappingURL=platform-mesh-portal-ui-lib-services.mjs.map