feat(snippets): add snippets entity, crud, and auto-browser-per-run
- add Snippet entity with name, description, code; full CRUD backend - add snippets pages (list, create, edit, detail) and nav entry - add runSnippet helper in code-executor using new Function with args array - add result param to execute() so validateCode can access exec output - remove sessionName from steps; each run now spawns its own fresh browser - fix waitForURL race by polling localStorage for token instead
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, KeySquare } from 'lucide-react';
|
||||
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare, Braces } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import styles from './App.module.css';
|
||||
import { SidePanel, ThemeSwitcher } from './ui';
|
||||
@@ -25,10 +25,15 @@ import { CredentialsPage } from './pages/credential/CredentialsPage';
|
||||
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
|
||||
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
|
||||
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
|
||||
import { SnippetsPage } from './pages/snippet/SnippetsPage';
|
||||
import { CreateSnippetPage } from './pages/snippet/CreateSnippetPage';
|
||||
import { EditSnippetPage } from './pages/snippet/EditSnippetPage';
|
||||
import { SnippetDetailPage } from './pages/snippet/SnippetDetailPage';
|
||||
|
||||
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
|
||||
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
|
||||
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
|
||||
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
|
||||
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
|
||||
@@ -87,6 +92,10 @@ export default function App() {
|
||||
<Route path="/credentials/new" element={<CreateCredentialPage />} />
|
||||
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
|
||||
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
|
||||
<Route path="/snippets" element={<SnippetsPage />} />
|
||||
<Route path="/snippets/new" element={<CreateSnippetPage />} />
|
||||
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
|
||||
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
|
||||
<Route path="/runs" element={<AllRunsPage />} />
|
||||
<Route path="*" element={<Navigate to="/scenarios" replace />} />
|
||||
</Routes>
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
ScenarioRunDetail,
|
||||
ScenarioRunStep,
|
||||
ScenarioStep,
|
||||
Snippet,
|
||||
} from './types';
|
||||
|
||||
// In dev, Vite proxies /environments /sessions /scenarios /keys to localhost:3000.
|
||||
@@ -58,6 +59,32 @@ export const credentials = {
|
||||
},
|
||||
};
|
||||
|
||||
// ── Snippets ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const snippets = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Snippet>> {
|
||||
return request(`/snippets?page=${page}&limit=${limit}`);
|
||||
},
|
||||
get(id: number): Promise<Snippet> {
|
||||
return request(`/snippets/${id}`);
|
||||
},
|
||||
create(payload: Pick<Snippet, 'name' | 'code'> & { description?: string }): Promise<Snippet> {
|
||||
return request('/snippets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
update(id: number, patch: Partial<Pick<Snippet, 'name' | 'description' | 'code'>>): Promise<Snippet> {
|
||||
return request(`/snippets/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
},
|
||||
remove(id: number): Promise<void> {
|
||||
return request(`/snippets/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Environments ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const environments = {
|
||||
@@ -184,7 +211,6 @@ export interface CreateStepPayload {
|
||||
title?: string;
|
||||
order: number;
|
||||
type: 'login' | 'exec' | 'sign';
|
||||
sessionName: string;
|
||||
execCode?: string;
|
||||
validateCode?: string;
|
||||
}
|
||||
@@ -193,7 +219,6 @@ export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
type?: 'login' | 'exec' | 'sign';
|
||||
sessionName?: string;
|
||||
execCode?: string;
|
||||
validateCode?: string;
|
||||
}
|
||||
|
||||
+12
-1
@@ -35,6 +35,17 @@ export interface Credential {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ── Snippets ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Snippet {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface KeysResponse {
|
||||
@@ -65,7 +76,7 @@ export interface ScenarioStep {
|
||||
order: number;
|
||||
type: StepType;
|
||||
title: string | null;
|
||||
sessionName: string;
|
||||
sessionName: string | null;
|
||||
execCode: string | null;
|
||||
validateCode: string | null;
|
||||
createdAt: string;
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
"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.",
|
||||
"not_found_snippet": "Snippet {{id}} does not exist or has been deleted.",
|
||||
"generic": "Something went wrong. Please try again."
|
||||
},
|
||||
"nav": {
|
||||
"environments": "Environments",
|
||||
"credentials": "Credentials",
|
||||
"snippets": "Snippets",
|
||||
"keys": "Keys",
|
||||
"sessions": "Sessions",
|
||||
"scenarios": "Scenarios",
|
||||
@@ -199,5 +201,33 @@
|
||||
"log_level": "Level",
|
||||
"log_message": "Message",
|
||||
"log_time": "Time"
|
||||
},
|
||||
"snippets": {
|
||||
"title": "Snippets",
|
||||
"empty": "No snippets yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Snippet options",
|
||||
"action_edit": "Edit",
|
||||
"action_delete": "Delete",
|
||||
"action_add": "Add snippet",
|
||||
"action_save": "Create",
|
||||
"action_update": "Save changes",
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Snippet",
|
||||
"edit_title": "Edit Snippet",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. clickLoginButton",
|
||||
"form_name_required": "Name is required",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "What does this snippet do?",
|
||||
"form_code": "Code",
|
||||
"form_code_placeholder": "await page.click('#login-btn');",
|
||||
"form_code_required": "Code is required",
|
||||
"field_id": "ID",
|
||||
"field_name": "Name",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
"section_code": "Code"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,11 +119,6 @@ export function RunDetailPage() {
|
||||
width: 80,
|
||||
render: (s) => <Badge variant="neutral">{s.scenarioStep?.type ?? '–'}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'session',
|
||||
header: t('runs.step_session'),
|
||||
render: (s) => s.scenarioStep?.sessionName ?? '–',
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: t('runs.step_status'),
|
||||
|
||||
@@ -18,7 +18,6 @@ export function CreateStepPage() {
|
||||
const [order, setOrder] = useState('0');
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [sessionName, setSessionName] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [validateCode, setValidateCode] = useState('');
|
||||
const [errors, setErrors] = useState<Partial<Record<keyof CreateStepPayload, string>>>({});
|
||||
@@ -32,7 +31,6 @@ export function CreateStepPage() {
|
||||
|
||||
const validate = (): boolean => {
|
||||
const next: typeof errors = {};
|
||||
if (!sessionName.trim()) next.sessionName = t('steps.form_session_required');
|
||||
if (isNaN(Number(order)) || Number(order) < 0) next.order = t('steps.form_order_invalid');
|
||||
setErrors(next);
|
||||
return Object.keys(next).length === 0;
|
||||
@@ -48,7 +46,6 @@ export function CreateStepPage() {
|
||||
order: Number(order),
|
||||
title: title.trim() || undefined,
|
||||
type,
|
||||
sessionName: sessionName.trim(),
|
||||
execCode: execCode.trim() || undefined,
|
||||
validateCode: validateCode.trim() || undefined,
|
||||
});
|
||||
@@ -100,17 +97,6 @@ export function CreateStepPage() {
|
||||
onChange={(e) => setType(e.target.value as StepType)}
|
||||
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
|
||||
/>
|
||||
<Input
|
||||
label={t('steps.form_session')}
|
||||
placeholder={t('steps.form_session_placeholder')}
|
||||
value={sessionName}
|
||||
onChange={(e) => {
|
||||
setSessionName(e.target.value);
|
||||
setErrors((prev) => ({ ...prev, sessionName: undefined }));
|
||||
}}
|
||||
error={errors.sessionName}
|
||||
required
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<textarea
|
||||
|
||||
@@ -18,10 +18,8 @@ export function EditStepPage() {
|
||||
const [order, setOrder] = useState('');
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [sessionName, setSessionName] = useState('');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [validateCode, setValidateCode] = useState('');
|
||||
const [sessionError, setSessionError] = useState('');
|
||||
const [orderError, setOrderError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -36,7 +34,6 @@ export function EditStepPage() {
|
||||
setOrder(String(st.order));
|
||||
setTitle(st.title ?? '');
|
||||
setType(st.type);
|
||||
setSessionName(st.sessionName);
|
||||
setExecCode(st.execCode ?? '');
|
||||
setValidateCode(st.validateCode ?? '');
|
||||
})
|
||||
@@ -46,10 +43,6 @@ export function EditStepPage() {
|
||||
|
||||
const validate = (): boolean => {
|
||||
let valid = true;
|
||||
if (!sessionName.trim()) {
|
||||
setSessionError(t('steps.form_session_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (isNaN(Number(order)) || Number(order) < 0) {
|
||||
setOrderError(t('steps.form_order_invalid'));
|
||||
valid = false;
|
||||
@@ -67,7 +60,6 @@ export function EditStepPage() {
|
||||
order: Number(order),
|
||||
title: title.trim() || undefined,
|
||||
type,
|
||||
sessionName: sessionName.trim(),
|
||||
execCode: execCode.trim() || undefined,
|
||||
validateCode: validateCode.trim() || undefined,
|
||||
});
|
||||
@@ -124,17 +116,6 @@ export function EditStepPage() {
|
||||
onChange={(e) => setType(e.target.value as StepType)}
|
||||
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
|
||||
/>
|
||||
<Input
|
||||
label={t('steps.form_session')}
|
||||
placeholder={t('steps.form_session_placeholder')}
|
||||
value={sessionName}
|
||||
onChange={(e) => {
|
||||
setSessionName(e.target.value);
|
||||
setSessionError('');
|
||||
}}
|
||||
error={sessionError || undefined}
|
||||
required
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<textarea
|
||||
|
||||
@@ -117,7 +117,7 @@ export function ScenarioDetailPage() {
|
||||
{
|
||||
key: 'title',
|
||||
header: t('scenarios.step_title'),
|
||||
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{s.sessionName}</span>,
|
||||
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>,
|
||||
},
|
||||
{
|
||||
key: 'updated',
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { snippets } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateSnippetPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [codeError, setCodeError] = 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('snippets.form_name_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
setCodeError(t('snippets.form_code_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const snippet = await snippets.create({
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
code: code.trim(),
|
||||
});
|
||||
navigate(`/snippets/${snippet.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
|
||||
{ label: t('snippets.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('snippets.form_name')}
|
||||
placeholder={t('snippets.form_name_placeholder')}
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameError('');
|
||||
}}
|
||||
error={nameError || undefined}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
label={t('snippets.form_description')}
|
||||
placeholder={t('snippets.form_description_placeholder')}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<textarea
|
||||
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
|
||||
rows={14}
|
||||
value={code}
|
||||
onChange={(e) => {
|
||||
setCode(e.target.value);
|
||||
setCodeError('');
|
||||
}}
|
||||
placeholder={t('snippets.form_code_placeholder')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
{codeError && <span className={styles.fieldError}>{codeError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate('/snippets')}>
|
||||
{t('snippets.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t('snippets.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditSnippetPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [codeError, setCodeError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
snippets
|
||||
.get(Number(id))
|
||||
.then((s) => {
|
||||
setSnippet(s);
|
||||
setName(s.name);
|
||||
setDescription(s.description ?? '');
|
||||
setCode(s.code);
|
||||
})
|
||||
.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('snippets.form_name_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
setCodeError(t('snippets.form_code_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await snippets.update(Number(id), {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
code: code.trim(),
|
||||
});
|
||||
navigate(`/snippets/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
|
||||
{
|
||||
label: snippet?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/snippets/${id}`),
|
||||
},
|
||||
{ label: t('snippets.edit_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
|
||||
|
||||
{!loading && snippet && (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('snippets.form_name')}
|
||||
placeholder={t('snippets.form_name_placeholder')}
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameError('');
|
||||
}}
|
||||
error={nameError || undefined}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
label={t('snippets.form_description')}
|
||||
placeholder={t('snippets.form_description_placeholder')}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<textarea
|
||||
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
|
||||
rows={14}
|
||||
value={code}
|
||||
onChange={(e) => {
|
||||
setCode(e.target.value);
|
||||
setCodeError('');
|
||||
}}
|
||||
placeholder={t('snippets.form_code_placeholder')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
{codeError && <span className={styles.fieldError}>{codeError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/snippets/${id}`)}
|
||||
>
|
||||
{t('snippets.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t('snippets.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SnippetDetailPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
snippets
|
||||
.get(Number(id))
|
||||
.then(setSnippet)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!snippet) return;
|
||||
await snippets.remove(snippet.id);
|
||||
navigate('/snippets');
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
|
||||
{ label: snippet?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{snippet && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => navigate(`/snippets/${snippet.id}/edit`)}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
{t('snippets.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Trash2 size={14} />
|
||||
{t('snippets.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_snippet', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
|
||||
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
|
||||
|
||||
{snippet && (
|
||||
<>
|
||||
<div className={styles.detailMeta}>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
items={[
|
||||
{ term: t('snippets.field_id'), detail: snippet.id },
|
||||
{ term: t('snippets.field_name'), detail: snippet.name },
|
||||
{
|
||||
term: t('snippets.field_description'),
|
||||
detail: snippet.description ?? '—',
|
||||
},
|
||||
{
|
||||
term: t('snippets.field_created'),
|
||||
detail: <Timestamp value={snippet.createdAt} />,
|
||||
},
|
||||
{
|
||||
term: t('snippets.field_updated'),
|
||||
detail: <Timestamp value={snippet.updatedAt} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeader}>
|
||||
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<pre className={styles.codeBlock}>{snippet.code}</pre>
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Code, Pencil, Trash2, Plus } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, ContextMenu, Timestamp } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function SnippetCard({
|
||||
snippet,
|
||||
onDelete,
|
||||
}: {
|
||||
snippet: Snippet;
|
||||
onDelete: (id: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const header = (
|
||||
<div className={styles.envCardHeader}>
|
||||
<span className={styles.envCardName}>{snippet.name}</span>
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<ContextMenu
|
||||
align="right"
|
||||
trigger={
|
||||
<Button variant="ghost" size="sm" aria-label={t('snippets.menu_label')}>
|
||||
<Code size={14} />
|
||||
</Button>
|
||||
}
|
||||
items={[
|
||||
{
|
||||
label: t('snippets.action_edit'),
|
||||
icon: <Pencil size={14} />,
|
||||
onClick: () => navigate(`/snippets/${snippet.id}/edit`),
|
||||
},
|
||||
{
|
||||
label: t('snippets.action_delete'),
|
||||
icon: <Trash2 size={14} />,
|
||||
variant: 'danger',
|
||||
onClick: () => onDelete(snippet.id),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const footer = (
|
||||
<div className={styles.envCardFooter}>
|
||||
<span className={styles.envCardId}>#{snippet.id}</span>
|
||||
<Timestamp value={snippet.updatedAt} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={styles.envCard}
|
||||
header={header}
|
||||
headerVariant="primary"
|
||||
footer={footer}
|
||||
onClick={() => navigate(`/snippets/${snippet.id}`)}
|
||||
>
|
||||
{snippet.description && (
|
||||
<p className={styles.muted}>{snippet.description}</p>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function AddSnippetCard() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
return (
|
||||
<div className={styles.envCardAdd}>
|
||||
<Button variant="ghost" onClick={() => navigate('/snippets/new')}>
|
||||
<Plus size={16} />
|
||||
{t('snippets.action_add')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SnippetsPage() {
|
||||
const { t } = useTranslation();
|
||||
const [items, setItems] = useState<Snippet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = () => {
|
||||
snippets
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
await snippets.remove(id);
|
||||
load();
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('snippets.title') }]} />
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
|
||||
|
||||
{!loading && (
|
||||
<div className={styles.envGrid}>
|
||||
{items.map((s) => (
|
||||
<SnippetCard key={s.id} snippet={s} onDelete={handleDelete} />
|
||||
))}
|
||||
{items.length === 0 && (
|
||||
<p className={styles.muted}>{t('snippets.empty')}</p>
|
||||
)}
|
||||
<AddSnippetCard />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
'/environments': 'http://localhost:13000',
|
||||
'/credentials': 'http://localhost:13000',
|
||||
'/credentials': 'http://localhost:13000', '/snippets': 'http://localhost:13000', '/snippets': 'http://localhost:13000',
|
||||
'/sessions': 'http://localhost:13000',
|
||||
'/scenarios': 'http://localhost:13000',
|
||||
'/keys': 'http://localhost:13000',
|
||||
|
||||
@@ -19,6 +19,8 @@ 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";
|
||||
import { SnippetEntity } from "./snippet/snippet.entity";
|
||||
import { SnippetModule } from "./snippet/snippet.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -43,6 +45,7 @@ import { ScenarioModule } from "./scenario/scenario.module";
|
||||
ScenarioRunStepEntity,
|
||||
ScenarioRunLogEntity,
|
||||
ScenarioCredentialEntity,
|
||||
SnippetEntity,
|
||||
],
|
||||
synchronize: true,
|
||||
}),
|
||||
@@ -52,6 +55,7 @@ import { ScenarioModule } from "./scenario/scenario.module";
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
ScenarioModule,
|
||||
SnippetModule,
|
||||
McpModule,
|
||||
HealthModule,
|
||||
],
|
||||
|
||||
@@ -50,6 +50,8 @@ export class CodeExecutorService {
|
||||
getStepOutput?: (order: number) => Promise<unknown>,
|
||||
credentials?: Record<string, unknown>,
|
||||
environment?: EnvironmentUrls | null,
|
||||
snippets?: Record<string, string> | null,
|
||||
result?: unknown,
|
||||
): Promise<ExecResult> {
|
||||
const scriptLog: ScriptLogger =
|
||||
log ?? ((level, msg) => this.logger[level](msg));
|
||||
@@ -60,9 +62,22 @@ export class CodeExecutorService {
|
||||
|
||||
const credMap: Record<string, unknown> = credentials ?? {};
|
||||
const envUrls: EnvironmentUrls = environment ?? {};
|
||||
const snippetMap: Record<string, string> = snippets ?? {};
|
||||
|
||||
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
|
||||
// eslint-disable-next-line prefer-const
|
||||
let pageHelpers: Record<string, unknown>;
|
||||
|
||||
const fakeConsole = {
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
info: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
debug: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
};
|
||||
|
||||
try {
|
||||
const pageHelpers = {
|
||||
pageHelpers = {
|
||||
dumpDom: (selector?: string) => dumpDom(page, selector),
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
@@ -88,14 +103,27 @@ export class CodeExecutorService {
|
||||
}
|
||||
return value;
|
||||
},
|
||||
};
|
||||
|
||||
const fakeConsole = {
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
info: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
debug: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
/**
|
||||
* Runs a named snippet by name. Snippets receive the same page/context/helpers
|
||||
* as regular exec code, plus any positional args you pass.
|
||||
*
|
||||
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
|
||||
*/
|
||||
runSnippet: async (name: string, ...args: unknown[]): Promise<unknown> => {
|
||||
const snippetCode = snippetMap[name];
|
||||
if (snippetCode == null) {
|
||||
throw new Error(`Snippet "${name}" not found`);
|
||||
}
|
||||
const snippetFn = new Function(
|
||||
"page",
|
||||
"context",
|
||||
"helpers",
|
||||
"console",
|
||||
"snippetArgs",
|
||||
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
|
||||
);
|
||||
return snippetFn(page, context, pageHelpers, fakeConsole, args);
|
||||
},
|
||||
};
|
||||
|
||||
// Passing `console` as a named parameter shadows the global in the script scope.
|
||||
@@ -104,11 +132,12 @@ export class CodeExecutorService {
|
||||
"context",
|
||||
"helpers",
|
||||
"console",
|
||||
"result",
|
||||
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
|
||||
);
|
||||
this.logger.debug("Executing user code");
|
||||
const result = await fn(page, context, pageHelpers, fakeConsole);
|
||||
return { result };
|
||||
const execResult = await fn(page, context, pageHelpers, fakeConsole, result);
|
||||
return { result: execResult };
|
||||
} catch (err) {
|
||||
throw new InternalServerErrorException(
|
||||
`Code execution failed: ${(err as Error).message}`,
|
||||
|
||||
@@ -24,14 +24,14 @@ export class CreateScenarioStepDto {
|
||||
@IsIn(["login", "exec", "sign"])
|
||||
type: StepType;
|
||||
|
||||
@ApiProperty({
|
||||
description:
|
||||
"Session name used by this step. login steps create it; exec steps consume it.",
|
||||
@ApiPropertyOptional({
|
||||
description: "Session name (deprecated — browser is created automatically per run).",
|
||||
example: "my-session",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
sessionName: string;
|
||||
sessionName?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: "return await page.title();" })
|
||||
@IsOptional()
|
||||
|
||||
@@ -25,7 +25,7 @@ export class ScenarioStepExportDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
sessionName: string;
|
||||
sessionName: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
|
||||
@@ -14,10 +14,10 @@ import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||
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";
|
||||
import { SnippetService } from "../snippet/snippet.service";
|
||||
|
||||
interface ValidateResult {
|
||||
success: boolean;
|
||||
@@ -39,6 +39,8 @@ export class ScenarioSchedulerService {
|
||||
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>();
|
||||
// Cache snippet code map per run (built once when a run starts)
|
||||
private readonly runSnippets = new Map<number, Record<string, string>>();
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
@@ -49,9 +51,9 @@ export class ScenarioSchedulerService {
|
||||
private readonly runLogRepo: Repository<ScenarioRunLogEntity>,
|
||||
private readonly authService: AuthService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly scenarioService: ScenarioService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly snippetService: SnippetService,
|
||||
) {}
|
||||
|
||||
private persistLog(
|
||||
@@ -133,6 +135,11 @@ export class ScenarioSchedulerService {
|
||||
// Resolve environment from the first login step (best-effort)
|
||||
const envUrls = await this.resolveRunEnvironment(run.scenarioId);
|
||||
if (envUrls) this.runEnvironments.set(run.id, envUrls);
|
||||
// Pre-load snippet map
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({} as Record<string, string>));
|
||||
this.runSnippets.set(run.id, snippetMap);
|
||||
const traceId = crypto.randomUUID();
|
||||
void traceStorage.run({ traceId }, () =>
|
||||
this.processRunToCompletion(run.id),
|
||||
@@ -170,6 +177,7 @@ export class ScenarioSchedulerService {
|
||||
this.activeRuns.delete(runId);
|
||||
this.runCredentials.delete(runId);
|
||||
this.runEnvironments.delete(runId);
|
||||
this.runSnippets.delete(runId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,39 +207,20 @@ export class ScenarioSchedulerService {
|
||||
|
||||
// ── Shared browser per run ─────────────────────────────────────────────────
|
||||
|
||||
private async getOrCreateBrowserHandle(
|
||||
runId: number,
|
||||
sessionName: string,
|
||||
): Promise<BrowserHandle> {
|
||||
private async getOrCreateBrowserHandle(runId: number): Promise<BrowserHandle> {
|
||||
const existing = this.runBrowsers.get(runId);
|
||||
if (existing) return existing;
|
||||
|
||||
const session = await this.sessionService.findBySessionName(sessionName);
|
||||
if (!session) throw new Error(`Session not found: ${sessionName}`);
|
||||
|
||||
const cookies = JSON.parse(session.cookies) as Parameters<
|
||||
BrowserContext["addCookies"]
|
||||
>[0];
|
||||
const localStorageData: Record<string, string> = JSON.parse(
|
||||
session.localStorage,
|
||||
);
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
// TODO: env var move to config
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
await context.addCookies(cookies);
|
||||
await context.addInitScript((entries: Record<string, string>) => {
|
||||
for (const [k, v] of Object.entries(entries))
|
||||
window.localStorage.setItem(k, v);
|
||||
}, localStorageData);
|
||||
const page = await context.newPage();
|
||||
|
||||
const handle: BrowserHandle = { browser, context, page };
|
||||
this.runBrowsers.set(runId, handle);
|
||||
this.logger.log(`Run #${runId}: browser created (session: ${sessionName})`);
|
||||
this.logger.log(`Run #${runId}: browser created`);
|
||||
return handle;
|
||||
}
|
||||
|
||||
@@ -273,7 +262,7 @@ export class ScenarioSchedulerService {
|
||||
const loginResult = await this.authService.login(
|
||||
params.keyId,
|
||||
params.environmentName,
|
||||
step.sessionName,
|
||||
step.sessionName ?? undefined,
|
||||
);
|
||||
this.logger.log(
|
||||
`StepRun #${stepRun.id}: login OK, session=${loginResult.sessionName}`,
|
||||
@@ -282,7 +271,6 @@ export class ScenarioSchedulerService {
|
||||
if (step.validateCode) {
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(
|
||||
stepRun.runId,
|
||||
step.sessionName,
|
||||
);
|
||||
this.codeExecutor.validate(step.validateCode);
|
||||
const { result } = await this.codeExecutor.execute(
|
||||
@@ -293,6 +281,8 @@ export class ScenarioSchedulerService {
|
||||
this.makeGetStepOutput(stepRun),
|
||||
this.runCredentials.get(stepRun.runId),
|
||||
this.runEnvironments.get(stepRun.runId),
|
||||
this.runSnippets.get(stepRun.runId),
|
||||
null,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
@@ -312,11 +302,11 @@ export class ScenarioSchedulerService {
|
||||
this.codeExecutor.validate(step.execCode);
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(
|
||||
stepRun.runId,
|
||||
step.sessionName,
|
||||
);
|
||||
const getStepOutput = this.makeGetStepOutput(stepRun);
|
||||
const creds = this.runCredentials.get(stepRun.runId);
|
||||
const env = this.runEnvironments.get(stepRun.runId);
|
||||
const snips = this.runSnippets.get(stepRun.runId);
|
||||
const { result: execOutput } = await this.codeExecutor.execute(
|
||||
page,
|
||||
context,
|
||||
@@ -325,6 +315,7 @@ export class ScenarioSchedulerService {
|
||||
getStepOutput,
|
||||
creds,
|
||||
env,
|
||||
snips,
|
||||
);
|
||||
this.logger.log(`StepRun #${stepRun.id}: exec OK`);
|
||||
|
||||
@@ -338,6 +329,8 @@ export class ScenarioSchedulerService {
|
||||
getStepOutput,
|
||||
creds,
|
||||
env,
|
||||
snips,
|
||||
execOutput,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
@@ -363,7 +356,6 @@ export class ScenarioSchedulerService {
|
||||
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(
|
||||
stepRun.runId,
|
||||
step.sessionName,
|
||||
);
|
||||
await this.authService.signWithKey(params.keyId, page);
|
||||
this.logger.log(`StepRun #${stepRun.id}: sign OK`);
|
||||
@@ -378,6 +370,8 @@ export class ScenarioSchedulerService {
|
||||
this.makeGetStepOutput(stepRun),
|
||||
this.runCredentials.get(stepRun.runId),
|
||||
this.runEnvironments.get(stepRun.runId),
|
||||
this.runSnippets.get(stepRun.runId),
|
||||
null,
|
||||
);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? "Validation failed");
|
||||
|
||||
@@ -34,8 +34,8 @@ export class ScenarioStepEntity {
|
||||
@Column({ type: "text", nullable: true })
|
||||
title: string | null;
|
||||
|
||||
@Column({ type: "text" })
|
||||
sessionName: string;
|
||||
@Column({ type: "text", nullable: true })
|
||||
sessionName: string | null;
|
||||
|
||||
@Column({ type: "text", nullable: true })
|
||||
execCode: string | null;
|
||||
|
||||
@@ -14,6 +14,7 @@ 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";
|
||||
import { SnippetModule } from "../snippet/snippet.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -30,6 +31,7 @@ import { EnvironmentModule } from "../environment/environment.module";
|
||||
CodeExecutorModule,
|
||||
SessionModule,
|
||||
EnvironmentModule,
|
||||
SnippetModule,
|
||||
],
|
||||
controllers: [ScenarioController],
|
||||
providers: [ScenarioService, ScenarioSchedulerService],
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class CreateSnippetDto {
|
||||
@ApiProperty({ example: "clickLoginButton" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: "Clicks the login button and waits for navigation" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty({ example: "await page.click('#login-btn');\nawait page.waitForNavigation();" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
code: string;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class UpdateSnippetDto {
|
||||
@ApiPropertyOptional({ example: "clickLoginButton" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
code?: string;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { SnippetService, SnippetOrderBy } from "./snippet.service";
|
||||
import { CreateSnippetDto } from "./dto/create-snippet.dto";
|
||||
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
|
||||
@ApiTags("snippets")
|
||||
@Controller("snippets")
|
||||
export class SnippetController {
|
||||
constructor(private readonly snippetService: SnippetService) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: "Create a new snippet" })
|
||||
@ApiResponse({ status: 201, description: "Snippet created" })
|
||||
@ApiResponse({ status: 409, description: "Name already taken" })
|
||||
create(@Body() dto: CreateSnippetDto) {
|
||||
return this.snippetService.create(dto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: "List all snippets (paginated)" })
|
||||
@ApiResponse({ status: 200, description: "Paginated snippets" })
|
||||
findAll(@Query() query: PaginationQueryDto<SnippetOrderBy>) {
|
||||
return this.snippetService.findAll(query);
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "Get snippet by ID" })
|
||||
@ApiResponse({ status: 200, description: "Snippet record" })
|
||||
@ApiResponse({ status: 404, description: "Snippet not found" })
|
||||
findOne(@Param("id", ParseIntPipe) id: number) {
|
||||
return this.snippetService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@ApiOperation({ summary: "Update a snippet" })
|
||||
@ApiResponse({ status: 200, description: "Snippet updated" })
|
||||
@ApiResponse({ status: 404, description: "Snippet not found" })
|
||||
@ApiResponse({ status: 409, description: "Name already taken" })
|
||||
update(
|
||||
@Param("id", ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateSnippetDto,
|
||||
) {
|
||||
return this.snippetService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: "Delete a snippet" })
|
||||
@ApiResponse({ status: 204, description: "Snippet deleted" })
|
||||
@ApiResponse({ status: 404, description: "Snippet not found" })
|
||||
remove(@Param("id", ParseIntPipe) id: number) {
|
||||
return this.snippetService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
|
||||
@Entity("snippets")
|
||||
export class SnippetEntity {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
/** Unique identifier used to call the snippet: helpers.runSnippet('mySnippet', ...) */
|
||||
@Column({ unique: true })
|
||||
name: string;
|
||||
|
||||
@Column("text", { nullable: true })
|
||||
description: string | null;
|
||||
|
||||
/**
|
||||
* The snippet body — written as a regular async function body.
|
||||
* It receives the same `page`, `context`, and `helpers` as exec code, plus
|
||||
* any positional `...args` passed by the caller.
|
||||
*/
|
||||
@Column("text")
|
||||
code: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { SnippetEntity } from "./snippet.entity";
|
||||
import { SnippetService } from "./snippet.service";
|
||||
import { SnippetController } from "./snippet.controller";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([SnippetEntity])],
|
||||
controllers: [SnippetController],
|
||||
providers: [SnippetService],
|
||||
exports: [SnippetService],
|
||||
})
|
||||
export class SnippetModule {}
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
import { SnippetEntity } from "./snippet.entity";
|
||||
import { CreateSnippetDto } from "./dto/create-snippet.dto";
|
||||
import { UpdateSnippetDto } from "./dto/update-snippet.dto";
|
||||
import {
|
||||
PaginationQueryDto,
|
||||
PaginatedResult,
|
||||
} from "../common/dto/pagination.dto";
|
||||
|
||||
export type SnippetOrderBy = "id" | "name" | "createdAt" | "updatedAt";
|
||||
|
||||
@Injectable()
|
||||
export class SnippetService {
|
||||
constructor(
|
||||
@InjectRepository(SnippetEntity)
|
||||
private readonly repo: Repository<SnippetEntity>,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateSnippetDto): Promise<SnippetEntity> {
|
||||
const existing = await this.repo.findOneBy({ name: dto.name });
|
||||
if (existing) {
|
||||
throw new ConflictException(`Snippet "${dto.name}" already exists`);
|
||||
}
|
||||
return this.repo.save(
|
||||
this.repo.create({ ...dto, description: dto.description ?? null }),
|
||||
);
|
||||
}
|
||||
|
||||
async findAll(
|
||||
query: PaginationQueryDto<SnippetOrderBy> = {},
|
||||
): Promise<PaginatedResult<SnippetEntity>> {
|
||||
const page = query.page ?? 1;
|
||||
const limit = query.limit ?? 50;
|
||||
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<SnippetEntity> {
|
||||
const snippet = await this.repo.findOneBy({ id });
|
||||
if (!snippet) throw new NotFoundException(`Snippet ${id} not found`);
|
||||
return snippet;
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateSnippetDto): Promise<SnippetEntity> {
|
||||
const snippet = await this.findOne(id);
|
||||
if (dto.name && dto.name !== snippet.name) {
|
||||
const conflict = await this.repo.findOneBy({ name: dto.name });
|
||||
if (conflict) throw new ConflictException(`Snippet "${dto.name}" already exists`);
|
||||
}
|
||||
Object.assign(snippet, dto);
|
||||
return this.repo.save(snippet);
|
||||
}
|
||||
|
||||
async remove(id: number): Promise<void> {
|
||||
await this.findOne(id);
|
||||
await this.repo.delete(id);
|
||||
}
|
||||
|
||||
/** Returns a name→code map for all snippets (used by the executor). */
|
||||
async buildSnippetMap(): Promise<Record<string, string>> {
|
||||
const { data } = await this.findAll({ limit: 1000 });
|
||||
return Object.fromEntries(data.map((s) => [s.name, s.code]));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user