@backstage/plugin-scaffolder 1.12.0 → 1.13.0-next.1

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 (37) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/alpha/package.json +1 -1
  3. package/dist/alpha.d.ts +12 -59
  4. package/dist/alpha.esm.js +27 -33
  5. package/dist/alpha.esm.js.map +1 -1
  6. package/dist/esm/{alpha/ListTasksPage-2e8f4176.esm.js → ListTasksPage-ca799894.esm.js} +3 -2
  7. package/dist/esm/ListTasksPage-ca799894.esm.js.map +1 -0
  8. package/dist/esm/{index/Router-6fd61bff.esm.js → Router-1b71c4f0.esm.js} +39 -28
  9. package/dist/esm/Router-1b71c4f0.esm.js.map +1 -0
  10. package/dist/esm/TaskPage-589238dc.esm.js +1684 -0
  11. package/dist/esm/TaskPage-589238dc.esm.js.map +1 -0
  12. package/dist/esm/TemplateEditorIntro-644bad26.esm.js +1128 -0
  13. package/dist/esm/TemplateEditorIntro-644bad26.esm.js.map +1 -0
  14. package/dist/esm/TemplateFormPreviewer-32c3dcf3.esm.js +630 -0
  15. package/dist/esm/TemplateFormPreviewer-32c3dcf3.esm.js.map +1 -0
  16. package/dist/esm/TemplateTypePicker-4f07b216.esm.js +58 -0
  17. package/dist/esm/TemplateTypePicker-4f07b216.esm.js.map +1 -0
  18. package/dist/esm/{alpha/index-2131f4a0.esm.js → index-bce9c23d.esm.js} +95 -156
  19. package/dist/esm/index-bce9c23d.esm.js.map +1 -0
  20. package/dist/index.d.ts +28 -167
  21. package/dist/index.esm.js +27 -65
  22. package/dist/index.esm.js.map +1 -1
  23. package/dist/types/plugin.d-bc532f9e.d.ts +232 -0
  24. package/package.json +24 -22
  25. package/dist/esm/alpha/ListTasksPage-2e8f4176.esm.js.map +0 -1
  26. package/dist/esm/alpha/Router-2826a2b8.esm.js +0 -1566
  27. package/dist/esm/alpha/Router-2826a2b8.esm.js.map +0 -1
  28. package/dist/esm/alpha/alpha-714dad1b.esm.js +0 -3422
  29. package/dist/esm/alpha/alpha-714dad1b.esm.js.map +0 -1
  30. package/dist/esm/alpha/index-2131f4a0.esm.js.map +0 -1
  31. package/dist/esm/index/ListTasksPage-fa403ee3.esm.js +0 -192
  32. package/dist/esm/index/ListTasksPage-fa403ee3.esm.js.map +0 -1
  33. package/dist/esm/index/Router-6fd61bff.esm.js.map +0 -1
  34. package/dist/esm/index/index-0b6cdf44.esm.js +0 -3475
  35. package/dist/esm/index/index-0b6cdf44.esm.js.map +0 -1
  36. package/dist/esm/index/index-f404fb0b.esm.js +0 -449
  37. package/dist/esm/index/index-f404fb0b.esm.js.map +0 -1
