feat(scenarios): add step title, scenario credentials, and environment context in executor
- add nullable title column to scenario steps; exposed in create/edit forms and step table - add scenario-credential join (many-to-many with CredentialEntity) with CRUD endpoints - expose environment URLs in code executor helpers via helpers.env and helpers.getEnvUrl() - resolve and cache environment per run from the login step's environmentName in scheduler - add section spacing and step table title column to ScenarioDetailPage
This commit is contained in:
+10
-1
@@ -1,6 +1,6 @@
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Globe, KeyRound, Monitor, ClipboardList, Activity } from 'lucide-react';
|
||||
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import styles from './App.module.css';
|
||||
import { SidePanel, ThemeSwitcher } from './ui';
|
||||
@@ -21,9 +21,14 @@ import { EditStepPage } from './pages/scenario/EditStepPage';
|
||||
import { RunsPage } from './pages/run/RunsPage';
|
||||
import { RunDetailPage } from './pages/run/RunDetailPage';
|
||||
import { AllRunsPage } from './pages/run/AllRunsPage';
|
||||
import { CredentialsPage } from './pages/credential/CredentialsPage';
|
||||
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
|
||||
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
|
||||
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
|
||||
|
||||
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
|
||||
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
|
||||
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
|
||||
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
|
||||
@@ -78,6 +83,10 @@ export default function App() {
|
||||
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
|
||||
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
|
||||
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
|
||||
<Route path="/credentials" element={<CredentialsPage />} />
|
||||
<Route path="/credentials/new" element={<CreateCredentialPage />} />
|
||||
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
|
||||
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
|
||||
<Route path="/runs" element={<AllRunsPage />} />
|
||||
<Route path="*" element={<Navigate to="/scenarios" replace />} />
|
||||
</Routes>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type {
|
||||
PaginatedResponse,
|
||||
Credential,
|
||||
Environment,
|
||||
KeysResponse,
|
||||
ScenarioCredential,
|
||||
Session,
|
||||
Scenario,
|
||||
ScenarioRun,
|
||||
@@ -30,6 +32,32 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const credentials = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Credential>> {
|
||||
return request(`/credentials?page=${page}&limit=${limit}`);
|
||||
},
|
||||
get(id: number): Promise<Credential> {
|
||||
return request(`/credentials/${id}`);
|
||||
},
|
||||
create(name: string, data?: string): Promise<Credential> {
|
||||
return request('/credentials', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, data }),
|
||||
});
|
||||
},
|
||||
update(id: number, patch: Partial<Pick<Credential, 'name' | 'data'>>): Promise<Credential> {
|
||||
return request(`/credentials/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
},
|
||||
remove(id: number): Promise<void> {
|
||||
return request(`/credentials/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Environments ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const environments = {
|
||||
@@ -132,9 +160,28 @@ export const runs = {
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Steps ────────────────────────────────────────────────────────────
|
||||
// ── Scenario Credentials ──────────────────────────────────────────────────────
|
||||
|
||||
export const scenarioCredentials = {
|
||||
list(scenarioId: number): Promise<ScenarioCredential[]> {
|
||||
return request(`/scenarios/${scenarioId}/credentials`);
|
||||
},
|
||||
add(scenarioId: number, credentialId: number, alias: string): Promise<ScenarioCredential> {
|
||||
return request(`/scenarios/${scenarioId}/credentials`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ credentialId, alias }),
|
||||
});
|
||||
},
|
||||
remove(scenarioId: number, scCredId: number): Promise<void> {
|
||||
return request(`/scenarios/${scenarioId}/credentials/${scCredId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Steps ────────────────────────────────────────────────────────────
|
||||
export interface CreateStepPayload {
|
||||
title?: string;
|
||||
order: number;
|
||||
type: 'login' | 'exec' | 'sign';
|
||||
sessionName: string;
|
||||
@@ -143,6 +190,7 @@ export interface CreateStepPayload {
|
||||
}
|
||||
|
||||
export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
type?: 'login' | 'exec' | 'sign';
|
||||
sessionName?: string;
|
||||
|
||||
@@ -24,6 +24,17 @@ export interface Environment {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Credential {
|
||||
id: number;
|
||||
name: string;
|
||||
data: string | null;
|
||||
lastUsedAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface KeysResponse {
|
||||
@@ -53,6 +64,7 @@ export interface ScenarioStep {
|
||||
scenarioId: number;
|
||||
order: number;
|
||||
type: StepType;
|
||||
title: string | null;
|
||||
sessionName: string;
|
||||
execCode: string | null;
|
||||
validateCode: string | null;
|
||||
@@ -60,10 +72,20 @@ export interface ScenarioStep {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ScenarioCredential {
|
||||
id: number;
|
||||
scenarioId: number;
|
||||
credentialId: number;
|
||||
alias: string;
|
||||
credential: Credential;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Scenario {
|
||||
id: number;
|
||||
name: string;
|
||||
steps?: ScenarioStep[];
|
||||
scenarioCredentials?: ScenarioCredential[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
"not_found": "Not found",
|
||||
"not_found_session": "Session {{id}} does not exist or has been deleted.",
|
||||
"not_found_environment": "Environment {{id}} does not exist or has been deleted.",
|
||||
"not_found_credential": "Credential {{id}} does not exist or has been deleted.",
|
||||
"not_found_scenario": "Scenario {{id}} does not exist or has been deleted.",
|
||||
"generic": "Something went wrong. Please try again."
|
||||
},
|
||||
"nav": {
|
||||
"environments": "Environments",
|
||||
"credentials": "Credentials",
|
||||
"keys": "Keys",
|
||||
"sessions": "Sessions",
|
||||
"scenarios": "Scenarios",
|
||||
@@ -44,8 +46,32 @@
|
||||
"field_updated": "Updated",
|
||||
"section_urls": "URLs"
|
||||
},
|
||||
"credentials": {
|
||||
"title": "Credentials",
|
||||
"empty": "No credentials yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Credential options",
|
||||
"action_edit": "Edit",
|
||||
"action_delete": "Delete",
|
||||
"action_add": "Add credential",
|
||||
"action_save": "Create",
|
||||
"action_update": "Save changes",
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Credential",
|
||||
"edit_title": "Edit Credential",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. staging-api-key",
|
||||
"form_name_required": "Name is required",
|
||||
"form_data": "Data (JSON)",
|
||||
"form_data_placeholder": "{\"token\": \"…\"}",
|
||||
"form_data_invalid_json": "Must be valid JSON",
|
||||
"field_id": "ID",
|
||||
"field_last_used": "Last Used",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
"section_data": "Data"
|
||||
},
|
||||
"keys": {
|
||||
"title": "Keys",
|
||||
"col_name": "Key name",
|
||||
"empty": "No key files found."
|
||||
},
|
||||
@@ -81,6 +107,7 @@
|
||||
"field_updated": "Updated",
|
||||
"steps_heading": "Steps",
|
||||
"step_order": "#",
|
||||
"step_title": "Title",
|
||||
"step_type": "Type",
|
||||
"step_session": "Session",
|
||||
"step_updated": "Updated",
|
||||
@@ -94,7 +121,22 @@
|
||||
"edit_title": "Edit Scenario",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. Login flow",
|
||||
"form_name_required": "Name is required"
|
||||
"form_name_required": "Name is required",
|
||||
"credentials_heading": "Credentials",
|
||||
"cred_empty": "No credentials assigned.",
|
||||
"cred_col_alias": "Alias",
|
||||
"cred_col_name": "Credential",
|
||||
"cred_col_added": "Added",
|
||||
"cred_action_add": "Add credential",
|
||||
"cred_action_remove": "Remove",
|
||||
"cred_action_save": "Add",
|
||||
"cred_action_cancel": "Cancel",
|
||||
"cred_form_cred": "Credential",
|
||||
"cred_form_cred_placeholder": "Select credential…",
|
||||
"cred_form_cred_required": "Select a credential",
|
||||
"cred_form_alias": "Alias",
|
||||
"cred_form_alias_placeholder": "e.g. api_key",
|
||||
"cred_form_alias_required": "Alias is required"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -121,6 +163,8 @@
|
||||
"action_cancel": "Cancel",
|
||||
"form_order": "Order",
|
||||
"form_order_invalid": "Order must be a non-negative integer",
|
||||
"form_title": "Title",
|
||||
"form_title_placeholder": "e.g. Check login page",
|
||||
"form_type": "Type",
|
||||
"form_session": "Session name",
|
||||
"form_session_placeholder": "e.g. my-session",
|
||||
|
||||
@@ -6,14 +6,15 @@
|
||||
}
|
||||
|
||||
.sectionHeading {
|
||||
margin: var(--space-6) 0 var(--space-3);
|
||||
margin: 0;
|
||||
line-height: 1;
|
||||
font-size: var(--font-size-md);
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.stepsSection {
|
||||
margin-top: var(--space-2);
|
||||
margin-top: var(--space-6);
|
||||
}
|
||||
|
||||
.breadcrumbs {
|
||||
@@ -311,3 +312,15 @@
|
||||
.envDetailUrlVal a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* ── Code block ────────────────────────────────────────────────────────── */
|
||||
|
||||
.codeBlock {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono, ui-monospace, monospace);
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-text);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { credentials } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateCredentialPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [data, setData] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
setNameError(t('credentials.form_name_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (data.trim()) {
|
||||
try {
|
||||
JSON.parse(data.trim());
|
||||
} catch {
|
||||
setDataError(t('credentials.form_data_invalid_json'));
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const credential = await credentials.create(name.trim(), data.trim() || undefined);
|
||||
navigate(`/credentials/${credential.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
|
||||
{ label: t('credentials.create_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('credentials.form_name')}
|
||||
placeholder={t('credentials.form_name_placeholder')}
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameError('');
|
||||
}}
|
||||
error={nameError || undefined}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Textarea
|
||||
label={t('credentials.form_data')}
|
||||
placeholder={t('credentials.form_data_placeholder')}
|
||||
value={data}
|
||||
onChange={(e) => {
|
||||
setData(e.target.value);
|
||||
setDataError('');
|
||||
}}
|
||||
error={dataError || undefined}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate('/credentials')}>
|
||||
{t('credentials.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
{t('credentials.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CredentialDetailPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
credentials
|
||||
.get(Number(id))
|
||||
.then(setCredential)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!credential) return;
|
||||
await credentials.remove(credential.id);
|
||||
navigate('/credentials');
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
|
||||
{ label: credential?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{credential && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => navigate(`/credentials/${credential.id}/edit`)}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
{t('credentials.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Trash2 size={14} />
|
||||
{t('credentials.action_delete')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification
|
||||
variant="error"
|
||||
title={error.startsWith('404') ? t('errors.not_found') : undefined}
|
||||
>
|
||||
{error.startsWith('404') ? t('errors.not_found_credential', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
|
||||
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
|
||||
|
||||
{credential && (
|
||||
<>
|
||||
<div className={styles.detailMeta}>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
items={[
|
||||
{ term: t('credentials.field_id'), detail: credential.id },
|
||||
{
|
||||
term: t('credentials.field_last_used'),
|
||||
detail: credential.lastUsedAt ? (
|
||||
<Timestamp value={credential.lastUsedAt} />
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
{
|
||||
term: t('credentials.field_created'),
|
||||
detail: <Timestamp value={credential.createdAt} />,
|
||||
},
|
||||
{
|
||||
term: t('credentials.field_updated'),
|
||||
detail: <Timestamp value={credential.updatedAt} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{credential.data && (
|
||||
<>
|
||||
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
|
||||
<Card>
|
||||
<pre className={styles.codeBlock}>
|
||||
{(() => {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(credential.data), null, 2);
|
||||
} catch {
|
||||
return credential.data;
|
||||
}
|
||||
})()}
|
||||
</pre>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Settings, Pencil, Trash2, Plus } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function CredentialCard({
|
||||
credential,
|
||||
onDelete,
|
||||
}: {
|
||||
credential: Credential;
|
||||
onDelete: (id: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const header = (
|
||||
<div className={styles.envCardHeader}>
|
||||
<span className={styles.envCardName}>{credential.name}</span>
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<ContextMenu
|
||||
align="right"
|
||||
trigger={
|
||||
<Button variant="ghost" size="sm" aria-label={t('credentials.menu_label')}>
|
||||
<Settings size={14} />
|
||||
</Button>
|
||||
}
|
||||
items={[
|
||||
{
|
||||
label: t('credentials.action_edit'),
|
||||
icon: <Pencil size={14} />,
|
||||
onClick: () => navigate(`/credentials/${credential.id}/edit`),
|
||||
},
|
||||
{
|
||||
label: t('credentials.action_delete'),
|
||||
icon: <Trash2 size={14} />,
|
||||
variant: 'danger',
|
||||
onClick: () => onDelete(credential.id),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const footer = (
|
||||
<div className={styles.envCardFooter}>
|
||||
<span className={styles.envCardId}>#{credential.id}</span>
|
||||
<Timestamp value={credential.updatedAt} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={styles.envCard}
|
||||
header={header}
|
||||
headerVariant="primary"
|
||||
footer={footer}
|
||||
onClick={() => navigate(`/credentials/${credential.id}`)}
|
||||
>
|
||||
<DescriptionList
|
||||
layout="compact"
|
||||
truncate
|
||||
items={[
|
||||
{
|
||||
term: t('credentials.field_last_used'),
|
||||
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function AddCredentialCard() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
return (
|
||||
<div className={styles.envCardAdd}>
|
||||
<Button variant="ghost" onClick={() => navigate('/credentials/new')}>
|
||||
<Plus size={16} />
|
||||
{t('credentials.action_add')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CredentialsPage() {
|
||||
const { t } = useTranslation();
|
||||
const [items, setItems] = useState<Credential[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = () => {
|
||||
credentials
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
await credentials.remove(id);
|
||||
setItems((prev) => prev.filter((c) => c.id !== id));
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Breadcrumbs items={[{ label: t('credentials.title') }]} className={styles.breadcrumbs} />
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading ? (
|
||||
<p className={styles.muted}>{t('credentials.loading')}</p>
|
||||
) : (
|
||||
<div className={styles.envGrid}>
|
||||
{items.map((credential) => (
|
||||
<CredentialCard key={credential.id} credential={credential} onDelete={handleDelete} />
|
||||
))}
|
||||
<AddCredentialCard />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditCredentialPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [data, setData] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
credentials
|
||||
.get(Number(id))
|
||||
.then((c) => {
|
||||
setCredential(c);
|
||||
setName(c.name);
|
||||
setData(c.data ?? '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
setNameError(t('credentials.form_name_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (data.trim()) {
|
||||
try {
|
||||
JSON.parse(data.trim());
|
||||
} catch {
|
||||
setDataError(t('credentials.form_data_invalid_json'));
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await credentials.update(Number(id), {
|
||||
name: name.trim(),
|
||||
data: data.trim() || null,
|
||||
});
|
||||
navigate(`/credentials/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: credential?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/credentials/${id}`),
|
||||
},
|
||||
{ label: t('credentials.edit_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
|
||||
|
||||
{!loading && credential && (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('credentials.form_name')}
|
||||
placeholder={t('credentials.form_name_placeholder')}
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameError('');
|
||||
}}
|
||||
error={nameError || undefined}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Textarea
|
||||
label={t('credentials.form_data')}
|
||||
placeholder={t('credentials.form_data_placeholder')}
|
||||
value={data}
|
||||
onChange={(e) => {
|
||||
setData(e.target.value);
|
||||
setDataError('');
|
||||
}}
|
||||
error={dataError || undefined}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/credentials/${id}`)}
|
||||
>
|
||||
{t('credentials.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
{t('credentials.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ export function CreateStepPage() {
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [order, setOrder] = useState('0');
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [sessionName, setSessionName] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
@@ -45,6 +46,7 @@ export function CreateStepPage() {
|
||||
try {
|
||||
await steps.create(Number(id), {
|
||||
order: Number(order),
|
||||
title: title.trim() || undefined,
|
||||
type,
|
||||
sessionName: sessionName.trim(),
|
||||
execCode: execCode.trim() || undefined,
|
||||
@@ -86,6 +88,12 @@ export function CreateStepPage() {
|
||||
onChange={(e) => setOrder(e.target.value)}
|
||||
error={errors.order}
|
||||
/>
|
||||
<Input
|
||||
label={t('steps.form_title')}
|
||||
placeholder={t('steps.form_title_placeholder')}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
label={t('steps.form_type')}
|
||||
value={type}
|
||||
|
||||
@@ -16,6 +16,7 @@ export function EditStepPage() {
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [step, setStep] = useState<ScenarioStep | null>(null);
|
||||
const [order, setOrder] = useState('');
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [sessionName, setSessionName] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
@@ -33,6 +34,7 @@ export function EditStepPage() {
|
||||
setScenario(sc);
|
||||
setStep(st);
|
||||
setOrder(String(st.order));
|
||||
setTitle(st.title ?? '');
|
||||
setType(st.type);
|
||||
setSessionName(st.sessionName);
|
||||
setExecCode(st.execCode ?? '');
|
||||
@@ -63,6 +65,7 @@ export function EditStepPage() {
|
||||
try {
|
||||
await steps.update(Number(id), Number(stepId), {
|
||||
order: Number(order),
|
||||
title: title.trim() || undefined,
|
||||
type,
|
||||
sessionName: sessionName.trim(),
|
||||
execCode: execCode.trim() || undefined,
|
||||
@@ -109,6 +112,12 @@ export function EditStepPage() {
|
||||
}}
|
||||
error={orderError || undefined}
|
||||
/>
|
||||
<Input
|
||||
label={t('steps.form_title')}
|
||||
placeholder={t('steps.form_title_placeholder')}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
label={t('steps.form_type')}
|
||||
value={type}
|
||||
|
||||
@@ -2,15 +2,17 @@ import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Play, Pencil, Plus, History, Trash2 } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, ScenarioStep } from '../../api';
|
||||
import { scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
|
||||
import type { Scenario, ScenarioStep, ScenarioCredential, Credential } from '../../api';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Input,
|
||||
Notification,
|
||||
Select,
|
||||
Table,
|
||||
Timestamp,
|
||||
type TableColumn,
|
||||
@@ -31,13 +33,30 @@ export function ScenarioDetailPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Credentials state
|
||||
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
|
||||
const [allCredentials, setAllCredentials] = useState<Credential[]>([]);
|
||||
const [addCredOpen, setAddCredOpen] = useState(false);
|
||||
const [addCredId, setAddCredId] = useState('');
|
||||
const [addAlias, setAddAlias] = useState('');
|
||||
const [addCredError, setAddCredError] = useState('');
|
||||
const [addAliasError, setAddAliasError] = useState('');
|
||||
const [addCredSaving, setAddCredSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
scenarios
|
||||
.get(Number(id))
|
||||
.then(setScenario)
|
||||
.then((s) => {
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
credentialsApi
|
||||
.list(1, 200)
|
||||
.then((r) => setAllCredentials(r.data))
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
const handleRun = async () => {
|
||||
@@ -59,6 +78,34 @@ export function ScenarioDetailPage() {
|
||||
);
|
||||
};
|
||||
|
||||
const handleAddCredential = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!addCredId) { setAddCredError(t('scenarios.cred_form_cred_required')); valid = false; }
|
||||
if (!addAlias.trim()) { setAddAliasError(t('scenarios.cred_form_alias_required')); valid = false; }
|
||||
if (!valid) return;
|
||||
setAddCredSaving(true);
|
||||
try {
|
||||
const sc = await scenarioCredentials.add(Number(id), Number(addCredId), addAlias.trim());
|
||||
// Re-fetch the credential object since the response may not include it
|
||||
const full = await scenarioCredentials.list(Number(id));
|
||||
setScenarioCreds(full);
|
||||
void sc;
|
||||
setAddCredOpen(false);
|
||||
setAddCredId('');
|
||||
setAddAlias('');
|
||||
} catch (err) {
|
||||
setAddCredError((err as Error).message);
|
||||
} finally {
|
||||
setAddCredSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveCredential = async (scCredId: number) => {
|
||||
await scenarioCredentials.remove(Number(id), scCredId);
|
||||
setScenarioCreds((prev) => prev.filter((sc) => sc.id !== scCredId));
|
||||
};
|
||||
|
||||
const stepColumns: TableColumn<ScenarioStep>[] = [
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
|
||||
{
|
||||
@@ -67,7 +114,11 @@ export function ScenarioDetailPage() {
|
||||
width: 90,
|
||||
render: (s) => <Badge variant={STEP_TYPE_VARIANT[s.type] ?? 'neutral'}>{s.type}</Badge>,
|
||||
},
|
||||
{ key: 'session', header: t('scenarios.step_session'), render: (s) => s.sessionName },
|
||||
{
|
||||
key: 'title',
|
||||
header: t('scenarios.step_title'),
|
||||
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{s.sessionName}</span>,
|
||||
},
|
||||
{
|
||||
key: 'updated',
|
||||
header: t('scenarios.step_updated'),
|
||||
@@ -108,6 +159,40 @@ export function ScenarioDetailPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const credColumns: TableColumn<ScenarioCredential>[] = [
|
||||
{ key: 'alias', header: t('scenarios.cred_col_alias'), render: (sc) => sc.alias },
|
||||
{
|
||||
key: 'name',
|
||||
header: t('scenarios.cred_col_name'),
|
||||
render: (sc) => sc.credential?.name ?? `#${sc.credentialId}`,
|
||||
},
|
||||
{
|
||||
key: 'added',
|
||||
header: t('scenarios.cred_col_added'),
|
||||
width: 140,
|
||||
render: (sc) => <Timestamp value={sc.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
width: 60,
|
||||
align: 'right',
|
||||
render: (sc) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
title={t('scenarios.cred_action_remove')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveCredential(sc.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
@@ -199,6 +284,68 @@ export function ScenarioDetailPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Credentials section ──────────────────────────────────── */}
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.credentials_heading')}</h2>
|
||||
<Button size="sm" onClick={() => setAddCredOpen((v) => !v)}>
|
||||
<Plus size={14} />
|
||||
{t('scenarios.cred_action_add')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{addCredOpen && (
|
||||
<Card className={styles.formCard} style={{ marginBottom: 'var(--space-4)' }}>
|
||||
<form onSubmit={handleAddCredential} noValidate>
|
||||
<div className={styles.formFields}>
|
||||
<Select
|
||||
label={t('scenarios.cred_form_cred')}
|
||||
value={addCredId}
|
||||
onChange={(e) => { setAddCredId(e.target.value); setAddCredError(''); }}
|
||||
error={addCredError || undefined}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
|
||||
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.cred_form_alias')}
|
||||
placeholder={t('scenarios.cred_form_alias_placeholder')}
|
||||
value={addAlias}
|
||||
onChange={(e) => { setAddAlias(e.target.value); setAddAliasError(''); }}
|
||||
error={addAliasError || undefined}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => { setAddCredOpen(false); setAddCredId(''); setAddAlias(''); }}
|
||||
>
|
||||
{t('scenarios.cred_action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" loading={addCredSaving}>
|
||||
{t('scenarios.cred_action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{scenarioCreds.length > 0 ? (
|
||||
<Table
|
||||
columns={credColumns}
|
||||
data={scenarioCreds}
|
||||
rowKey={(sc) => sc.id}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
/>
|
||||
) : (
|
||||
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
.wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
font-family: var(--font-family);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 500;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
font-family: var(--font-family-mono, monospace);
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-text);
|
||||
background: var(--color-bg);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
width: 100%;
|
||||
outline: none;
|
||||
resize: vertical;
|
||||
transition: border-color var(--transition), box-shadow var(--transition);
|
||||
}
|
||||
|
||||
.textarea::placeholder {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.textarea:focus {
|
||||
border-color: var(--color-primary);
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
.textarea:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
background: var(--color-bg-subtle);
|
||||
}
|
||||
|
||||
.hasError {
|
||||
border-color: var(--color-error-fg);
|
||||
}
|
||||
.hasError:focus {
|
||||
border-color: var(--color-error-fg);
|
||||
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2);
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.error {
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--color-error-fg);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import React, { useId } from 'react';
|
||||
import styles from './Textarea.module.css';
|
||||
|
||||
export interface TextareaProps
|
||||
extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'id'> {
|
||||
label?: string;
|
||||
hint?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function Textarea({ label, hint, error, className, ...props }: TextareaProps) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
{label && (
|
||||
<label htmlFor={id} className={styles.label}>
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
<textarea
|
||||
id={id}
|
||||
className={[styles.textarea, error ? styles.hasError : '', className]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
aria-describedby={error ? `${id}-error` : hint ? `${id}-hint` : undefined}
|
||||
aria-invalid={error ? true : undefined}
|
||||
{...props}
|
||||
/>
|
||||
{error ? (
|
||||
<span id={`${id}-error`} className={styles.error} role="alert">
|
||||
{error}
|
||||
</span>
|
||||
) : hint ? (
|
||||
<span id={`${id}-hint`} className={styles.hint}>
|
||||
{hint}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,9 @@ export type { BadgeProps, BadgeVariant } from './Badge/Badge';
|
||||
export { Input } from './Input/Input';
|
||||
export type { InputProps } from './Input/Input';
|
||||
|
||||
export { Textarea } from './Textarea/Textarea';
|
||||
export type { TextareaProps } from './Textarea/Textarea';
|
||||
|
||||
export { Select } from './Select/Select';
|
||||
export type { SelectProps, SelectOption } from './Select/Select';
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
'/environments': 'http://localhost:13000',
|
||||
'/credentials': 'http://localhost:13000',
|
||||
'/sessions': 'http://localhost:13000',
|
||||
'/scenarios': 'http://localhost:13000',
|
||||
'/keys': 'http://localhost:13000',
|
||||
|
||||
@@ -9,12 +9,15 @@ import { BrowserModule } from "./browser/browser.module";
|
||||
import { SessionEntity } from "./session/session.entity";
|
||||
import { EnvironmentEntity } from "./environment/environment.entity";
|
||||
import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { CredentialEntity } from "./credential/credential.entity";
|
||||
import { CredentialModule } from "./credential/credential.module";
|
||||
import { McpModule } from "./mcp/mcp.module";
|
||||
import { ScenarioEntity } from "./scenario/scenario.entity";
|
||||
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
|
||||
import { ScenarioModule } from "./scenario/scenario.module";
|
||||
|
||||
@Module({
|
||||
@@ -33,11 +36,13 @@ import { ScenarioModule } from "./scenario/scenario.module";
|
||||
entities: [
|
||||
SessionEntity,
|
||||
EnvironmentEntity,
|
||||
CredentialEntity,
|
||||
ScenarioEntity,
|
||||
ScenarioStepEntity,
|
||||
ScenarioRunEntity,
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
],
|
||||
synchronize: true,
|
||||
}),
|
||||
@@ -45,6 +50,7 @@ import { ScenarioModule } from "./scenario/scenario.module";
|
||||
AuthModule,
|
||||
BrowserModule,
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
ScenarioModule,
|
||||
McpModule,
|
||||
HealthModule,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { TraceLogger } from "../common/trace-logger";
|
||||
import { parse } from "acorn";
|
||||
import type { Page, BrowserContext } from "playwright";
|
||||
import { dumpDom } from "./dom-helpers";
|
||||
import type { EnvironmentUrls } from "../environment/environment.entity";
|
||||
|
||||
export interface ExecResult {
|
||||
result: unknown;
|
||||
@@ -47,6 +48,8 @@ export class CodeExecutorService {
|
||||
code: string,
|
||||
log?: ScriptLogger,
|
||||
getStepOutput?: (order: number) => Promise<unknown>,
|
||||
credentials?: Record<string, unknown>,
|
||||
environment?: EnvironmentUrls | null,
|
||||
): Promise<ExecResult> {
|
||||
const scriptLog: ScriptLogger =
|
||||
log ?? ((level, msg) => this.logger[level](msg));
|
||||
@@ -55,6 +58,9 @@ export class CodeExecutorService {
|
||||
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
|
||||
.join(" ");
|
||||
|
||||
const credMap: Record<string, unknown> = credentials ?? {};
|
||||
const envUrls: EnvironmentUrls = environment ?? {};
|
||||
|
||||
try {
|
||||
const pageHelpers = {
|
||||
dumpDom: (selector?: string) => dumpDom(page, selector),
|
||||
@@ -62,6 +68,26 @@ export class CodeExecutorService {
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
|
||||
getCredential: (alias: string): unknown => {
|
||||
if (!(alias in credMap)) {
|
||||
throw new Error(
|
||||
`Credential alias "${alias}" not found in this scenario`,
|
||||
);
|
||||
}
|
||||
return credMap[alias];
|
||||
},
|
||||
/** All URLs defined for the current environment (may be empty if no environment is set). */
|
||||
env: { ...envUrls },
|
||||
/** Returns the URL for the given key, or throws if it is not defined. */
|
||||
getEnvUrl: (key: string): string => {
|
||||
const value = envUrls[key];
|
||||
if (value == null) {
|
||||
throw new Error(
|
||||
`Environment URL "${key}" is not defined for this environment`,
|
||||
);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
};
|
||||
|
||||
const fakeConsole = {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { CredentialService } from "./credential.service";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy } from "./credential.service";
|
||||
|
||||
@ApiTags("credentials")
|
||||
@Controller("credentials")
|
||||
export class CredentialController {
|
||||
constructor(private readonly credentialService: CredentialService) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "Create a new credential" })
|
||||
@ApiResponse({ status: 201, description: "Credential created" })
|
||||
create(@Body() dto: CreateCredentialDto) {
|
||||
return this.credentialService.create(dto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all credentials (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated credentials" })
|
||||
findAll(@Query() query: PaginationQueryDto<CredentialOrderBy>) {
|
||||
return this.credentialService.findAll(query);
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "Get credential by ID" })
|
||||
@ApiResponse({ status: 200, description: "Credential record" })
|
||||
@ApiResponse({ status: 404, description: "Credential not found" })
|
||||
findOne(@Param("id", ParseIntPipe) id: number) {
|
||||
return this.credentialService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@ApiOperation({ summary: "Update a credential" })
|
||||
@ApiResponse({ status: 200, description: "Credential updated" })
|
||||
@ApiResponse({ status: 404, description: "Credential not found" })
|
||||
update(
|
||||
@Param("id", ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateCredentialDto,
|
||||
) {
|
||||
return this.credentialService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: "Delete a credential" })
|
||||
@ApiResponse({ status: 204, description: "Credential deleted" })
|
||||
@ApiResponse({ status: 404, description: "Credential not found" })
|
||||
remove(@Param("id", ParseIntPipe) id: number) {
|
||||
return this.credentialService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
|
||||
@Entity("credentials")
|
||||
export class CredentialEntity {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
data: string | null;
|
||||
|
||||
@Column({ type: "datetime", nullable: true })
|
||||
lastUsedAt: Date | null;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { CredentialEntity } from "./credential.entity";
|
||||
import { CredentialService } from "./credential.service";
|
||||
import { CredentialController } from "./credential.controller";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([CredentialEntity])],
|
||||
controllers: [CredentialController],
|
||||
providers: [CredentialService],
|
||||
exports: [CredentialService],
|
||||
})
|
||||
export class CredentialModule {}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import { CredentialEntity } from "./credential.entity";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
import {
|
||||
PaginationQueryDto,
|
||||
PaginatedResult,
|
||||
} from "../common/dto/pagination.dto";
|
||||
|
||||
export type CredentialOrderBy = "id" | "name" | "lastUsedAt" | "createdAt" | "updatedAt";
|
||||
|
||||
@Injectable()
|
||||
export class CredentialService {
|
||||
constructor(
|
||||
@InjectRepository(CredentialEntity)
|
||||
private readonly repo: Repository<CredentialEntity>,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateCredentialDto): Promise<CredentialEntity> {
|
||||
return this.repo.save(this.repo.create({ ...dto, data: dto.data ?? null }));
|
||||
}
|
||||
|
||||
async findAll(
|
||||
query: PaginationQueryDto<CredentialOrderBy> = {},
|
||||
): Promise<PaginatedResult<CredentialEntity>> {
|
||||
const page = query.page ?? 1;
|
||||
const limit = query.limit ?? 20;
|
||||
const orderBy = query.orderBy ?? "id";
|
||||
const orderDir = query.orderDir ?? "ASC";
|
||||
const [data, total] = await this.repo.findAndCount({
|
||||
order: { [orderBy]: orderDir },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
});
|
||||
return { data, total, page, limit };
|
||||
}
|
||||
|
||||
async findOne(id: number): Promise<CredentialEntity> {
|
||||
const credential = await this.repo.findOneBy({ id });
|
||||
if (!credential) throw new NotFoundException(`Credential ${id} not found`);
|
||||
return credential;
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateCredentialDto): Promise<CredentialEntity> {
|
||||
const credential = await this.findOne(id);
|
||||
Object.assign(credential, dto);
|
||||
return this.repo.save(credential);
|
||||
}
|
||||
|
||||
async remove(id: number): Promise<void> {
|
||||
await this.findOne(id);
|
||||
await this.repo.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class CreateCredentialDto {
|
||||
@ApiProperty({ example: "my-api-key" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: "JSON-encoded credential payload",
|
||||
example: '{"token":"abc123","secret":"xyz"}',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
data?: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateCredentialDto } from "./create-credential.dto";
|
||||
|
||||
export class UpdateCredentialDto extends PartialType(CreateCredentialDto) {}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsInt, IsNotEmpty, IsPositive, IsString } from "class-validator";
|
||||
|
||||
export class AddScenarioCredentialDto {
|
||||
@ApiProperty({ example: 1 })
|
||||
@IsInt()
|
||||
@IsPositive()
|
||||
credentialId: number;
|
||||
|
||||
@ApiProperty({ example: "api_key" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
alias: string;
|
||||
}
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
import { StepType } from "../scenario-step.entity";
|
||||
|
||||
export class CreateScenarioStepDto {
|
||||
@ApiPropertyOptional({ example: "Check login page title" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
|
||||
@ApiProperty({ example: 0, description: "Execution order (ascending)" })
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
import { StepType } from "../scenario-step.entity";
|
||||
|
||||
export class UpdateScenarioStepDto {
|
||||
@ApiPropertyOptional({ example: "Check login page title" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 0 })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
ManyToOne,
|
||||
JoinColumn,
|
||||
CreateDateColumn,
|
||||
Unique,
|
||||
} from "typeorm";
|
||||
import { ScenarioEntity } from "./scenario.entity";
|
||||
import { CredentialEntity } from "../credential/credential.entity";
|
||||
|
||||
@Entity("scenario_credentials")
|
||||
@Unique(["scenarioId", "alias"])
|
||||
export class ScenarioCredentialEntity {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
scenarioId: number;
|
||||
|
||||
@Column()
|
||||
credentialId: number;
|
||||
|
||||
@Column()
|
||||
alias: string;
|
||||
|
||||
@ManyToOne(() => ScenarioEntity, { onDelete: "CASCADE" })
|
||||
@JoinColumn({ name: "scenarioId" })
|
||||
scenario: ScenarioEntity;
|
||||
|
||||
@ManyToOne(() => CredentialEntity, { onDelete: "CASCADE", eager: true })
|
||||
@JoinColumn({ name: "credentialId" })
|
||||
credential: CredentialEntity;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -15,6 +15,9 @@ import type { ScriptLogger } from "../code-executor/code-executor.service";
|
||||
import { AuthService } from "../auth/auth.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { SessionService } from "../session/session.service";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
import { EnvironmentService } from "../environment/environment.service";
|
||||
import type { EnvironmentUrls } from "../environment/environment.entity";
|
||||
|
||||
interface ValidateResult {
|
||||
success: boolean;
|
||||
@@ -32,6 +35,10 @@ export class ScenarioSchedulerService {
|
||||
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
|
||||
private readonly activeRuns = new Set<number>();
|
||||
private readonly runBrowsers = new Map<number, BrowserHandle>();
|
||||
// Cache credential maps per run (built once when a run starts)
|
||||
private readonly runCredentials = new Map<number, Record<string, unknown>>();
|
||||
// Cache environment URLs per run (resolved from the first login step)
|
||||
private readonly runEnvironments = new Map<number, EnvironmentUrls>();
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
@@ -43,6 +50,8 @@ export class ScenarioSchedulerService {
|
||||
private readonly authService: AuthService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly scenarioService: ScenarioService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
) {}
|
||||
|
||||
private persistLog(
|
||||
@@ -81,6 +90,30 @@ export class ScenarioSchedulerService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first login step for a scenario and returns the environment URLs
|
||||
* for the environment named in that step's execCode. Returns null if there is
|
||||
* no login step or the environment cannot be found.
|
||||
*/
|
||||
private async resolveRunEnvironment(
|
||||
scenarioId: number,
|
||||
): Promise<EnvironmentUrls | null> {
|
||||
try {
|
||||
const scenario = await this.scenarioService.findOne(scenarioId);
|
||||
const loginStep = scenario.steps.find((s) => s.type === "login");
|
||||
if (!loginStep?.execCode) return null;
|
||||
const params = JSON.parse(loginStep.execCode) as {
|
||||
environmentName?: string;
|
||||
};
|
||||
if (!params.environmentName) return null;
|
||||
const { data } = await this.environmentService.findAll({});
|
||||
const env = data.find((e) => e.name === params.environmentName);
|
||||
return env?.urls ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Job: pick up pending runs and process each to completion ─────────────
|
||||
|
||||
@Interval(1000)
|
||||
@@ -92,6 +125,14 @@ export class ScenarioSchedulerService {
|
||||
run.status = "in_progress";
|
||||
await this.runRepo.save(run);
|
||||
this.logger.log(`Run #${run.id} → in_progress`);
|
||||
// Pre-load credential map for the scenario
|
||||
const credMap = await this.scenarioService
|
||||
.buildCredentialMap(run.scenarioId)
|
||||
.catch(() => ({} as Record<string, unknown>));
|
||||
this.runCredentials.set(run.id, credMap);
|
||||
// Resolve environment from the first login step (best-effort)
|
||||
const envUrls = await this.resolveRunEnvironment(run.scenarioId);
|
||||
if (envUrls) this.runEnvironments.set(run.id, envUrls);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
@@ -114,8 +155,6 @@ export class ScenarioSchedulerService {
|
||||
order: { order: "ASC" },
|
||||
});
|
||||
}
|
||||
// Guard: if there were no steps (or all steps already resolved via passStepRun),
|
||||
// ensure the run is not left in in_progress.
|
||||
await this.runRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
@@ -129,6 +168,8 @@ export class ScenarioSchedulerService {
|
||||
await this.runRepo.update(runId, { status: "fail" });
|
||||
} finally {
|
||||
this.activeRuns.delete(runId);
|
||||
this.runCredentials.delete(runId);
|
||||
this.runEnvironments.delete(runId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,6 +291,8 @@ export class ScenarioSchedulerService {
|
||||
step.validateCode,
|
||||
this.stepLogger(stepRun.id, stepRun.runId),
|
||||
this.makeGetStepOutput(stepRun),
|
||||
this.runCredentials.get(stepRun.runId),
|
||||
this.runEnvironments.get(stepRun.runId),
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
@@ -272,12 +315,16 @@ export class ScenarioSchedulerService {
|
||||
step.sessionName,
|
||||
);
|
||||
const getStepOutput = this.makeGetStepOutput(stepRun);
|
||||
const creds = this.runCredentials.get(stepRun.runId);
|
||||
const env = this.runEnvironments.get(stepRun.runId);
|
||||
const { result: execOutput } = await this.codeExecutor.execute(
|
||||
page,
|
||||
context,
|
||||
step.execCode,
|
||||
this.stepLogger(stepRun.id, stepRun.runId),
|
||||
getStepOutput,
|
||||
creds,
|
||||
env,
|
||||
);
|
||||
this.logger.log(`StepRun #${stepRun.id}: exec OK`);
|
||||
|
||||
@@ -289,6 +336,8 @@ export class ScenarioSchedulerService {
|
||||
step.validateCode,
|
||||
this.stepLogger(stepRun.id, stepRun.runId),
|
||||
getStepOutput,
|
||||
creds,
|
||||
env,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
@@ -327,6 +376,8 @@ export class ScenarioSchedulerService {
|
||||
step.validateCode,
|
||||
this.stepLogger(stepRun.id, stepRun.runId),
|
||||
this.makeGetStepOutput(stepRun),
|
||||
this.runCredentials.get(stepRun.runId),
|
||||
this.runEnvironments.get(stepRun.runId),
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
|
||||
@@ -31,6 +31,9 @@ export class ScenarioStepEntity {
|
||||
@Column({ type: "text" })
|
||||
type: StepType;
|
||||
|
||||
@Column({ type: "text", nullable: true })
|
||||
title: string | null;
|
||||
|
||||
@Column({ type: "text" })
|
||||
sessionName: string;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { CreateScenarioDto } from "./dto/create-scenario.dto";
|
||||
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
|
||||
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
|
||||
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
|
||||
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
|
||||
import { PaginationQueryDto } from "./dto/pagination-query.dto";
|
||||
import { ScenarioOrderBy } from "./scenario.service";
|
||||
import { RunsQueryDto } from "./dto/runs-query.dto";
|
||||
@@ -140,6 +141,40 @@ export class ScenarioController {
|
||||
return this.scenarioService.removeStep(id, stepId);
|
||||
}
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────
|
||||
|
||||
@Get(":id/credentials")
|
||||
@ApiOperation({ summary: "List credentials assigned to a scenario" })
|
||||
@ApiResponse({ status: 200 })
|
||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||
findScenarioCredentials(@Param("id", ParseIntPipe) id: number) {
|
||||
return this.scenarioService.findScenarioCredentials(id);
|
||||
}
|
||||
|
||||
@Post(":id/credentials")
|
||||
@ApiOperation({ summary: "Add a credential to a scenario with an alias" })
|
||||
@ApiResponse({ status: 201, description: "Credential added" })
|
||||
@ApiResponse({ status: 404, description: "Scenario or credential not found" })
|
||||
@ApiResponse({ status: 409, description: "Alias already used in this scenario" })
|
||||
addScenarioCredential(
|
||||
@Param("id", ParseIntPipe) id: number,
|
||||
@Body() dto: AddScenarioCredentialDto,
|
||||
) {
|
||||
return this.scenarioService.addScenarioCredential(id, dto);
|
||||
}
|
||||
|
||||
@Delete(":id/credentials/:scCredId")
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: "Remove a credential from a scenario" })
|
||||
@ApiResponse({ status: 204 })
|
||||
@ApiResponse({ status: 404, description: "Scenario or credential assignment not found" })
|
||||
removeScenarioCredential(
|
||||
@Param("id", ParseIntPipe) id: number,
|
||||
@Param("scCredId", ParseIntPipe) scCredId: number,
|
||||
) {
|
||||
return this.scenarioService.removeScenarioCredential(id, scCredId);
|
||||
}
|
||||
|
||||
// ── Runs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@Get(":id/runs")
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
OneToMany,
|
||||
} from "typeorm";
|
||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
|
||||
@Entity("scenarios")
|
||||
export class ScenarioEntity {
|
||||
@@ -22,6 +23,12 @@ export class ScenarioEntity {
|
||||
})
|
||||
steps: ScenarioStepEntity[];
|
||||
|
||||
@OneToMany(() => ScenarioCredentialEntity, (sc) => sc.scenario, {
|
||||
cascade: true,
|
||||
eager: false,
|
||||
})
|
||||
scenarioCredentials: ScenarioCredentialEntity[];
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
|
||||
@@ -5,12 +5,15 @@ import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
import { CredentialEntity } from "../credential/credential.entity";
|
||||
import { ScenarioService } from "./scenario.service";
|
||||
import { ScenarioController } from "./scenario.controller";
|
||||
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CodeExecutorModule } from "../code-executor/code-executor.module";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { EnvironmentModule } from "../environment/environment.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -20,10 +23,13 @@ import { SessionModule } from "../session/session.module";
|
||||
ScenarioRunEntity,
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
CredentialEntity,
|
||||
]),
|
||||
AuthModule,
|
||||
CodeExecutorModule,
|
||||
SessionModule,
|
||||
EnvironmentModule,
|
||||
],
|
||||
controllers: [ScenarioController],
|
||||
providers: [ScenarioService, ScenarioSchedulerService],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { ConflictException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import { ScenarioEntity } from "./scenario.entity";
|
||||
@@ -6,10 +6,13 @@ import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
||||
import { CredentialEntity } from "../credential/credential.entity";
|
||||
import { CreateScenarioDto } from "./dto/create-scenario.dto";
|
||||
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
|
||||
import { CreateScenarioStepDto } from "./dto/create-scenario-step.dto";
|
||||
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
|
||||
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
|
||||
import {
|
||||
PaginationQueryDto,
|
||||
PaginatedResult,
|
||||
@@ -33,6 +36,10 @@ export class ScenarioService {
|
||||
private readonly runStepRepo: Repository<ScenarioRunStepEntity>,
|
||||
@InjectRepository(ScenarioRunLogEntity)
|
||||
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
|
||||
@InjectRepository(ScenarioCredentialEntity)
|
||||
private readonly scenarioCredRepo: Repository<ScenarioCredentialEntity>,
|
||||
@InjectRepository(CredentialEntity)
|
||||
private readonly credentialRepo: Repository<CredentialEntity>,
|
||||
) {}
|
||||
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────
|
||||
@@ -59,7 +66,7 @@ export class ScenarioService {
|
||||
async findOne(id: number): Promise<ScenarioEntity> {
|
||||
const scenario = await this.scenarioRepo.findOne({
|
||||
where: { id },
|
||||
relations: ["steps"],
|
||||
relations: ["steps", "scenarioCredentials", "scenarioCredentials.credential"],
|
||||
order: { steps: { order: "ASC" } },
|
||||
});
|
||||
if (!scenario) throw new NotFoundException(`Scenario ${id} not found`);
|
||||
@@ -121,6 +128,84 @@ export class ScenarioService {
|
||||
await this.stepRepo.delete(stepId);
|
||||
}
|
||||
|
||||
// ── Scenario Credentials ──────────────────────────────────────────────────
|
||||
|
||||
async findScenarioCredentials(
|
||||
scenarioId: number,
|
||||
): Promise<ScenarioCredentialEntity[]> {
|
||||
await this.findOne(scenarioId); // 404 guard
|
||||
return this.scenarioCredRepo.find({
|
||||
where: { scenarioId },
|
||||
relations: ["credential"],
|
||||
order: { alias: "ASC" },
|
||||
});
|
||||
}
|
||||
|
||||
async addScenarioCredential(
|
||||
scenarioId: number,
|
||||
dto: AddScenarioCredentialDto,
|
||||
): Promise<ScenarioCredentialEntity> {
|
||||
await this.findOne(scenarioId); // 404 guard
|
||||
const credential = await this.credentialRepo.findOneBy({
|
||||
id: dto.credentialId,
|
||||
});
|
||||
if (!credential)
|
||||
throw new NotFoundException(`Credential ${dto.credentialId} not found`);
|
||||
const existing = await this.scenarioCredRepo.findOneBy({
|
||||
scenarioId,
|
||||
alias: dto.alias,
|
||||
});
|
||||
if (existing)
|
||||
throw new ConflictException(
|
||||
`Alias "${dto.alias}" already used in this scenario`,
|
||||
);
|
||||
const sc = this.scenarioCredRepo.create({
|
||||
scenarioId,
|
||||
credentialId: dto.credentialId,
|
||||
alias: dto.alias,
|
||||
});
|
||||
return this.scenarioCredRepo.save(sc);
|
||||
}
|
||||
|
||||
async removeScenarioCredential(
|
||||
scenarioId: number,
|
||||
scCredId: number,
|
||||
): Promise<void> {
|
||||
await this.findOne(scenarioId); // 404 guard
|
||||
const sc = await this.scenarioCredRepo.findOneBy({
|
||||
id: scCredId,
|
||||
scenarioId,
|
||||
});
|
||||
if (!sc)
|
||||
throw new NotFoundException(
|
||||
`Scenario credential ${scCredId} not found in scenario ${scenarioId}`,
|
||||
);
|
||||
await this.scenarioCredRepo.delete(scCredId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a map of alias → parsed credential data for use in code execution.
|
||||
* Returns null values for credentials with no data.
|
||||
*/
|
||||
async buildCredentialMap(scenarioId: number): Promise<Record<string, unknown>> {
|
||||
const scs = await this.findScenarioCredentials(scenarioId);
|
||||
const map: Record<string, unknown> = {};
|
||||
for (const sc of scs) {
|
||||
let parsed: unknown = null;
|
||||
if (sc.credential.data) {
|
||||
try {
|
||||
parsed = JSON.parse(sc.credential.data);
|
||||
} catch {
|
||||
parsed = sc.credential.data;
|
||||
}
|
||||
}
|
||||
map[sc.alias] = parsed;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// ── Runs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async findRuns(
|
||||
scenarioId: number,
|
||||
query: RunsQueryDto,
|
||||
|
||||
Reference in New Issue
Block a user