@backstage/plugin-scaffolder 1.3.0-next.0 → 1.3.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.
@@ -0,0 +1,2392 @@
1
+ import React, { useState, useContext, useCallback, createContext, useEffect, useRef, useMemo, Children, Component, Fragment } from 'react';
2
+ import { useNavigate, Navigate, useOutlet, Routes, Route, useParams as useParams$1 } from 'react-router';
3
+ import { ItemCardHeader, MarkdownContent, Button, ContentHeader, Progress, WarningPanel, Link as Link$1, Content, ItemCardGrid, Page, Header, CreateButton, SupportButton, StructuredMetadataTable, InfoCard, ErrorPage, ErrorPanel, LogViewer, StatusError, StatusOK, StatusPending, Lifecycle, EmptyState } from '@backstage/core-components';
4
+ import { useRouteRef, useApi, errorApiRef, featureFlagsApiRef, useApiHolder, alertApiRef, useElementFilter } from '@backstage/core-plugin-api';
5
+ import { getEntityRelations, getEntitySourceLocation, FavoriteEntity, EntityRefLinks, useEntityList, EntityListProvider, CatalogFilterLayout, EntitySearchBar, EntityKindPicker, UserListPicker, EntityTagPicker, catalogApiRef, humanizeEntityRef, EntityRefLink } from '@backstage/plugin-catalog-react';
6
+ import { s as selectedTemplateRouteRef, e as editRouteRef, a as actionsRouteRef, b as scaffolderListTaskRouteRef, r as registerComponentRouteRef, T as TemplateTypePicker, S as SecretsContext, c as scaffolderApiRef, d as scaffolderTaskRouteRef, f as rootRouteRef, g as TaskStatusStepper, h as TaskPageLinks, F as FIELD_EXTENSION_WRAPPER_KEY, i as FIELD_EXTENSION_KEY, l as legacySelectedTemplateRouteRef, j as SecretsContextProvider, k as TaskPage } from './index-6712a69a.esm.js';
7
+ import { RELATION_OWNED_BY, parseEntityRef, stringifyEntityRef } from '@backstage/catalog-model';
8
+ import { makeStyles, useTheme, Card, CardMedia, CardContent, Box, Typography, Chip, CardActions, IconButton, Tooltip, Link, Stepper, Step, StepLabel, StepContent, Button as Button$1, Paper, LinearProgress, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, Divider as Divider$1, FormControl, InputLabel, Select, MenuItem as MenuItem$1, List as List$2, ListItemIcon as ListItemIcon$1, ListItemText as ListItemText$1 } from '@material-ui/core';
9
+ import { scmIntegrationsApiRef, ScmIntegrationIcon } from '@backstage/integration-react';
10
+ import WarningIcon from '@material-ui/icons/Warning';
11
+ import { catalogEntityCreatePermission } from '@backstage/plugin-catalog-common';
12
+ import { usePermission } from '@backstage/plugin-permission-react';
13
+ import IconButton$1 from '@material-ui/core/IconButton';
14
+ import ListItemIcon from '@material-ui/core/ListItemIcon';
15
+ import ListItemText from '@material-ui/core/ListItemText';
16
+ import MenuItem from '@material-ui/core/MenuItem';
17
+ import MenuList from '@material-ui/core/MenuList';
18
+ import Popover from '@material-ui/core/Popover';
19
+ import { makeStyles as makeStyles$1 } from '@material-ui/core/styles';
20
+ import Description from '@material-ui/icons/Description';
21
+ import Edit from '@material-ui/icons/Edit';
22
+ import List from '@material-ui/icons/List';
23
+ import MoreVert from '@material-ui/icons/MoreVert';
24
+ import qs from 'qs';
25
+ import { useParams } from 'react-router-dom';
26
+ import useAsync from 'react-use/lib/useAsync';
27
+ import { withTheme } from '@rjsf/core';
28
+ import { Theme } from '@rjsf/material-ui';
29
+ import cloneDeep from 'lodash/cloneDeep';
30
+ import classNames from 'classnames';
31
+ import Card$1 from '@material-ui/core/Card';
32
+ import CardActionArea from '@material-ui/core/CardActionArea';
33
+ import CardContent$1 from '@material-ui/core/CardContent';
34
+ import Tooltip$1 from '@material-ui/core/Tooltip';
35
+ import Typography$1 from '@material-ui/core/Typography';
36
+ import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined';
37
+ import { useAsync as useAsync$1, useRerender, usePrevious, useKeyboardEvent } from '@react-hookz/web';
38
+ import yaml from 'yaml';
39
+ import Accordion from '@material-ui/core/Accordion';
40
+ import AccordionDetails from '@material-ui/core/AccordionDetails';
41
+ import AccordionSummary from '@material-ui/core/AccordionSummary';
42
+ import Divider from '@material-ui/core/Divider';
43
+ import ExpandMoreIcon$1 from '@material-ui/icons/ExpandLess';
44
+ import List$1 from '@material-ui/core/List';
45
+ import ListItem from '@material-ui/core/ListItem';
46
+ import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
47
+ import Cancel from '@material-ui/icons/Cancel';
48
+ import Check from '@material-ui/icons/Check';
49
+ import DeleteIcon from '@material-ui/icons/Delete';
50
+ import { StreamLanguage } from '@codemirror/language';
51
+ import { yaml as yaml$1 } from '@codemirror/legacy-modes/mode/yaml';
52
+ import Box$1 from '@material-ui/core/Box';
53
+ import Tab from '@material-ui/core/Tab';
54
+ import Tabs from '@material-ui/core/Tabs';
55
+ import CodeMirror from '@uiw/react-codemirror';
56
+ import TreeView from '@material-ui/lab/TreeView';
57
+ import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
58
+ import ChevronRightIcon from '@material-ui/icons/ChevronRight';
59
+ import TreeItem from '@material-ui/lab/TreeItem';
60
+ import CloseIcon from '@material-ui/icons/Close';
61
+ import RefreshIcon from '@material-ui/icons/Refresh';
62
+ import SaveIcon from '@material-ui/icons/Save';
63
+ import useDebounce from 'react-use/lib/useDebounce';
64
+ import { showPanel } from '@codemirror/view';
65
+ import MaterialTable from '@material-table/core';
66
+ import SettingsIcon from '@material-ui/icons/Settings';
67
+ import AllIcon from '@material-ui/icons/FontDownload';
68
+ import { DateTime, Interval } from 'luxon';
69
+ import humanizeDuration from 'humanize-duration';
70
+ import { D as DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS } from './default-6ab4a4ed.esm.js';
71
+ import '@backstage/errors';
72
+ import 'zen-observable';
73
+ import '@material-ui/core/FormControl';
74
+ import '@material-ui/lab/Autocomplete';
75
+ import 'react-use/lib/useEffectOnce';
76
+ import '@material-ui/lab';
77
+ import '@material-ui/core/FormHelperText';
78
+ import '@material-ui/core/Input';
79
+ import '@material-ui/core/InputLabel';
80
+ import 'lodash/capitalize';
81
+ import '@material-ui/icons/CheckBox';
82
+ import '@material-ui/icons/CheckBoxOutlineBlank';
83
+ import '@material-ui/core/Grid';
84
+ import '@material-ui/core/Step';
85
+ import '@material-ui/core/StepLabel';
86
+ import '@material-ui/core/Stepper';
87
+ import '@material-ui/icons/FiberManualRecord';
88
+ import 'react-use/lib/useInterval';
89
+ import 'use-immer';
90
+ import '@material-ui/icons/Language';
91
+
92
+ const useStyles$e = makeStyles((theme) => ({
93
+ cardHeader: {
94
+ position: "relative"
95
+ },
96
+ title: {
97
+ backgroundImage: ({ backgroundImage }) => backgroundImage
98
+ },
99
+ box: {
100
+ overflow: "hidden",
101
+ textOverflow: "ellipsis",
102
+ display: "-webkit-box",
103
+ "-webkit-line-clamp": 10,
104
+ "-webkit-box-orient": "vertical",
105
+ paddingBottom: "0.8em"
106
+ },
107
+ label: {
108
+ color: theme.palette.text.secondary,
109
+ textTransform: "uppercase",
110
+ fontSize: "0.65rem",
111
+ fontWeight: "bold",
112
+ letterSpacing: 0.5,
113
+ lineHeight: 1,
114
+ paddingBottom: "0.2rem"
115
+ },
116
+ leftButton: {
117
+ marginRight: "auto"
118
+ },
119
+ starButton: {
120
+ position: "absolute",
121
+ top: theme.spacing(0.5),
122
+ right: theme.spacing(0.5),
123
+ padding: "0.25rem",
124
+ color: "#fff"
125
+ }
126
+ }));
127
+ const useDeprecationStyles = makeStyles((theme) => ({
128
+ deprecationIcon: {
129
+ position: "absolute",
130
+ top: theme.spacing(0.5),
131
+ right: theme.spacing(3.5),
132
+ padding: "0.25rem"
133
+ },
134
+ link: {
135
+ color: theme.palette.warning.light
136
+ }
137
+ }));
138
+ const getTemplateCardProps = (template) => {
139
+ var _a, _b, _c, _d, _e;
140
+ return {
141
+ key: template.metadata.uid,
142
+ name: template.metadata.name,
143
+ title: `${(_a = template.metadata.title || template.metadata.name) != null ? _a : ""}`,
144
+ type: (_b = template.spec.type) != null ? _b : "",
145
+ description: (_c = template.metadata.description) != null ? _c : "-",
146
+ tags: (_e = (_d = template.metadata) == null ? void 0 : _d.tags) != null ? _e : []
147
+ };
148
+ };
149
+ const DeprecationWarning = () => {
150
+ const styles = useDeprecationStyles();
151
+ const Title = /* @__PURE__ */ React.createElement(Typography, {
152
+ style: { padding: 10, maxWidth: 300 }
153
+ }, "This template uses a syntax that has been deprecated, and should be migrated to a newer syntax. Click for more info.");
154
+ return /* @__PURE__ */ React.createElement("div", {
155
+ className: styles.deprecationIcon
156
+ }, /* @__PURE__ */ React.createElement(Tooltip, {
157
+ title: Title
158
+ }, /* @__PURE__ */ React.createElement(Link, {
159
+ href: "https://backstage.io/docs/features/software-templates/migrating-from-v1beta2-to-v1beta3",
160
+ className: styles.link
161
+ }, /* @__PURE__ */ React.createElement(WarningIcon, null))));
162
+ };
163
+ const TemplateCard = ({ template, deprecated }) => {
164
+ var _a;
165
+ const backstageTheme = useTheme();
166
+ const templateRoute = useRouteRef(selectedTemplateRouteRef);
167
+ const templateProps = getTemplateCardProps(template);
168
+ const ownedByRelations = getEntityRelations(template, RELATION_OWNED_BY);
169
+ const themeId = backstageTheme.getPageTheme({ themeId: templateProps.type }) ? templateProps.type : "other";
170
+ const theme = backstageTheme.getPageTheme({ themeId });
171
+ const classes = useStyles$e({ backgroundImage: theme.backgroundImage });
172
+ const { name, namespace } = parseEntityRef(stringifyEntityRef(template));
173
+ const href = templateRoute({ templateName: name, namespace });
174
+ const scmIntegrationsApi = useApi(scmIntegrationsApiRef);
175
+ const sourceLocation = getEntitySourceLocation(template, scmIntegrationsApi);
176
+ return /* @__PURE__ */ React.createElement(Card, null, /* @__PURE__ */ React.createElement(CardMedia, {
177
+ className: classes.cardHeader
178
+ }, /* @__PURE__ */ React.createElement(FavoriteEntity, {
179
+ className: classes.starButton,
180
+ entity: template
181
+ }), deprecated && /* @__PURE__ */ React.createElement(DeprecationWarning, null), /* @__PURE__ */ React.createElement(ItemCardHeader, {
182
+ title: templateProps.title,
183
+ subtitle: templateProps.type,
184
+ classes: { root: classes.title }
185
+ })), /* @__PURE__ */ React.createElement(CardContent, {
186
+ style: { display: "grid" }
187
+ }, /* @__PURE__ */ React.createElement(Box, {
188
+ className: classes.box
189
+ }, /* @__PURE__ */ React.createElement(Typography, {
190
+ variant: "body2",
191
+ className: classes.label
192
+ }, "Description"), /* @__PURE__ */ React.createElement(MarkdownContent, {
193
+ content: templateProps.description
194
+ })), /* @__PURE__ */ React.createElement(Box, {
195
+ className: classes.box
196
+ }, /* @__PURE__ */ React.createElement(Typography, {
197
+ variant: "body2",
198
+ className: classes.label
199
+ }, "Owner"), /* @__PURE__ */ React.createElement(EntityRefLinks, {
200
+ entityRefs: ownedByRelations,
201
+ defaultKind: "Group"
202
+ })), /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Typography, {
203
+ variant: "body2",
204
+ className: classes.label
205
+ }, "Tags"), (_a = templateProps.tags) == null ? void 0 : _a.map((tag) => /* @__PURE__ */ React.createElement(Chip, {
206
+ size: "small",
207
+ label: tag,
208
+ key: tag
209
+ })))), /* @__PURE__ */ React.createElement(CardActions, null, sourceLocation && /* @__PURE__ */ React.createElement(IconButton, {
210
+ className: classes.leftButton,
211
+ href: sourceLocation.locationTargetUrl
212
+ }, /* @__PURE__ */ React.createElement(ScmIntegrationIcon, {
213
+ type: sourceLocation.integrationType
214
+ })), /* @__PURE__ */ React.createElement(Button, {
215
+ color: "primary",
216
+ to: href,
217
+ "aria-label": `Choose ${templateProps.title}`
218
+ }, "Choose")));
219
+ };
220
+
221
+ const TemplateList = ({
222
+ TemplateCardComponent,
223
+ group
224
+ }) => {
225
+ const { loading, error, entities } = useEntityList();
226
+ const Card = TemplateCardComponent || TemplateCard;
227
+ const maybeFilteredEntities = group ? entities.filter((e) => group.filter(e)) : entities;
228
+ const titleComponent = (() => {
229
+ if (group && group.title) {
230
+ if (typeof group.title === "string") {
231
+ return /* @__PURE__ */ React.createElement(ContentHeader, {
232
+ title: group.title
233
+ });
234
+ }
235
+ return group.title;
236
+ }
237
+ return /* @__PURE__ */ React.createElement(ContentHeader, {
238
+ title: "Other Templates"
239
+ });
240
+ })();
241
+ if (group && maybeFilteredEntities.length === 0) {
242
+ return null;
243
+ }
244
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, loading && /* @__PURE__ */ React.createElement(Progress, null), error && /* @__PURE__ */ React.createElement(WarningPanel, {
245
+ title: "Oops! Something went wrong loading the templates"
246
+ }, error.message), !error && !loading && !entities.length && /* @__PURE__ */ React.createElement(Typography, {
247
+ variant: "body2"
248
+ }, "No templates found that match your filter. Learn more about", " ", /* @__PURE__ */ React.createElement(Link$1, {
249
+ to: "https://backstage.io/docs/features/software-templates/adding-templates"
250
+ }, "adding templates"), "."), /* @__PURE__ */ React.createElement(Content, null, titleComponent, /* @__PURE__ */ React.createElement(ItemCardGrid, null, maybeFilteredEntities && (maybeFilteredEntities == null ? void 0 : maybeFilteredEntities.length) > 0 && maybeFilteredEntities.map((template) => /* @__PURE__ */ React.createElement(Card, {
251
+ key: stringifyEntityRef(template),
252
+ template,
253
+ deprecated: template.apiVersion === "backstage.io/v1beta2"
254
+ })))));
255
+ };
256
+
257
+ const useStyles$d = makeStyles$1({
258
+ button: {
259
+ color: "white"
260
+ }
261
+ });
262
+ function ScaffolderPageContextMenu(props) {
263
+ const classes = useStyles$d();
264
+ const [anchorEl, setAnchorEl] = useState();
265
+ const editLink = useRouteRef(editRouteRef);
266
+ const actionsLink = useRouteRef(actionsRouteRef);
267
+ const tasksLink = useRouteRef(scaffolderListTaskRouteRef);
268
+ const navigate = useNavigate();
269
+ const showEditor = props.editor !== false;
270
+ const showActions = props.actions !== false;
271
+ const showTasks = props.tasks !== false;
272
+ if (!showEditor && !showActions) {
273
+ return null;
274
+ }
275
+ const onOpen = (event) => {
276
+ setAnchorEl(event.currentTarget);
277
+ };
278
+ const onClose = () => {
279
+ setAnchorEl(void 0);
280
+ };
281
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(IconButton$1, {
282
+ "aria-label": "more",
283
+ "aria-controls": "long-menu",
284
+ "aria-haspopup": "true",
285
+ onClick: onOpen,
286
+ "data-testid": "menu-button",
287
+ color: "inherit",
288
+ className: classes.button
289
+ }, /* @__PURE__ */ React.createElement(MoreVert, null)), /* @__PURE__ */ React.createElement(Popover, {
290
+ open: Boolean(anchorEl),
291
+ onClose,
292
+ anchorEl,
293
+ anchorOrigin: { vertical: "bottom", horizontal: "right" },
294
+ transformOrigin: { vertical: "top", horizontal: "right" }
295
+ }, /* @__PURE__ */ React.createElement(MenuList, null, showEditor && /* @__PURE__ */ React.createElement(MenuItem, {
296
+ onClick: () => navigate(editLink())
297
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, null, /* @__PURE__ */ React.createElement(Edit, {
298
+ fontSize: "small"
299
+ })), /* @__PURE__ */ React.createElement(ListItemText, {
300
+ primary: "Template Editor"
301
+ })), showActions && /* @__PURE__ */ React.createElement(MenuItem, {
302
+ onClick: () => navigate(actionsLink())
303
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, null, /* @__PURE__ */ React.createElement(Description, {
304
+ fontSize: "small"
305
+ })), /* @__PURE__ */ React.createElement(ListItemText, {
306
+ primary: "Installed Actions"
307
+ })), showTasks && /* @__PURE__ */ React.createElement(MenuItem, {
308
+ onClick: () => navigate(tasksLink())
309
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, null, /* @__PURE__ */ React.createElement(List, {
310
+ fontSize: "small"
311
+ })), /* @__PURE__ */ React.createElement(ListItemText, {
312
+ primary: "Task List"
313
+ })))));
314
+ }
315
+
316
+ const ScaffolderPageContents = ({
317
+ TemplateCardComponent,
318
+ groups,
319
+ contextMenu
320
+ }) => {
321
+ const registerComponentLink = useRouteRef(registerComponentRouteRef);
322
+ const otherTemplatesGroup = {
323
+ title: groups ? "Other Templates" : "Templates",
324
+ filter: (entity) => {
325
+ const filtered = (groups != null ? groups : []).map((group) => group.filter(entity));
326
+ return !filtered.some((result) => result === true);
327
+ }
328
+ };
329
+ const { allowed } = usePermission({
330
+ permission: catalogEntityCreatePermission
331
+ });
332
+ return /* @__PURE__ */ React.createElement(Page, {
333
+ themeId: "home"
334
+ }, /* @__PURE__ */ React.createElement(Header, {
335
+ pageTitleOverride: "Create a New Component",
336
+ title: "Create a New Component",
337
+ subtitle: "Create new software components using standard templates"
338
+ }, /* @__PURE__ */ React.createElement(ScaffolderPageContextMenu, {
339
+ ...contextMenu
340
+ })), /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(ContentHeader, {
341
+ title: "Available Templates"
342
+ }, allowed && /* @__PURE__ */ React.createElement(CreateButton, {
343
+ title: "Register Existing Component",
344
+ to: registerComponentLink && registerComponentLink()
345
+ }), /* @__PURE__ */ React.createElement(SupportButton, null, "Create new software components using standard templates. Different templates create different kinds of components (services, websites, documentation, ...).")), /* @__PURE__ */ React.createElement(CatalogFilterLayout, null, /* @__PURE__ */ React.createElement(CatalogFilterLayout.Filters, null, /* @__PURE__ */ React.createElement(EntitySearchBar, null), /* @__PURE__ */ React.createElement(EntityKindPicker, {
346
+ initialFilter: "template",
347
+ hidden: true
348
+ }), /* @__PURE__ */ React.createElement(UserListPicker, {
349
+ initialFilter: "all",
350
+ availableFilters: ["all", "starred"]
351
+ }), /* @__PURE__ */ React.createElement(TemplateTypePicker, null), /* @__PURE__ */ React.createElement(EntityTagPicker, null)), /* @__PURE__ */ React.createElement(CatalogFilterLayout.Content, null, groups && groups.map((group, index) => /* @__PURE__ */ React.createElement(TemplateList, {
352
+ key: index,
353
+ TemplateCardComponent,
354
+ group
355
+ })), /* @__PURE__ */ React.createElement(TemplateList, {
356
+ key: "other",
357
+ TemplateCardComponent,
358
+ group: otherTemplatesGroup
359
+ })))));
360
+ };
361
+ const ScaffolderPage = ({
362
+ TemplateCardComponent,
363
+ groups
364
+ }) => /* @__PURE__ */ React.createElement(EntityListProvider, null, /* @__PURE__ */ React.createElement(ScaffolderPageContents, {
365
+ TemplateCardComponent,
366
+ groups
367
+ }));
368
+
369
+ function isObject$1(value) {
370
+ return typeof value === "object" && value !== null && !Array.isArray(value);
371
+ }
372
+ function extractUiSchema(schema, uiSchema) {
373
+ if (!isObject$1(schema)) {
374
+ return;
375
+ }
376
+ const { properties, items, anyOf, oneOf, allOf, dependencies } = schema;
377
+ for (const propName in schema) {
378
+ if (!schema.hasOwnProperty(propName)) {
379
+ continue;
380
+ }
381
+ if (propName.startsWith("ui:")) {
382
+ uiSchema[propName] = schema[propName];
383
+ delete schema[propName];
384
+ }
385
+ }
386
+ if (isObject$1(properties)) {
387
+ for (const propName in properties) {
388
+ if (!properties.hasOwnProperty(propName)) {
389
+ continue;
390
+ }
391
+ const schemaNode = properties[propName];
392
+ if (!isObject$1(schemaNode)) {
393
+ continue;
394
+ }
395
+ const innerUiSchema = {};
396
+ uiSchema[propName] = innerUiSchema;
397
+ extractUiSchema(schemaNode, innerUiSchema);
398
+ }
399
+ }
400
+ if (isObject$1(items)) {
401
+ const innerUiSchema = {};
402
+ uiSchema.items = innerUiSchema;
403
+ extractUiSchema(items, innerUiSchema);
404
+ }
405
+ if (Array.isArray(anyOf)) {
406
+ for (const schemaNode of anyOf) {
407
+ if (!isObject$1(schemaNode)) {
408
+ continue;
409
+ }
410
+ extractUiSchema(schemaNode, uiSchema);
411
+ }
412
+ }
413
+ if (Array.isArray(oneOf)) {
414
+ for (const schemaNode of oneOf) {
415
+ if (!isObject$1(schemaNode)) {
416
+ continue;
417
+ }
418
+ extractUiSchema(schemaNode, uiSchema);
419
+ }
420
+ }
421
+ if (Array.isArray(allOf)) {
422
+ for (const schemaNode of allOf) {
423
+ if (!isObject$1(schemaNode)) {
424
+ continue;
425
+ }
426
+ extractUiSchema(schemaNode, uiSchema);
427
+ }
428
+ }
429
+ if (isObject$1(dependencies)) {
430
+ for (const depName of Object.keys(dependencies)) {
431
+ const schemaNode = dependencies[depName];
432
+ if (!isObject$1(schemaNode)) {
433
+ continue;
434
+ }
435
+ extractUiSchema(schemaNode, uiSchema);
436
+ }
437
+ }
438
+ }
439
+ function transformSchemaToProps(inputSchema) {
440
+ inputSchema.type = inputSchema.type || "object";
441
+ const schema = JSON.parse(JSON.stringify(inputSchema));
442
+ delete schema.title;
443
+ const uiSchema = {};
444
+ extractUiSchema(schema, uiSchema);
445
+ return { schema, uiSchema };
446
+ }
447
+
448
+ const DescriptionField = ({ description }) => description && /* @__PURE__ */ React.createElement(MarkdownContent, {
449
+ content: description,
450
+ linkTarget: "_blank"
451
+ });
452
+
453
+ var fieldOverrides = /*#__PURE__*/Object.freeze({
454
+ __proto__: null,
455
+ DescriptionField: DescriptionField
456
+ });
457
+
458
+ const Form = withTheme(Theme);
459
+ function getUiSchemasFromSteps(steps) {
460
+ const uiSchemas = [];
461
+ steps.forEach((step) => {
462
+ const schemaProps = step.schema.properties;
463
+ for (const key in schemaProps) {
464
+ if (schemaProps.hasOwnProperty(key)) {
465
+ const uiSchema = schemaProps[key];
466
+ uiSchema.name = key;
467
+ uiSchemas.push(uiSchema);
468
+ }
469
+ }
470
+ });
471
+ return uiSchemas;
472
+ }
473
+ function getReviewData(formData, steps) {
474
+ const uiSchemas = getUiSchemasFromSteps(steps);
475
+ const reviewData = {};
476
+ for (const key in formData) {
477
+ if (formData.hasOwnProperty(key)) {
478
+ const uiSchema = uiSchemas.find((us) => us.name === key);
479
+ if (!uiSchema) {
480
+ reviewData[key] = formData[key];
481
+ continue;
482
+ }
483
+ if (uiSchema["ui:widget"] === "password") {
484
+ reviewData[key] = "******";
485
+ continue;
486
+ }
487
+ if (!uiSchema["ui:backstage"] || !uiSchema["ui:backstage"].review) {
488
+ reviewData[key] = formData[key];
489
+ continue;
490
+ }
491
+ const review = uiSchema["ui:backstage"].review;
492
+ if (review.mask) {
493
+ reviewData[key] = review.mask;
494
+ continue;
495
+ }
496
+ if (!review.show) {
497
+ continue;
498
+ }
499
+ reviewData[key] = formData[key];
500
+ }
501
+ }
502
+ return reviewData;
503
+ }
504
+ const MultistepJsonForm = (props) => {
505
+ const {
506
+ formData,
507
+ onChange,
508
+ onReset,
509
+ onFinish,
510
+ fields,
511
+ widgets,
512
+ finishButtonLabel
513
+ } = props;
514
+ const [activeStep, setActiveStep] = useState(0);
515
+ const [disableButtons, setDisableButtons] = useState(false);
516
+ const errorApi = useApi(errorApiRef);
517
+ const featureFlagApi = useApi(featureFlagsApiRef);
518
+ const featureFlagKey = "backstage:featureFlag";
519
+ const filterOutProperties = (step) => {
520
+ var _a;
521
+ const filteredStep = cloneDeep(step);
522
+ const removedPropertyKeys = [];
523
+ if (filteredStep.schema.properties) {
524
+ filteredStep.schema.properties = Object.fromEntries(Object.entries(filteredStep.schema.properties).filter(([key, value]) => {
525
+ if (value[featureFlagKey]) {
526
+ if (featureFlagApi.isActive(value[featureFlagKey])) {
527
+ return true;
528
+ }
529
+ removedPropertyKeys.push(key);
530
+ return false;
531
+ }
532
+ return true;
533
+ }));
534
+ filteredStep.schema.required = Array.isArray(filteredStep.schema.required) ? (_a = filteredStep.schema.required) == null ? void 0 : _a.filter((r) => !removedPropertyKeys.includes(r)) : filteredStep.schema.required;
535
+ }
536
+ return filteredStep;
537
+ };
538
+ const steps = props.steps.filter((step) => {
539
+ const featureFlag = step.schema[featureFlagKey];
540
+ return typeof featureFlag !== "string" || featureFlagApi.isActive(featureFlag);
541
+ }).map(filterOutProperties);
542
+ const handleReset = () => {
543
+ setActiveStep(0);
544
+ onReset();
545
+ };
546
+ const handleNext = () => {
547
+ setActiveStep(Math.min(activeStep + 1, steps.length));
548
+ };
549
+ const handleBack = () => setActiveStep(Math.max(activeStep - 1, 0));
550
+ const handleCreate = async () => {
551
+ if (!onFinish) {
552
+ return;
553
+ }
554
+ setDisableButtons(true);
555
+ try {
556
+ await onFinish();
557
+ } catch (err) {
558
+ errorApi.post(err);
559
+ } finally {
560
+ setDisableButtons(false);
561
+ }
562
+ };
563
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Stepper, {
564
+ activeStep,
565
+ orientation: "vertical"
566
+ }, steps.map(({ title, schema, ...formProps }, index) => {
567
+ return /* @__PURE__ */ React.createElement(Step, {
568
+ key: title
569
+ }, /* @__PURE__ */ React.createElement(StepLabel, {
570
+ "aria-label": `Step ${index + 1} ${title}`,
571
+ "aria-disabled": "false",
572
+ tabIndex: 0
573
+ }, /* @__PURE__ */ React.createElement(Typography, {
574
+ variant: "h6",
575
+ component: "h3"
576
+ }, title)), /* @__PURE__ */ React.createElement(StepContent, {
577
+ key: title
578
+ }, /* @__PURE__ */ React.createElement(Form, {
579
+ showErrorList: false,
580
+ fields: { ...fieldOverrides, ...fields },
581
+ widgets,
582
+ noHtml5Validate: true,
583
+ formData,
584
+ formContext: { formData },
585
+ onChange,
586
+ onSubmit: (e) => {
587
+ if (e.errors.length === 0)
588
+ handleNext();
589
+ },
590
+ ...formProps,
591
+ ...transformSchemaToProps(schema)
592
+ }, /* @__PURE__ */ React.createElement(Button$1, {
593
+ disabled: activeStep === 0,
594
+ onClick: handleBack
595
+ }, "Back"), /* @__PURE__ */ React.createElement(Button$1, {
596
+ variant: "contained",
597
+ color: "primary",
598
+ type: "submit"
599
+ }, "Next step"))));
600
+ })), activeStep === steps.length && /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(Paper, {
601
+ square: true,
602
+ elevation: 0
603
+ }, /* @__PURE__ */ React.createElement(Typography, {
604
+ variant: "h6"
605
+ }, "Review and create"), /* @__PURE__ */ React.createElement(StructuredMetadataTable, {
606
+ dense: true,
607
+ metadata: getReviewData(formData, steps)
608
+ }), /* @__PURE__ */ React.createElement(Box, {
609
+ mb: 4
610
+ }), /* @__PURE__ */ React.createElement(Button$1, {
611
+ onClick: handleBack,
612
+ disabled: disableButtons
613
+ }, "Back"), /* @__PURE__ */ React.createElement(Button$1, {
614
+ onClick: handleReset,
615
+ disabled: disableButtons
616
+ }, "Reset"), /* @__PURE__ */ React.createElement(Button$1, {
617
+ variant: "contained",
618
+ color: "primary",
619
+ onClick: handleCreate,
620
+ disabled: !onFinish || disableButtons
621
+ }, finishButtonLabel != null ? finishButtonLabel : "Create"))));
622
+ };
623
+
624
+ function isObject(obj) {
625
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
626
+ }
627
+ const createValidator = (rootSchema, validators, context) => {
628
+ function validate(schema, formData, errors) {
629
+ const schemaProps = schema.properties;
630
+ const customObject = schema.type === "object" && schemaProps === void 0;
631
+ if (!isObject(schemaProps) && !customObject) {
632
+ return;
633
+ }
634
+ if (schemaProps) {
635
+ for (const [key, propData] of Object.entries(formData)) {
636
+ const propValidation = errors[key];
637
+ if (isObject(propData)) {
638
+ const propSchemaProps = schemaProps[key];
639
+ if (isObject(propSchemaProps)) {
640
+ validate(propSchemaProps, propData, propValidation);
641
+ }
642
+ } else {
643
+ const propSchema = schemaProps[key];
644
+ const fieldName = isObject(propSchema) && propSchema["ui:field"];
645
+ if (fieldName && typeof validators[fieldName] === "function") {
646
+ validators[fieldName](propData, propValidation, context);
647
+ }
648
+ }
649
+ }
650
+ } else if (customObject) {
651
+ const fieldName = schema["ui:field"];
652
+ if (fieldName && typeof validators[fieldName] === "function") {
653
+ validators[fieldName](formData, errors, context);
654
+ }
655
+ }
656
+ }
657
+ return (formData, errors) => {
658
+ validate(rootSchema, formData, errors);
659
+ return errors;
660
+ };
661
+ };
662
+
663
+ const useTemplateParameterSchema = (templateRef) => {
664
+ const scaffolderApi = useApi(scaffolderApiRef);
665
+ const { value, loading, error } = useAsync(() => scaffolderApi.getTemplateParameterSchema(templateRef), [scaffolderApi, templateRef]);
666
+ return { schema: value, loading, error };
667
+ };
668
+ const TemplatePage = ({
669
+ customFieldExtensions = []
670
+ }) => {
671
+ const apiHolder = useApiHolder();
672
+ const secretsContext = useContext(SecretsContext);
673
+ const errorApi = useApi(errorApiRef);
674
+ const scaffolderApi = useApi(scaffolderApiRef);
675
+ const { templateName, namespace } = useParams();
676
+ const templateRef = stringifyEntityRef({
677
+ name: templateName,
678
+ kind: "template",
679
+ namespace
680
+ });
681
+ const navigate = useNavigate();
682
+ const scaffolderTaskRoute = useRouteRef(scaffolderTaskRouteRef);
683
+ const rootRoute = useRouteRef(rootRouteRef);
684
+ const { schema, loading, error } = useTemplateParameterSchema(templateRef);
685
+ const [formState, setFormState] = useState(() => {
686
+ var _a;
687
+ const query = qs.parse(window.location.search, {
688
+ ignoreQueryPrefix: true
689
+ });
690
+ try {
691
+ return JSON.parse(query.formData);
692
+ } catch (e) {
693
+ return (_a = query.formData) != null ? _a : {};
694
+ }
695
+ });
696
+ const handleFormReset = () => setFormState({});
697
+ const handleChange = useCallback((e) => setFormState(e.formData), [setFormState]);
698
+ const handleCreate = async () => {
699
+ var _a;
700
+ const { taskId } = await scaffolderApi.scaffold({
701
+ templateRef,
702
+ values: formState,
703
+ secrets: secretsContext == null ? void 0 : secretsContext.secrets
704
+ });
705
+ const formParams = qs.stringify({ formData: formState }, { addQueryPrefix: true });
706
+ const newUrl = `${window.location.pathname}${formParams}`;
707
+ (_a = window.history) == null ? void 0 : _a.replaceState(null, document.title, newUrl);
708
+ navigate(scaffolderTaskRoute({ taskId }));
709
+ };
710
+ if (error) {
711
+ errorApi.post(new Error(`Failed to load template, ${error}`));
712
+ return /* @__PURE__ */ React.createElement(Navigate, {
713
+ to: rootRoute()
714
+ });
715
+ }
716
+ if (!loading && !schema) {
717
+ errorApi.post(new Error("Template was not found."));
718
+ return /* @__PURE__ */ React.createElement(Navigate, {
719
+ to: rootRoute()
720
+ });
721
+ }
722
+ const customFieldComponents = Object.fromEntries(customFieldExtensions.map(({ name, component }) => [name, component]));
723
+ const customFieldValidators = Object.fromEntries(customFieldExtensions.map(({ name, validation }) => [name, validation]));
724
+ return /* @__PURE__ */ React.createElement(Page, {
725
+ themeId: "home"
726
+ }, /* @__PURE__ */ React.createElement(Header, {
727
+ pageTitleOverride: "Create a New Component",
728
+ title: "Create a New Component",
729
+ subtitle: "Create new software components using standard templates"
730
+ }), /* @__PURE__ */ React.createElement(Content, null, loading && /* @__PURE__ */ React.createElement(LinearProgress, {
731
+ "data-testid": "loading-progress"
732
+ }), schema && /* @__PURE__ */ React.createElement(InfoCard, {
733
+ title: schema.title,
734
+ noPadding: true,
735
+ titleTypographyProps: { component: "h2" }
736
+ }, /* @__PURE__ */ React.createElement(MultistepJsonForm, {
737
+ formData: formState,
738
+ fields: customFieldComponents,
739
+ onChange: handleChange,
740
+ onReset: handleFormReset,
741
+ onFinish: handleCreate,
742
+ steps: schema.steps.map((step) => {
743
+ return {
744
+ ...step,
745
+ validate: createValidator(step.schema, customFieldValidators, { apiHolder })
746
+ };
747
+ })
748
+ }))));
749
+ };
750
+
751
+ const useStyles$c = makeStyles((theme) => ({
752
+ code: {
753
+ fontFamily: "Menlo, monospace",
754
+ padding: theme.spacing(1),
755
+ backgroundColor: theme.palette.type === "dark" ? theme.palette.grey[700] : theme.palette.grey[300],
756
+ display: "inline-block",
757
+ borderRadius: 5,
758
+ border: `1px solid ${theme.palette.grey[500]}`,
759
+ position: "relative"
760
+ },
761
+ codeRequired: {
762
+ "&::after": {
763
+ position: "absolute",
764
+ content: '"*"',
765
+ top: 0,
766
+ right: theme.spacing(0.5),
767
+ fontWeight: "bolder",
768
+ color: theme.palette.error.light
769
+ }
770
+ }
771
+ }));
772
+ const ActionsPage = () => {
773
+ const api = useApi(scaffolderApiRef);
774
+ const classes = useStyles$c();
775
+ const { loading, value, error } = useAsync(async () => {
776
+ return api.listActions();
777
+ });
778
+ if (loading) {
779
+ return /* @__PURE__ */ React.createElement(Progress, null);
780
+ }
781
+ if (error) {
782
+ return /* @__PURE__ */ React.createElement(ErrorPage, {
783
+ statusMessage: "Failed to load installed actions",
784
+ status: "500"
785
+ });
786
+ }
787
+ const formatRows = (input) => {
788
+ const properties = input.properties;
789
+ if (!properties) {
790
+ return void 0;
791
+ }
792
+ return Object.entries(properties).map((entry) => {
793
+ var _a;
794
+ const [key] = entry;
795
+ const props = entry[1];
796
+ const codeClassname = classNames(classes.code, {
797
+ [classes.codeRequired]: (_a = input.required) == null ? void 0 : _a.includes(key)
798
+ });
799
+ return /* @__PURE__ */ React.createElement(TableRow, {
800
+ key
801
+ }, /* @__PURE__ */ React.createElement(TableCell, null, /* @__PURE__ */ React.createElement("div", {
802
+ className: codeClassname
803
+ }, key)), /* @__PURE__ */ React.createElement(TableCell, null, props.title), /* @__PURE__ */ React.createElement(TableCell, null, props.description), /* @__PURE__ */ React.createElement(TableCell, null, /* @__PURE__ */ React.createElement("span", {
804
+ className: classes.code
805
+ }, props.type)));
806
+ });
807
+ };
808
+ const renderTable = (input) => {
809
+ if (!input.properties) {
810
+ return void 0;
811
+ }
812
+ return /* @__PURE__ */ React.createElement(TableContainer, {
813
+ component: Paper
814
+ }, /* @__PURE__ */ React.createElement(Table, {
815
+ size: "small"
816
+ }, /* @__PURE__ */ React.createElement(TableHead, null, /* @__PURE__ */ React.createElement(TableRow, null, /* @__PURE__ */ React.createElement(TableCell, null, "Name"), /* @__PURE__ */ React.createElement(TableCell, null, "Title"), /* @__PURE__ */ React.createElement(TableCell, null, "Description"), /* @__PURE__ */ React.createElement(TableCell, null, "Type"))), /* @__PURE__ */ React.createElement(TableBody, null, formatRows(input))));
817
+ };
818
+ const renderTables = (name, input) => {
819
+ if (!input) {
820
+ return void 0;
821
+ }
822
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Typography, {
823
+ variant: "h6"
824
+ }, name), input.map((i, index) => /* @__PURE__ */ React.createElement("div", {
825
+ key: index
826
+ }, renderTable(i))));
827
+ };
828
+ const items = value == null ? void 0 : value.map((action) => {
829
+ var _a, _b, _c, _d;
830
+ if (action.id.startsWith("legacy:")) {
831
+ return void 0;
832
+ }
833
+ const oneOf = renderTables("oneOf", (_b = (_a = action.schema) == null ? void 0 : _a.input) == null ? void 0 : _b.oneOf);
834
+ return /* @__PURE__ */ React.createElement(Box, {
835
+ pb: 4,
836
+ key: action.id
837
+ }, /* @__PURE__ */ React.createElement(Typography, {
838
+ variant: "h4",
839
+ className: classes.code
840
+ }, action.id), /* @__PURE__ */ React.createElement(Typography, null, action.description), ((_c = action.schema) == null ? void 0 : _c.input) && /* @__PURE__ */ React.createElement(Box, {
841
+ pb: 2
842
+ }, /* @__PURE__ */ React.createElement(Typography, {
843
+ variant: "h5"
844
+ }, "Input"), renderTable(action.schema.input), oneOf), ((_d = action.schema) == null ? void 0 : _d.output) && /* @__PURE__ */ React.createElement(Box, {
845
+ pb: 2
846
+ }, /* @__PURE__ */ React.createElement(Typography, {
847
+ variant: "h5"
848
+ }, "Output"), renderTable(action.schema.output)));
849
+ });
850
+ return /* @__PURE__ */ React.createElement(Page, {
851
+ themeId: "home"
852
+ }, /* @__PURE__ */ React.createElement(Header, {
853
+ pageTitleOverride: "Create a New Component",
854
+ title: "Installed actions",
855
+ subtitle: "This is the collection of all installed actions"
856
+ }), /* @__PURE__ */ React.createElement(Content, null, items));
857
+ };
858
+
859
+ const showDirectoryPicker = window.showDirectoryPicker;
860
+ class WebFileAccess {
861
+ constructor(path, handle) {
862
+ this.path = path;
863
+ this.handle = handle;
864
+ }
865
+ file() {
866
+ return this.handle.getFile();
867
+ }
868
+ async save(data) {
869
+ const writable = await this.handle.createWritable();
870
+ await writable.write(data);
871
+ await writable.close();
872
+ }
873
+ }
874
+ class WebDirectoryAccess {
875
+ constructor(handle) {
876
+ this.handle = handle;
877
+ }
878
+ async listFiles() {
879
+ const content = [];
880
+ for await (const entry of this.listDirectoryContents(this.handle)) {
881
+ content.push(entry);
882
+ }
883
+ return content;
884
+ }
885
+ async *listDirectoryContents(dirHandle, basePath = []) {
886
+ for await (const handle of dirHandle.values()) {
887
+ if (handle.kind === "file") {
888
+ yield new WebFileAccess([...basePath, handle.name].join("/"), handle);
889
+ } else if (handle.kind === "directory") {
890
+ yield* this.listDirectoryContents(handle, [...basePath, handle.name]);
891
+ }
892
+ }
893
+ }
894
+ }
895
+ class WebFileSystemAccess {
896
+ static isSupported() {
897
+ return Boolean(showDirectoryPicker);
898
+ }
899
+ static async requestDirectoryAccess() {
900
+ if (!showDirectoryPicker) {
901
+ throw new Error("File system access is not supported");
902
+ }
903
+ const handle = await showDirectoryPicker();
904
+ return new WebDirectoryAccess(handle);
905
+ }
906
+ constructor() {
907
+ }
908
+ }
909
+
910
+ const useStyles$b = makeStyles$1((theme) => ({
911
+ introText: {
912
+ textAlign: "center",
913
+ marginTop: theme.spacing(2)
914
+ },
915
+ card: {
916
+ position: "relative",
917
+ maxWidth: 340,
918
+ marginTop: theme.spacing(4),
919
+ margin: theme.spacing(0, 2)
920
+ },
921
+ infoIcon: {
922
+ position: "absolute",
923
+ top: theme.spacing(1),
924
+ right: theme.spacing(1)
925
+ }
926
+ }));
927
+ function TemplateEditorIntro(props) {
928
+ const classes = useStyles$b();
929
+ const supportsLoad = WebFileSystemAccess.isSupported();
930
+ const cardLoadLocal = /* @__PURE__ */ React.createElement(Card$1, {
931
+ className: classes.card,
932
+ elevation: 4
933
+ }, /* @__PURE__ */ React.createElement(CardActionArea, {
934
+ disabled: !supportsLoad,
935
+ onClick: () => {
936
+ var _a;
937
+ return (_a = props.onSelect) == null ? void 0 : _a.call(props, "local");
938
+ }
939
+ }, /* @__PURE__ */ React.createElement(CardContent$1, null, /* @__PURE__ */ React.createElement(Typography$1, {
940
+ variant: "h5",
941
+ gutterBottom: true,
942
+ color: supportsLoad ? void 0 : "textSecondary",
943
+ style: { display: "flex", flexFlow: "row nowrap" }
944
+ }, "Load Template Directory"), /* @__PURE__ */ React.createElement(Typography$1, {
945
+ variant: "body1",
946
+ color: supportsLoad ? void 0 : "textSecondary"
947
+ }, "Load a local template directory, allowing you to both edit and try executing your own template."))), !supportsLoad && /* @__PURE__ */ React.createElement("div", {
948
+ className: classes.infoIcon
949
+ }, /* @__PURE__ */ React.createElement(Tooltip$1, {
950
+ placement: "top",
951
+ title: "Only supported in some Chromium-based browsers"
952
+ }, /* @__PURE__ */ React.createElement(InfoOutlinedIcon, null))));
953
+ const cardFormEditor = /* @__PURE__ */ React.createElement(Card$1, {
954
+ className: classes.card,
955
+ elevation: 4
956
+ }, /* @__PURE__ */ React.createElement(CardActionArea, {
957
+ onClick: () => {
958
+ var _a;
959
+ return (_a = props.onSelect) == null ? void 0 : _a.call(props, "form");
960
+ }
961
+ }, /* @__PURE__ */ React.createElement(CardContent$1, null, /* @__PURE__ */ React.createElement(Typography$1, {
962
+ variant: "h5",
963
+ gutterBottom: true
964
+ }, "Edit Template Form"), /* @__PURE__ */ React.createElement(Typography$1, {
965
+ variant: "body1"
966
+ }, "Preview and edit a template form, either using a sample template or by loading a template from the catalog."))));
967
+ return /* @__PURE__ */ React.createElement("div", {
968
+ style: props.style
969
+ }, /* @__PURE__ */ React.createElement(Typography$1, {
970
+ variant: "h6",
971
+ className: classes.introText
972
+ }, "Get started by choosing one of the options below"), /* @__PURE__ */ React.createElement("div", {
973
+ style: {
974
+ display: "flex",
975
+ flexFlow: "row wrap",
976
+ alignItems: "flex-start",
977
+ justifyContent: "center",
978
+ alignContent: "flex-start"
979
+ }
980
+ }, supportsLoad && cardLoadLocal, cardFormEditor, !supportsLoad && cardLoadLocal));
981
+ }
982
+
983
+ var __accessCheck = (obj, member, msg) => {
984
+ if (!member.has(obj))
985
+ throw TypeError("Cannot " + msg);
986
+ };
987
+ var __privateGet = (obj, member, getter) => {
988
+ __accessCheck(obj, member, "read from private field");
989
+ return getter ? getter.call(obj) : member.get(obj);
990
+ };
991
+ var __privateAdd = (obj, member, value) => {
992
+ if (member.has(obj))
993
+ throw TypeError("Cannot add the same private member more than once");
994
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
995
+ };
996
+ var __privateSet = (obj, member, value, setter) => {
997
+ __accessCheck(obj, member, "write to private field");
998
+ setter ? setter.call(obj, value) : member.set(obj, value);
999
+ return value;
1000
+ };
1001
+ var _access, _signalUpdate, _content, _savedContent, _access2, _listeners, _files, _selectedFile, _signalUpdate2;
1002
+ const MAX_SIZE = 1024 * 1024;
1003
+ const MAX_SIZE_MESSAGE = "This file is too large to be displayed";
1004
+ class DirectoryEditorFileManager {
1005
+ constructor(access, signalUpdate) {
1006
+ __privateAdd(this, _access, void 0);
1007
+ __privateAdd(this, _signalUpdate, void 0);
1008
+ __privateAdd(this, _content, void 0);
1009
+ __privateAdd(this, _savedContent, void 0);
1010
+ __privateSet(this, _access, access);
1011
+ __privateSet(this, _signalUpdate, signalUpdate);
1012
+ }
1013
+ get path() {
1014
+ return __privateGet(this, _access).path;
1015
+ }
1016
+ get content() {
1017
+ var _a;
1018
+ return (_a = __privateGet(this, _content)) != null ? _a : MAX_SIZE_MESSAGE;
1019
+ }
1020
+ updateContent(content) {
1021
+ if (__privateGet(this, _content) === void 0) {
1022
+ return;
1023
+ }
1024
+ __privateSet(this, _content, content);
1025
+ __privateGet(this, _signalUpdate).call(this);
1026
+ }
1027
+ get dirty() {
1028
+ return __privateGet(this, _content) !== __privateGet(this, _savedContent);
1029
+ }
1030
+ async save() {
1031
+ if (__privateGet(this, _content) !== void 0) {
1032
+ await __privateGet(this, _access).save(__privateGet(this, _content));
1033
+ __privateSet(this, _savedContent, __privateGet(this, _content));
1034
+ __privateGet(this, _signalUpdate).call(this);
1035
+ }
1036
+ }
1037
+ async reload() {
1038
+ const file = await __privateGet(this, _access).file();
1039
+ if (file.size > MAX_SIZE) {
1040
+ if (__privateGet(this, _content) !== void 0) {
1041
+ __privateSet(this, _content, void 0);
1042
+ __privateSet(this, _savedContent, void 0);
1043
+ __privateGet(this, _signalUpdate).call(this);
1044
+ }
1045
+ return;
1046
+ }
1047
+ const content = await file.text();
1048
+ if (__privateGet(this, _content) !== content) {
1049
+ __privateSet(this, _content, content);
1050
+ __privateSet(this, _savedContent, content);
1051
+ __privateGet(this, _signalUpdate).call(this);
1052
+ }
1053
+ }
1054
+ }
1055
+ _access = new WeakMap();
1056
+ _signalUpdate = new WeakMap();
1057
+ _content = new WeakMap();
1058
+ _savedContent = new WeakMap();
1059
+ class DirectoryEditorManager {
1060
+ constructor(access) {
1061
+ __privateAdd(this, _access2, void 0);
1062
+ __privateAdd(this, _listeners, /* @__PURE__ */ new Set());
1063
+ __privateAdd(this, _files, []);
1064
+ __privateAdd(this, _selectedFile, void 0);
1065
+ this.setSelectedFile = (path) => {
1066
+ const prev = __privateGet(this, _selectedFile);
1067
+ const next = __privateGet(this, _files).find((file) => file.path === path);
1068
+ if (prev !== next) {
1069
+ __privateSet(this, _selectedFile, next);
1070
+ __privateGet(this, _signalUpdate2).call(this);
1071
+ }
1072
+ };
1073
+ __privateAdd(this, _signalUpdate2, () => {
1074
+ __privateGet(this, _listeners).forEach((listener) => listener());
1075
+ });
1076
+ __privateSet(this, _access2, access);
1077
+ }
1078
+ get files() {
1079
+ return __privateGet(this, _files);
1080
+ }
1081
+ get selectedFile() {
1082
+ return __privateGet(this, _selectedFile);
1083
+ }
1084
+ get dirty() {
1085
+ return __privateGet(this, _files).some((file) => file.dirty);
1086
+ }
1087
+ async save() {
1088
+ await Promise.all(__privateGet(this, _files).map((file) => file.save()));
1089
+ }
1090
+ async reload() {
1091
+ var _a;
1092
+ const selectedPath = (_a = __privateGet(this, _selectedFile)) == null ? void 0 : _a.path;
1093
+ const files = await __privateGet(this, _access2).listFiles();
1094
+ const fileManagers = await Promise.all(files.map(async (file) => {
1095
+ const manager = new DirectoryEditorFileManager(file, __privateGet(this, _signalUpdate2));
1096
+ await manager.reload();
1097
+ return manager;
1098
+ }));
1099
+ __privateGet(this, _files).length = 0;
1100
+ __privateGet(this, _files).push(...fileManagers);
1101
+ this.setSelectedFile(selectedPath);
1102
+ __privateGet(this, _signalUpdate2).call(this);
1103
+ }
1104
+ subscribe(listener) {
1105
+ __privateGet(this, _listeners).add(listener);
1106
+ return () => {
1107
+ __privateGet(this, _listeners).delete(listener);
1108
+ };
1109
+ }
1110
+ }
1111
+ _access2 = new WeakMap();
1112
+ _listeners = new WeakMap();
1113
+ _files = new WeakMap();
1114
+ _selectedFile = new WeakMap();
1115
+ _signalUpdate2 = new WeakMap();
1116
+ const DirectoryEditorContext = createContext(void 0);
1117
+ function useDirectoryEditor() {
1118
+ const value = useContext(DirectoryEditorContext);
1119
+ const rerender = useRerender();
1120
+ useEffect(() => value == null ? void 0 : value.subscribe(rerender), [value, rerender]);
1121
+ if (!value) {
1122
+ throw new Error("must be used within a DirectoryEditorProvider");
1123
+ }
1124
+ return value;
1125
+ }
1126
+ function DirectoryEditorProvider(props) {
1127
+ const { directory } = props;
1128
+ const [{ result, error }, { execute }] = useAsync$1(async (dir) => {
1129
+ const manager = new DirectoryEditorManager(dir);
1130
+ await manager.reload();
1131
+ const firstYaml = manager.files.find((file) => file.path.match(/\.ya?ml$/));
1132
+ if (firstYaml) {
1133
+ manager.setSelectedFile(firstYaml.path);
1134
+ }
1135
+ return manager;
1136
+ });
1137
+ useEffect(() => {
1138
+ execute(directory);
1139
+ }, [execute, directory]);
1140
+ if (error) {
1141
+ return /* @__PURE__ */ React.createElement(ErrorPanel, {
1142
+ error
1143
+ });
1144
+ } else if (!result) {
1145
+ return /* @__PURE__ */ React.createElement(Progress, null);
1146
+ }
1147
+ return /* @__PURE__ */ React.createElement(DirectoryEditorContext.Provider, {
1148
+ value: result
1149
+ }, props.children);
1150
+ }
1151
+
1152
+ const MAX_CONTENT_SIZE = 256 * 1024;
1153
+ const CHUNK_SIZE = 32768;
1154
+ const DryRunContext = createContext(void 0);
1155
+ function base64EncodeContent(content) {
1156
+ if (content.length > MAX_CONTENT_SIZE) {
1157
+ return btoa("<file too large>");
1158
+ }
1159
+ try {
1160
+ return btoa(content);
1161
+ } catch {
1162
+ const decoder = new TextEncoder();
1163
+ const buffer = decoder.encode(content);
1164
+ const chunks = new Array();
1165
+ for (let offset = 0; offset < buffer.length; offset += CHUNK_SIZE) {
1166
+ chunks.push(String.fromCharCode(...buffer.slice(offset, offset + CHUNK_SIZE)));
1167
+ }
1168
+ return btoa(chunks.join(""));
1169
+ }
1170
+ }
1171
+ function DryRunProvider(props) {
1172
+ const scaffolderApi = useApi(scaffolderApiRef);
1173
+ const [state, setState] = useState({
1174
+ results: [],
1175
+ selectedResult: void 0
1176
+ });
1177
+ const idRef = useRef(1);
1178
+ const selectResult = useCallback((id) => {
1179
+ setState((prevState) => {
1180
+ const result = prevState.results.find((r) => r.id === id);
1181
+ if (result === prevState.selectedResult) {
1182
+ return prevState;
1183
+ }
1184
+ return {
1185
+ results: prevState.results,
1186
+ selectedResult: result
1187
+ };
1188
+ });
1189
+ }, []);
1190
+ const deleteResult = useCallback((id) => {
1191
+ setState((prevState) => {
1192
+ var _a;
1193
+ const index = prevState.results.findIndex((r) => r.id === id);
1194
+ if (index === -1) {
1195
+ return prevState;
1196
+ }
1197
+ const newResults = prevState.results.slice();
1198
+ const [deleted] = newResults.splice(index, 1);
1199
+ return {
1200
+ results: newResults,
1201
+ selectedResult: ((_a = prevState.selectedResult) == null ? void 0 : _a.id) === deleted.id ? newResults[0] : prevState.selectedResult
1202
+ };
1203
+ });
1204
+ }, []);
1205
+ const execute = useCallback(async (options) => {
1206
+ if (!scaffolderApi.dryRun) {
1207
+ throw new Error("Scaffolder API does not support dry-run");
1208
+ }
1209
+ const parsed = yaml.parse(options.templateContent);
1210
+ const response = await scaffolderApi.dryRun({
1211
+ template: parsed,
1212
+ values: options.values,
1213
+ secrets: {},
1214
+ directoryContents: options.files.map((file) => ({
1215
+ path: file.path,
1216
+ base64Content: base64EncodeContent(file.content)
1217
+ }))
1218
+ });
1219
+ const result = {
1220
+ ...response,
1221
+ id: idRef.current++
1222
+ };
1223
+ setState((prevState) => {
1224
+ var _a;
1225
+ return {
1226
+ results: [...prevState.results, result],
1227
+ selectedResult: (_a = prevState.selectedResult) != null ? _a : result
1228
+ };
1229
+ });
1230
+ }, [scaffolderApi]);
1231
+ const dryRun = useMemo(() => ({
1232
+ ...state,
1233
+ selectResult,
1234
+ deleteResult,
1235
+ execute
1236
+ }), [state, selectResult, deleteResult, execute]);
1237
+ return /* @__PURE__ */ React.createElement(DryRunContext.Provider, {
1238
+ value: dryRun
1239
+ }, props.children);
1240
+ }
1241
+ function useDryRun() {
1242
+ const value = useContext(DryRunContext);
1243
+ if (!value) {
1244
+ throw new Error("must be used within a DryRunProvider");
1245
+ }
1246
+ return value;
1247
+ }
1248
+
1249
+ const useStyles$a = makeStyles$1((theme) => ({
1250
+ root: {
1251
+ overflowY: "auto",
1252
+ background: theme.palette.background.default
1253
+ },
1254
+ iconSuccess: {
1255
+ minWidth: 0,
1256
+ marginRight: theme.spacing(1),
1257
+ color: theme.palette.status.ok
1258
+ },
1259
+ iconFailure: {
1260
+ minWidth: 0,
1261
+ marginRight: theme.spacing(1),
1262
+ color: theme.palette.status.error
1263
+ }
1264
+ }));
1265
+ function DryRunResultsList() {
1266
+ const classes = useStyles$a();
1267
+ const dryRun = useDryRun();
1268
+ return /* @__PURE__ */ React.createElement(List$1, {
1269
+ className: classes.root,
1270
+ dense: true
1271
+ }, dryRun.results.map((result) => {
1272
+ var _a;
1273
+ const failed = result.log.some((l) => l.body.status === "failed");
1274
+ return /* @__PURE__ */ React.createElement(ListItem, {
1275
+ button: true,
1276
+ key: result.id,
1277
+ selected: ((_a = dryRun.selectedResult) == null ? void 0 : _a.id) === result.id,
1278
+ onClick: () => dryRun.selectResult(result.id)
1279
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, {
1280
+ className: failed ? classes.iconFailure : classes.iconSuccess
1281
+ }, failed ? /* @__PURE__ */ React.createElement(Cancel, null) : /* @__PURE__ */ React.createElement(Check, null)), /* @__PURE__ */ React.createElement(ListItemText, {
1282
+ primary: `Result ${result.id}`
1283
+ }), /* @__PURE__ */ React.createElement(ListItemSecondaryAction, null, /* @__PURE__ */ React.createElement(IconButton$1, {
1284
+ edge: "end",
1285
+ "aria-label": "delete",
1286
+ onClick: () => dryRun.deleteResult(result.id)
1287
+ }, /* @__PURE__ */ React.createElement(DeleteIcon, null))));
1288
+ }));
1289
+ }
1290
+
1291
+ const useStyles$9 = makeStyles$1({
1292
+ root: {
1293
+ whiteSpace: "nowrap",
1294
+ overflowY: "auto"
1295
+ }
1296
+ });
1297
+ function parseFileEntires(paths) {
1298
+ const root = {
1299
+ type: "directory",
1300
+ name: "",
1301
+ path: "",
1302
+ children: []
1303
+ };
1304
+ for (const path of paths.slice().sort()) {
1305
+ const parts = path.split("/");
1306
+ let current = root;
1307
+ for (let i = 0; i < parts.length; i++) {
1308
+ const part = parts[i];
1309
+ if (part === "") {
1310
+ throw new Error(`Invalid path part: ''`);
1311
+ }
1312
+ const entryPath = parts.slice(0, i + 1).join("/");
1313
+ const existing = current.children.find((child) => child.name === part);
1314
+ if ((existing == null ? void 0 : existing.type) === "file") {
1315
+ throw new Error(`Duplicate filename at '${entryPath}'`);
1316
+ } else if (existing) {
1317
+ current = existing;
1318
+ } else {
1319
+ if (i < parts.length - 1) {
1320
+ const newEntry = {
1321
+ type: "directory",
1322
+ name: part,
1323
+ path: entryPath,
1324
+ children: []
1325
+ };
1326
+ const firstFileIndex = current.children.findIndex((child) => child.type === "file");
1327
+ current.children.splice(firstFileIndex, 0, newEntry);
1328
+ current = newEntry;
1329
+ } else {
1330
+ current.children.push({
1331
+ type: "file",
1332
+ name: part,
1333
+ path: entryPath
1334
+ });
1335
+ }
1336
+ }
1337
+ }
1338
+ }
1339
+ return root.children;
1340
+ }
1341
+ function FileTreeItem({ entry }) {
1342
+ if (entry.type === "file") {
1343
+ return /* @__PURE__ */ React.createElement(TreeItem, {
1344
+ nodeId: entry.path,
1345
+ label: entry.name
1346
+ });
1347
+ }
1348
+ return /* @__PURE__ */ React.createElement(TreeItem, {
1349
+ nodeId: entry.path,
1350
+ label: entry.name
1351
+ }, entry.children.map((child) => /* @__PURE__ */ React.createElement(FileTreeItem, {
1352
+ key: child.path,
1353
+ entry: child
1354
+ })));
1355
+ }
1356
+ function FileBrowser(props) {
1357
+ const classes = useStyles$9();
1358
+ const fileTree = useMemo(() => parseFileEntires(props.filePaths), [props.filePaths]);
1359
+ return /* @__PURE__ */ React.createElement(TreeView, {
1360
+ selected: props.selected,
1361
+ className: classes.root,
1362
+ defaultCollapseIcon: /* @__PURE__ */ React.createElement(ExpandMoreIcon, null),
1363
+ defaultExpandIcon: /* @__PURE__ */ React.createElement(ChevronRightIcon, null),
1364
+ onNodeSelect: (_e, nodeId) => {
1365
+ if (props.onSelect && props.filePaths.includes(nodeId)) {
1366
+ props.onSelect(nodeId);
1367
+ }
1368
+ }
1369
+ }, fileTree.map((entry) => /* @__PURE__ */ React.createElement(FileTreeItem, {
1370
+ key: entry.path,
1371
+ entry
1372
+ })));
1373
+ }
1374
+
1375
+ const useStyles$8 = makeStyles$1((theme) => ({
1376
+ root: {
1377
+ display: "grid",
1378
+ gridTemplateColumns: "280px auto 3fr",
1379
+ gridTemplateRows: "1fr"
1380
+ },
1381
+ child: {
1382
+ overflowY: "auto",
1383
+ height: "100%",
1384
+ minHeight: 0
1385
+ },
1386
+ firstChild: {
1387
+ background: theme.palette.background.paper
1388
+ }
1389
+ }));
1390
+ function DryRunResultsSplitView(props) {
1391
+ const classes = useStyles$8();
1392
+ const childArray = Children.toArray(props.children);
1393
+ if (childArray.length !== 2) {
1394
+ throw new Error("must have exactly 2 children");
1395
+ }
1396
+ return /* @__PURE__ */ React.createElement("div", {
1397
+ className: classes.root
1398
+ }, /* @__PURE__ */ React.createElement("div", {
1399
+ className: classNames(classes.child, classes.firstChild)
1400
+ }, childArray[0]), /* @__PURE__ */ React.createElement(Divider, {
1401
+ orientation: "horizontal"
1402
+ }), /* @__PURE__ */ React.createElement("div", {
1403
+ className: classes.child
1404
+ }, childArray[1]));
1405
+ }
1406
+
1407
+ const useStyles$7 = makeStyles$1({
1408
+ root: {
1409
+ display: "flex",
1410
+ flexFlow: "column nowrap"
1411
+ },
1412
+ contentWrapper: {
1413
+ flex: 1,
1414
+ position: "relative"
1415
+ },
1416
+ content: {
1417
+ position: "absolute",
1418
+ top: 0,
1419
+ left: 0,
1420
+ right: 0,
1421
+ bottom: 0,
1422
+ display: "flex",
1423
+ "& > *": {
1424
+ flex: 1
1425
+ }
1426
+ },
1427
+ codeMirror: {
1428
+ height: "100%",
1429
+ overflowY: "auto"
1430
+ }
1431
+ });
1432
+ function FilesContent() {
1433
+ const classes = useStyles$7();
1434
+ const { selectedResult } = useDryRun();
1435
+ const [selectedPath, setSelectedPath] = useState("");
1436
+ const selectedFile = selectedResult == null ? void 0 : selectedResult.directoryContents.find((f) => f.path === selectedPath);
1437
+ useEffect(() => {
1438
+ if (selectedResult) {
1439
+ const [firstFile] = selectedResult.directoryContents;
1440
+ if (firstFile) {
1441
+ setSelectedPath(firstFile.path);
1442
+ } else {
1443
+ setSelectedPath("");
1444
+ }
1445
+ }
1446
+ return void 0;
1447
+ }, [selectedResult]);
1448
+ if (!selectedResult) {
1449
+ return null;
1450
+ }
1451
+ return /* @__PURE__ */ React.createElement(DryRunResultsSplitView, null, /* @__PURE__ */ React.createElement(FileBrowser, {
1452
+ selected: selectedPath,
1453
+ onSelect: setSelectedPath,
1454
+ filePaths: selectedResult.directoryContents.map((file) => file.path)
1455
+ }), /* @__PURE__ */ React.createElement(CodeMirror, {
1456
+ className: classes.codeMirror,
1457
+ theme: "dark",
1458
+ height: "100%",
1459
+ extensions: [StreamLanguage.define(yaml$1)],
1460
+ readOnly: true,
1461
+ value: (selectedFile == null ? void 0 : selectedFile.base64Content) ? atob(selectedFile.base64Content) : ""
1462
+ }));
1463
+ }
1464
+ function LogContent() {
1465
+ var _a, _b;
1466
+ const { selectedResult } = useDryRun();
1467
+ const [currentStepId, setUserSelectedStepId] = useState();
1468
+ const steps = useMemo(() => {
1469
+ var _a2;
1470
+ if (!selectedResult) {
1471
+ return [];
1472
+ }
1473
+ return (_a2 = selectedResult.steps.map((step) => {
1474
+ var _a3, _b2;
1475
+ const stepLog = selectedResult.log.filter((l) => l.body.stepId === step.id);
1476
+ return {
1477
+ id: step.id,
1478
+ name: step.name,
1479
+ logString: stepLog.map((l) => l.body.message).join("\n"),
1480
+ status: (_b2 = (_a3 = stepLog[stepLog.length - 1]) == null ? void 0 : _a3.body.status) != null ? _b2 : "completed"
1481
+ };
1482
+ })) != null ? _a2 : [];
1483
+ }, [selectedResult]);
1484
+ if (!selectedResult) {
1485
+ return null;
1486
+ }
1487
+ const selectedStep = (_a = steps.find((s) => s.id === currentStepId)) != null ? _a : steps[0];
1488
+ return /* @__PURE__ */ React.createElement(DryRunResultsSplitView, null, /* @__PURE__ */ React.createElement(TaskStatusStepper, {
1489
+ steps,
1490
+ currentStepId: selectedStep.id,
1491
+ onUserStepChange: setUserSelectedStepId
1492
+ }), /* @__PURE__ */ React.createElement(LogViewer, {
1493
+ text: (_b = selectedStep == null ? void 0 : selectedStep.logString) != null ? _b : ""
1494
+ }));
1495
+ }
1496
+ function OutputContent() {
1497
+ var _a, _b;
1498
+ const classes = useStyles$7();
1499
+ const { selectedResult } = useDryRun();
1500
+ if (!selectedResult) {
1501
+ return null;
1502
+ }
1503
+ return /* @__PURE__ */ React.createElement(DryRunResultsSplitView, null, /* @__PURE__ */ React.createElement(Box$1, {
1504
+ pt: 2
1505
+ }, ((_b = (_a = selectedResult.output) == null ? void 0 : _a.links) == null ? void 0 : _b.length) && /* @__PURE__ */ React.createElement(TaskPageLinks, {
1506
+ output: selectedResult.output
1507
+ })), /* @__PURE__ */ React.createElement(CodeMirror, {
1508
+ className: classes.codeMirror,
1509
+ theme: "dark",
1510
+ height: "100%",
1511
+ extensions: [StreamLanguage.define(yaml$1)],
1512
+ readOnly: true,
1513
+ value: JSON.stringify(selectedResult.output, null, 2)
1514
+ }));
1515
+ }
1516
+ function DryRunResultsView() {
1517
+ const classes = useStyles$7();
1518
+ const [selectedTab, setSelectedTab] = useState("files");
1519
+ return /* @__PURE__ */ React.createElement("div", {
1520
+ className: classes.root
1521
+ }, /* @__PURE__ */ React.createElement(Tabs, {
1522
+ value: selectedTab,
1523
+ onChange: (_, v) => setSelectedTab(v)
1524
+ }, /* @__PURE__ */ React.createElement(Tab, {
1525
+ value: "files",
1526
+ label: "Files"
1527
+ }), /* @__PURE__ */ React.createElement(Tab, {
1528
+ value: "log",
1529
+ label: "Log"
1530
+ }), /* @__PURE__ */ React.createElement(Tab, {
1531
+ value: "output",
1532
+ label: "Output"
1533
+ })), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement("div", {
1534
+ className: classes.contentWrapper
1535
+ }, /* @__PURE__ */ React.createElement("div", {
1536
+ className: classes.content
1537
+ }, selectedTab === "files" && /* @__PURE__ */ React.createElement(FilesContent, null), selectedTab === "log" && /* @__PURE__ */ React.createElement(LogContent, null), selectedTab === "output" && /* @__PURE__ */ React.createElement(OutputContent, null))));
1538
+ }
1539
+
1540
+ const useStyles$6 = makeStyles$1((theme) => ({
1541
+ header: {
1542
+ height: 48,
1543
+ minHeight: 0,
1544
+ "&.Mui-expanded": {
1545
+ height: 48,
1546
+ minHeight: 0
1547
+ }
1548
+ },
1549
+ content: {
1550
+ display: "grid",
1551
+ background: theme.palette.background.default,
1552
+ gridTemplateColumns: "180px auto 1fr",
1553
+ gridTemplateRows: "1fr",
1554
+ padding: 0,
1555
+ height: 400
1556
+ }
1557
+ }));
1558
+ function DryRunResults() {
1559
+ const classes = useStyles$6();
1560
+ const dryRun = useDryRun();
1561
+ const [expanded, setExpanded] = useState(false);
1562
+ const [hidden, setHidden] = useState(true);
1563
+ const resultsLength = dryRun.results.length;
1564
+ const prevResultsLength = usePrevious(resultsLength);
1565
+ useEffect(() => {
1566
+ if (prevResultsLength === 0 && resultsLength === 1) {
1567
+ setHidden(false);
1568
+ setExpanded(true);
1569
+ } else if (prevResultsLength === 1 && resultsLength === 0) {
1570
+ setExpanded(false);
1571
+ }
1572
+ }, [prevResultsLength, resultsLength]);
1573
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Accordion, {
1574
+ variant: "outlined",
1575
+ expanded,
1576
+ hidden: resultsLength === 0 && hidden,
1577
+ onChange: (_, exp) => setExpanded(exp),
1578
+ onTransitionEnd: () => resultsLength === 0 && setHidden(true)
1579
+ }, /* @__PURE__ */ React.createElement(AccordionSummary, {
1580
+ className: classes.header,
1581
+ expandIcon: /* @__PURE__ */ React.createElement(ExpandMoreIcon$1, null)
1582
+ }, /* @__PURE__ */ React.createElement(Typography$1, null, "Dry-run results")), /* @__PURE__ */ React.createElement(Divider, {
1583
+ orientation: "horizontal"
1584
+ }), /* @__PURE__ */ React.createElement(AccordionDetails, {
1585
+ className: classes.content
1586
+ }, /* @__PURE__ */ React.createElement(DryRunResultsList, null), /* @__PURE__ */ React.createElement(Divider, {
1587
+ orientation: "horizontal"
1588
+ }), /* @__PURE__ */ React.createElement(DryRunResultsView, null))));
1589
+ }
1590
+
1591
+ const useStyles$5 = makeStyles((theme) => ({
1592
+ button: {
1593
+ padding: theme.spacing(1)
1594
+ },
1595
+ buttons: {
1596
+ display: "flex",
1597
+ flexFlow: "row nowrap",
1598
+ alignItems: "center",
1599
+ justifyContent: "flex-start"
1600
+ },
1601
+ buttonsGap: {
1602
+ flex: "1 1 auto"
1603
+ },
1604
+ buttonsDivider: {
1605
+ marginBottom: theme.spacing(1)
1606
+ }
1607
+ }));
1608
+ function TemplateEditorBrowser(props) {
1609
+ var _a, _b;
1610
+ const classes = useStyles$5();
1611
+ const directoryEditor = useDirectoryEditor();
1612
+ const changedFiles = directoryEditor.files.filter((file) => file.dirty);
1613
+ const handleClose = () => {
1614
+ if (!props.onClose) {
1615
+ return;
1616
+ }
1617
+ if (changedFiles.length > 0) {
1618
+ const accepted = window.confirm("Are you sure? Unsaved changes will be lost");
1619
+ if (!accepted) {
1620
+ return;
1621
+ }
1622
+ }
1623
+ props.onClose();
1624
+ };
1625
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
1626
+ className: classes.buttons
1627
+ }, /* @__PURE__ */ React.createElement(Tooltip, {
1628
+ title: "Save all files"
1629
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1630
+ className: classes.button,
1631
+ disabled: directoryEditor.files.every((file) => !file.dirty),
1632
+ onClick: () => directoryEditor.save()
1633
+ }, /* @__PURE__ */ React.createElement(SaveIcon, null))), /* @__PURE__ */ React.createElement(Tooltip, {
1634
+ title: "Reload directory"
1635
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1636
+ className: classes.button,
1637
+ onClick: () => directoryEditor.reload()
1638
+ }, /* @__PURE__ */ React.createElement(RefreshIcon, null))), /* @__PURE__ */ React.createElement("div", {
1639
+ className: classes.buttonsGap
1640
+ }), /* @__PURE__ */ React.createElement(Tooltip, {
1641
+ title: "Close directory"
1642
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1643
+ className: classes.button,
1644
+ onClick: handleClose
1645
+ }, /* @__PURE__ */ React.createElement(CloseIcon, null)))), /* @__PURE__ */ React.createElement(Divider$1, {
1646
+ className: classes.buttonsDivider
1647
+ }), /* @__PURE__ */ React.createElement(FileBrowser, {
1648
+ selected: (_b = (_a = directoryEditor.selectedFile) == null ? void 0 : _a.path) != null ? _b : "",
1649
+ onSelect: directoryEditor.setSelectedFile,
1650
+ filePaths: directoryEditor.files.map((file) => file.path)
1651
+ }));
1652
+ }
1653
+
1654
+ const useStyles$4 = makeStyles$1({
1655
+ containerWrapper: {
1656
+ position: "relative",
1657
+ width: "100%",
1658
+ height: "100%"
1659
+ },
1660
+ container: {
1661
+ position: "absolute",
1662
+ top: 0,
1663
+ bottom: 0,
1664
+ left: 0,
1665
+ right: 0,
1666
+ overflow: "auto"
1667
+ }
1668
+ });
1669
+ class ErrorBoundary extends Component {
1670
+ constructor() {
1671
+ super(...arguments);
1672
+ this.state = {
1673
+ shouldRender: true
1674
+ };
1675
+ }
1676
+ componentDidUpdate(prevProps) {
1677
+ if (prevProps.invalidator !== this.props.invalidator) {
1678
+ this.setState({ shouldRender: true });
1679
+ }
1680
+ }
1681
+ componentDidCatch(error) {
1682
+ this.props.setErrorText(error.message);
1683
+ this.setState({ shouldRender: false });
1684
+ }
1685
+ render() {
1686
+ return this.state.shouldRender ? this.props.children : null;
1687
+ }
1688
+ }
1689
+ function isJsonObject(value) {
1690
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1691
+ }
1692
+ function TemplateEditorForm(props) {
1693
+ const {
1694
+ content,
1695
+ contentIsSpec,
1696
+ data,
1697
+ onUpdate,
1698
+ onDryRun,
1699
+ setErrorText,
1700
+ fieldExtensions = []
1701
+ } = props;
1702
+ const classes = useStyles$4();
1703
+ const apiHolder = useApiHolder();
1704
+ const [steps, setSteps] = useState();
1705
+ const fields = useMemo(() => {
1706
+ return Object.fromEntries(fieldExtensions.map(({ name, component }) => [name, component]));
1707
+ }, [fieldExtensions]);
1708
+ useDebounce(() => {
1709
+ try {
1710
+ if (!content) {
1711
+ setSteps(void 0);
1712
+ return;
1713
+ }
1714
+ const parsed = yaml.parse(content);
1715
+ if (!isJsonObject(parsed)) {
1716
+ setSteps(void 0);
1717
+ return;
1718
+ }
1719
+ let rootObj = parsed;
1720
+ if (!contentIsSpec) {
1721
+ const isTemplate = String(parsed.kind).toLocaleLowerCase("en-US") === "template";
1722
+ if (!isTemplate) {
1723
+ setSteps(void 0);
1724
+ return;
1725
+ }
1726
+ rootObj = isJsonObject(parsed.spec) ? parsed.spec : {};
1727
+ }
1728
+ const { parameters } = rootObj;
1729
+ if (!Array.isArray(parameters)) {
1730
+ setErrorText("Template parameters must be an array");
1731
+ setSteps(void 0);
1732
+ return;
1733
+ }
1734
+ const fieldValidators = Object.fromEntries(fieldExtensions.map(({ name, validation }) => [name, validation]));
1735
+ setErrorText();
1736
+ setSteps(parameters.flatMap((param) => isJsonObject(param) ? [
1737
+ {
1738
+ title: String(param.title),
1739
+ schema: param,
1740
+ validate: createValidator(param, fieldValidators, {
1741
+ apiHolder
1742
+ })
1743
+ }
1744
+ ] : []));
1745
+ } catch (e) {
1746
+ setErrorText(e.message);
1747
+ }
1748
+ }, 250, [contentIsSpec, content, apiHolder]);
1749
+ if (!steps) {
1750
+ return null;
1751
+ }
1752
+ return /* @__PURE__ */ React.createElement("div", {
1753
+ className: classes.containerWrapper
1754
+ }, /* @__PURE__ */ React.createElement("div", {
1755
+ className: classes.container
1756
+ }, /* @__PURE__ */ React.createElement(ErrorBoundary, {
1757
+ invalidator: steps,
1758
+ setErrorText
1759
+ }, /* @__PURE__ */ React.createElement(MultistepJsonForm, {
1760
+ steps,
1761
+ fields,
1762
+ formData: data,
1763
+ onChange: (e) => onUpdate(e.formData),
1764
+ onReset: () => onUpdate({}),
1765
+ finishButtonLabel: onDryRun && "Try It",
1766
+ onFinish: onDryRun && (() => onDryRun(data))
1767
+ }))));
1768
+ }
1769
+ function TemplateEditorFormDirectoryEditorDryRun(props) {
1770
+ const { setErrorText, fieldExtensions = [] } = props;
1771
+ const dryRun = useDryRun();
1772
+ const directoryEditor = useDirectoryEditor();
1773
+ const { selectedFile } = directoryEditor;
1774
+ const [data, setData] = useState({});
1775
+ const handleDryRun = async () => {
1776
+ if (!selectedFile) {
1777
+ return;
1778
+ }
1779
+ await dryRun.execute({
1780
+ templateContent: selectedFile.content,
1781
+ values: data,
1782
+ files: directoryEditor.files
1783
+ });
1784
+ };
1785
+ const content = selectedFile && selectedFile.path.match(/\.ya?ml$/) ? selectedFile.content : void 0;
1786
+ return /* @__PURE__ */ React.createElement(TemplateEditorForm, {
1787
+ onDryRun: handleDryRun,
1788
+ fieldExtensions,
1789
+ setErrorText,
1790
+ content,
1791
+ data,
1792
+ onUpdate: setData
1793
+ });
1794
+ }
1795
+ TemplateEditorForm.DirectoryEditorDryRun = TemplateEditorFormDirectoryEditorDryRun;
1796
+
1797
+ const useStyles$3 = makeStyles((theme) => ({
1798
+ container: {
1799
+ position: "relative",
1800
+ width: "100%",
1801
+ height: "100%"
1802
+ },
1803
+ codeMirror: {
1804
+ position: "absolute",
1805
+ top: 0,
1806
+ bottom: 0,
1807
+ left: 0,
1808
+ right: 0
1809
+ },
1810
+ errorPanel: {
1811
+ color: theme.palette.error.main,
1812
+ lineHeight: 2,
1813
+ margin: theme.spacing(0, 1)
1814
+ },
1815
+ floatingButtons: {
1816
+ position: "absolute",
1817
+ top: theme.spacing(1),
1818
+ right: theme.spacing(3)
1819
+ },
1820
+ floatingButton: {
1821
+ padding: theme.spacing(1)
1822
+ }
1823
+ }));
1824
+ function TemplateEditorTextArea(props) {
1825
+ const { errorText } = props;
1826
+ const classes = useStyles$3();
1827
+ const panelExtension = useMemo(() => {
1828
+ if (!errorText) {
1829
+ return showPanel.of(null);
1830
+ }
1831
+ const dom = document.createElement("div");
1832
+ dom.classList.add(classes.errorPanel);
1833
+ dom.textContent = errorText;
1834
+ return showPanel.of(() => ({ dom, bottom: true }));
1835
+ }, [classes, errorText]);
1836
+ useKeyboardEvent((e) => e.key === "s" && (e.ctrlKey || e.metaKey), (e) => {
1837
+ e.preventDefault();
1838
+ if (props.onSave) {
1839
+ props.onSave();
1840
+ }
1841
+ });
1842
+ return /* @__PURE__ */ React.createElement("div", {
1843
+ className: classes.container
1844
+ }, /* @__PURE__ */ React.createElement(CodeMirror, {
1845
+ className: classes.codeMirror,
1846
+ theme: "dark",
1847
+ height: "100%",
1848
+ extensions: [StreamLanguage.define(yaml$1), panelExtension],
1849
+ value: props.content,
1850
+ onChange: props.onUpdate
1851
+ }), (props.onSave || props.onReload) && /* @__PURE__ */ React.createElement("div", {
1852
+ className: classes.floatingButtons
1853
+ }, /* @__PURE__ */ React.createElement(Paper, null, props.onSave && /* @__PURE__ */ React.createElement(Tooltip, {
1854
+ title: "Save file"
1855
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1856
+ className: classes.floatingButton,
1857
+ onClick: () => {
1858
+ var _a;
1859
+ return (_a = props.onSave) == null ? void 0 : _a.call(props);
1860
+ }
1861
+ }, /* @__PURE__ */ React.createElement(SaveIcon, null))), props.onReload && /* @__PURE__ */ React.createElement(Tooltip, {
1862
+ title: "Reload file"
1863
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1864
+ className: classes.floatingButton,
1865
+ onClick: () => {
1866
+ var _a;
1867
+ return (_a = props.onReload) == null ? void 0 : _a.call(props);
1868
+ }
1869
+ }, /* @__PURE__ */ React.createElement(RefreshIcon, null))))));
1870
+ }
1871
+ function TemplateEditorDirectoryEditorTextArea(props) {
1872
+ var _a, _b;
1873
+ const directoryEditor = useDirectoryEditor();
1874
+ const actions = ((_a = directoryEditor.selectedFile) == null ? void 0 : _a.dirty) ? {
1875
+ onSave: () => directoryEditor.save(),
1876
+ onReload: () => directoryEditor.reload()
1877
+ } : {
1878
+ onReload: () => directoryEditor.reload()
1879
+ };
1880
+ return /* @__PURE__ */ React.createElement(TemplateEditorTextArea, {
1881
+ errorText: props.errorText,
1882
+ content: (_b = directoryEditor.selectedFile) == null ? void 0 : _b.content,
1883
+ onUpdate: (content) => {
1884
+ var _a2;
1885
+ return (_a2 = directoryEditor.selectedFile) == null ? void 0 : _a2.updateContent(content);
1886
+ },
1887
+ ...actions
1888
+ });
1889
+ }
1890
+ TemplateEditorTextArea.DirectoryEditor = TemplateEditorDirectoryEditorTextArea;
1891
+
1892
+ const useStyles$2 = makeStyles({
1893
+ root: {
1894
+ gridArea: "pageContent",
1895
+ display: "grid",
1896
+ gridTemplateAreas: `
1897
+ "browser editor preview"
1898
+ "results results results"
1899
+ `,
1900
+ gridTemplateColumns: "1fr 3fr 2fr",
1901
+ gridTemplateRows: "1fr auto"
1902
+ },
1903
+ browser: {
1904
+ gridArea: "browser",
1905
+ overflow: "auto"
1906
+ },
1907
+ editor: {
1908
+ gridArea: "editor",
1909
+ overflow: "auto"
1910
+ },
1911
+ preview: {
1912
+ gridArea: "preview",
1913
+ overflow: "auto"
1914
+ },
1915
+ results: {
1916
+ gridArea: "results"
1917
+ }
1918
+ });
1919
+ const TemplateEditor = (props) => {
1920
+ const classes = useStyles$2();
1921
+ const [errorText, setErrorText] = useState();
1922
+ return /* @__PURE__ */ React.createElement(DirectoryEditorProvider, {
1923
+ directory: props.directory
1924
+ }, /* @__PURE__ */ React.createElement(DryRunProvider, null, /* @__PURE__ */ React.createElement("main", {
1925
+ className: classes.root
1926
+ }, /* @__PURE__ */ React.createElement("section", {
1927
+ className: classes.browser
1928
+ }, /* @__PURE__ */ React.createElement(TemplateEditorBrowser, {
1929
+ onClose: props.onClose
1930
+ })), /* @__PURE__ */ React.createElement("section", {
1931
+ className: classes.editor
1932
+ }, /* @__PURE__ */ React.createElement(TemplateEditorTextArea.DirectoryEditor, {
1933
+ errorText
1934
+ })), /* @__PURE__ */ React.createElement("section", {
1935
+ className: classes.preview
1936
+ }, /* @__PURE__ */ React.createElement(TemplateEditorForm.DirectoryEditorDryRun, {
1937
+ setErrorText,
1938
+ fieldExtensions: props.fieldExtensions
1939
+ })), /* @__PURE__ */ React.createElement("section", {
1940
+ className: classes.results
1941
+ }, /* @__PURE__ */ React.createElement(DryRunResults, null)))));
1942
+ };
1943
+
1944
+ const EXAMPLE_TEMPLATE_PARAMS_YAML = `# Edit the template parameters below to see how they will render in the scaffolder form UI
1945
+ parameters:
1946
+ - title: Fill in some steps
1947
+ required:
1948
+ - name
1949
+ properties:
1950
+ name:
1951
+ title: Name
1952
+ type: string
1953
+ description: Unique name of the component
1954
+ owner:
1955
+ title: Owner
1956
+ type: string
1957
+ description: Owner of the component
1958
+ ui:field: OwnerPicker
1959
+ ui:options:
1960
+ allowedKinds:
1961
+ - Group
1962
+ - title: Choose a location
1963
+ required:
1964
+ - repoUrl
1965
+ properties:
1966
+ repoUrl:
1967
+ title: Repository Location
1968
+ type: string
1969
+ ui:field: RepoUrlPicker
1970
+ ui:options:
1971
+ allowedHosts:
1972
+ - github.com
1973
+ steps:
1974
+ - id: fetch-base
1975
+ name: Fetch Base
1976
+ action: fetch:template
1977
+ input:
1978
+ url: ./template
1979
+ values:
1980
+ name: \${{parameters.name}}
1981
+ `;
1982
+ const useStyles$1 = makeStyles((theme) => ({
1983
+ root: {
1984
+ gridArea: "pageContent",
1985
+ display: "grid",
1986
+ gridTemplateAreas: `
1987
+ "controls controls"
1988
+ "textArea preview"
1989
+ `,
1990
+ gridTemplateRows: "auto 1fr",
1991
+ gridTemplateColumns: "1fr 1fr"
1992
+ },
1993
+ controls: {
1994
+ gridArea: "controls",
1995
+ display: "flex",
1996
+ flexFlow: "row nowrap",
1997
+ alignItems: "center",
1998
+ margin: theme.spacing(1)
1999
+ },
2000
+ textArea: {
2001
+ gridArea: "textArea"
2002
+ },
2003
+ preview: {
2004
+ gridArea: "preview"
2005
+ }
2006
+ }));
2007
+ const TemplateFormPreviewer = ({
2008
+ defaultPreviewTemplate = EXAMPLE_TEMPLATE_PARAMS_YAML,
2009
+ customFieldExtensions = [],
2010
+ onClose
2011
+ }) => {
2012
+ const classes = useStyles$1();
2013
+ const alertApi = useApi(alertApiRef);
2014
+ const catalogApi = useApi(catalogApiRef);
2015
+ const [selectedTemplate, setSelectedTemplate] = useState("");
2016
+ const [errorText, setErrorText] = useState();
2017
+ const [templateOptions, setTemplateOptions] = useState([]);
2018
+ const [templateYaml, setTemplateYaml] = useState(defaultPreviewTemplate);
2019
+ const [formState, setFormState] = useState({});
2020
+ const { loading } = useAsync(() => catalogApi.getEntities({
2021
+ filter: { kind: "template" },
2022
+ fields: [
2023
+ "kind",
2024
+ "metadata.namespace",
2025
+ "metadata.name",
2026
+ "metadata.title",
2027
+ "spec.parameters",
2028
+ "spec.steps",
2029
+ "spec.output"
2030
+ ]
2031
+ }).then(({ items }) => setTemplateOptions(items.map((template) => {
2032
+ var _a;
2033
+ return {
2034
+ label: (_a = template.metadata.title) != null ? _a : humanizeEntityRef(template, { defaultKind: "template" }),
2035
+ value: template
2036
+ };
2037
+ }))).catch((e) => alertApi.post({
2038
+ message: `Error loading exisiting templates: ${e.message}`,
2039
+ severity: "error"
2040
+ })), [catalogApi]);
2041
+ const handleSelectChange = useCallback((selected) => {
2042
+ setSelectedTemplate(selected);
2043
+ setTemplateYaml(yaml.stringify(selected.spec));
2044
+ }, [setTemplateYaml]);
2045
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, loading && /* @__PURE__ */ React.createElement(LinearProgress, null), /* @__PURE__ */ React.createElement("main", {
2046
+ className: classes.root
2047
+ }, /* @__PURE__ */ React.createElement("div", {
2048
+ className: classes.controls
2049
+ }, /* @__PURE__ */ React.createElement(FormControl, {
2050
+ variant: "outlined",
2051
+ size: "small",
2052
+ fullWidth: true
2053
+ }, /* @__PURE__ */ React.createElement(InputLabel, {
2054
+ id: "select-template-label"
2055
+ }, "Load Existing Template"), /* @__PURE__ */ React.createElement(Select, {
2056
+ value: selectedTemplate,
2057
+ label: "Load Existing Template",
2058
+ labelId: "select-template-label",
2059
+ onChange: (e) => handleSelectChange(e.target.value)
2060
+ }, templateOptions.map((option, idx) => /* @__PURE__ */ React.createElement(MenuItem$1, {
2061
+ key: idx,
2062
+ value: option.value
2063
+ }, option.label)))), /* @__PURE__ */ React.createElement(IconButton, {
2064
+ size: "medium",
2065
+ onClick: onClose
2066
+ }, /* @__PURE__ */ React.createElement(CloseIcon, null))), /* @__PURE__ */ React.createElement("div", {
2067
+ className: classes.textArea
2068
+ }, /* @__PURE__ */ React.createElement(TemplateEditorTextArea, {
2069
+ content: templateYaml,
2070
+ onUpdate: setTemplateYaml,
2071
+ errorText
2072
+ })), /* @__PURE__ */ React.createElement("div", {
2073
+ className: classes.preview
2074
+ }, /* @__PURE__ */ React.createElement(TemplateEditorForm, {
2075
+ content: templateYaml,
2076
+ contentIsSpec: true,
2077
+ fieldExtensions: customFieldExtensions,
2078
+ data: formState,
2079
+ onUpdate: setFormState,
2080
+ setErrorText
2081
+ }))));
2082
+ };
2083
+
2084
+ function TemplateEditorPage(props) {
2085
+ const [selection, setSelection] = useState();
2086
+ let content = null;
2087
+ if ((selection == null ? void 0 : selection.type) === "local") {
2088
+ content = /* @__PURE__ */ React.createElement(TemplateEditor, {
2089
+ directory: selection.directory,
2090
+ fieldExtensions: props.customFieldExtensions,
2091
+ onClose: () => setSelection(void 0)
2092
+ });
2093
+ } else if ((selection == null ? void 0 : selection.type) === "form") {
2094
+ content = /* @__PURE__ */ React.createElement(TemplateFormPreviewer, {
2095
+ defaultPreviewTemplate: props.defaultPreviewTemplate,
2096
+ customFieldExtensions: props.customFieldExtensions,
2097
+ onClose: () => setSelection(void 0)
2098
+ });
2099
+ } else {
2100
+ content = /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(TemplateEditorIntro, {
2101
+ onSelect: (option) => {
2102
+ if (option === "local") {
2103
+ WebFileSystemAccess.requestDirectoryAccess().then((directory) => setSelection({ type: "local", directory })).catch(() => {
2104
+ });
2105
+ } else if (option === "form") {
2106
+ setSelection({ type: "form" });
2107
+ }
2108
+ }
2109
+ }));
2110
+ }
2111
+ return /* @__PURE__ */ React.createElement(Page, {
2112
+ themeId: "home"
2113
+ }, /* @__PURE__ */ React.createElement(Header, {
2114
+ title: "Template Editor",
2115
+ subtitle: "Edit, preview, and try out templates and template forms"
2116
+ }), content);
2117
+ }
2118
+
2119
+ const useStyles = makeStyles((theme) => ({
2120
+ root: {
2121
+ backgroundColor: "rgba(0, 0, 0, .11)",
2122
+ boxShadow: "none",
2123
+ margin: theme.spacing(1, 0, 1, 0)
2124
+ },
2125
+ title: {
2126
+ margin: theme.spacing(1, 0, 0, 1),
2127
+ textTransform: "uppercase",
2128
+ fontSize: 12,
2129
+ fontWeight: "bold"
2130
+ },
2131
+ listIcon: {
2132
+ minWidth: 30,
2133
+ color: theme.palette.text.primary
2134
+ },
2135
+ menuItem: {
2136
+ minHeight: theme.spacing(6)
2137
+ },
2138
+ groupWrapper: {
2139
+ margin: theme.spacing(1, 1, 2, 1)
2140
+ }
2141
+ }), {
2142
+ name: "ScaffolderReactOwnerListPicker"
2143
+ });
2144
+ function getFilterGroups() {
2145
+ return [
2146
+ {
2147
+ name: "Task Owner",
2148
+ items: [
2149
+ {
2150
+ id: "owned",
2151
+ label: "Owned",
2152
+ icon: SettingsIcon
2153
+ },
2154
+ {
2155
+ id: "all",
2156
+ label: "All",
2157
+ icon: AllIcon
2158
+ }
2159
+ ]
2160
+ }
2161
+ ];
2162
+ }
2163
+ const OwnerListPicker = (props) => {
2164
+ const { filter, onSelectOwner } = props;
2165
+ const classes = useStyles();
2166
+ const filterGroups = getFilterGroups();
2167
+ return /* @__PURE__ */ React.createElement(Card, {
2168
+ className: classes.root
2169
+ }, filterGroups.map((group) => /* @__PURE__ */ React.createElement(Fragment, {
2170
+ key: group.name
2171
+ }, /* @__PURE__ */ React.createElement(Typography, {
2172
+ variant: "subtitle2",
2173
+ className: classes.title
2174
+ }, group.name), /* @__PURE__ */ React.createElement(Card, {
2175
+ className: classes.groupWrapper
2176
+ }, /* @__PURE__ */ React.createElement(List$2, {
2177
+ disablePadding: true,
2178
+ dense: true
2179
+ }, group.items.map((item) => /* @__PURE__ */ React.createElement(MenuItem$1, {
2180
+ key: item.id,
2181
+ button: true,
2182
+ divider: true,
2183
+ onClick: () => onSelectOwner(item.id),
2184
+ selected: item.id === filter,
2185
+ className: classes.menuItem,
2186
+ "data-testid": `owner-picker-${item.id}`
2187
+ }, item.icon && /* @__PURE__ */ React.createElement(ListItemIcon$1, {
2188
+ className: classes.listIcon
2189
+ }, /* @__PURE__ */ React.createElement(item.icon, {
2190
+ fontSize: "small"
2191
+ })), /* @__PURE__ */ React.createElement(ListItemText$1, null, /* @__PURE__ */ React.createElement(Typography, {
2192
+ variant: "body1"
2193
+ }, item.label)))))))));
2194
+ };
2195
+
2196
+ const CreatedAtColumn = ({ createdAt }) => {
2197
+ const createdAtTime = DateTime.fromISO(createdAt);
2198
+ const formatted = Interval.fromDateTimes(createdAtTime, DateTime.local()).toDuration().valueOf();
2199
+ return /* @__PURE__ */ React.createElement("p", null, humanizeDuration(formatted, { round: true }), " ago");
2200
+ };
2201
+
2202
+ const OwnerEntityColumn = ({ entityRef }) => {
2203
+ var _a, _b, _c;
2204
+ const catalogApi = useApi(catalogApiRef);
2205
+ const { value, loading, error } = useAsync(() => catalogApi.getEntityByRef(entityRef || ""), [catalogApi, entityRef]);
2206
+ if (!entityRef) {
2207
+ return /* @__PURE__ */ React.createElement("p", null, "Unknown");
2208
+ }
2209
+ if (loading || error) {
2210
+ return null;
2211
+ }
2212
+ return /* @__PURE__ */ React.createElement(EntityRefLink, {
2213
+ entityRef: parseEntityRef(entityRef),
2214
+ title: (_c = (_b = (_a = value == null ? void 0 : value.spec) == null ? void 0 : _a.profile) == null ? void 0 : _b.displayName) != null ? _c : value == null ? void 0 : value.metadata.name
2215
+ });
2216
+ };
2217
+
2218
+ const TaskStatusColumn = ({ status }) => {
2219
+ switch (status) {
2220
+ case "processing":
2221
+ return /* @__PURE__ */ React.createElement(StatusPending, null, status);
2222
+ case "completed":
2223
+ return /* @__PURE__ */ React.createElement(StatusOK, null, status);
2224
+ case "error":
2225
+ default:
2226
+ return /* @__PURE__ */ React.createElement(StatusError, null, status);
2227
+ }
2228
+ };
2229
+
2230
+ const TemplateTitleColumn = ({ entityRef }) => {
2231
+ const scaffolder = useApi(scaffolderApiRef);
2232
+ const { value, loading, error } = useAsync(() => scaffolder.getTemplateParameterSchema(entityRef || ""), [scaffolder, entityRef]);
2233
+ if (loading || error || !entityRef) {
2234
+ return null;
2235
+ }
2236
+ return /* @__PURE__ */ React.createElement(EntityRefLink, {
2237
+ entityRef: parseEntityRef(entityRef),
2238
+ title: value == null ? void 0 : value.title
2239
+ });
2240
+ };
2241
+
2242
+ const ListTaskPageContent = (props) => {
2243
+ var _a;
2244
+ const { initiallySelectedFilter = "owned" } = props;
2245
+ const scaffolderApi = useApi(scaffolderApiRef);
2246
+ const rootLink = useRouteRef(rootRouteRef);
2247
+ const [ownerFilter, setOwnerFilter] = useState(initiallySelectedFilter);
2248
+ const { value, loading, error } = useAsync(() => {
2249
+ var _a2;
2250
+ if (scaffolderApi.listTasks) {
2251
+ return (_a2 = scaffolderApi.listTasks) == null ? void 0 : _a2.call(scaffolderApi, { filterByOwnership: ownerFilter });
2252
+ }
2253
+ console.warn("listTasks is not implemented in the scaffolderApi, please make sure to implement this method.");
2254
+ return Promise.resolve({ tasks: [] });
2255
+ }, [scaffolderApi, ownerFilter]);
2256
+ if (loading) {
2257
+ return /* @__PURE__ */ React.createElement(Progress, null);
2258
+ }
2259
+ if (error) {
2260
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ErrorPanel, {
2261
+ error
2262
+ }), /* @__PURE__ */ React.createElement(EmptyState, {
2263
+ missing: "info",
2264
+ title: "No information to display",
2265
+ description: "There is no Tasks or there was an issue communicating with backend."
2266
+ }));
2267
+ }
2268
+ return /* @__PURE__ */ React.createElement(CatalogFilterLayout, null, /* @__PURE__ */ React.createElement(CatalogFilterLayout.Filters, null, /* @__PURE__ */ React.createElement(OwnerListPicker, {
2269
+ filter: ownerFilter,
2270
+ onSelectOwner: (id) => setOwnerFilter(id)
2271
+ })), /* @__PURE__ */ React.createElement(CatalogFilterLayout.Content, null, /* @__PURE__ */ React.createElement(MaterialTable, {
2272
+ data: (_a = value == null ? void 0 : value.tasks) != null ? _a : [],
2273
+ title: "Tasks",
2274
+ columns: [
2275
+ {
2276
+ title: "Task ID",
2277
+ field: "id",
2278
+ render: (row) => /* @__PURE__ */ React.createElement(Link$1, {
2279
+ to: `${rootLink()}/tasks/${row.id}`
2280
+ }, row.id)
2281
+ },
2282
+ {
2283
+ title: "Template",
2284
+ render: (row) => {
2285
+ var _a2;
2286
+ return /* @__PURE__ */ React.createElement(TemplateTitleColumn, {
2287
+ entityRef: (_a2 = row.spec.templateInfo) == null ? void 0 : _a2.entityRef
2288
+ });
2289
+ }
2290
+ },
2291
+ {
2292
+ title: "Created",
2293
+ field: "createdAt",
2294
+ render: (row) => /* @__PURE__ */ React.createElement(CreatedAtColumn, {
2295
+ createdAt: row.createdAt
2296
+ })
2297
+ },
2298
+ {
2299
+ title: "Owner",
2300
+ field: "createdBy",
2301
+ render: (row) => {
2302
+ var _a2, _b;
2303
+ return /* @__PURE__ */ React.createElement(OwnerEntityColumn, {
2304
+ entityRef: (_b = (_a2 = row.spec) == null ? void 0 : _a2.user) == null ? void 0 : _b.ref
2305
+ });
2306
+ }
2307
+ },
2308
+ {
2309
+ title: "Status",
2310
+ field: "status",
2311
+ render: (row) => /* @__PURE__ */ React.createElement(TaskStatusColumn, {
2312
+ status: row.status
2313
+ })
2314
+ }
2315
+ ]
2316
+ })));
2317
+ };
2318
+ const ListTasksPage = (props) => {
2319
+ return /* @__PURE__ */ React.createElement(Page, {
2320
+ themeId: "home"
2321
+ }, /* @__PURE__ */ React.createElement(Header, {
2322
+ pageTitleOverride: "Templates Tasks",
2323
+ title: /* @__PURE__ */ React.createElement(React.Fragment, null, "List template tasks ", /* @__PURE__ */ React.createElement(Lifecycle, {
2324
+ shorthand: true,
2325
+ alpha: true
2326
+ })),
2327
+ subtitle: "All tasks that have been started"
2328
+ }), /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(ListTaskPageContent, {
2329
+ ...props
2330
+ })));
2331
+ };
2332
+
2333
+ const Router = (props) => {
2334
+ const { groups, components = {}, defaultPreviewTemplate } = props;
2335
+ const { TemplateCardComponent, TaskPageComponent } = components;
2336
+ const outlet = useOutlet();
2337
+ const TaskPageElement = TaskPageComponent != null ? TaskPageComponent : TaskPage;
2338
+ const customFieldExtensions = useElementFilter(outlet, (elements) => elements.selectByComponentData({
2339
+ key: FIELD_EXTENSION_WRAPPER_KEY
2340
+ }).findComponentData({
2341
+ key: FIELD_EXTENSION_KEY
2342
+ }));
2343
+ const fieldExtensions = [
2344
+ ...customFieldExtensions,
2345
+ ...DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS.filter(({ name }) => !customFieldExtensions.some((customFieldExtension) => customFieldExtension.name === name))
2346
+ ];
2347
+ const RedirectingComponent = () => {
2348
+ const { templateName } = useParams$1();
2349
+ const newLink = useRouteRef(selectedTemplateRouteRef);
2350
+ useEffect(() => console.warn("The route /template/:templateName is deprecated, please use the new /template/:namespace/:templateName route instead"), []);
2351
+ return /* @__PURE__ */ React.createElement(Navigate, {
2352
+ to: newLink({ namespace: "default", templateName })
2353
+ });
2354
+ };
2355
+ return /* @__PURE__ */ React.createElement(Routes, null, /* @__PURE__ */ React.createElement(Route, {
2356
+ element: /* @__PURE__ */ React.createElement(ScaffolderPage, {
2357
+ groups,
2358
+ TemplateCardComponent,
2359
+ contextMenu: props.contextMenu
2360
+ })
2361
+ }), /* @__PURE__ */ React.createElement(Route, {
2362
+ path: legacySelectedTemplateRouteRef.path
2363
+ }, /* @__PURE__ */ React.createElement(RedirectingComponent, null)), /* @__PURE__ */ React.createElement(Route, {
2364
+ path: selectedTemplateRouteRef.path,
2365
+ element: /* @__PURE__ */ React.createElement(SecretsContextProvider, null, /* @__PURE__ */ React.createElement(TemplatePage, {
2366
+ customFieldExtensions: fieldExtensions
2367
+ }))
2368
+ }), /* @__PURE__ */ React.createElement(Route, {
2369
+ path: scaffolderListTaskRouteRef.path,
2370
+ element: /* @__PURE__ */ React.createElement(ListTasksPage, null)
2371
+ }), /* @__PURE__ */ React.createElement(Route, {
2372
+ path: scaffolderTaskRouteRef.path,
2373
+ element: /* @__PURE__ */ React.createElement(TaskPageElement, null)
2374
+ }), /* @__PURE__ */ React.createElement(Route, {
2375
+ path: actionsRouteRef.path,
2376
+ element: /* @__PURE__ */ React.createElement(ActionsPage, null)
2377
+ }), /* @__PURE__ */ React.createElement(Route, {
2378
+ path: editRouteRef.path,
2379
+ element: /* @__PURE__ */ React.createElement(SecretsContextProvider, null, /* @__PURE__ */ React.createElement(TemplateEditorPage, {
2380
+ defaultPreviewTemplate,
2381
+ customFieldExtensions: fieldExtensions
2382
+ }))
2383
+ }), /* @__PURE__ */ React.createElement(Route, {
2384
+ path: "preview",
2385
+ element: /* @__PURE__ */ React.createElement(Navigate, {
2386
+ to: "../edit"
2387
+ })
2388
+ }));
2389
+ };
2390
+
2391
+ export { Router };
2392
+ //# sourceMappingURL=Router-2a5afa3f.esm.js.map