@@ -0,0 +1,1684 @@
1
+ import { scmIntegrationsApiRef, scmAuthApiRef } from '@backstage/integration-react';
2
+ import { scaffolderApiRef, useTemplateSecrets, createScaffolderFieldExtension, useTaskEventStream } from '@backstage/plugin-scaffolder-react';
3
+ import { parseEntityRef, stringifyEntityRef, KubernetesValidatorFunctions, RELATION_OWNED_BY, makeValidator } from '@backstage/catalog-model';
4
+ import { ResponseError } from '@backstage/errors';
5
+ import qs from 'qs';
6
+ import ObservableImpl from 'zen-observable';
7
+ import { CATALOG_FILTER_EXISTS } from '@backstage/catalog-client';
8
+ import { useApi, identityApiRef, createExternalRouteRef, createRouteRef, createSubRouteRef, createPlugin, createApiFactory, discoveryApiRef, fetchApiRef, createRoutableExtension, useApp, useRouteRef, useRouteRefParams } from '@backstage/core-plugin-api';
9
+ import { catalogApiRef, humanizeEntityRef, entityRouteRef } from '@backstage/plugin-catalog-react';
10
+ import { TextField, FormControl as FormControl$1, Box, makeStyles, Grid, Typography, StepButton, Paper, Button, CircularProgress } from '@material-ui/core';
11
+ import FormControl from '@material-ui/core/FormControl';
12
+ import Autocomplete from '@material-ui/lab/Autocomplete';
13
+ import React, { useCallback, useEffect, useState, useMemo, useRef, memo } from 'react';
14
+ import useAsync from 'react-use/lib/useAsync';
15
+ import { z } from 'zod';
16
+ import zodToJsonSchema from 'zod-to-json-schema';
17
+ import FormHelperText from '@material-ui/core/FormHelperText';
18
+ import Input from '@material-ui/core/Input';
19
+ import InputLabel from '@material-ui/core/InputLabel';
20
+ import { Select, Progress, DismissableBanner, Link, Page, Header, Content, ErrorPage, LogViewer } from '@backstage/core-components';
21
+ import useDebounce from 'react-use/lib/useDebounce';
22
+ import useEffectOnce from 'react-use/lib/useEffectOnce';
23
+ import { Autocomplete as Autocomplete$1 } from '@material-ui/lab';
24
+ import Grid$1 from '@material-ui/core/Grid';
25
+ import Step from '@material-ui/core/Step';
26
+ import StepLabel from '@material-ui/core/StepLabel';
27
+ import Stepper from '@material-ui/core/Stepper';
28
+ import { makeStyles as makeStyles$1, createStyles } from '@material-ui/core/styles';
29
+ import Typography$1 from '@material-ui/core/Typography';
30
+ import Cancel from '@material-ui/icons/Cancel';
31
+ import Check from '@material-ui/icons/Check';
32
+ import FiberManualRecordIcon from '@material-ui/icons/FiberManualRecord';
33
+ import classNames from 'classnames';
34
+ import { DateTime, Interval } from 'luxon';
35
+ import { useNavigate } from 'react-router-dom';
36
+ import useInterval from 'react-use/lib/useInterval';
37
+ import LanguageIcon from '@material-ui/icons/Language';
38
+
39
+ class ScaffolderClient {
40
+ constructor(options) {
41
+ var _a, _b;
42
+ this.discoveryApi = options.discoveryApi;
43
+ this.fetchApi = (_a = options.fetchApi) != null ? _a : { fetch };
44
+ this.scmIntegrationsApi = options.scmIntegrationsApi;
45
+ this.useLongPollingLogs = (_b = options.useLongPollingLogs) != null ? _b : false;
46
+ this.identityApi = options.identityApi;
47
+ }
48
+ async listTasks(options) {
49
+ if (!this.identityApi) {
50
+ throw new Error(
51
+ "IdentityApi is not available in the ScaffolderClient, please pass through the IdentityApi to the ScaffolderClient constructor in order to use the listTasks method"
52
+ );
53
+ }
54
+ const baseUrl = await this.discoveryApi.getBaseUrl("scaffolder");
55
+ const { userEntityRef } = await this.identityApi.getBackstageIdentity();
56
+ const query = qs.stringify(
57
+ options.filterByOwnership === "owned" ? { createdBy: userEntityRef } : {}
58
+ );
59
+ const response = await this.fetchApi.fetch(`${baseUrl}/v2/tasks?${query}`);
60
+ if (!response.ok) {
61
+ throw await ResponseError.fromResponse(response);
62
+ }
63
+ return await response.json();
64
+ }
65
+ async getIntegrationsList(options) {
66
+ const integrations = [
67
+ ...this.scmIntegrationsApi.azure.list(),
68
+ ...this.scmIntegrationsApi.bitbucket.list().filter(
69
+ (item) => !this.scmIntegrationsApi.bitbucketCloud.byHost(item.config.host) && !this.scmIntegrationsApi.bitbucketServer.byHost(item.config.host)
70
+ ),
71
+ ...this.scmIntegrationsApi.bitbucketCloud.list(),
72
+ ...this.scmIntegrationsApi.bitbucketServer.list(),
73
+ ...this.scmIntegrationsApi.gerrit.list(),
74
+ ...this.scmIntegrationsApi.github.list(),
75
+ ...this.scmIntegrationsApi.gitlab.list()
76
+ ].map((c) => ({ type: c.type, title: c.title, host: c.config.host })).filter((c) => options.allowedHosts.includes(c.host));
77
+ return {
78
+ integrations
79
+ };
80
+ }
81
+ async getTemplateParameterSchema(templateRef) {
82
+ const { namespace, kind, name } = parseEntityRef(templateRef, {
83
+ defaultKind: "template"
84
+ });
85
+ const baseUrl = await this.discoveryApi.getBaseUrl("scaffolder");
86
+ const templatePath = [namespace, kind, name].map((s) => encodeURIComponent(s)).join("/");
87
+ const url = `${baseUrl}/v2/templates/${templatePath}/parameter-schema`;
88
+ const response = await this.fetchApi.fetch(url);
89
+ if (!response.ok) {
90
+ throw await ResponseError.fromResponse(response);
91
+ }
92
+ const schema = await response.json();
93
+ return schema;
94
+ }
95
+ async scaffold(options) {
96
+ const { templateRef, values, secrets = {} } = options;
97
+ const url = `${await this.discoveryApi.getBaseUrl("scaffolder")}/v2/tasks`;
98
+ const response = await this.fetchApi.fetch(url, {
99
+ method: "POST",
100
+ headers: {
101
+ "Content-Type": "application/json"
102
+ },
103
+ body: JSON.stringify({
104
+ templateRef,
105
+ values: { ...values },
106
+ secrets
107
+ })
108
+ });
109
+ if (response.status !== 201) {
110
+ const status = `${response.status} ${response.statusText}`;
111
+ const body = await response.text();
112
+ throw new Error(`Backend request failed, ${status} ${body.trim()}`);
113
+ }
114
+ const { id } = await response.json();
115
+ return { taskId: id };
116
+ }
117
+ async getTask(taskId) {
118
+ const baseUrl = await this.discoveryApi.getBaseUrl("scaffolder");
119
+ const url = `${baseUrl}/v2/tasks/${encodeURIComponent(taskId)}`;
120
+ const response = await this.fetchApi.fetch(url);
121
+ if (!response.ok) {
122
+ throw await ResponseError.fromResponse(response);
123
+ }
124
+ return await response.json();
125
+ }
126
+ streamLogs(options) {
127
+ if (this.useLongPollingLogs) {
128
+ return this.streamLogsPolling(options);
129
+ }
130
+ return this.streamLogsEventStream(options);
131
+ }
132
+ async dryRun(options) {
133
+ const baseUrl = await this.discoveryApi.getBaseUrl("scaffolder");
134
+ const response = await this.fetchApi.fetch(`${baseUrl}/v2/dry-run`, {
135
+ method: "POST",
136
+ headers: {
137
+ "Content-Type": "application/json"
138
+ },
139
+ body: JSON.stringify({
140
+ template: options.template,
141
+ values: options.values,
142
+ secrets: options.secrets,
143
+ directoryContents: options.directoryContents
144
+ })
145
+ });
146
+ if (!response.ok) {
147
+ throw await ResponseError.fromResponse(response);
148
+ }
149
+ return response.json();
150
+ }
151
+ streamLogsEventStream({
152
+ taskId,
153
+ after
154
+ }) {
155
+ return new ObservableImpl((subscriber) => {
156
+ const params = new URLSearchParams();
157
+ if (after !== void 0) {
158
+ params.set("after", String(Number(after)));
159
+ }
160
+ this.discoveryApi.getBaseUrl("scaffolder").then(
161
+ (baseUrl) => {
162
+ const url = `${baseUrl}/v2/tasks/${encodeURIComponent(
163
+ taskId
164
+ )}/eventstream`;
165
+ const processEvent = (event) => {
166
+ if (event.data) {
167
+ try {
168
+ subscriber.next(JSON.parse(event.data));
169
+ } catch (ex) {
170
+ subscriber.error(ex);
171
+ }
172
+ }
173
+ };
174
+ const eventSource = new EventSource(url, { withCredentials: true });
175
+ eventSource.addEventListener("log", processEvent);
176
+ eventSource.addEventListener("cancelled", processEvent);
177
+ eventSource.addEventListener("completion", (event) => {
178
+ processEvent(event);
179
+ eventSource.close();
180
+ subscriber.complete();
181
+ });
182
+ eventSource.addEventListener("error", (event) => {
183
+ subscriber.error(event);
184
+ });
185
+ },
186
+ (error) => {
187
+ subscriber.error(error);
188
+ }
189
+ );
190
+ });
191
+ }
192
+ streamLogsPolling({
193
+ taskId,
194
+ after: inputAfter
195
+ }) {
196
+ let after = inputAfter;
197
+ return new ObservableImpl((subscriber) => {
198
+ this.discoveryApi.getBaseUrl("scaffolder").then(async (baseUrl) => {
199
+ while (!subscriber.closed) {
200
+ const url = `${baseUrl}/v2/tasks/${encodeURIComponent(
201
+ taskId
202
+ )}/events?${qs.stringify({ after })}`;
203
+ const response = await this.fetchApi.fetch(url);
204
+ if (!response.ok) {
205
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
206
+ continue;
207
+ }
208
+ const logs = await response.json();
209
+ for (const event of logs) {
210
+ after = Number(event.id);
211
+ subscriber.next(event);
212
+ if (event.type === "completion") {
213
+ subscriber.complete();
214
+ return;
215
+ }
216
+ }
217
+ }
218
+ });
219
+ });
220
+ }
221
+ async listActions() {
222
+ const baseUrl = await this.discoveryApi.getBaseUrl("scaffolder");
223
+ const response = await this.fetchApi.fetch(`${baseUrl}/v2/actions`);
224
+ if (!response.ok) {
225
+ throw await ResponseError.fromResponse(response);
226
+ }
227
+ return await response.json();
228
+ }
229
+ async cancelTask(taskId) {
230
+ const baseUrl = await this.discoveryApi.getBaseUrl("scaffolder");
231
+ const url = `${baseUrl}/v2/tasks/${encodeURIComponent(taskId)}/cancel`;
232
+ const response = await this.fetchApi.fetch(url, {
233
+ method: "POST"
234
+ });
235
+ if (!response.ok) {
236
+ throw await ResponseError.fromResponse(response);
237
+ }
238
+ return await response.json();
239
+ }
240
+ }
241
+
242
+ function makeFieldSchemaFromZod(returnSchema, uiOptionsSchema) {
243
+ return {
244
+ schema: {
245
+ returnValue: zodToJsonSchema(returnSchema),
246
+ uiOptions: uiOptionsSchema ? zodToJsonSchema(uiOptionsSchema) : void 0
247
+ },
248
+ type: null,
249
+ uiOptionsType: null
250
+ };
251
+ }
252
+
253
+ const entityQueryFilterExpressionSchema = z.record(
254
+ z.string().or(z.object({ exists: z.boolean().optional() })).or(z.array(z.string()))
255
+ );
256
+ const EntityPickerFieldSchema = makeFieldSchemaFromZod(
257
+ z.string(),
258
+ z.object({
259
+ /**
260
+ * @deprecated Use `catalogFilter` instead.
261
+ */
262
+ allowedKinds: z.array(z.string()).optional().describe(
263
+ "DEPRECATED: Use `catalogFilter` instead. List of kinds of entities to derive options from"
264
+ ),
265
+ defaultKind: z.string().optional().describe(
266
+ "The default entity kind. Options of this kind will not be prefixed."
267
+ ),
268
+ allowArbitraryValues: z.boolean().optional().describe("Whether to allow arbitrary user input. Defaults to true"),
269
+ defaultNamespace: z.union([z.string(), z.literal(false)]).optional().describe(
270
+ "The default namespace. Options with this namespace will not be prefixed."
271
+ ),
272
+ catalogFilter: z.array(entityQueryFilterExpressionSchema).or(entityQueryFilterExpressionSchema).optional().describe("List of key-value filter expression for entities")
273
+ })
274
+ );
275
+ const EntityPickerSchema = EntityPickerFieldSchema.schema;
276
+
277
+ const EntityPicker = (props) => {
278
+ var _a, _b, _c, _d, _e;
279
+ const {
280
+ onChange,
281
+ schema: { title = "Entity", description = "An entity from the catalog" },
282
+ required,
283
+ uiSchema,
284
+ rawErrors,
285
+ formData,
286
+ idSchema
287
+ } = props;
288
+ const catalogFilter = buildCatalogFilter(uiSchema);
289
+ const defaultKind = (_a = uiSchema["ui:options"]) == null ? void 0 : _a.defaultKind;
290
+ const defaultNamespace = ((_b = uiSchema["ui:options"]) == null ? void 0 : _b.defaultNamespace) || void 0;
291
+ const catalogApi = useApi(catalogApiRef);
292
+ const { value: entities, loading } = useAsync(async () => {
293
+ const { items } = await catalogApi.getEntities(
294
+ catalogFilter ? { filter: catalogFilter } : void 0
295
+ );
296
+ return items;
297
+ });
298
+ const allowArbitraryValues = (_d = (_c = uiSchema["ui:options"]) == null ? void 0 : _c.allowArbitraryValues) != null ? _d : true;
299
+ const getLabel = useCallback(
300
+ (ref) => {
301
+ try {
302
+ return humanizeEntityRef(
303
+ parseEntityRef(ref, { defaultKind, defaultNamespace }),
304
+ {
305
+ defaultKind,
306
+ defaultNamespace
307
+ }
308
+ );
309
+ } catch (err) {
310
+ return ref;
311
+ }
312
+ },
313
+ [defaultKind, defaultNamespace]
314
+ );
315
+ const onSelect = useCallback(
316
+ (_, ref, reason) => {
317
+ if (typeof ref !== "string") {
318
+ onChange(ref ? stringifyEntityRef(ref) : "");
319
+ } else {
320
+ if (reason === "blur" || reason === "create-option") {
321
+ let entityRef = ref;
322
+ try {
323
+ entityRef = stringifyEntityRef(
324
+ parseEntityRef(ref, {
325
+ defaultKind,
326
+ defaultNamespace
327
+ })
328
+ );
329
+ } catch (err) {
330
+ }
331
+ if (formData !== ref || allowArbitraryValues) {
332
+ onChange(entityRef);
333
+ }
334
+ }
335
+ }
336
+ },
337
+ [onChange, formData, defaultKind, defaultNamespace, allowArbitraryValues]
338
+ );
339
+ useEffect(() => {
340
+ if ((entities == null ? void 0 : entities.length) === 1) {
341
+ onChange(stringifyEntityRef(entities[0]));
342
+ }
343
+ }, [entities, onChange]);
344
+ return /* @__PURE__ */ React.createElement(
345
+ FormControl,
346
+ {
347
+ margin: "normal",
348
+ required,
349
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !formData
350
+ },
351
+ /* @__PURE__ */ React.createElement(
352
+ Autocomplete,
353
+ {
354
+ disabled: (entities == null ? void 0 : entities.length) === 1,
355
+ id: idSchema == null ? void 0 : idSchema.$id,
356
+ value: (
357
+ // Since free solo can be enabled, attempt to parse as a full entity ref first, then fall
358
+ // back to the given value.
359
+ (_e = entities == null ? void 0 : entities.find((e) => stringifyEntityRef(e) === formData)) != null ? _e : allowArbitraryValues && formData ? getLabel(formData) : ""
360
+ ),
361
+ loading,
362
+ onChange: onSelect,
363
+ options: entities || [],
364
+ getOptionLabel: (option) => (
365
+ // option can be a string due to freeSolo.
366
+ typeof option === "string" ? option : humanizeEntityRef(option, { defaultKind, defaultNamespace })
367
+ ),
368
+ autoSelect: true,
369
+ freeSolo: allowArbitraryValues,
370
+ renderInput: (params) => /* @__PURE__ */ React.createElement(
371
+ TextField,
372
+ {
373
+ ...params,
374
+ label: title,
375
+ margin: "dense",
376
+ helperText: description,
377
+ FormHelperTextProps: { margin: "dense", style: { marginLeft: 0 } },
378
+ variant: "outlined",
379
+ required,
380
+ InputProps: params.InputProps
381
+ }
382
+ )
383
+ }
384
+ )
385
+ );
386
+ };
387
+ function convertOpsValues(value) {
388
+ if (typeof value === "object" && value.exists) {
389
+ return CATALOG_FILTER_EXISTS;
390
+ }
391
+ return value == null ? void 0 : value.toString();
392
+ }
393
+ function convertSchemaFiltersToQuery(schemaFilters) {
394
+ const query = {};
395
+ for (const [key, value] of Object.entries(schemaFilters)) {
396
+ if (Array.isArray(value)) {
397
+ query[key] = value;
398
+ } else {
399
+ query[key] = convertOpsValues(value);
400
+ }
401
+ }
402
+ return query;
403
+ }
404
+ function buildCatalogFilter(uiSchema) {
405
+ var _a, _b;
406
+ const allowedKinds = (_a = uiSchema["ui:options"]) == null ? void 0 : _a.allowedKinds;
407
+ const catalogFilter = ((_b = uiSchema["ui:options"]) == null ? void 0 : _b.catalogFilter) || allowedKinds && { kind: allowedKinds };
408
+ if (!catalogFilter) {
409
+ return void 0;
410
+ }
411
+ if (Array.isArray(catalogFilter)) {
412
+ return catalogFilter.map(convertSchemaFiltersToQuery);
413
+ }
414
+ return convertSchemaFiltersToQuery(catalogFilter);
415
+ }
416
+
417
+ const entityNamePickerValidation = (value, validation) => {
418
+ if (!KubernetesValidatorFunctions.isValidObjectName(value)) {
419
+ validation.addError(
420
+ "Must start and end with an alphanumeric character, and contain only alphanumeric characters, hyphens, underscores, and periods. Maximum length is 63 characters."
421
+ );
422
+ }
423
+ };
424
+
425
+ const EntityNamePickerFieldSchema = makeFieldSchemaFromZod(z.string());
426
+ const EntityNamePickerSchema = EntityNamePickerFieldSchema.schema;
427
+
428
+ const EntityNamePicker = (props) => {
429
+ const {
430
+ onChange,
431
+ required,
432
+ schema: { title = "Name", description = "Unique name of the component" },
433
+ rawErrors,
434
+ formData,
435
+ uiSchema: { "ui:autofocus": autoFocus },
436
+ idSchema,
437
+ placeholder
438
+ } = props;
439
+ return /* @__PURE__ */ React.createElement(
440
+ TextField,
441
+ {
442
+ id: idSchema == null ? void 0 : idSchema.$id,
443
+ label: title,
444
+ placeholder,
445
+ helperText: description,
446
+ required,
447
+ value: formData != null ? formData : "",
448
+ onChange: ({ target: { value } }) => onChange(value),
449
+ margin: "normal",
450
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !formData,
451
+ inputProps: { autoFocus }
452
+ }
453
+ );
454
+ };
455
+
456
+ const OwnerPickerFieldSchema = makeFieldSchemaFromZod(
457
+ z.string(),
458
+ z.object({
459
+ /**
460
+ * @deprecated Use `catalogFilter` instead.
461
+ */
462
+ allowedKinds: z.array(z.string()).default(["Group", "User"]).optional().describe(
463
+ "DEPRECATED: Use `catalogFilter` instead. List of kinds of entities to derive options from. Defaults to Group and User"
464
+ ),
465
+ allowArbitraryValues: z.boolean().optional().describe("Whether to allow arbitrary user input. Defaults to true"),
466
+ defaultNamespace: z.union([z.string(), z.literal(false)]).optional().describe(
467
+ "The default namespace. Options with this namespace will not be prefixed."
468
+ ),
469
+ catalogFilter: z.array(entityQueryFilterExpressionSchema).or(entityQueryFilterExpressionSchema).optional().describe("List of key-value filter expression for entities")
470
+ })
471
+ );
472
+ const OwnerPickerSchema = OwnerPickerFieldSchema.schema;
473
+
474
+ const OwnerPicker = (props) => {
475
+ var _a, _b, _c, _d, _e;
476
+ const {
477
+ schema: { title = "Owner", description = "The owner of the component" },
478
+ uiSchema,
479
+ ...restProps
480
+ } = props;
481
+ const defaultNamespace = (_a = uiSchema["ui:options"]) == null ? void 0 : _a.defaultNamespace;
482
+ const allowedKinds = (_b = uiSchema["ui:options"]) == null ? void 0 : _b.allowedKinds;
483
+ const catalogFilter = ((_c = uiSchema["ui:options"]) == null ? void 0 : _c.catalogFilter) || {
484
+ kind: allowedKinds || ["Group", "User"]
485
+ };
486
+ const ownerUiSchema = {
487
+ ...uiSchema,
488
+ "ui:options": {
489
+ catalogFilter,
490
+ defaultKind: "Group",
491
+ allowArbitraryValues: (_e = (_d = uiSchema["ui:options"]) == null ? void 0 : _d.allowArbitraryValues) != null ? _e : true,
492
+ ...defaultNamespace !== void 0 ? { defaultNamespace } : {}
493
+ }
494
+ };
495
+ return /* @__PURE__ */ React.createElement(
496
+ EntityPicker,
497
+ {
498
+ ...restProps,
499
+ schema: { title, description },
500
+ uiSchema: ownerUiSchema
501
+ }
502
+ );
503
+ };
504
+
505
+ const RepoUrlPickerFieldSchema = makeFieldSchemaFromZod(
506
+ z.string(),
507
+ z.object({
508
+ allowedHosts: z.array(z.string()).optional().describe("List of allowed SCM platform hosts"),
509
+ allowedOrganizations: z.array(z.string()).optional().describe("List of allowed organizations in the given SCM platform"),
510
+ allowedOwners: z.array(z.string()).optional().describe("List of allowed owners in the given SCM platform"),
511
+ allowedProjects: z.array(z.string()).optional().describe("List of allowed projects in the given SCM platform"),
512
+ allowedRepos: z.array(z.string()).optional().describe("List of allowed repos in the given SCM platform"),
513
+ requestUserCredentials: z.object({
514
+ secretsKey: z.string().describe(
515
+ "Key used within the template secrets context to store the credential"
516
+ ),
517
+ additionalScopes: z.object({
518
+ gerrit: z.array(z.string()).optional().describe("Additional Gerrit scopes to request"),
519
+ github: z.array(z.string()).optional().describe("Additional GitHub scopes to request"),
520
+ gitlab: z.array(z.string()).optional().describe("Additional GitLab scopes to request"),
521
+ bitbucket: z.array(z.string()).optional().describe("Additional BitBucket scopes to request"),
522
+ azure: z.array(z.string()).optional().describe("Additional Azure scopes to request")
523
+ }).optional().describe("Additional permission scopes to request")
524
+ }).optional().describe(
525
+ "If defined will request user credentials to auth against the given SCM platform"
526
+ )
527
+ })
528
+ );
529
+ const RepoUrlPickerSchema = RepoUrlPickerFieldSchema.schema;
530
+
531
+ const repoPickerValidation = (value, validation, context) => {
532
+ var _a, _b;
533
+ try {
534
+ const { host, searchParams } = new URL(`https://${value}`);
535
+ const integrationApi = context.apiHolder.get(scmIntegrationsApiRef);
536
+ if (!host) {
537
+ validation.addError(
538
+ "Incomplete repository location provided, host not provided"
539
+ );
540
+ } else {
541
+ if (((_a = integrationApi == null ? void 0 : integrationApi.byHost(host)) == null ? void 0 : _a.type) === "bitbucket") {
542
+ if (host === "bitbucket.org" && !searchParams.get("workspace")) {
543
+ validation.addError(
544
+ "Incomplete repository location provided, workspace not provided"
545
+ );
546
+ }
547
+ if (!searchParams.get("project")) {
548
+ validation.addError(
549
+ "Incomplete repository location provided, project not provided"
550
+ );
551
+ }
552
+ } else if (((_b = integrationApi == null ? void 0 : integrationApi.byHost(host)) == null ? void 0 : _b.type) !== "gerrit") {
553
+ if (!searchParams.get("owner")) {
554
+ validation.addError(
555
+ "Incomplete repository location provided, owner not provided"
556
+ );
557
+ }
558
+ }
559
+ if (!searchParams.get("repo")) {
560
+ validation.addError(
561
+ "Incomplete repository location provided, repo not provided"
562
+ );
563
+ }
564
+ }
565
+ } catch {
566
+ validation.addError("Unable to parse the Repository URL");
567
+ }
568
+ };
569
+
570
+ const GithubRepoPicker = (props) => {
571
+ const { allowedOwners = [], rawErrors, state, onChange } = props;
572
+ const ownerItems = allowedOwners ? allowedOwners.map((i) => ({ label: i, value: i })) : [{ label: "Loading...", value: "loading" }];
573
+ const { owner } = state;
574
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
575
+ FormControl,
576
+ {
577
+ margin: "normal",
578
+ required: true,
579
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !owner
580
+ },
581
+ (allowedOwners == null ? void 0 : allowedOwners.length) ? /* @__PURE__ */ React.createElement(
582
+ Select,
583
+ {
584
+ native: true,
585
+ label: "Owner Available",
586
+ onChange: (s) => onChange({ owner: String(Array.isArray(s) ? s[0] : s) }),
587
+ disabled: allowedOwners.length === 1,
588
+ selected: owner,
589
+ items: ownerItems
590
+ }
591
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "ownerInput" }, "Owner"), /* @__PURE__ */ React.createElement(
592
+ Input,
593
+ {
594
+ id: "ownerInput",
595
+ onChange: (e) => onChange({ owner: e.target.value }),
596
+ value: owner
597
+ }
598
+ )),
599
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The organization, user or project that this repo will belong to")
600
+ ));
601
+ };
602
+
603
+ const GitlabRepoPicker = (props) => {
604
+ const { allowedOwners = [], state, onChange, rawErrors } = props;
605
+ const ownerItems = allowedOwners ? allowedOwners.map((i) => ({ label: i, value: i })) : [{ label: "Loading...", value: "loading" }];
606
+ const { owner } = state;
607
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
608
+ FormControl,
609
+ {
610
+ margin: "normal",
611
+ required: true,
612
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !owner
613
+ },
614
+ (allowedOwners == null ? void 0 : allowedOwners.length) ? /* @__PURE__ */ React.createElement(
615
+ Select,
616
+ {
617
+ native: true,
618
+ label: "Owner Available",
619
+ onChange: (selected) => onChange({
620
+ owner: String(Array.isArray(selected) ? selected[0] : selected)
621
+ }),
622
+ disabled: allowedOwners.length === 1,
623
+ selected: owner,
624
+ items: ownerItems
625
+ }
626
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "ownerInput" }, "Owner"), /* @__PURE__ */ React.createElement(
627
+ Input,
628
+ {
629
+ id: "ownerInput",
630
+ onChange: (e) => onChange({ owner: e.target.value }),
631
+ value: owner
632
+ }
633
+ )),
634
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "GitLab namespace where this repository will belong to. It can be the name of organization, group, subgroup, user, or the project.")
635
+ ));
636
+ };
637
+
638
+ const AzureRepoPicker = (props) => {
639
+ const {
640
+ allowedOrganizations = [],
641
+ allowedOwners = [],
642
+ rawErrors,
643
+ state,
644
+ onChange
645
+ } = props;
646
+ const organizationItems = allowedOrganizations ? allowedOrganizations.map((i) => ({ label: i, value: i })) : [{ label: "Loading...", value: "loading" }];
647
+ const ownerItems = allowedOwners ? allowedOwners.map((i) => ({ label: i, value: i })) : [{ label: "Loading...", value: "loading" }];
648
+ const { organization, owner } = state;
649
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
650
+ FormControl,
651
+ {
652
+ margin: "normal",
653
+ required: true,
654
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !organization
655
+ },
656
+ (allowedOrganizations == null ? void 0 : allowedOrganizations.length) ? /* @__PURE__ */ React.createElement(
657
+ Select,
658
+ {
659
+ native: true,
660
+ label: "Organization",
661
+ onChange: (s) => onChange({ organization: String(Array.isArray(s) ? s[0] : s) }),
662
+ disabled: allowedOrganizations.length === 1,
663
+ selected: organization,
664
+ items: organizationItems
665
+ }
666
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "orgInput" }, "Organization"), /* @__PURE__ */ React.createElement(
667
+ Input,
668
+ {
669
+ id: "orgInput",
670
+ onChange: (e) => onChange({ organization: e.target.value }),
671
+ value: organization
672
+ }
673
+ )),
674
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The Organization that this repo will belong to")
675
+ ), /* @__PURE__ */ React.createElement(
676
+ FormControl,
677
+ {
678
+ margin: "normal",
679
+ required: true,
680
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !owner
681
+ },
682
+ (allowedOwners == null ? void 0 : allowedOwners.length) ? /* @__PURE__ */ React.createElement(
683
+ Select,
684
+ {
685
+ native: true,
686
+ label: "Owner",
687
+ onChange: (s) => onChange({ owner: String(Array.isArray(s) ? s[0] : s) }),
688
+ disabled: allowedOwners.length === 1,
689
+ selected: owner,
690
+ items: ownerItems
691
+ }
692
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "ownerInput" }, "Project"), /* @__PURE__ */ React.createElement(
693
+ Input,
694
+ {
695
+ id: "ownerInput",
696
+ onChange: (e) => onChange({ owner: e.target.value }),
697
+ value: owner
698
+ }
699
+ )),
700
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The Project that this repo will belong to")
701
+ ));
702
+ };
703
+
704
+ const BitbucketRepoPicker = (props) => {
705
+ const {
706
+ allowedOwners = [],
707
+ allowedProjects = [],
708
+ onChange,
709
+ rawErrors,
710
+ state
711
+ } = props;
712
+ const { host, workspace, project } = state;
713
+ const ownerItems = allowedOwners ? allowedOwners == null ? void 0 : allowedOwners.map((i) => ({ label: i, value: i })) : [];
714
+ const projectItems = allowedProjects ? allowedProjects == null ? void 0 : allowedProjects.map((i) => ({ label: i, value: i })) : [];
715
+ useEffect(() => {
716
+ if (host === "bitbucket.org" && allowedOwners.length) {
717
+ onChange({ workspace: allowedOwners[0] });
718
+ }
719
+ }, [allowedOwners, host, onChange]);
720
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, host === "bitbucket.org" && /* @__PURE__ */ React.createElement(
721
+ FormControl,
722
+ {
723
+ margin: "normal",
724
+ required: true,
725
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !workspace
726
+ },
727
+ (allowedOwners == null ? void 0 : allowedOwners.length) ? /* @__PURE__ */ React.createElement(
728
+ Select,
729
+ {
730
+ native: true,
731
+ label: "Allowed Workspaces",
732
+ onChange: (s) => onChange({ workspace: String(Array.isArray(s) ? s[0] : s) }),
733
+ disabled: allowedOwners.length === 1,
734
+ selected: workspace,
735
+ items: ownerItems
736
+ }
737
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "workspaceInput" }, "Workspace"), /* @__PURE__ */ React.createElement(
738
+ Input,
739
+ {
740
+ id: "workspaceInput",
741
+ onChange: (e) => onChange({ workspace: e.target.value }),
742
+ value: workspace
743
+ }
744
+ )),
745
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The Workspace that this repo will belong to")
746
+ ), /* @__PURE__ */ React.createElement(
747
+ FormControl,
748
+ {
749
+ margin: "normal",
750
+ required: true,
751
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !project
752
+ },
753
+ (allowedProjects == null ? void 0 : allowedProjects.length) ? /* @__PURE__ */ React.createElement(
754
+ Select,
755
+ {
756
+ native: true,
757
+ label: "Allowed Projects",
758
+ onChange: (s) => onChange({ project: String(Array.isArray(s) ? s[0] : s) }),
759
+ disabled: allowedProjects.length === 1,
760
+ selected: project,
761
+ items: projectItems
762
+ }
763
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "projectInput" }, "Project"), /* @__PURE__ */ React.createElement(
764
+ Input,
765
+ {
766
+ id: "projectInput",
767
+ onChange: (e) => onChange({ project: e.target.value }),
768
+ value: project
769
+ }
770
+ )),
771
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The Project that this repo will belong to")
772
+ ));
773
+ };
774
+
775
+ const GerritRepoPicker = (props) => {
776
+ const { onChange, rawErrors, state } = props;
777
+ const { workspace, owner } = state;
778
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(FormControl, { margin: "normal", error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !workspace }, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "ownerInput" }, "Owner"), /* @__PURE__ */ React.createElement(
779
+ Input,
780
+ {
781
+ id: "ownerInput",
782
+ onChange: (e) => onChange({ owner: e.target.value }),
783
+ value: owner
784
+ }
785
+ ), /* @__PURE__ */ React.createElement(FormHelperText, null, "The owner of the project (optional)")), /* @__PURE__ */ React.createElement(
786
+ FormControl,
787
+ {
788
+ margin: "normal",
789
+ required: true,
790
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !workspace
791
+ },
792
+ /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "parentInput" }, "Parent"),
793
+ /* @__PURE__ */ React.createElement(
794
+ Input,
795
+ {
796
+ id: "parentInput",
797
+ onChange: (e) => onChange({ workspace: e.target.value }),
798
+ value: workspace
799
+ }
800
+ ),
801
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The project parent that the repo will belong to")
802
+ ));
803
+ };
804
+
805
+ const RepoUrlPickerHost = (props) => {
806
+ const { host, hosts, onChange, rawErrors } = props;
807
+ const scaffolderApi = useApi(scaffolderApiRef);
808
+ const { value: { integrations } = { integrations: [] }, loading } = useAsync(
809
+ async () => {
810
+ return await scaffolderApi.getIntegrationsList({
811
+ allowedHosts: hosts != null ? hosts : []
812
+ });
813
+ }
814
+ );
815
+ useEffect(() => {
816
+ if (!host) {
817
+ if (hosts == null ? void 0 : hosts.length) {
818
+ onChange(hosts[0]);
819
+ } else if (integrations == null ? void 0 : integrations.length) {
820
+ onChange(integrations[0].host);
821
+ }
822
+ }
823
+ }, [hosts, host, onChange, integrations]);
824
+ const hostsOptions = integrations ? integrations.filter((i) => (hosts == null ? void 0 : hosts.length) ? hosts == null ? void 0 : hosts.includes(i.host) : true).map((i) => ({ label: i.title, value: i.host })) : [{ label: "Loading...", value: "loading" }];
825
+ if (loading) {
826
+ return /* @__PURE__ */ React.createElement(Progress, null);
827
+ }
828
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
829
+ FormControl,
830
+ {
831
+ margin: "normal",
832
+ required: true,
833
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !host
834
+ },
835
+ /* @__PURE__ */ React.createElement(
836
+ Select,
837
+ {
838
+ native: true,
839
+ disabled: (hosts == null ? void 0 : hosts.length) === 1,
840
+ label: "Host",
841
+ onChange: (s) => onChange(String(Array.isArray(s) ? s[0] : s)),
842
+ selected: host,
843
+ items: hostsOptions,
844
+ "data-testid": "host-select"
845
+ }
846
+ ),
847
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The host where the repository will be created")
848
+ ));
849
+ };
850
+
851
+ const RepoUrlPickerRepoName = (props) => {
852
+ const { repoName, allowedRepos, onChange, rawErrors } = props;
853
+ useEffect(() => {
854
+ if (!repoName) {
855
+ if (allowedRepos == null ? void 0 : allowedRepos.length) {
856
+ onChange(allowedRepos[0]);
857
+ }
858
+ }
859
+ }, [allowedRepos, repoName, onChange]);
860
+ const repoItems = allowedRepos ? allowedRepos.map((i) => ({ label: i, value: i })) : [{ label: "Loading...", value: "loading" }];
861
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
862
+ FormControl,
863
+ {
864
+ margin: "normal",
865
+ required: true,
866
+ error: (rawErrors == null ? void 0 : rawErrors.length) > 0 && !repoName
867
+ },
868
+ (allowedRepos == null ? void 0 : allowedRepos.length) ? /* @__PURE__ */ React.createElement(
869
+ Select,
870
+ {
871
+ native: true,
872
+ label: "Repositories Available",
873
+ onChange: (selected) => String(Array.isArray(selected) ? selected[0] : selected),
874
+ disabled: allowedRepos.length === 1,
875
+ selected: repoName,
876
+ items: repoItems
877
+ }
878
+ ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InputLabel, { htmlFor: "repoNameInput" }, "Repository"), /* @__PURE__ */ React.createElement(
879
+ Input,
880
+ {
881
+ id: "repoNameInput",
882
+ onChange: (e) => onChange(String(e.target.value)),
883
+ value: repoName
884
+ }
885
+ )),
886
+ /* @__PURE__ */ React.createElement(FormHelperText, null, "The name of the repository")
887
+ ));
888
+ };
889
+
890
+ function serializeRepoPickerUrl(data) {
891
+ if (!data.host) {
892
+ return void 0;
893
+ }
894
+ const params = new URLSearchParams();
895
+ if (data.owner) {
896
+ params.set("owner", data.owner);
897
+ }
898
+ if (data.repoName) {
899
+ params.set("repo", data.repoName);
900
+ }
901
+ if (data.organization) {
902
+ params.set("organization", data.organization);
903
+ }
904
+ if (data.workspace) {
905
+ params.set("workspace", data.workspace);
906
+ }
907
+ if (data.project) {
908
+ params.set("project", data.project);
909
+ }
910
+ return `${data.host}?${params.toString()}`;
911
+ }
912
+ function parseRepoPickerUrl(url) {
913
+ let host = "";
914
+ let owner = "";
915
+ let repoName = "";
916
+ let organization = "";
917
+ let workspace = "";
918
+ let project = "";
919
+ try {
920
+ if (url) {
921
+ const parsed = new URL(`https://${url}`);
922
+ host = parsed.host;
923
+ owner = parsed.searchParams.get("owner") || "";
924
+ repoName = parsed.searchParams.get("repo") || "";
925
+ organization = parsed.searchParams.get("organization") || "";
926
+ workspace = parsed.searchParams.get("workspace") || "";
927
+ project = parsed.searchParams.get("project") || "";
928
+ }
929
+ } catch {
930
+ }
931
+ return { host, owner, repoName, organization, workspace, project };
932
+ }
933
+
934
+ const RepoUrlPicker = (props) => {
935
+ var _a, _b;
936
+ const { uiSchema, onChange, rawErrors, formData } = props;
937
+ const [state, setState] = useState(
938
+ parseRepoPickerUrl(formData)
939
+ );
940
+ const integrationApi = useApi(scmIntegrationsApiRef);
941
+ const scmAuthApi = useApi(scmAuthApiRef);
942
+ const { setSecrets } = useTemplateSecrets();
943
+ const allowedHosts = useMemo(
944
+ () => {
945
+ var _a2, _b2;
946
+ return (_b2 = (_a2 = uiSchema == null ? void 0 : uiSchema["ui:options"]) == null ? void 0 : _a2.allowedHosts) != null ? _b2 : [];
947
+ },
948
+ [uiSchema]
949
+ );
950
+ const allowedOrganizations = useMemo(
951
+ () => {
952
+ var _a2, _b2;
953
+ return (_b2 = (_a2 = uiSchema == null ? void 0 : uiSchema["ui:options"]) == null ? void 0 : _a2.allowedOrganizations) != null ? _b2 : [];
954
+ },
955
+ [uiSchema]
956
+ );
957
+ const allowedOwners = useMemo(
958
+ () => {
959
+ var _a2, _b2;
960
+ return (_b2 = (_a2 = uiSchema == null ? void 0 : uiSchema["ui:options"]) == null ? void 0 : _a2.allowedOwners) != null ? _b2 : [];
961
+ },
962
+ [uiSchema]
963
+ );
964
+ const allowedProjects = useMemo(
965
+ () => {
966
+ var _a2, _b2;
967
+ return (_b2 = (_a2 = uiSchema == null ? void 0 : uiSchema["ui:options"]) == null ? void 0 : _a2.allowedProjects) != null ? _b2 : [];
968
+ },
969
+ [uiSchema]
970
+ );
971
+ const allowedRepos = useMemo(
972
+ () => {
973
+ var _a2, _b2;
974
+ return (_b2 = (_a2 = uiSchema == null ? void 0 : uiSchema["ui:options"]) == null ? void 0 : _a2.allowedRepos) != null ? _b2 : [];
975
+ },
976
+ [uiSchema]
977
+ );
978
+ const { owner, organization, project, repoName } = state;
979
+ useEffect(() => {
980
+ onChange(serializeRepoPickerUrl(state));
981
+ }, [state, onChange]);
982
+ useEffect(() => {
983
+ if (allowedOrganizations.length > 0 && !organization) {
984
+ setState((prevState) => ({
985
+ ...prevState,
986
+ organization: allowedOrganizations[0]
987
+ }));
988
+ }
989
+ }, [setState, allowedOrganizations, organization]);
990
+ useEffect(() => {
991
+ if (allowedOwners.length > 0 && !owner) {
992
+ setState((prevState) => ({
993
+ ...prevState,
994
+ owner: allowedOwners[0]
995
+ }));
996
+ }
997
+ }, [setState, allowedOwners, owner]);
998
+ useEffect(() => {
999
+ if (allowedProjects.length > 0 && !project) {
1000
+ setState((prevState) => ({
1001
+ ...prevState,
1002
+ project: allowedProjects[0]
1003
+ }));
1004
+ }
1005
+ }, [setState, allowedProjects, project]);
1006
+ useEffect(() => {
1007
+ if (allowedRepos.length > 0 && !repoName) {
1008
+ setState((prevState) => ({ ...prevState, repoName: allowedRepos[0] }));
1009
+ }
1010
+ }, [setState, allowedRepos, repoName]);
1011
+ const updateLocalState = useCallback(
1012
+ (newState) => {
1013
+ setState((prevState) => ({ ...prevState, ...newState }));
1014
+ },
1015
+ [setState]
1016
+ );
1017
+ useDebounce(
1018
+ async () => {
1019
+ var _a2;
1020
+ const { requestUserCredentials } = (_a2 = uiSchema == null ? void 0 : uiSchema["ui:options"]) != null ? _a2 : {};
1021
+ const workspace = state.owner ? state.owner : state.project;
1022
+ if (!requestUserCredentials || !(state.host && workspace && state.repoName)) {
1023
+ return;
1024
+ }
1025
+ const [encodedHost, encodedWorkspace, encodedRepoName] = [
1026
+ state.host,
1027
+ workspace,
1028
+ state.repoName
1029
+ ].map(encodeURIComponent);
1030
+ const { token } = await scmAuthApi.getCredentials({
1031
+ url: `https://${encodedHost}/${encodedWorkspace}/${encodedRepoName}`,
1032
+ additionalScope: {
1033
+ repoWrite: true,
1034
+ customScopes: requestUserCredentials.additionalScopes
1035
+ }
1036
+ });
1037
+ setSecrets({ [requestUserCredentials.secretsKey]: token });
1038
+ },
1039
+ 500,
1040
+ [state, uiSchema]
1041
+ );
1042
+ const hostType = (_b = state.host && ((_a = integrationApi.byHost(state.host)) == null ? void 0 : _a.type)) != null ? _b : null;
1043
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
1044
+ RepoUrlPickerHost,
1045
+ {
1046
+ host: state.host,
1047
+ hosts: allowedHosts,
1048
+ onChange: (host) => setState((prevState) => ({ ...prevState, host })),
1049
+ rawErrors
1050
+ }
1051
+ ), hostType === "github" && /* @__PURE__ */ React.createElement(
1052
+ GithubRepoPicker,
1053
+ {
1054
+ allowedOwners,
1055
+ onChange: updateLocalState,
1056
+ rawErrors,
1057
+ state
1058
+ }
1059
+ ), hostType === "gitlab" && /* @__PURE__ */ React.createElement(
1060
+ GitlabRepoPicker,
1061
+ {
1062
+ allowedOwners,
1063
+ rawErrors,
1064
+ state,
1065
+ onChange: updateLocalState
1066
+ }
1067
+ ), hostType === "bitbucket" && /* @__PURE__ */ React.createElement(
1068
+ BitbucketRepoPicker,
1069
+ {
1070
+ allowedOwners,
1071
+ allowedProjects,
1072
+ rawErrors,
1073
+ state,
1074
+ onChange: updateLocalState
1075
+ }
1076
+ ), hostType === "azure" && /* @__PURE__ */ React.createElement(
1077
+ AzureRepoPicker,
1078
+ {
1079
+ allowedOrganizations,
1080
+ allowedOwners,
1081
+ rawErrors,
1082
+ state,
1083
+ onChange: updateLocalState
1084
+ }
1085
+ ), hostType === "gerrit" && /* @__PURE__ */ React.createElement(
1086
+ GerritRepoPicker,
1087
+ {
1088
+ rawErrors,
1089
+ state,
1090
+ onChange: updateLocalState
1091
+ }
1092
+ ), /* @__PURE__ */ React.createElement(
1093
+ RepoUrlPickerRepoName,
1094
+ {
1095
+ repoName: state.repoName,
1096
+ allowedRepos,
1097
+ onChange: (repo) => setState((prevState) => ({ ...prevState, repoName: repo })),
1098
+ rawErrors
1099
+ }
1100
+ ));
1101
+ };
1102
+
1103
+ const OwnedEntityPickerFieldSchema = makeFieldSchemaFromZod(
1104
+ z.string(),
1105
+ z.object({
1106
+ allowedKinds: z.array(z.string()).optional().describe("List of kinds of entities to derive options from"),
1107
+ defaultKind: z.string().optional().describe(
1108
+ "The default entity kind. Options of this kind will not be prefixed."
1109
+ ),
1110
+ allowArbitraryValues: z.boolean().optional().describe("Whether to allow arbitrary user input. Defaults to true"),
1111
+ defaultNamespace: z.union([z.string(), z.literal(false)]).optional().describe(
1112
+ "The default namespace. Options with this namespace will not be prefixed."
1113
+ )
1114
+ })
1115
+ );
1116
+ const OwnedEntityPickerSchema = OwnedEntityPickerFieldSchema.schema;
1117
+
1118
+ const OwnedEntityPicker = (props) => {
1119
+ var _a;
1120
+ const {
1121
+ schema: { title = "Entity", description = "An entity from the catalog" },
1122
+ uiSchema,
1123
+ required
1124
+ } = props;
1125
+ const identityApi = useApi(identityApiRef);
1126
+ const { loading, value: identityRefs } = useAsync(async () => {
1127
+ const identity = await identityApi.getBackstageIdentity();
1128
+ return identity.ownershipEntityRefs;
1129
+ });
1130
+ const allowedKinds = (_a = uiSchema["ui:options"]) == null ? void 0 : _a.allowedKinds;
1131
+ if (loading)
1132
+ return /* @__PURE__ */ React.createElement(
1133
+ Autocomplete,
1134
+ {
1135
+ loading,
1136
+ renderInput: (params) => /* @__PURE__ */ React.createElement(
1137
+ TextField,
1138
+ {
1139
+ ...params,
1140
+ label: title,
1141
+ margin: "dense",
1142
+ helperText: description,
1143
+ FormHelperTextProps: { margin: "dense", style: { marginLeft: 0 } },
1144
+ variant: "outlined",
1145
+ required,
1146
+ InputProps: params.InputProps
1147
+ }
1148
+ ),
1149
+ options: []
1150
+ }
1151
+ );
1152
+ return /* @__PURE__ */ React.createElement(
1153
+ EntityPicker,
1154
+ {
1155
+ ...props,
1156
+ schema: { title, description },
1157
+ allowedKinds,
1158
+ catalogFilter: allowedKinds ? {
1159
+ filter: {
1160
+ kind: allowedKinds,
1161
+ [`relations.${RELATION_OWNED_BY}`]: identityRefs || []
1162
+ }
1163
+ } : {
1164
+ filter: {
1165
+ [`relations.${RELATION_OWNED_BY}`]: identityRefs || []
1166
+ }
1167
+ }
1168
+ }
1169
+ );
1170
+ };
1171
+
1172
+ const EntityTagsPickerFieldSchema = makeFieldSchemaFromZod(
1173
+ z.array(z.string()),
1174
+ z.object({
1175
+ kinds: z.array(z.string()).optional().describe("List of kinds of entities to derive tags from"),
1176
+ showCounts: z.boolean().optional().describe("Whether to show usage counts per tag"),
1177
+ helperText: z.string().optional().describe("Helper text to display")
1178
+ })
1179
+ );
1180
+ const EntityTagsPickerSchema = EntityTagsPickerFieldSchema.schema;
1181
+
1182
+ const EntityTagsPicker = (props) => {
1183
+ var _a, _b, _c;
1184
+ const { formData, onChange, uiSchema } = props;
1185
+ const catalogApi = useApi(catalogApiRef);
1186
+ const [tagOptions, setTagOptions] = useState([]);
1187
+ const [inputValue, setInputValue] = useState("");
1188
+ const [inputError, setInputError] = useState(false);
1189
+ const tagValidator = makeValidator().isValidTag;
1190
+ const kinds = (_a = uiSchema["ui:options"]) == null ? void 0 : _a.kinds;
1191
+ const showCounts = (_b = uiSchema["ui:options"]) == null ? void 0 : _b.showCounts;
1192
+ const helperText = (_c = uiSchema["ui:options"]) == null ? void 0 : _c.helperText;
1193
+ const { loading, value: existingTags } = useAsync(async () => {
1194
+ const facet = "metadata.tags";
1195
+ const tagsRequest = { facets: [facet] };
1196
+ if (kinds) {
1197
+ tagsRequest.filter = { kind: kinds };
1198
+ }
1199
+ const { facets } = await catalogApi.getEntityFacets(tagsRequest);
1200
+ const tagFacets = Object.fromEntries(
1201
+ facets[facet].map(({ value, count }) => [value, count])
1202
+ );
1203
+ setTagOptions(
1204
+ Object.keys(tagFacets).sort(
1205
+ (a, b) => showCounts ? tagFacets[b] - tagFacets[a] : a.localeCompare(b)
1206
+ )
1207
+ );
1208
+ return tagFacets;
1209
+ });
1210
+ const setTags = (_, values) => {
1211
+ let hasError = false;
1212
+ let addDuplicate = false;
1213
+ const currentTags = formData || [];
1214
+ if ((values == null ? void 0 : values.length) && currentTags.length < values.length) {
1215
+ const newTag = values[values.length - 1] = values[values.length - 1].toLocaleLowerCase("en-US").trim();
1216
+ hasError = !tagValidator(newTag);
1217
+ addDuplicate = currentTags.indexOf(newTag) !== -1;
1218
+ }
1219
+ setInputError(hasError);
1220
+ setInputValue(!hasError ? "" : inputValue);
1221
+ if (!hasError && !addDuplicate) {
1222
+ onChange(values || []);
1223
+ }
1224
+ };
1225
+ useEffectOnce(() => onChange(formData || []));
1226
+ return /* @__PURE__ */ React.createElement(FormControl$1, { margin: "normal" }, /* @__PURE__ */ React.createElement(
1227
+ Autocomplete$1,
1228
+ {
1229
+ multiple: true,
1230
+ freeSolo: true,
1231
+ filterSelectedOptions: true,
1232
+ onChange: setTags,
1233
+ value: formData || [],
1234
+ inputValue,
1235
+ loading,
1236
+ options: tagOptions,
1237
+ ChipProps: { size: "small" },
1238
+ renderOption: (option) => showCounts ? `${option} (${existingTags == null ? void 0 : existingTags[option]})` : option,
1239
+ renderInput: (params) => /* @__PURE__ */ React.createElement(
1240
+ TextField,
1241
+ {
1242
+ ...params,
1243
+ label: "Tags",
1244
+ onChange: (e) => setInputValue(e.target.value),
1245
+ error: inputError,
1246
+ helperText: helperText != null ? helperText : "Add any relevant tags, hit 'Enter' to add new tags. Valid format: [a-z0-9+#] separated by [-], at most 63 characters"
1247
+ }
1248
+ )
1249
+ }
1250
+ ));
1251
+ };
1252
+
1253
+ const registerComponentRouteRef = createExternalRouteRef({
1254
+ id: "register-component",
1255
+ optional: true
1256
+ });
1257
+ const viewTechDocRouteRef = createExternalRouteRef({
1258
+ id: "view-techdoc",
1259
+ optional: true,
1260
+ params: ["namespace", "kind", "name"]
1261
+ });
1262
+ const rootRouteRef = createRouteRef({
1263
+ id: "scaffolder"
1264
+ });
1265
+ const legacySelectedTemplateRouteRef = createSubRouteRef({
1266
+ id: "scaffolder/legacy/selected-template",
1267
+ parent: rootRouteRef,
1268
+ path: "/templates/:templateName"
1269
+ });
1270
+ const selectedTemplateRouteRef = createSubRouteRef({
1271
+ id: "scaffolder/selected-template",
1272
+ parent: rootRouteRef,
1273
+ path: "/templates/:namespace/:templateName"
1274
+ });
1275
+ const scaffolderTaskRouteRef = createSubRouteRef({
1276
+ id: "scaffolder/task",
1277
+ parent: rootRouteRef,
1278
+ path: "/tasks/:taskId"
1279
+ });
1280
+ const scaffolderListTaskRouteRef = createSubRouteRef({
1281
+ id: "scaffolder/list-tasks",
1282
+ parent: rootRouteRef,
1283
+ path: "/tasks"
1284
+ });
1285
+ const actionsRouteRef = createSubRouteRef({
1286
+ id: "scaffolder/actions",
1287
+ parent: rootRouteRef,
1288
+ path: "/actions"
1289
+ });
1290
+ const editRouteRef = createSubRouteRef({
1291
+ id: "scaffolder/edit",
1292
+ parent: rootRouteRef,
1293
+ path: "/edit"
1294
+ });
1295
+
1296
+ const scaffolderPlugin = createPlugin({
1297
+ id: "scaffolder",
1298
+ apis: [
1299
+ createApiFactory({
1300
+ api: scaffolderApiRef,
1301
+ deps: {
1302
+ discoveryApi: discoveryApiRef,
1303
+ scmIntegrationsApi: scmIntegrationsApiRef,
1304
+ fetchApi: fetchApiRef,
1305
+ identityApi: identityApiRef
1306
+ },
1307
+ factory: ({ discoveryApi, scmIntegrationsApi, fetchApi, identityApi }) => new ScaffolderClient({
1308
+ discoveryApi,
1309
+ scmIntegrationsApi,
1310
+ fetchApi,
1311
+ identityApi
1312
+ })
1313
+ })
1314
+ ],
1315
+ routes: {
1316
+ root: rootRouteRef,
1317
+ selectedTemplate: selectedTemplateRouteRef,
1318
+ ongoingTask: scaffolderTaskRouteRef,
1319
+ actions: actionsRouteRef,
1320
+ listTasks: scaffolderListTaskRouteRef,
1321
+ edit: editRouteRef
1322
+ },
1323
+ externalRoutes: {
1324
+ registerComponent: registerComponentRouteRef,
1325
+ viewTechDoc: viewTechDocRouteRef
1326
+ }
1327
+ });
1328
+ const EntityPickerFieldExtension = scaffolderPlugin.provide(
1329
+ createScaffolderFieldExtension({
1330
+ component: EntityPicker,
1331
+ name: "EntityPicker",
1332
+ schema: EntityPickerSchema
1333
+ })
1334
+ );
1335
+ const EntityNamePickerFieldExtension = scaffolderPlugin.provide(
1336
+ createScaffolderFieldExtension({
1337
+ component: EntityNamePicker,
1338
+ name: "EntityNamePicker",
1339
+ validation: entityNamePickerValidation,
1340
+ schema: EntityNamePickerSchema
1341
+ })
1342
+ );
1343
+ const RepoUrlPickerFieldExtension = scaffolderPlugin.provide(
1344
+ createScaffolderFieldExtension({
1345
+ component: RepoUrlPicker,
1346
+ name: "RepoUrlPicker",
1347
+ validation: repoPickerValidation,
1348
+ schema: RepoUrlPickerSchema
1349
+ })
1350
+ );
1351
+ const OwnerPickerFieldExtension = scaffolderPlugin.provide(
1352
+ createScaffolderFieldExtension({
1353
+ component: OwnerPicker,
1354
+ name: "OwnerPicker",
1355
+ schema: OwnerPickerSchema
1356
+ })
1357
+ );
1358
+ const ScaffolderPage = scaffolderPlugin.provide(
1359
+ createRoutableExtension({
1360
+ name: "ScaffolderPage",
1361
+ component: () => import('./Router-1b71c4f0.esm.js').then((m) => m.Router),
1362
+ mountPoint: rootRouteRef
1363
+ })
1364
+ );
1365
+ const OwnedEntityPickerFieldExtension = scaffolderPlugin.provide(
1366
+ createScaffolderFieldExtension({
1367
+ component: OwnedEntityPicker,
1368
+ name: "OwnedEntityPicker",
1369
+ schema: OwnedEntityPickerSchema
1370
+ })
1371
+ );
1372
+ const EntityTagsPickerFieldExtension = scaffolderPlugin.provide(
1373
+ createScaffolderFieldExtension({
1374
+ component: EntityTagsPicker,
1375
+ name: "EntityTagsPicker",
1376
+ schema: EntityTagsPickerSchema
1377
+ })
1378
+ );
1379
+ const NextScaffolderPage = scaffolderPlugin.provide(
1380
+ createRoutableExtension({
1381
+ name: "NextScaffolderPage",
1382
+ component: () => import('./index-bce9c23d.esm.js').then((m) => m.Router),
1383
+ mountPoint: rootRouteRef
1384
+ })
1385
+ );
1386
+
1387
+ const TaskErrors = ({ error }) => {
1388
+ const id = useRef("");
1389
+ useEffect(() => {
1390
+ id.current = String(Math.random());
1391
+ }, [error]);
1392
+ return error ? /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(
1393
+ DismissableBanner,
1394
+ {
1395
+ id: id.current,
1396
+ variant: "warning",
1397
+ message: error.message
1398
+ }
1399
+ )) : null;
1400
+ };
1401
+
1402
+ const useStyles$1 = makeStyles({
1403
+ svgIcon: {
1404
+ display: "inline-block",
1405
+ "& svg": {
1406
+ display: "inline-block",
1407
+ fontSize: "inherit",
1408
+ verticalAlign: "baseline"
1409
+ }
1410
+ }
1411
+ });
1412
+ const IconLink = (props) => {
1413
+ const { href, text, Icon, ...linkProps } = props;
1414
+ const classes = useStyles$1();
1415
+ return /* @__PURE__ */ React.createElement(Grid, { container: true, direction: "row", spacing: 1 }, /* @__PURE__ */ React.createElement(Grid, { item: true }, /* @__PURE__ */ React.createElement(Typography, { component: "div", className: classes.svgIcon }, Icon ? /* @__PURE__ */ React.createElement(Icon, null) : /* @__PURE__ */ React.createElement(LanguageIcon, null))), /* @__PURE__ */ React.createElement(Grid, { item: true }, /* @__PURE__ */ React.createElement(Link, { to: href, ...linkProps }, text || href)));
1416
+ };
1417
+
1418
+ const TaskPageLinks = ({ output }) => {
1419
+ const { links = [] } = output;
1420
+ const app = useApp();
1421
+ const entityRoute = useRouteRef(entityRouteRef);
1422
+ const iconResolver = (key) => {
1423
+ var _a;
1424
+ return key ? (_a = app.getSystemIcon(key)) != null ? _a : LanguageIcon : LanguageIcon;
1425
+ };
1426
+ return /* @__PURE__ */ React.createElement(Box, { px: 3, pb: 3 }, links.filter(({ url, entityRef }) => url || entityRef).map(({ url, entityRef, title, icon }) => {
1427
+ if (entityRef) {
1428
+ const entityName = parseEntityRef(entityRef, {
1429
+ defaultKind: "<unknown>",
1430
+ defaultNamespace: "<unknown>"
1431
+ });
1432
+ const target = entityRoute(entityName);
1433
+ return { title, icon, url: target };
1434
+ }
1435
+ return { title, icon, url };
1436
+ }).map(({ url, title, icon }, i) => /* @__PURE__ */ React.createElement(
1437
+ IconLink,
1438
+ {
1439
+ key: `output-link-${i}`,
1440
+ href: url,
1441
+ text: title != null ? title : url,
1442
+ Icon: iconResolver(icon),
1443
+ target: "_blank"
1444
+ }
1445
+ )));
1446
+ };
1447
+
1448
+ const humanizeDuration = require("humanize-duration");
1449
+ const useStyles = makeStyles$1(
1450
+ (theme) => createStyles({
1451
+ root: {
1452
+ width: "100%"
1453
+ },
1454
+ button: {
1455
+ marginBottom: theme.spacing(2),
1456
+ marginLeft: theme.spacing(2)
1457
+ },
1458
+ actionsContainer: {
1459
+ marginBottom: theme.spacing(2)
1460
+ },
1461
+ resetContainer: {
1462
+ padding: theme.spacing(3)
1463
+ },
1464
+ labelWrapper: {
1465
+ display: "flex",
1466
+ flex: 1,
1467
+ flexDirection: "row",
1468
+ justifyContent: "space-between"
1469
+ },
1470
+ stepWrapper: {
1471
+ width: "100%"
1472
+ }
1473
+ })
1474
+ );
1475
+ const StepTimeTicker = ({ step }) => {
1476
+ const [time, setTime] = useState("");
1477
+ useInterval(() => {
1478
+ if (!step.startedAt) {
1479
+ setTime("");
1480
+ return;
1481
+ }
1482
+ const end = step.endedAt ? DateTime.fromISO(step.endedAt) : DateTime.local();
1483
+ const startedAt = DateTime.fromISO(step.startedAt);
1484
+ const formatted = Interval.fromDateTimes(startedAt, end).toDuration().valueOf();
1485
+ setTime(humanizeDuration(formatted, { round: true }));
1486
+ }, 1e3);
1487
+ return /* @__PURE__ */ React.createElement(Typography$1, { variant: "caption" }, time);
1488
+ };
1489
+ const useStepIconStyles = makeStyles$1(
1490
+ (theme) => createStyles({
1491
+ root: {
1492
+ color: theme.palette.text.disabled,
1493
+ display: "flex",
1494
+ height: 22,
1495
+ alignItems: "center"
1496
+ },
1497
+ completed: {
1498
+ color: theme.palette.status.ok
1499
+ },
1500
+ error: {
1501
+ color: theme.palette.status.error
1502
+ }
1503
+ })
1504
+ );
1505
+ function TaskStepIconComponent(props) {
1506
+ const classes = useStepIconStyles();
1507
+ const { active, completed, error } = props;
1508
+ const getMiddle = () => {
1509
+ if (active) {
1510
+ return /* @__PURE__ */ React.createElement(CircularProgress, { size: "24px" });
1511
+ }
1512
+ if (completed) {
1513
+ return /* @__PURE__ */ React.createElement(Check, null);
1514
+ }
1515
+ if (error) {
1516
+ return /* @__PURE__ */ React.createElement(Cancel, null);
1517
+ }
1518
+ return /* @__PURE__ */ React.createElement(FiberManualRecordIcon, null);
1519
+ };
1520
+ return /* @__PURE__ */ React.createElement(
1521
+ "div",
1522
+ {
1523
+ className: classNames(classes.root, {
1524
+ [classes.completed]: completed,
1525
+ [classes.error]: error
1526
+ })
1527
+ },
1528
+ getMiddle()
1529
+ );
1530
+ }
1531
+ const TaskStatusStepper = memo(
1532
+ (props) => {
1533
+ const { steps, currentStepId, onUserStepChange } = props;
1534
+ const classes = useStyles(props);
1535
+ return /* @__PURE__ */ React.createElement("div", { className: classes.root }, /* @__PURE__ */ React.createElement(
1536
+ Stepper,
1537
+ {
1538
+ activeStep: steps.findIndex((s) => s.id === currentStepId),
1539
+ orientation: "vertical",
1540
+ nonLinear: true
1541
+ },
1542
+ steps.map((step, index) => {
1543
+ const isCancelled = step.status === "cancelled";
1544
+ const isActive = step.status === "processing";
1545
+ const isCompleted = step.status === "completed";
1546
+ const isFailed = step.status === "failed";
1547
+ const isSkipped = step.status === "skipped";
1548
+ return /* @__PURE__ */ React.createElement(Step, { key: String(index), expanded: true }, /* @__PURE__ */ React.createElement(StepButton, { onClick: () => onUserStepChange(step.id) }, /* @__PURE__ */ React.createElement(
1549
+ StepLabel,
1550
+ {
1551
+ StepIconProps: {
1552
+ completed: isCompleted,
1553
+ error: isFailed || isCancelled,
1554
+ active: isActive
1555
+ },
1556
+ StepIconComponent: TaskStepIconComponent,
1557
+ className: classes.stepWrapper
1558
+ },
1559
+ /* @__PURE__ */ React.createElement("div", { className: classes.labelWrapper }, /* @__PURE__ */ React.createElement(Typography$1, { variant: "subtitle2" }, step.name), isSkipped ? /* @__PURE__ */ React.createElement(Typography$1, { variant: "caption" }, "Skipped") : /* @__PURE__ */ React.createElement(StepTimeTicker, { step }))
1560
+ )));
1561
+ })
1562
+ ));
1563
+ }
1564
+ );
1565
+ const hasLinks = ({ links = [] }) => links.length > 0;
1566
+ const TaskPage = (props) => {
1567
+ const { loadingText } = props;
1568
+ const classes = useStyles();
1569
+ const navigate = useNavigate();
1570
+ const rootPath = useRouteRef(rootRouteRef);
1571
+ const scaffolderApi = useApi(scaffolderApiRef);
1572
+ const templateRoute = useRouteRef(selectedTemplateRouteRef);
1573
+ const [userSelectedStepId, setUserSelectedStepId] = useState(void 0);
1574
+ const [clickedToCancel, setClickedToCancel] = useState(false);
1575
+ const [lastActiveStepId, setLastActiveStepId] = useState(
1576
+ void 0
1577
+ );
1578
+ const { taskId } = useRouteRefParams(scaffolderTaskRouteRef);
1579
+ const taskStream = useTaskEventStream(taskId);
1580
+ const completed = taskStream.completed;
1581
+ const taskCancelled = taskStream.cancelled;
1582
+ const steps = useMemo(
1583
+ () => {
1584
+ var _a, _b;
1585
+ return (_b = (_a = taskStream.task) == null ? void 0 : _a.spec.steps.map((step) => {
1586
+ var _a2;
1587
+ return {
1588
+ ...step,
1589
+ ...(_a2 = taskStream == null ? void 0 : taskStream.steps) == null ? void 0 : _a2[step.id]
1590
+ };
1591
+ })) != null ? _b : [];
1592
+ },
1593
+ [taskStream]
1594
+ );
1595
+ useEffect(() => {
1596
+ var _a;
1597
+ const mostRecentFailedOrActiveStep = steps.find(
1598
+ (step) => ["failed", "processing"].includes(step.status)
1599
+ );
1600
+ if (completed && !mostRecentFailedOrActiveStep) {
1601
+ setLastActiveStepId((_a = steps[steps.length - 1]) == null ? void 0 : _a.id);
1602
+ return;
1603
+ }
1604
+ setLastActiveStepId(mostRecentFailedOrActiveStep == null ? void 0 : mostRecentFailedOrActiveStep.id);
1605
+ }, [steps, completed]);
1606
+ const currentStepId = userSelectedStepId != null ? userSelectedStepId : lastActiveStepId;
1607
+ const logAsString = useMemo(() => {
1608
+ if (!currentStepId) {
1609
+ return loadingText ? loadingText : "Loading...";
1610
+ }
1611
+ const log = taskStream.stepLogs[currentStepId];
1612
+ if (!(log == null ? void 0 : log.length)) {
1613
+ return "Waiting for logs...";
1614
+ }
1615
+ return log.join("\n");
1616
+ }, [taskStream.stepLogs, currentStepId, loadingText]);
1617
+ const taskNotFound = taskStream.completed && !taskStream.loading && !taskStream.task;
1618
+ const { output } = taskStream;
1619
+ const handleStartOver = () => {
1620
+ var _a, _b, _c;
1621
+ if (!taskStream.task || !((_b = (_a = taskStream.task) == null ? void 0 : _a.spec.templateInfo) == null ? void 0 : _b.entityRef)) {
1622
+ navigate(rootPath());
1623
+ return;
1624
+ }
1625
+ const formData = taskStream.task.spec.parameters;
1626
+ const { name, namespace } = parseEntityRef(
1627
+ (_c = taskStream.task.spec.templateInfo) == null ? void 0 : _c.entityRef
1628
+ );
1629
+ navigate(
1630
+ `${templateRoute({ templateName: name, namespace })}?${qs.stringify({
1631
+ formData: JSON.stringify(formData)
1632
+ })}`
1633
+ );
1634
+ };
1635
+ const handleCancel = async () => {
1636
+ setClickedToCancel(true);
1637
+ await scaffolderApi.cancelTask(taskId);
1638
+ };
1639
+ return /* @__PURE__ */ React.createElement(Page, { themeId: "home" }, /* @__PURE__ */ React.createElement(
1640
+ Header,
1641
+ {
1642
+ pageTitleOverride: `Task ${taskId}`,
1643
+ title: "Task Activity",
1644
+ subtitle: `Activity for task: ${taskId}`
1645
+ }
1646
+ ), /* @__PURE__ */ React.createElement(Content, null, taskNotFound ? /* @__PURE__ */ React.createElement(
1647
+ ErrorPage,
1648
+ {
1649
+ status: "404",
1650
+ statusMessage: "Task not found",
1651
+ additionalInfo: "No task found with this ID"
1652
+ }
1653
+ ) : /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Grid$1, { container: true }, /* @__PURE__ */ React.createElement(Grid$1, { item: true, xs: 3 }, /* @__PURE__ */ React.createElement(Paper, null, /* @__PURE__ */ React.createElement(
1654
+ TaskStatusStepper,
1655
+ {
1656
+ steps,
1657
+ currentStepId,
1658
+ onUserStepChange: setUserSelectedStepId
1659
+ }
1660
+ ), output && hasLinks(output) && /* @__PURE__ */ React.createElement(TaskPageLinks, { output }), /* @__PURE__ */ React.createElement(
1661
+ Button,
1662
+ {
1663
+ className: classes.button,
1664
+ onClick: handleStartOver,
1665
+ disabled: !completed,
1666
+ variant: "contained",
1667
+ color: "primary"
1668
+ },
1669
+ "Start Over"
1670
+ ), /* @__PURE__ */ React.createElement(
1671
+ Button,
1672
+ {
1673
+ className: classes.button,
1674
+ onClick: handleCancel,
1675
+ disabled: completed || taskCancelled || clickedToCancel,
1676
+ variant: "outlined",
1677
+ color: "secondary"
1678
+ },
1679
+ (taskCancelled || clickedToCancel) && !completed ? "Cancelling..." : "Cancel"
1680
+ ))), /* @__PURE__ */ React.createElement(Grid$1, { item: true, xs: 9 }, !currentStepId && /* @__PURE__ */ React.createElement(Progress, null), /* @__PURE__ */ React.createElement("div", { style: { height: "80vh" } }, /* @__PURE__ */ React.createElement(TaskErrors, { error: taskStream.error }), /* @__PURE__ */ React.createElement(LogViewer, { text: logAsString })))))));
1681
+ };
1682
+
1683
+ export { entityNamePickerValidation as A, EntityNamePickerSchema as B, EntityTagsPicker as C, EntityTagsPickerSchema as D, EntityPickerFieldExtension as E, RepoUrlPicker as F, RepoUrlPickerSchema as G, OwnerPicker as H, OwnerPickerSchema as I, OwnedEntityPicker as J, OwnedEntityPickerSchema as K, NextScaffolderPage as N, OwnerPickerFieldExtension as O, RepoUrlPickerFieldExtension as R, ScaffolderClient as S, TaskPage as T, EntityNamePickerFieldExtension as a, EntityTagsPickerFieldExtension as b, OwnedEntityPickerFieldExtension as c, ScaffolderPage as d, EntityPickerFieldSchema as e, OwnerPickerFieldSchema as f, RepoUrlPickerFieldSchema as g, repoPickerValidation as h, OwnedEntityPickerFieldSchema as i, EntityTagsPickerFieldSchema as j, selectedTemplateRouteRef as k, TaskStatusStepper as l, makeFieldSchemaFromZod as m, TaskPageLinks as n, editRouteRef as o, actionsRouteRef as p, scaffolderListTaskRouteRef as q, rootRouteRef as r, scaffolderPlugin as s, registerComponentRouteRef as t, scaffolderTaskRouteRef as u, viewTechDocRouteRef as v, legacySelectedTemplateRouteRef as w, EntityPicker as x, EntityPickerSchema as y, EntityNamePicker as z };
1684
+ //# sourceMappingURL=TaskPage-589238dc.esm.js.map