Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bba6eb2f94 | ||
|
|
531754c3fa | ||
|
|
cafc126d1b | ||
|
|
f24a1b7dd5 | ||
|
|
63c2df96f1 | ||
|
|
23fa302b25 | ||
|
|
f43d902297 | ||
|
|
2129708819 | ||
|
|
6e9b99e415 | ||
|
|
8aadbd25fb | ||
|
|
9f341719ef | ||
|
|
5de9272281 | ||
|
|
a6d468bd2c | ||
|
|
b0f2c72b5f |
No files matched your search
+36
-21
@@ -1,26 +1,41 @@
|
|||||||
NODE_ENV=development
|
## Optional overrides: copy to .env and uncomment the settings you need.
|
||||||
PORT=3000
|
## Every setting has a default (shown below), so liqa runs without a .env file.
|
||||||
|
##
|
||||||
|
## Lines starting with "##" are descriptions.
|
||||||
|
## Lines starting with "# " are settings: remove the "# " to enable one.
|
||||||
|
|
||||||
# Directory (relative to cwd) containing *.json key descriptors
|
## production in the Docker image; also selects the default CORS origins
|
||||||
KEYS_DIR=keys
|
# NODE_ENV=development
|
||||||
|
# PORT=3000
|
||||||
|
|
||||||
# SQLite database path
|
## Origins allowed to call the API cross-origin (comma separated). Default: the
|
||||||
DB_PATH=data/sessions.db
|
## Vite dev server (http://localhost:5173) in development, the compose port
|
||||||
|
## (http://localhost:13000) in production
|
||||||
|
# CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||||
|
|
||||||
# Chromium binary to use instead of Playwright's own (not needed in Docker,
|
## SQLite database path
|
||||||
# which ships Playwright's chromium-headless-shell)
|
# DB_PATH=data/liqa.db
|
||||||
|
|
||||||
|
## Stored scenario files and run artifacts (downloads, failure dumps, traces)
|
||||||
|
# FILES_DIR=data/files
|
||||||
|
## Days to keep run artifacts before they are deleted
|
||||||
|
# FILE_RUN_EXPIRATION_DAYS=7
|
||||||
|
## When expired files are deleted (cron expression)
|
||||||
|
# FILE_CLEANUP_CRON=0 3 * * *
|
||||||
|
|
||||||
|
## Close open sessions that have been idle for longer than this many minutes
|
||||||
|
# SESSION_IDLE_TIMEOUT_MINUTES=30
|
||||||
|
## Delete closed sessions whose updatedAt is older than this many days
|
||||||
|
# SESSION_DELETE_CLOSED_DAYS=7
|
||||||
|
|
||||||
|
## Playwright trace recording for scenario runs: on | retain-on-failure | off
|
||||||
|
## (traces often reach ~10 MB per run; can be overridden per run in the run modal)
|
||||||
|
# PLAYWRIGHT_TRACE_MODE=off
|
||||||
|
|
||||||
|
## Chromium binary to use instead of Playwright's own (not needed in Docker,
|
||||||
|
## which ships Playwright's chromium-headless-shell)
|
||||||
# PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
# PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||||
|
|
||||||
# Session lifecycle
|
## Directory with the built client to serve at / (the Docker image sets it to
|
||||||
# Close open sessions that have been idle for longer than this many minutes
|
## "client"; leave unset to not serve the UI, e.g. when using the Vite dev server)
|
||||||
SESSION_IDLE_TIMEOUT_MINUTES=30
|
# CLIENT_DIR=client
|
||||||
# Delete closed sessions whose updatedAt is older than this many days
|
|
||||||
SESSION_DELETE_CLOSED_DAYS=7
|
|
||||||
|
|
||||||
# Playwright trace recording for scenario runs: on | retain-on-failure | off
|
|
||||||
# (traces often reach ~10 MB per run; can be overridden per run in the run modal)
|
|
||||||
PLAYWRIGHT_TRACE_MODE=off
|
|
||||||
|
|
||||||
# Directory with the built client to serve at / (set to "client" in the Docker image;
|
|
||||||
# leave empty to not serve the UI, e.g. when using the Vite dev server)
|
|
||||||
# CLIENT_DIR=
|
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Code quality checks on master and pull requests. On a push to master that
|
||||||
|
# changes the version in the root package.json, also builds the Docker image
|
||||||
|
# and pushes it to this Gitea instance's container registry, tagged with that
|
||||||
|
# version and `latest`.
|
||||||
|
#
|
||||||
|
# Needs a repository (or owner) secret REGISTRY_TOKEN: a Gitea access token
|
||||||
|
# with package write access for the repository owner. The registry host is
|
||||||
|
# set explicitly below rather than taken from the server URL, which is the
|
||||||
|
# address the runner was registered with and may be internal-only.
|
||||||
|
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: git.hq.ars9.space
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
server:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci -w server
|
||||||
|
- name: Lint
|
||||||
|
run: npm run -w server lint -- --max-warnings=0
|
||||||
|
- name: Type-check
|
||||||
|
run: npx tsc --noEmit -p server/tsconfig.json
|
||||||
|
- name: Test
|
||||||
|
run: npm test -w server
|
||||||
|
- name: Build
|
||||||
|
run: npm run -w server build
|
||||||
|
|
||||||
|
client:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci -w client
|
||||||
|
- name: Lint
|
||||||
|
run: npm run -w client lint -- --max-warnings=0
|
||||||
|
- name: Build
|
||||||
|
run: npm run -w client build
|
||||||
|
- name: Install headless Chromium for Storybook tests
|
||||||
|
run: npx playwright install --with-deps --only-shell chromium
|
||||||
|
- name: Storybook tests
|
||||||
|
run: npm run -w client test:storybook
|
||||||
|
|
||||||
|
# Compares the root package.json version with the one before the push
|
||||||
|
version:
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
version: ${{ steps.check.outputs.version }}
|
||||||
|
changed: ${{ steps.check.outputs.changed }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- id: check
|
||||||
|
env:
|
||||||
|
BEFORE: ${{ github.event.before }}
|
||||||
|
run: |
|
||||||
|
version=$(node -p "require('./package.json').version")
|
||||||
|
previous=""
|
||||||
|
if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
|
||||||
|
previous=$(git show "${BEFORE}:package.json" | node -p "JSON.parse(require('fs').readFileSync(0, 'utf8')).version")
|
||||||
|
fi
|
||||||
|
echo "version: ${previous:-none} -> ${version}"
|
||||||
|
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||||
|
if [ "$version" != "$previous" ]; then
|
||||||
|
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
image:
|
||||||
|
needs: [server, client, version]
|
||||||
|
if: needs.version.outputs.changed == 'true'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.version.outputs.version }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Log in to the registry
|
||||||
|
env:
|
||||||
|
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
OWNER: ${{ github.repository_owner }}
|
||||||
|
run: |
|
||||||
|
echo "IMAGE=${REGISTRY}/$(echo "${GITHUB_REPOSITORY}" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_ENV"
|
||||||
|
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$OWNER" --password-stdin
|
||||||
|
- name: Build
|
||||||
|
run: docker build --build-arg VERSION="${VERSION}" -t "${IMAGE}:${VERSION}" -t "${IMAGE}:latest" .
|
||||||
|
- name: Push
|
||||||
|
run: |
|
||||||
|
docker push "${IMAGE}:${VERSION}"
|
||||||
|
docker push "${IMAGE}:latest"
|
||||||
+122
@@ -2,6 +2,128 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented in this file.
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
## 1.22.2 - 2026-10-01
|
||||||
|
|
||||||
|
Changes since 1.22.1:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- MIT license (`LICENSE`), declared in all `package.json` files and the README.
|
||||||
|
- The Docker image includes the license notices of everything it ships: `scripts/third-party-licenses.mjs` collects the license of every production dependency of the client and server, the Node.js license is added, and the result is served at `/licenses.txt`, linked as "Licenses" in the sidebar footer.
|
||||||
|
- OCI image labels for title, version, license and source; CI passes the version as the `VERSION` build arg.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- The Docker image keeps packages' `LICENSE.md`/`NOTICE.md` files, which the 1.22.1 slimming step deleted along with other Markdown files.
|
||||||
|
|
||||||
|
## 1.22.1 - 2026-10-01
|
||||||
|
|
||||||
|
Changes since 1.22.0:
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The Docker image is about 20% smaller (1.09 GB → 876 MB on disk, 251 MB → 220 MB compressed). Production dependencies and Chromium are installed in a separate stage that drops files nothing loads at runtime (source maps, TypeScript sources and declarations, docs, TypeORM's browser build, better-sqlite3's C sources, Playwright's ffmpeg). The runtime image is `debian:bookworm-slim` with only the `node` binary, so it no longer contains `npm`, `npx`, `yarn` or `corepack`.
|
||||||
|
|
||||||
|
## 1.22.0 - 2026-10-01
|
||||||
|
|
||||||
|
Changes since 1.21.1:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- The Export Scenario dialog lists the snippets the scenario uses (including ones used only through other snippets), all checked by default. A selected snippet is exported once per version the scenario uses: the latest for `runSnippet("alias")`, plus each version pinned with `alias@N`. `GET /scenarios/:id/export` takes the new `snippetIds` query parameter for this.
|
||||||
|
- The Export Scenario dialog shows the scenario version next to its name and id.
|
||||||
|
|
||||||
|
## 1.21.1 - 2026-10-01
|
||||||
|
|
||||||
|
Changes since 1.21.0:
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The credential page hides the credential data when it opens; a Reveal button shows it and Hide hides it again. The data is not rendered on the page until revealed.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- A `RevealableCodeBlock` UI component (a CodeBlock that starts hidden behind a Reveal/Hide button), with a Storybook story.
|
||||||
|
|
||||||
|
## 1.21.0 - 2026-10-01
|
||||||
|
|
||||||
|
Changes since 1.20.2:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- UUID badges show a small colored circle in front of the short id. Its color comes from the first 6 hex digits of the UUID, so the same id always gets the same color, and its border uses the badge text color to stay visible in both themes.
|
||||||
|
- UUID badges get lighter on hover to show they can be clicked.
|
||||||
|
- `Badge` accepts an optional `className`.
|
||||||
|
- A Storybook "Colors" story for UuidBadge with six sample ids and a button to randomize them.
|
||||||
|
|
||||||
|
## 1.20.2 - 2026-09-30
|
||||||
|
|
||||||
|
Changes since 1.20.1:
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Text contrast now meets WCAG AA (4.5:1) in both themes:
|
||||||
|
- the "Live" refresh label and the table sort icon use a new `--color-primary-text` token (dark lime in the light theme) instead of the light lime brand color;
|
||||||
|
- the idle refresh label is no longer dimmed with opacity;
|
||||||
|
- the light theme's danger button is a little darker, and the dark theme's danger hover is lighter so its dark text stays readable;
|
||||||
|
- syntax highlighting colors are defined per theme (`--hl-*` tokens), darker in the light theme;
|
||||||
|
- muted text is slightly darker in the light theme.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- A Storybook "Accessibility / Contrast" page that measures the contrast of the most contrast-prone components in both themes.
|
||||||
|
- Storybook accessibility checks now fail the tests on violations (`a11y.test: 'error'`). The Colors story shows each token's current value per theme and includes the syntax colors.
|
||||||
|
|
||||||
|
## 1.20.1 - 2026-09-30
|
||||||
|
|
||||||
|
Changes since 1.20.0:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Storybook stories for AutoRefreshIndicator, CodeBlock, CodeEditor, MarkdownContent, Modal, Notification, Search, Textarea, Toast and UuidBadge, with interaction tests where the component has behavior. The DescriptionList story covers all four layouts.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated all client and server dependencies to the latest versions within their ranges, including React 19.3, Storybook 10.6, NestJS 11.2, TypeORM 0.3.31 and Playwright 1.63 (the Docker image now ships HeadlessChrome 153).
|
||||||
|
- The Storybook tests are part of the pre-commit checks.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Code flagged by the stricter React hooks lint rules: the runs list no longer writes refs during render, and the scenario list, scenario files and sessions list no longer set state synchronously inside effects.
|
||||||
|
|
||||||
|
## 1.20.0 - 2026-09-30
|
||||||
|
|
||||||
|
Changes since 1.19.3:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Database migrations: the SQLite schema is now managed by TypeORM migrations (`server/src/database/migrations/`) instead of `synchronize`. The Docker container applies pending migrations before starting the server, and the server refuses to start while migrations are pending.
|
||||||
|
- `npm -w server run migration:run`, `migration:show` and `migration:generate` scripts; the workflow for schema changes is described in `docs/development.md`.
|
||||||
|
- A test that fails when an entity changes without a matching migration.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Databases created before migrations (by `synchronize`) are adopted automatically: the initial migration is recorded as applied without changing them.
|
||||||
|
- Tests now build their database from the migrations instead of `synchronize`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Startup failures were logged but the process exited with code 0; they now exit with code 1.
|
||||||
|
|
||||||
|
## 1.19.3 - 2026-09-30
|
||||||
|
|
||||||
|
Changes since 1.19.2:
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The Docker image runs with `NODE_ENV=production`.
|
||||||
|
- The origins allowed to call the API cross-origin depend on `NODE_ENV`: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) in development, the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) in production. The new `CORS_ORIGINS` setting (comma separated) overrides both. A `NODE_ENV=development` in `.env` overrides the image's production mode.
|
||||||
|
- `.env` is optional: compose loads it only when it exists, and every setting in `.env.example` is commented out and shows its default.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- The unused `KEYS_DIR` setting and the `./keys` mount in `compose.yaml`.
|
||||||
|
|
||||||
## 1.19.2 - 2026-09-30
|
## 1.19.2 - 2026-09-30
|
||||||
|
|
||||||
Changes since 1.19.1:
|
Changes since 1.19.1:
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
# liqa
|
# liqa
|
||||||
|
|
||||||
liqa (liquio-qa-bot) is a QA automation service for Liquio environments. It stores **scenarios** (ordered Playwright steps), **snippets** (reusable code run via `context.runSnippet`), **environments**, **credentials** and **sessions**, and runs scenarios in headless Chromium. Scenarios and snippets are versioned; each run records the scenario version it executed.
|
liqa is a browser automation and QA service for web applications. It stores **scenarios** (ordered Playwright steps), **snippets** (reusable code run via `context.runSnippet`), **environments**, **credentials** and **sessions**, and runs scenarios in headless Chromium. Scenarios and snippets are versioned; each run records the scenario version it executed.
|
||||||
|
|
||||||
It is an npm workspace with two packages:
|
It is an npm workspace with two packages:
|
||||||
|
|
||||||
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM (`synchronize: true`, so entity changes alter the schema on startup - there are no migrations). REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`.
|
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM; the schema is managed by migrations in `server/src/database/migrations/` (see "Database migrations" in `docs/development.md`). Any entity change needs a generated migration - `test/migrations.spec.ts` fails otherwise. REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`.
|
||||||
- `client/` - React 19 + Vite SPA (i18n strings in `client/src/i18n/locales/en.json`).
|
- `client/` - React 19 + Vite SPA (i18n strings in `client/src/i18n/locales/en.json`).
|
||||||
|
|
||||||
## Docs
|
## Docs
|
||||||
@@ -20,11 +20,11 @@ It is an npm workspace with two packages:
|
|||||||
|
|
||||||
## Default deployment (docker compose)
|
## Default deployment (docker compose)
|
||||||
|
|
||||||
`compose.yaml` at the repo root runs a single `liqa` container, built from the root `Dockerfile`, at http://localhost:13000. The server serves everything: the UI at `/` (the built client, via `CLIENT_DIR`), the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. It reads `.env` and mounts `./data` (SQLite DB `data/liqa.db` + stored files) and `./keys`.
|
`compose.yaml` at the repo root runs a single `liqa` container, built from the root `Dockerfile`, at http://localhost:13000. The server serves everything: the UI at `/` (the built client, via `CLIENT_DIR`), the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. It reads `.env` if present (optional - every setting has a default) and mounts `./data` (SQLite DB `data/liqa.db` + stored files).
|
||||||
|
|
||||||
Rebuild and restart: `docker compose up -d --build`. Check with `docker compose ps`, `curl localhost:13000/health` and `docker compose logs liqa`.
|
Rebuild and restart: `docker compose up -d --build`. Check with `docker compose ps`, `curl localhost:13000/health` and `docker compose logs liqa`.
|
||||||
|
|
||||||
The live database is `data/liqa.db`. Because the schema is synced on startup, back it up before deploying entity changes.
|
The live database is `data/liqa.db`. The container applies pending migrations before starting the server, so back it up before deploying a release with new migrations.
|
||||||
|
|
||||||
## Code quality
|
## Code quality
|
||||||
|
|
||||||
@@ -34,10 +34,11 @@ Before committing, run and pass all of these (and report the results):
|
|||||||
# server
|
# server
|
||||||
cd server && npm run lint && npx tsc --noEmit -p tsconfig.json && npm test && npm run build
|
cd server && npm run lint && npx tsc --noEmit -p tsconfig.json && npm test && npm run build
|
||||||
# client
|
# client
|
||||||
cd client && npm run lint && npm run build
|
cd client && npm run lint && npm run build && npm run test:storybook
|
||||||
```
|
```
|
||||||
|
|
||||||
- Lint must stay clean in both packages (no errors, no warnings).
|
- Lint must stay clean in both packages (no errors, no warnings).
|
||||||
|
- `test:storybook` runs every story in `client/.storybook/stories/` in headless Chromium (needs `npx playwright install --only-shell chromium` once, and again after Playwright updates). Add or update a story when adding or changing a `client/src/ui/` component.
|
||||||
- Don't run prettier over whole existing files; several aren't prettier-clean and it produces unrelated diffs. Format only new files or the lines you changed.
|
- Don't run prettier over whole existing files; several aren't prettier-clean and it produces unrelated diffs. Format only new files or the lines you changed.
|
||||||
- Server tests use an in-memory DB, a Playwright mock (`server/test/__mocks__/playwright.ts`), and a temporary files directory per test app (see `server/test/app.harness.ts`).
|
- Server tests use an in-memory DB, a Playwright mock (`server/test/__mocks__/playwright.ts`), and a temporary files directory per test app (see `server/test/app.harness.ts`).
|
||||||
- Import Node.js built-in modules with the `node:` prefix (`node:fs`, `node:path`, `node:crypto`, ...).
|
- Import Node.js built-in modules with the `node:` prefix (`node:fs`, `node:path`, `node:crypto`, ...).
|
||||||
|
|||||||
+79
-9
@@ -28,8 +28,73 @@ COPY server/tsconfig*.json ./server/
|
|||||||
COPY server/src ./server/src
|
COPY server/src ./server/src
|
||||||
RUN npm run -w server build
|
RUN npm run -w server build
|
||||||
|
|
||||||
|
# ── Runtime dependencies ──────────────────────────────────────────────────────
|
||||||
|
FROM node:24-slim AS runtime-deps
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
COPY server/package.json ./server/
|
||||||
|
|
||||||
|
# Production dependencies and Playwright's headless-only Chromium build,
|
||||||
|
# matching the installed Playwright version. All browser launches are
|
||||||
|
# headless, so the full desktop Chromium (GTK, Mesa/LLVM, icon themes) isn't
|
||||||
|
# needed, and neither is ffmpeg (only used for video recording).
|
||||||
|
#
|
||||||
|
# Then drop what nothing loads at runtime: source maps, TypeScript sources and
|
||||||
|
# declarations, docs (but not license files), TypeORM's browser build and
|
||||||
|
# better-sqlite3's C sources (the addon is already compiled).
|
||||||
|
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||||
|
RUN npm ci --omit=dev -w server \
|
||||||
|
&& npx playwright install --only-shell chromium \
|
||||||
|
&& rm -rf /ms-playwright/ffmpeg-* \
|
||||||
|
&& find node_modules -type f \( \
|
||||||
|
-name '*.map' -o -name '*.ts' -o -name '*.mts' -o -name '*.cts' \
|
||||||
|
-o \( \( -iname '*.md' -o -iname '*.markdown' \) \
|
||||||
|
! -iname 'licen[cs]e*' ! -iname 'notice*' ! -iname 'copying*' \) \
|
||||||
|
\) -delete \
|
||||||
|
&& rm -rf node_modules/typeorm/browser \
|
||||||
|
node_modules/better-sqlite3/deps \
|
||||||
|
node_modules/better-sqlite3/src
|
||||||
|
|
||||||
|
# ── License notices ───────────────────────────────────────────────────────────
|
||||||
|
# One file with the project's LICENSE and the license of everything the image
|
||||||
|
# ships: the production dependencies of both workspaces (the client's are
|
||||||
|
# bundled into its build, so their license files aren't in the image
|
||||||
|
# otherwise) and the Node.js binary, whose LICENSE the node image doesn't
|
||||||
|
# include.
|
||||||
|
FROM node:24-slim AS licenses
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json LICENSE ./
|
||||||
|
COPY client/package.json ./client/
|
||||||
|
COPY server/package.json ./server/
|
||||||
|
COPY scripts/third-party-licenses.mjs ./scripts/
|
||||||
|
RUN npm ci --omit=dev --ignore-scripts \
|
||||||
|
&& node scripts/third-party-licenses.mjs > licenses.txt \
|
||||||
|
&& node -e ' \
|
||||||
|
const url = `https://raw.githubusercontent.com/nodejs/node/v${process.versions.node}/LICENSE`; \
|
||||||
|
fetch(url).then(async (r) => { \
|
||||||
|
if (!r.ok) throw new Error(`${url}: ${r.status}`); \
|
||||||
|
const rule = "-".repeat(79); \
|
||||||
|
process.stdout.write(`\n${rule}\n\nnode@${process.versions.node}\nLicense: MIT\n\n${(await r.text()).trim()}\n`); \
|
||||||
|
}).catch((e) => { console.error(e.message); process.exit(1); });' >> licenses.txt
|
||||||
|
|
||||||
# ── Runtime ───────────────────────────────────────────────────────────────────
|
# ── Runtime ───────────────────────────────────────────────────────────────────
|
||||||
FROM node:24-slim AS runtime
|
# Plain Debian with just the node binary: npm, yarn, corepack and the C
|
||||||
|
# headers that come with the node image aren't needed to run the app.
|
||||||
|
FROM debian:bookworm-slim AS runtime
|
||||||
|
|
||||||
|
# Set by CI from the root package.json version
|
||||||
|
ARG VERSION=dev
|
||||||
|
LABEL org.opencontainers.image.title="liqa" \
|
||||||
|
org.opencontainers.image.version="${VERSION}" \
|
||||||
|
org.opencontainers.image.licenses="MIT" \
|
||||||
|
org.opencontainers.image.source="https://git.hq.ars9.space/ars9/liqa"
|
||||||
|
|
||||||
|
# Runtime only: in the build stages it would make npm ci skip devDependencies
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
# Shared libraries chrome-headless-shell links against (from `ldd`), plus
|
# Shared libraries chrome-headless-shell links against (from `ldd`), plus
|
||||||
# fontconfig and basic fonts for text rendering. Playwright's `--with-deps`
|
# fontconfig and basic fonts for text rendering. Playwright's `--with-deps`
|
||||||
@@ -60,28 +125,33 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
libxrandr2 \
|
libxrandr2 \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY --from=runtime-deps /usr/local/bin/node /usr/local/bin/node
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
COPY server/package.json ./server/
|
COPY server/package.json ./server/
|
||||||
|
|
||||||
# Playwright's headless-only Chromium build, matching the installed Playwright
|
|
||||||
# version. All browser launches are headless, so the full desktop Chromium
|
|
||||||
# (GTK, Mesa/LLVM, icon themes) isn't needed.
|
|
||||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||||
RUN npm ci --omit=dev -w server \
|
COPY --from=runtime-deps /ms-playwright /ms-playwright
|
||||||
&& npx playwright install --only-shell chromium \
|
COPY --from=runtime-deps /app/node_modules ./node_modules
|
||||||
&& npm cache clean --force
|
|
||||||
|
|
||||||
COPY --from=server-build /app/server/dist ./dist
|
COPY --from=server-build /app/server/dist ./dist
|
||||||
COPY --from=client-build /app/client/dist ./client
|
COPY --from=client-build /app/client/dist ./client
|
||||||
|
|
||||||
|
# The project's license, and every shipped component's license notices (also
|
||||||
|
# served by the app at /licenses.txt)
|
||||||
|
COPY LICENSE ./
|
||||||
|
COPY --from=licenses /app/licenses.txt ./client/licenses.txt
|
||||||
|
|
||||||
# Serve the built client at / (see server/src/common/client-static.ts)
|
# Serve the built client at / (see server/src/common/client-static.ts)
|
||||||
ENV CLIENT_DIR=client
|
ENV CLIENT_DIR=client
|
||||||
|
|
||||||
# Runtime directories (keys and SQLite DB mounted via volumes)
|
# Runtime directory (SQLite DB and stored files, mounted as a volume)
|
||||||
RUN mkdir -p data
|
RUN mkdir -p data
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|
||||||
CMD ["node", "dist/main"]
|
# Apply pending database migrations, then start the server (which refuses to
|
||||||
|
# start while migrations are pending)
|
||||||
|
CMD ["sh", "-c", "node dist/database/migrate && exec node dist/main"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Andrii Arsenin
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -1,46 +1,48 @@
|
|||||||
# liquio-qa-bot
|
# liqa
|
||||||
|
|
||||||
A headless QA automation service for Liquio environments. Exposes an **MCP (Model Context Protocol)** server that lets AI agents define, run, and monitor multi-step browser test scenarios using [Playwright](https://playwright.dev/).
|
A browser automation and QA service for web applications. It stores multi-step browser scenarios, runs them with [Playwright](https://playwright.dev/) in headless Chromium, and keeps their results, logs and artifacts. Scenarios are managed from a web UI, a REST API, or an **MCP (Model Context Protocol)** server that lets AI agents define, run and debug them.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
|
||||||
|
|
||||||
|
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
The bot manages four core concepts:
|
|
||||||
|
|
||||||
| Concept | Description |
|
| Concept | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Environment** | A named set of URLs for a deployment target (e.g. `liquio-diia-stg`) |
|
| **Scenario** | An ordered list of steps (async Playwright JS) that run in sequence in one browser. Versioned: every content change creates a new version |
|
||||||
| **Key** | A JSON descriptor in `keys/` that points to an EDS key file + password |
|
| **Run** | One execution of a scenario version in an environment, with per-step status and output, logs, and run files (downloads, failure screenshots, Playwright traces) |
|
||||||
| **Session** | Saved browser state (cookies + localStorage) produced by a login |
|
| **Snippet** | Reusable, versioned code called from steps with `context.runSnippet("alias")` (or `"alias@N"` for a specific version) |
|
||||||
| **Scenario** | An ordered list of steps that run in sequence against a shared browser instance |
|
| **Environment** | A named set of key/value settings for a deployment target (URLs etc.), read with `context.getEnv(key)` |
|
||||||
|
| **Credential** | Secret data (e.g. a key file and password), assigned to scenarios under an alias and read with `context.getCredential(alias)` |
|
||||||
|
| **Session** | Saved browser state (cookies + localStorage), e.g. kept from a run with "save session" |
|
||||||
|
|
||||||
|
Scenarios, snippets, environments and credentials can be exported as YAML and imported back (one file may hold several of them).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Architecture
|
## Documentation
|
||||||
|
|
||||||
See [docs/architecture.md](docs/architecture.md).
|
- [docs/architecture.md](docs/architecture.md) - components, data model, client
|
||||||
|
- [docs/scenario.md](docs/scenario.md) - runs, the script `context` API, versioning, import/export, Playwright traces
|
||||||
|
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||||
|
- [docs/development.md](docs/development.md) - setup, configuration, running, testing, linting, Docker
|
||||||
|
- [CHANGELOG.md](CHANGELOG.md) - release notes
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Key descriptors
|
## License
|
||||||
|
|
||||||
See [docs/key-descriptors.md](docs/key-descriptors.md).
|
[MIT](LICENSE) © 2026 Andrii Arsenin
|
||||||
|
|
||||||
---
|
Third-party packages keep their own licenses. The Docker image includes all their notices, and the app serves them at `/licenses.txt` (linked as "Licenses" in the sidebar footer). See [docs/development.md](docs/development.md#licenses).
|
||||||
|
|
||||||
## MCP tools
|
|
||||||
|
|
||||||
See [docs/mcp.md](docs/mcp.md).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Scenario execution
|
|
||||||
|
|
||||||
See [docs/scenario.md](docs/scenario.md).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
See [docs/development.md](docs/development.md) for setup, running, testing, linting, and Docker instructions.
|
|
||||||
@@ -12,7 +12,7 @@ function getAbsolutePath(value: string) {
|
|||||||
return dirname(fileURLToPath(import.meta.resolve(`${value}/package.json`)));
|
return dirname(fileURLToPath(import.meta.resolve(`${value}/package.json`)));
|
||||||
}
|
}
|
||||||
const config: StorybookConfig = {
|
const config: StorybookConfig = {
|
||||||
stories: ['./stories/**/*.mdx', './stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
|
stories: ['./stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
|
||||||
addons: [
|
addons: [
|
||||||
getAbsolutePath('@storybook/addon-vitest'),
|
getAbsolutePath('@storybook/addon-vitest'),
|
||||||
getAbsolutePath('@storybook/addon-a11y'),
|
getAbsolutePath('@storybook/addon-a11y'),
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ const preview: Preview = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
a11y: {
|
a11y: {
|
||||||
test: 'todo',
|
// Accessibility violations (e.g. color contrast) fail the story's test
|
||||||
|
test: 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, fn, userEvent, within } from 'storybook/test';
|
||||||
|
import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator';
|
||||||
|
|
||||||
|
const meta: Meta<typeof AutoRefreshIndicator> = {
|
||||||
|
title: 'UI/AutoRefreshIndicator',
|
||||||
|
component: AutoRefreshIndicator,
|
||||||
|
parameters: { layout: 'centered' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
args: { onClick: fn() },
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof AutoRefreshIndicator>;
|
||||||
|
|
||||||
|
export const Active: Story = { args: { active: true, pulseKey: 1 } };
|
||||||
|
export const Idle: Story = { args: { active: false } };
|
||||||
|
export const Errored: Story = { args: { active: false, error: true } };
|
||||||
|
|
||||||
|
export const ClickToRefresh: Story = {
|
||||||
|
args: { active: false },
|
||||||
|
play: async ({ args, canvasElement }) => {
|
||||||
|
await userEvent.click(within(canvasElement).getByRole('button'));
|
||||||
|
await expect(args.onClick).toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect } from 'storybook/test';
|
||||||
|
import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock';
|
||||||
|
|
||||||
|
const meta: Meta<typeof CodeBlock> = {
|
||||||
|
title: 'UI/CodeBlock',
|
||||||
|
component: CodeBlock,
|
||||||
|
parameters: { layout: 'padded' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof CodeBlock>;
|
||||||
|
|
||||||
|
export const JavaScript: Story = {
|
||||||
|
args: {
|
||||||
|
language: 'javascript',
|
||||||
|
code: "const url = context.getEnv('BASE_URL');\nawait context.page.goto(url);\nreturn await context.page.title();",
|
||||||
|
},
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
// Highlighting splits the code into many spans: check the whole text and
|
||||||
|
// that highlighting actually happened
|
||||||
|
const code = canvasElement.querySelector('code');
|
||||||
|
await expect(code).toHaveTextContent('await context.page.goto(url);');
|
||||||
|
await expect(code?.querySelector('.hljs-keyword')).not.toBeNull();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Json: Story = {
|
||||||
|
args: {
|
||||||
|
language: 'json',
|
||||||
|
code: JSON.stringify({ status: 'pass', output: { title: 'Dashboard' } }, null, 2),
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { CodeEditor, type CodeEditorProps } from '../../src/ui/CodeEditor/CodeEditor';
|
||||||
|
|
||||||
|
// Monaco is loaded from a CDN at runtime, so these stories only check that the
|
||||||
|
// editor mounts; they have no interaction tests.
|
||||||
|
function ControlledEditor(
|
||||||
|
props: Omit<CodeEditorProps, 'value' | 'onChange'> & { initial: string },
|
||||||
|
) {
|
||||||
|
const { initial, ...rest } = props;
|
||||||
|
const [value, setValue] = useState(initial);
|
||||||
|
return <CodeEditor {...rest} value={value} onChange={setValue} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: Meta<typeof ControlledEditor> = {
|
||||||
|
title: 'UI/CodeEditor',
|
||||||
|
component: ControlledEditor,
|
||||||
|
parameters: { layout: 'padded' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof ControlledEditor>;
|
||||||
|
|
||||||
|
export const JavaScript: Story = {
|
||||||
|
args: {
|
||||||
|
language: 'javascript',
|
||||||
|
rows: 8,
|
||||||
|
initial:
|
||||||
|
"await context.page.goto(context.getEnv('BASE_URL'));\nreturn await context.page.title();",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WithError: Story = {
|
||||||
|
args: { language: 'javascript', rows: 4, error: true, initial: 'await context.page.goto(' },
|
||||||
|
};
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
import React from 'react';
|
import React, { useLayoutEffect, useRef, useState } from 'react';
|
||||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
|
||||||
const palette = [
|
const palette = [
|
||||||
{ name: 'Atlantis', token: '--color-primary', hex: '#9DD341', role: 'Primary / Action' },
|
{ name: 'Atlantis', token: '--color-primary', hex: '#9DD341', role: 'Primary / Action' },
|
||||||
|
{
|
||||||
|
name: 'Atlantis text',
|
||||||
|
token: '--color-primary-text',
|
||||||
|
hex: '#496904',
|
||||||
|
role: 'Primary as text / icon',
|
||||||
|
},
|
||||||
{ name: 'Outer Space', token: '--color-text', hex: '#2D3339', role: 'Text / Surface' },
|
{ name: 'Outer Space', token: '--color-text', hex: '#2D3339', role: 'Text / Surface' },
|
||||||
{ name: 'Kimberly', token: '--color-text-muted', hex: '#6650C0', role: 'Muted text / Info' },
|
{ name: 'Kimberly', token: '--color-text-muted', hex: '#634DBD', role: 'Muted text / Info' },
|
||||||
{ name: 'Powder Ash', token: '--color-border', hex: '#AFBFB9', role: 'Border / Neutral' },
|
{ name: 'Powder Ash', token: '--color-border', hex: '#AFBFB9', role: 'Border / Neutral' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -23,12 +29,23 @@ const semanticColors = [
|
|||||||
{ name: 'Running fg', token: '--color-running-fg', hex: '#6B4A00' },
|
{ name: 'Running fg', token: '--color-running-fg', hex: '#6B4A00' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const syntaxColors = [
|
||||||
|
{ name: 'Comment', token: '--hl-comment', hex: '#4F6557' },
|
||||||
|
{ name: 'Keyword', token: '--hl-keyword', hex: '#764E99' },
|
||||||
|
{ name: 'String / title', token: '--hl-string', hex: '#4F6821' },
|
||||||
|
{ name: 'Number', token: '--hl-number', hex: '#895403' },
|
||||||
|
{ name: 'Function', token: '--hl-function', hex: '#056980' },
|
||||||
|
{ name: 'Variable / params', token: '--hl-variable', hex: '#815354' },
|
||||||
|
{ name: 'Property', token: '--hl-property', hex: '#1D6971' },
|
||||||
|
{ name: 'Meta', token: '--hl-meta', hex: '#615B7E' },
|
||||||
|
];
|
||||||
|
|
||||||
const surfaceColors = [
|
const surfaceColors = [
|
||||||
{ name: 'Background', token: '--color-bg', hex: '#E6EDEA' },
|
{ name: 'Background', token: '--color-bg', hex: '#E6EDEA' },
|
||||||
{ name: 'Background subtle', token: '--color-bg-subtle', hex: '#D8E2DE' },
|
{ name: 'Background subtle', token: '--color-bg-subtle', hex: '#D8E2DE' },
|
||||||
{ name: 'Secondary', token: '--color-secondary', hex: '#EDF1EF' },
|
{ name: 'Secondary', token: '--color-secondary', hex: '#EDF1EF' },
|
||||||
{ name: 'Secondary hover', token: '--color-secondary-hover', hex: '#DFE6E3' },
|
{ name: 'Secondary hover', token: '--color-secondary-hover', hex: '#DFE6E3' },
|
||||||
{ name: 'Danger', token: '--color-danger', hex: '#D94F4F' },
|
{ name: 'Danger', token: '--color-danger', hex: '#CE4546' },
|
||||||
{ name: 'Primary fg', token: '--color-primary-fg', hex: '#2D3339' },
|
{ name: 'Primary fg', token: '--color-primary-fg', hex: '#2D3339' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -43,8 +60,27 @@ function Swatch({
|
|||||||
hex: string;
|
hex: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
}) {
|
}) {
|
||||||
|
// Show the token's current value (per theme) rather than a hard-coded copy
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const [value, setValue] = useState(hex);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const read = () => {
|
||||||
|
if (!ref.current) return;
|
||||||
|
const resolved = getComputedStyle(ref.current).getPropertyValue(token).trim();
|
||||||
|
if (resolved) setValue(resolved.toUpperCase());
|
||||||
|
};
|
||||||
|
read();
|
||||||
|
// Re-read when the theme toolbar switches data-theme on <html>
|
||||||
|
const observer = new MutationObserver(read);
|
||||||
|
observer.observe(document.documentElement, {
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ['data-theme'],
|
||||||
|
});
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [token]);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
ref={ref}
|
||||||
style={{
|
style={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
flexDirection: 'column',
|
flexDirection: 'column',
|
||||||
@@ -72,7 +108,7 @@ function Swatch({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
|
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
|
||||||
{hex}
|
{value}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
|
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
|
||||||
{token}
|
{token}
|
||||||
@@ -128,6 +164,11 @@ function ColorPalette() {
|
|||||||
<Swatch key={c.token} {...c} />
|
<Swatch key={c.token} {...c} />
|
||||||
))}
|
))}
|
||||||
</Section>
|
</Section>
|
||||||
|
<Section title="Syntax highlighting">
|
||||||
|
{syntaxColors.map((c) => (
|
||||||
|
<Swatch key={c.token} {...c} />
|
||||||
|
))}
|
||||||
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export default meta;
|
|||||||
type Story = StoryObj<typeof ContextMenu>;
|
type Story = StoryObj<typeof ContextMenu>;
|
||||||
|
|
||||||
const trigger = (
|
const trigger = (
|
||||||
<Button variant="ghost" size="sm">
|
<Button variant="ghost" size="sm" aria-label="Actions">
|
||||||
<Settings size={16} />
|
<Settings size={16} />
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,330 @@
|
|||||||
|
import React, { useLayoutEffect, useRef, useState } from 'react';
|
||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator';
|
||||||
|
import { Button } from '../../src/ui/Button/Button';
|
||||||
|
import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock';
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Text contrast review page (WCAG AA: 4.5:1 for normal text, 3:1 for large
|
||||||
|
* text) for the components where contrast is easiest to get wrong: light
|
||||||
|
* brand colors used as text, dimmed labels, colored buttons and syntax
|
||||||
|
* highlighting. Every sample is the real component, shown in both themes, and
|
||||||
|
* the contrast of each piece of text is measured live from the rendered
|
||||||
|
* colors - so this page stays accurate as the design tokens change.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ── Contrast measurement ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type Rgba = [number, number, number, number];
|
||||||
|
|
||||||
|
function parseColor(value: string): Rgba {
|
||||||
|
const parts = value.match(/[\d.]+/g)?.map(Number) ?? [0, 0, 0];
|
||||||
|
return [parts[0], parts[1], parts[2], parts[3] ?? 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
function luminance([r, g, b]: Rgba): number {
|
||||||
|
const channel = (c: number) => {
|
||||||
|
const s = c / 255;
|
||||||
|
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||||
|
};
|
||||||
|
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
function contrast(a: Rgba, b: Rgba): number {
|
||||||
|
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
||||||
|
return (hi + 0.05) / (lo + 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Blends `top` over an opaque `bottom`. */
|
||||||
|
function blend(top: Rgba, bottom: Rgba): Rgba {
|
||||||
|
const a = top[3];
|
||||||
|
return [0, 1, 2].map((i) => top[i] * a + bottom[i] * (1 - a)).concat(1) as Rgba;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Product of the `opacity` of `el` and its ancestors (e.g. a dimmed idle label). */
|
||||||
|
function opacityChain(el: Element): number {
|
||||||
|
let opacity = 1;
|
||||||
|
for (let node: Element | null = el; node; node = node.parentElement) {
|
||||||
|
opacity *= parseFloat(getComputedStyle(node).opacity);
|
||||||
|
}
|
||||||
|
return opacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The opaque color behind `el`, from its own and its ancestors' backgrounds. */
|
||||||
|
function effectiveBackground(el: Element): Rgba {
|
||||||
|
const layers: Rgba[] = [];
|
||||||
|
for (let node: Element | null = el; node; node = node.parentElement) {
|
||||||
|
const bg = parseColor(getComputedStyle(node).backgroundColor);
|
||||||
|
bg[3] *= opacityChain(node);
|
||||||
|
if (bg[3] > 0) layers.push(bg);
|
||||||
|
if (bg[3] >= 1) break;
|
||||||
|
}
|
||||||
|
return layers.reduceRight<Rgba>((under, layer) => blend(layer, under), [255, 255, 255, 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hex = ([r, g, b]: Rgba) =>
|
||||||
|
'#' + [r, g, b].map((c) => Math.round(c).toString(16).padStart(2, '0')).join('');
|
||||||
|
|
||||||
|
interface Measurement {
|
||||||
|
text: string;
|
||||||
|
fg: string;
|
||||||
|
bg: string;
|
||||||
|
ratio: number;
|
||||||
|
required: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Measures every element that directly contains visible text. */
|
||||||
|
function measure(root: HTMLElement): Measurement[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const results: Measurement[] = [];
|
||||||
|
for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {
|
||||||
|
const text = Array.from(el.childNodes)
|
||||||
|
.filter((n) => n.nodeType === Node.TEXT_NODE)
|
||||||
|
.map((n) => n.textContent ?? '')
|
||||||
|
.join('')
|
||||||
|
.trim();
|
||||||
|
if (!text || el.closest('[aria-hidden="true"]')) continue;
|
||||||
|
const style = getComputedStyle(el);
|
||||||
|
const fontSize = parseFloat(style.fontSize);
|
||||||
|
const bold = Number(style.fontWeight) >= 700;
|
||||||
|
// WCAG "large text": at least 24px, or 18.66px bold
|
||||||
|
const required = fontSize >= 24 || (bold && fontSize >= 18.66) ? 3 : 4.5;
|
||||||
|
const bgColor = effectiveBackground(el);
|
||||||
|
const fg = parseColor(style.color);
|
||||||
|
fg[3] *= opacityChain(el);
|
||||||
|
const fgColor = blend(fg, bgColor);
|
||||||
|
const key = `${hex(fgColor)}|${hex(bgColor)}|${required}`;
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
results.push({
|
||||||
|
text: text.length > 28 ? `${text.slice(0, 28)}…` : text,
|
||||||
|
fg: hex(fgColor),
|
||||||
|
bg: hex(bgColor),
|
||||||
|
ratio: contrast(fgColor, bgColor),
|
||||||
|
required,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return results.sort((a, b) => a.ratio / a.required - b.ratio / b.required);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Readout({ items }: { items: Measurement[] }) {
|
||||||
|
return (
|
||||||
|
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 8 }}>
|
||||||
|
<tbody>
|
||||||
|
{items.map((m) => {
|
||||||
|
const pass = m.ratio >= m.required;
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={`${m.fg}${m.bg}${m.required}`}
|
||||||
|
style={{ borderTop: '1px solid var(--color-border)' }}
|
||||||
|
>
|
||||||
|
<td style={{ padding: '4px 6px' }}>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
display: 'inline-block',
|
||||||
|
padding: '1px 6px',
|
||||||
|
borderRadius: 3,
|
||||||
|
background: m.bg,
|
||||||
|
color: m.fg,
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{m.text}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
style={{
|
||||||
|
padding: '4px 6px',
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
color: 'var(--color-text-muted)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{m.fg} on {m.bg}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
style={{
|
||||||
|
padding: '4px 6px',
|
||||||
|
textAlign: 'right',
|
||||||
|
fontWeight: 700,
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
color: pass ? 'var(--color-text)' : 'var(--color-danger)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{m.ratio.toFixed(2)}:1 {pass ? '✓' : `✗ needs ${m.required}:1`}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renders a sample and measures its text contrast after layout. */
|
||||||
|
function Sample({ children }: { children: React.ReactNode }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const [items, setItems] = useState<Measurement[]>([]);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
// Measure after the theme/styles have applied
|
||||||
|
const frame = requestAnimationFrame(() => setItems(measure(el)));
|
||||||
|
return () => cancelAnimationFrame(frame);
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div ref={ref}>{children}</div>
|
||||||
|
<Readout items={items} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Page ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Covers every syntax color: comment, keyword, string, number, function
|
||||||
|
// (title), params, property
|
||||||
|
const JS_CODE = [
|
||||||
|
'// Open the app and wait for the dashboard',
|
||||||
|
'async function openDashboard(context, timeoutMs) {',
|
||||||
|
" const url = context.getEnv('BASE_URL');",
|
||||||
|
' await context.page.goto(url, { timeout: timeoutMs ?? 30000 });',
|
||||||
|
' return context.page.title();',
|
||||||
|
'}',
|
||||||
|
].join('\n');
|
||||||
|
const JSON_CODE = JSON.stringify(
|
||||||
|
{ status: 'pass', attempts: 2, cached: false, output: { title: 'Dashboard' } },
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
|
||||||
|
interface Issue {
|
||||||
|
title: string;
|
||||||
|
note: string;
|
||||||
|
render: () => React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ISSUES: Issue[] = [
|
||||||
|
{
|
||||||
|
title: 'AutoRefreshIndicator label',
|
||||||
|
note: 'Active ("Live", --color-primary-text), idle and error labels (runs pages).',
|
||||||
|
render: () => (
|
||||||
|
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
|
||||||
|
<AutoRefreshIndicator active pulseKey={1} />
|
||||||
|
<AutoRefreshIndicator active={false} />
|
||||||
|
<AutoRefreshIndicator active={false} error />
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Danger button',
|
||||||
|
note: 'Danger, primary and secondary buttons (text on colored backgrounds).',
|
||||||
|
render: () => (
|
||||||
|
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||||
|
<Button variant="danger">Delete</Button>
|
||||||
|
<Button variant="danger" size="sm">
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
<Button variant="primary">Run</Button>
|
||||||
|
<Button variant="secondary">Cancel</Button>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Code highlighting - JavaScript',
|
||||||
|
note: 'All --hl-* syntax colors on the page background (step code, snippets).',
|
||||||
|
render: () => <CodeBlock language="javascript" code={JS_CODE} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Code highlighting - JSON',
|
||||||
|
note: 'Keys, strings, numbers and literals in JSON step outputs.',
|
||||||
|
render: () => <CodeBlock language="json" code={JSON_CODE} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Muted text',
|
||||||
|
note: '--color-text-muted on both background shades (hints, table headers, descriptions).',
|
||||||
|
render: () => (
|
||||||
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
{['var(--color-bg)', 'var(--color-bg-subtle)'].map((bg) => (
|
||||||
|
<span
|
||||||
|
key={bg}
|
||||||
|
style={{
|
||||||
|
background: bg,
|
||||||
|
color: 'var(--color-text-muted)',
|
||||||
|
padding: '4px 8px',
|
||||||
|
fontSize: 13,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Last run 2 minutes ago
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function Panel({ theme }: { theme: 'light' | 'dark' }) {
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
// The dark tokens apply under [data-theme="dark"]; light is the page default
|
||||||
|
data-theme={theme === 'dark' ? 'dark' : undefined}
|
||||||
|
style={{
|
||||||
|
flex: '1 1 420px',
|
||||||
|
minWidth: 0,
|
||||||
|
padding: 16,
|
||||||
|
borderRadius: 8,
|
||||||
|
background: 'var(--color-bg)',
|
||||||
|
color: 'var(--color-text)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h2 style={{ margin: '0 0 12px', fontSize: 16 }}>
|
||||||
|
{theme === 'dark' ? 'Dark theme' : 'Light theme'}
|
||||||
|
</h2>
|
||||||
|
{ISSUES.map((issue) => (
|
||||||
|
<div key={issue.title} style={{ marginBottom: 24 }}>
|
||||||
|
<h3 style={{ margin: '0 0 2px', fontSize: 14 }}>{issue.title}</h3>
|
||||||
|
<p style={{ margin: '0 0 8px', fontSize: 12, color: 'var(--color-text-muted)' }}>
|
||||||
|
{issue.note}
|
||||||
|
</p>
|
||||||
|
<Sample>{issue.render()}</Sample>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ContrastPage() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 16 }}>
|
||||||
|
<p
|
||||||
|
style={{
|
||||||
|
margin: '0 0 16px',
|
||||||
|
fontSize: 13,
|
||||||
|
color: 'var(--color-text-muted)',
|
||||||
|
maxWidth: 820,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Text contrast of the components where it's easiest to get wrong (WCAG AA: 4.5:1 for normal
|
||||||
|
text, 3:1 for large text). Each row is a piece of text in the sample, measured from its
|
||||||
|
rendered colors, worst first.
|
||||||
|
</p>
|
||||||
|
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
|
||||||
|
<Panel theme="light" />
|
||||||
|
<Panel theme="dark" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: Meta<typeof ContrastPage> = {
|
||||||
|
title: 'Accessibility/Contrast',
|
||||||
|
component: ContrastPage,
|
||||||
|
// a11y checks use the project default ('error' in preview.tsx)
|
||||||
|
parameters: { layout: 'fullscreen' },
|
||||||
|
// The light panel relies on the page default (light) theme
|
||||||
|
globals: { theme: 'light' },
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof ContrastPage>;
|
||||||
|
|
||||||
|
export const Overview: Story = {};
|
||||||
@@ -15,7 +15,7 @@ const meta: Meta<typeof DescriptionList> = {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
argTypes: {
|
argTypes: {
|
||||||
layout: { control: 'select', options: ['inline', 'compact'] },
|
layout: { control: 'select', options: ['inline', 'compact', 'comfortable', 'grid'] },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
export default meta;
|
export default meta;
|
||||||
@@ -35,6 +35,14 @@ export const Compact: Story = {
|
|||||||
args: { items: urlItems, layout: 'compact' },
|
args: { items: urlItems, layout: 'compact' },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const Comfortable: Story = {
|
||||||
|
args: { items: urlItems, layout: 'comfortable' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Grid: Story = {
|
||||||
|
args: { items: urlItems, layout: 'grid' },
|
||||||
|
};
|
||||||
|
|
||||||
export const WithLinks: Story = {
|
export const WithLinks: Story = {
|
||||||
args: {
|
args: {
|
||||||
layout: 'inline',
|
layout: 'inline',
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, within } from 'storybook/test';
|
||||||
|
import { MarkdownContent } from '../../src/ui/MarkdownContent/MarkdownContent';
|
||||||
|
|
||||||
|
const meta: Meta<typeof MarkdownContent> = {
|
||||||
|
title: 'UI/MarkdownContent',
|
||||||
|
component: MarkdownContent,
|
||||||
|
parameters: { layout: 'padded' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof MarkdownContent>;
|
||||||
|
|
||||||
|
export const Description: Story = {
|
||||||
|
args: {
|
||||||
|
content: [
|
||||||
|
'## Login flow',
|
||||||
|
'',
|
||||||
|
'Logs in with the **test user** and checks the dashboard.',
|
||||||
|
'',
|
||||||
|
'- Uses the `BASE_URL` environment value',
|
||||||
|
'- Needs the `user` credential alias',
|
||||||
|
'',
|
||||||
|
'```js',
|
||||||
|
"await context.page.goto(context.getEnv('BASE_URL'));",
|
||||||
|
'```',
|
||||||
|
].join('\n'),
|
||||||
|
},
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
await expect(canvas.getByRole('heading', { name: 'Login flow' })).toBeInTheDocument();
|
||||||
|
await expect(canvas.getByText('test user').tagName).toBe('STRONG');
|
||||||
|
await expect(canvas.getAllByRole('listitem')).toHaveLength(2);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, userEvent, within } from 'storybook/test';
|
||||||
|
import { Modal } from '../../src/ui/Modal/Modal';
|
||||||
|
import { Button } from '../../src/ui/Button/Button';
|
||||||
|
|
||||||
|
function ModalDemo({ title, body }: { title: string; body: string }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button onClick={() => setOpen(true)}>Open modal</Button>
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
title={title}
|
||||||
|
onClose={() => setOpen(false)}
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button variant="secondary" onClick={() => setOpen(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => setOpen(false)}>Confirm</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{body}
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: Meta<typeof ModalDemo> = {
|
||||||
|
title: 'UI/Modal',
|
||||||
|
component: ModalDemo,
|
||||||
|
parameters: { layout: 'centered' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
args: { title: 'Delete scenario', body: 'This deletes the scenario, its versions and its runs.' },
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof ModalDemo>;
|
||||||
|
|
||||||
|
export const Default: Story = {
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||||
|
const dialog = canvas.getByRole('dialog', { name: 'Delete scenario' });
|
||||||
|
await expect(dialog).toHaveTextContent('its versions and its runs');
|
||||||
|
await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||||
|
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClosesOnEscapeAndBackdrop: Story = {
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||||
|
await userEvent.keyboard('{Escape}');
|
||||||
|
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||||
|
await userEvent.click(canvas.getByRole('presentation'));
|
||||||
|
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { Notification } from '../../src/ui/Notification/Notification';
|
||||||
|
|
||||||
|
const meta: Meta<typeof Notification> = {
|
||||||
|
title: 'UI/Notification',
|
||||||
|
component: Notification,
|
||||||
|
parameters: { layout: 'padded' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
argTypes: {
|
||||||
|
variant: { control: 'select', options: ['info', 'success', 'error', 'warning', 'note'] },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof Notification>;
|
||||||
|
|
||||||
|
export const Info: Story = {
|
||||||
|
args: {
|
||||||
|
variant: 'info',
|
||||||
|
title: 'Traces are off',
|
||||||
|
children: 'Enable them per run in the run modal.',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
export const Success: Story = { args: { variant: 'success', children: 'Scenario imported.' } };
|
||||||
|
export const Error: Story = {
|
||||||
|
args: { variant: 'error', title: 'Run failed', children: 'Step 2 timed out after 60s.' },
|
||||||
|
};
|
||||||
|
export const Warning: Story = {
|
||||||
|
args: { variant: 'warning', children: 'The environment of this run no longer exists.' },
|
||||||
|
};
|
||||||
|
export const Note: Story = { args: { variant: 'note', children: 'Pinned snippet version: v3.' } };
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, userEvent, within } from 'storybook/test';
|
||||||
|
import { RevealableCodeBlock } from '../../src/ui/RevealableCodeBlock/RevealableCodeBlock';
|
||||||
|
|
||||||
|
const meta: Meta<typeof RevealableCodeBlock> = {
|
||||||
|
title: 'UI/RevealableCodeBlock',
|
||||||
|
component: RevealableCodeBlock,
|
||||||
|
parameters: { layout: 'padded' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof RevealableCodeBlock>;
|
||||||
|
|
||||||
|
export const Default: Story = {
|
||||||
|
args: {
|
||||||
|
language: 'json',
|
||||||
|
code: JSON.stringify({ username: 'admin', password: 's3cr3t-p4ss' }, null, 2),
|
||||||
|
},
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
// The code is not rendered until revealed, and hidden again on the second click
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
const toggle = canvas.getByRole('button');
|
||||||
|
await expect(canvasElement).not.toHaveTextContent('s3cr3t-p4ss');
|
||||||
|
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||||
|
|
||||||
|
await userEvent.click(toggle);
|
||||||
|
await expect(canvasElement.querySelector('code')).toHaveTextContent('s3cr3t-p4ss');
|
||||||
|
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||||
|
|
||||||
|
await userEvent.click(toggle);
|
||||||
|
await expect(canvasElement).not.toHaveTextContent('s3cr3t-p4ss');
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, userEvent, within } from 'storybook/test';
|
||||||
|
import { Search } from '../../src/ui/Search/Search';
|
||||||
|
|
||||||
|
function ControlledSearch({ placeholder }: { placeholder?: string }) {
|
||||||
|
const [value, setValue] = useState('');
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Search value={value} onChange={setValue} placeholder={placeholder} />
|
||||||
|
<p data-testid="query">{value}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: Meta<typeof ControlledSearch> = {
|
||||||
|
title: 'UI/Search',
|
||||||
|
component: ControlledSearch,
|
||||||
|
parameters: { layout: 'centered' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof ControlledSearch>;
|
||||||
|
|
||||||
|
export const Default: Story = {};
|
||||||
|
|
||||||
|
export const Typing: Story = {
|
||||||
|
args: { placeholder: 'Filter logs…' },
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
await userEvent.type(canvas.getByPlaceholderText('Filter logs…'), 'timeout');
|
||||||
|
await expect(canvas.getByTestId('query')).toHaveTextContent('timeout');
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, within } from 'storybook/test';
|
||||||
|
import { Textarea } from '../../src/ui/Textarea/Textarea';
|
||||||
|
|
||||||
|
const meta: Meta<typeof Textarea> = {
|
||||||
|
title: 'UI/Textarea',
|
||||||
|
component: Textarea,
|
||||||
|
parameters: { layout: 'centered' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
decorators: [
|
||||||
|
(Story) => (
|
||||||
|
<div style={{ width: 360 }}>
|
||||||
|
<Story />
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof Textarea>;
|
||||||
|
|
||||||
|
export const Default: Story = {
|
||||||
|
args: { label: 'Description', placeholder: 'Describe this scenario', rows: 4 },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WithHint: Story = {
|
||||||
|
args: { label: 'Description', hint: 'Markdown is supported.', rows: 4 },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WithError: Story = {
|
||||||
|
args: { label: 'Description', error: 'Description is too long.', rows: 4 },
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
const textarea = canvas.getByLabelText('Description');
|
||||||
|
await expect(textarea).toHaveAttribute('aria-invalid', 'true');
|
||||||
|
await expect(canvas.getByRole('alert')).toHaveTextContent('Description is too long.');
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { expect, userEvent, within } from 'storybook/test';
|
||||||
|
import { ToastProvider } from '../../src/ui/Toast/ToastProvider';
|
||||||
|
import { useToast } from '../../src/ui/Toast/useToast';
|
||||||
|
import { Button } from '../../src/ui/Button/Button';
|
||||||
|
|
||||||
|
function ToastButtons() {
|
||||||
|
const toast = useToast();
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
<Button onClick={() => toast.success('Scenario run started')}>Success</Button>
|
||||||
|
<Button variant="danger" onClick={() => toast.error('Environment not found')}>
|
||||||
|
Error
|
||||||
|
</Button>
|
||||||
|
<Button variant="secondary" onClick={() => toast.info('Traces are off')}>
|
||||||
|
Info
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: Meta<typeof ToastProvider> = {
|
||||||
|
title: 'UI/Toast',
|
||||||
|
component: ToastProvider,
|
||||||
|
parameters: { layout: 'centered' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
args: { durationMs: 3500, children: <ToastButtons /> },
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof ToastProvider>;
|
||||||
|
|
||||||
|
export const Default: Story = {};
|
||||||
|
|
||||||
|
export const ShowsToast: Story = {
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
await userEvent.click(canvas.getByRole('button', { name: 'Success' }));
|
||||||
|
await expect(await within(document.body).findByText('Scenario run started')).toBeVisible();
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { expect, within } from 'storybook/test';
|
||||||
|
import { Button } from '../../src/ui/Button/Button';
|
||||||
|
import { UuidBadge } from '../../src/ui/UuidBadge/UuidBadge';
|
||||||
|
|
||||||
|
const meta: Meta<typeof UuidBadge> = {
|
||||||
|
title: 'UI/UuidBadge',
|
||||||
|
component: UuidBadge,
|
||||||
|
parameters: { layout: 'centered' },
|
||||||
|
tags: ['autodocs'],
|
||||||
|
};
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof UuidBadge>;
|
||||||
|
|
||||||
|
export const Default: Story = {
|
||||||
|
args: { id: '61d2b1c2-7664-4dca-974f-436c2ee90b2e' },
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
// Shows a shortened id and keeps the full one in the tooltip
|
||||||
|
const badge = within(canvasElement).getByTitle('61d2b1c2-7664-4dca-974f-436c2ee90b2e');
|
||||||
|
await expect(badge).toHaveTextContent('61d2…0b2e');
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const SAMPLE_IDS = [
|
||||||
|
'61d2b1c2-7664-4dca-974f-436c2ee90b2e',
|
||||||
|
'e83f0a5d-1b9c-4f27-8d6e-2a4c9b7f1e03',
|
||||||
|
'0c7a94f1-3e52-4b8d-a1f6-9d2e5c8b4a70',
|
||||||
|
'f4b21e8c-9a07-4c63-b5d2-7e1f0a3c6d98',
|
||||||
|
'8d5e3a10-c4f7-4e29-9b81-5f6a2d0c7e14',
|
||||||
|
'2a9fc067-58d3-4a1e-86b4-c3e7f19d5b2a',
|
||||||
|
];
|
||||||
|
|
||||||
|
function Gallery() {
|
||||||
|
const [ids, setIds] = useState(SAMPLE_IDS);
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 12 }}>
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
|
||||||
|
{ids.map((id) => (
|
||||||
|
<UuidBadge key={id} id={id} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
onClick={() => setIds(ids.map(() => crypto.randomUUID()))}
|
||||||
|
>
|
||||||
|
Randomize
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Colors: Story = {
|
||||||
|
render: () => <Gallery />,
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
// Each sample id gets its own badge
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
for (const id of SAMPLE_IDS) {
|
||||||
|
await expect(canvas.getByTitle(id)).toBeInTheDocument();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "liqa-client",
|
"name": "liqa-client",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"author": "Andrii Arsenin",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -52,6 +52,16 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.versionLink {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.versionLink:hover,
|
||||||
|
.versionLink:focus-visible {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
.navItem {
|
.navItem {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
+11
-1
@@ -140,7 +140,17 @@ export default function App() {
|
|||||||
|
|
||||||
<div className={styles.sideFooter}>
|
<div className={styles.sideFooter}>
|
||||||
<ThemeSwitcher />
|
<ThemeSwitcher />
|
||||||
<div className={styles.version}>v{__APP_VERSION__}</div>
|
<div className={styles.version}>
|
||||||
|
v{__APP_VERSION__} ·{' '}
|
||||||
|
<a
|
||||||
|
className={styles.versionLink}
|
||||||
|
href="/licenses.txt"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
{t('nav.licenses')}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</SidePanel>
|
</SidePanel>
|
||||||
|
|||||||
@@ -247,9 +247,10 @@ export const scenarios = {
|
|||||||
},
|
},
|
||||||
exportScenario(
|
exportScenario(
|
||||||
id: string,
|
id: string,
|
||||||
options: { includeEnvironment: boolean; credentialIds: string[] } = {
|
options: { includeEnvironment: boolean; credentialIds: string[]; snippetIds: string[] } = {
|
||||||
includeEnvironment: false,
|
includeEnvironment: false,
|
||||||
credentialIds: [],
|
credentialIds: [],
|
||||||
|
snippetIds: [],
|
||||||
},
|
},
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -257,6 +258,9 @@ export const scenarios = {
|
|||||||
for (const cid of options.credentialIds) {
|
for (const cid of options.credentialIds) {
|
||||||
params.append('credentialIds', cid);
|
params.append('credentialIds', cid);
|
||||||
}
|
}
|
||||||
|
for (const sid of options.snippetIds) {
|
||||||
|
params.append('snippetIds', sid);
|
||||||
|
}
|
||||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||||
},
|
},
|
||||||
exportE2eTestUrl(id: string): string {
|
exportE2eTestUrl(id: string): string {
|
||||||
|
|||||||
@@ -61,3 +61,8 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
accent-color: var(--color-primary);
|
accent-color: var(--color-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.versions {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-size: var(--font-size-xs);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { X, Upload } from 'lucide-react';
|
import { X, Upload } from 'lucide-react';
|
||||||
import { Modal, Button, UuidBadge } from '../../ui';
|
import { Modal, Button, UuidBadge } from '../../ui';
|
||||||
import type { Scenario, ScenarioCredential } from '../../api';
|
import type { Scenario, ScenarioCredential, UsedSnippet } from '../../api';
|
||||||
import styles from './ExportScenarioModal.module.css';
|
import styles from './ExportScenarioModal.module.css';
|
||||||
|
|
||||||
export interface ExportScenarioModalProps {
|
export interface ExportScenarioModalProps {
|
||||||
@@ -13,6 +13,9 @@ export interface ExportScenarioModalProps {
|
|||||||
onIncludeEnvironmentChange: (v: boolean) => void;
|
onIncludeEnvironmentChange: (v: boolean) => void;
|
||||||
includedCredentialIds: Set<string>;
|
includedCredentialIds: Set<string>;
|
||||||
onCredentialToggle: (id: string, checked: boolean) => void;
|
onCredentialToggle: (id: string, checked: boolean) => void;
|
||||||
|
usedSnippets: UsedSnippet[];
|
||||||
|
includedSnippetIds: Set<string>;
|
||||||
|
onSnippetToggle: (id: string, checked: boolean) => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onExport: () => void;
|
onExport: () => void;
|
||||||
isExporting: boolean;
|
isExporting: boolean;
|
||||||
@@ -27,12 +30,24 @@ export function ExportScenarioModal({
|
|||||||
onIncludeEnvironmentChange,
|
onIncludeEnvironmentChange,
|
||||||
includedCredentialIds,
|
includedCredentialIds,
|
||||||
onCredentialToggle,
|
onCredentialToggle,
|
||||||
|
usedSnippets,
|
||||||
|
includedSnippetIds,
|
||||||
|
onSnippetToggle,
|
||||||
onClose,
|
onClose,
|
||||||
onExport,
|
onExport,
|
||||||
isExporting,
|
isExporting,
|
||||||
}: ExportScenarioModalProps) {
|
}: ExportScenarioModalProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
// One row per snippet, listing every version the scenario uses (latest or pinned)
|
||||||
|
const snippetRows = new Map<string, { alias: string; versions: number[] }>();
|
||||||
|
for (const s of usedSnippets) {
|
||||||
|
const row = snippetRows.get(s.id) ?? { alias: s.alias, versions: [] };
|
||||||
|
const version = s.pinnedVersion ?? s.version;
|
||||||
|
if (!row.versions.includes(version)) row.versions.push(version);
|
||||||
|
snippetRows.set(s.id, row);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
@@ -64,6 +79,10 @@ export function ExportScenarioModal({
|
|||||||
<UuidBadge id={scenario.id} />
|
<UuidBadge id={scenario.id} />
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div className={styles.metaRow}>
|
||||||
|
<span className={styles.metaLabel}>{t('scenarios.field_version')}</span>
|
||||||
|
<span className={styles.metaValue}>v{scenario.version}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{environment && (
|
{environment && (
|
||||||
@@ -95,6 +114,25 @@ export function ExportScenarioModal({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{snippetRows.size > 0 && (
|
||||||
|
<div className={styles.section}>
|
||||||
|
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_snippets')}</h4>
|
||||||
|
{[...snippetRows].map(([snippetId, row]) => (
|
||||||
|
<label key={snippetId} className={styles.checkboxRow}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={includedSnippetIds.has(snippetId)}
|
||||||
|
onChange={(e) => onSnippetToggle(snippetId, e.target.checked)}
|
||||||
|
/>
|
||||||
|
<span>{row.alias}</span>
|
||||||
|
<span className={styles.versions}>
|
||||||
|
{row.versions.map((v) => `v${v}`).join(', ')}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
"generic": "Something went wrong. Please try again."
|
"generic": "Something went wrong. Please try again."
|
||||||
},
|
},
|
||||||
"nav": {
|
"nav": {
|
||||||
|
"licenses": "Licenses",
|
||||||
"environments": "Environments",
|
"environments": "Environments",
|
||||||
"credentials": "Credentials",
|
"credentials": "Credentials",
|
||||||
"snippets": "Snippets",
|
"snippets": "Snippets",
|
||||||
@@ -217,11 +218,10 @@
|
|||||||
"export_modal_title": "Export Scenario",
|
"export_modal_title": "Export Scenario",
|
||||||
"export_include_environment": "Include Environment",
|
"export_include_environment": "Include Environment",
|
||||||
"export_include_credentials": "Include Credentials",
|
"export_include_credentials": "Include Credentials",
|
||||||
|
"export_include_snippets": "Include Snippets",
|
||||||
"form_timeout": "Scenario Timeout (seconds)",
|
"form_timeout": "Scenario Timeout (seconds)",
|
||||||
"form_timeout_placeholder": "Default: 600",
|
"form_timeout_placeholder": "Default: 600",
|
||||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
|
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)"
|
||||||
"field_name": "Name",
|
|
||||||
"field_id": "ID"
|
|
||||||
},
|
},
|
||||||
"theme": {
|
"theme": {
|
||||||
"switch_to_light": "Switch to light theme",
|
"switch_to_light": "Switch to light theme",
|
||||||
@@ -229,6 +229,11 @@
|
|||||||
"light_mode": "Light mode",
|
"light_mode": "Light mode",
|
||||||
"dark_mode": "Dark mode"
|
"dark_mode": "Dark mode"
|
||||||
},
|
},
|
||||||
|
"revealable": {
|
||||||
|
"hidden": "Hidden so secrets aren't exposed on screen.",
|
||||||
|
"reveal": "Reveal",
|
||||||
|
"hide": "Hide"
|
||||||
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
"prev": "Previous page",
|
"prev": "Previous page",
|
||||||
"next": "Next page",
|
"next": "Next page",
|
||||||
|
|||||||
@@ -3,11 +3,18 @@ import { useNavigate, useParams } from 'react-router-dom';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||||
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
|
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
|
||||||
import { CodeBlock } from '../../ui';
|
|
||||||
import { stringify as yamlStringify } from 'yaml';
|
import { stringify as yamlStringify } from 'yaml';
|
||||||
import { credentials } from '../../api';
|
import { credentials } from '../../api';
|
||||||
import type { Credential } from '../../api';
|
import type { Credential } from '../../api';
|
||||||
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
import {
|
||||||
|
Breadcrumbs,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
DescriptionList,
|
||||||
|
RevealableCodeBlock,
|
||||||
|
Timestamp,
|
||||||
|
UuidBadge,
|
||||||
|
} from '../../ui';
|
||||||
import { DeleteConfirmationModal } from '../../components/modals';
|
import { DeleteConfirmationModal } from '../../components/modals';
|
||||||
import styles from '../Page.module.css';
|
import styles from '../Page.module.css';
|
||||||
|
|
||||||
@@ -117,7 +124,8 @@ export function CredentialDetailPage() {
|
|||||||
<div className={styles.stepsSection}>
|
<div className={styles.stepsSection}>
|
||||||
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
|
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
|
||||||
<Card>
|
<Card>
|
||||||
<CodeBlock
|
<RevealableCodeBlock
|
||||||
|
key={credential.id}
|
||||||
language="json"
|
language="json"
|
||||||
code={(() => {
|
code={(() => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -68,10 +68,12 @@ export function RunsPage() {
|
|||||||
const sortDirRef = useRef(sortDir);
|
const sortDirRef = useRef(sortDir);
|
||||||
const pageRef = useRef(page);
|
const pageRef = useRef(page);
|
||||||
const pageSizeRef = useRef(pageSize);
|
const pageSizeRef = useRef(pageSize);
|
||||||
sortByRef.current = sortBy;
|
useEffect(() => {
|
||||||
sortDirRef.current = sortDir;
|
sortByRef.current = sortBy;
|
||||||
pageRef.current = page;
|
sortDirRef.current = sortDir;
|
||||||
pageSizeRef.current = pageSize;
|
pageRef.current = page;
|
||||||
|
pageSizeRef.current = pageSize;
|
||||||
|
}, [sortBy, sortDir, page, pageSize]);
|
||||||
|
|
||||||
const load = useCallback(
|
const load = useCallback(
|
||||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||||
|
|||||||
@@ -94,11 +94,12 @@ export function ScenarioDetailPage() {
|
|||||||
const [exportModalOpen, setExportModalOpen] = useState(false);
|
const [exportModalOpen, setExportModalOpen] = useState(false);
|
||||||
const [includeEnvironment, setIncludeEnvironment] = useState(true);
|
const [includeEnvironment, setIncludeEnvironment] = useState(true);
|
||||||
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
|
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
|
||||||
|
const [includedSnippetIds, setIncludedSnippetIds] = useState<Set<string>>(new Set());
|
||||||
const [isExporting, setIsExporting] = useState(false);
|
const [isExporting, setIsExporting] = useState(false);
|
||||||
|
|
||||||
// Files state
|
// Files state
|
||||||
const [files, setFiles] = useState<FileMetadata[]>([]);
|
const [files, setFiles] = useState<FileMetadata[]>([]);
|
||||||
const [filesLoading, setFilesLoading] = useState(false);
|
const [filesLoading, setFilesLoading] = useState(true);
|
||||||
const [uploadOpen, setUploadOpen] = useState(false);
|
const [uploadOpen, setUploadOpen] = useState(false);
|
||||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||||
const [uploadExpiresAt, setUploadExpiresAt] = useState('');
|
const [uploadExpiresAt, setUploadExpiresAt] = useState('');
|
||||||
@@ -106,9 +107,10 @@ export function ScenarioDetailPage() {
|
|||||||
|
|
||||||
const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]);
|
const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]);
|
||||||
|
|
||||||
const loadFiles = useCallback(async () => {
|
// Fetches the files; `filesLoading` starts as true for the fetch from the
|
||||||
|
// load effect, and `loadFiles` sets it for reloads (e.g. after an upload)
|
||||||
|
const fetchFiles = useCallback(async () => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
setFilesLoading(true);
|
|
||||||
try {
|
try {
|
||||||
const result = await scenarioFiles.list(id);
|
const result = await scenarioFiles.list(id);
|
||||||
setFiles(result.items);
|
setFiles(result.items);
|
||||||
@@ -117,6 +119,11 @@ export function ScenarioDetailPage() {
|
|||||||
}
|
}
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
|
const loadFiles = async () => {
|
||||||
|
setFilesLoading(true);
|
||||||
|
await fetchFiles();
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
void scenarios
|
void scenarios
|
||||||
@@ -126,7 +133,7 @@ export function ScenarioDetailPage() {
|
|||||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
void loadFiles();
|
void fetchFiles();
|
||||||
scenarios
|
scenarios
|
||||||
.usedSnippets(id)
|
.usedSnippets(id)
|
||||||
.then(setUsedSnippets)
|
.then(setUsedSnippets)
|
||||||
@@ -141,7 +148,7 @@ export function ScenarioDetailPage() {
|
|||||||
setEnvs(r.data);
|
setEnvs(r.data);
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, [id, loadFiles]);
|
}, [id, fetchFiles]);
|
||||||
|
|
||||||
const openRunModal = () => {
|
const openRunModal = () => {
|
||||||
// Preselect the scenario's default environment (or the first one) when the
|
// Preselect the scenario's default environment (or the first one) when the
|
||||||
@@ -206,8 +213,9 @@ export function ScenarioDetailPage() {
|
|||||||
|
|
||||||
const handleOpenExportModal = () => {
|
const handleOpenExportModal = () => {
|
||||||
if (!scenario) return;
|
if (!scenario) return;
|
||||||
// Initialise all credential checkboxes to checked
|
// Initialise all credential and snippet checkboxes to checked
|
||||||
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
|
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
|
||||||
|
setIncludedSnippetIds(new Set(usedSnippets.map((s) => s.id)));
|
||||||
setIncludeEnvironment(true);
|
setIncludeEnvironment(true);
|
||||||
setExportModalOpen(true);
|
setExportModalOpen(true);
|
||||||
};
|
};
|
||||||
@@ -220,6 +228,7 @@ export function ScenarioDetailPage() {
|
|||||||
const yamlContent = await scenarios.exportScenario(scenario.id, {
|
const yamlContent = await scenarios.exportScenario(scenario.id, {
|
||||||
includeEnvironment,
|
includeEnvironment,
|
||||||
credentialIds: credIds,
|
credentialIds: credIds,
|
||||||
|
snippetIds: Array.from(includedSnippetIds),
|
||||||
});
|
});
|
||||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
@@ -893,6 +902,16 @@ export function ScenarioDetailPage() {
|
|||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
|
usedSnippets={usedSnippets}
|
||||||
|
includedSnippetIds={includedSnippetIds}
|
||||||
|
onSnippetToggle={(snippetId, checked) => {
|
||||||
|
setIncludedSnippetIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (checked) next.add(snippetId);
|
||||||
|
else next.delete(snippetId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}}
|
||||||
onClose={() => setExportModalOpen(false)}
|
onClose={() => setExportModalOpen(false)}
|
||||||
onExport={handleExport}
|
onExport={handleExport}
|
||||||
isExporting={isExporting}
|
isExporting={isExporting}
|
||||||
|
|||||||
@@ -68,9 +68,10 @@ export function ScenariosPage() {
|
|||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
|
|
||||||
const load = useCallback(
|
// Fetches a page; `loading` starts as true for the initial fetch from the
|
||||||
|
// effect, and `load` sets it for later ones (no setState inside the effect)
|
||||||
|
const fetchPage = useCallback(
|
||||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||||
setLoading(true);
|
|
||||||
Promise.all([
|
Promise.all([
|
||||||
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||||
environments.list(1, 200),
|
environments.list(1, 200),
|
||||||
@@ -88,9 +89,14 @@ export function ScenariosPage() {
|
|||||||
[toast],
|
[toast],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const load = (orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||||
|
setLoading(true);
|
||||||
|
fetchPage(orderBy, orderDir, p, limit);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
load('updatedAt', 'desc', 1, 10);
|
fetchPage('updatedAt', 'desc', 1, 10);
|
||||||
}, [load]);
|
}, [fetchPage]);
|
||||||
|
|
||||||
const handleSort = (key: string, dir: SortDirection) => {
|
const handleSort = (key: string, dir: SortDirection) => {
|
||||||
setSortBy(key);
|
setSortBy(key);
|
||||||
|
|||||||
@@ -23,7 +23,9 @@ export function SessionsPage() {
|
|||||||
usePageTitle(t('sessions.title'));
|
usePageTitle(t('sessions.title'));
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [items, setItems] = useState<Session[]>([]);
|
const [items, setItems] = useState<Session[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
// Loading until the current query's result has arrived (derived, so the
|
||||||
|
// loading effect doesn't have to set state synchronously)
|
||||||
|
const [loadedQuery, setLoadedQuery] = useState<string | null>(null);
|
||||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||||
const [deleting, setDeleting] = useState(false);
|
const [deleting, setDeleting] = useState(false);
|
||||||
const [sortBy, setSortBy] = useState('id');
|
const [sortBy, setSortBy] = useState('id');
|
||||||
@@ -32,15 +34,18 @@ export function SessionsPage() {
|
|||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
|
|
||||||
|
const query = `${sortBy}|${sortDir}|${page}|${pageSize}`;
|
||||||
|
const loading = loadedQuery !== query;
|
||||||
|
|
||||||
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||||
setLoading(true);
|
const key = `${orderBy}|${orderDir}|${p}|${limit}`;
|
||||||
sessions
|
sessions
|
||||||
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
|
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
setItems(res.data);
|
setItems(res.data);
|
||||||
setTotal(res.total);
|
setTotal(res.total);
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoadedQuery(key));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -71,7 +71,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.active .label {
|
.active .label {
|
||||||
color: var(--color-primary);
|
color: var(--color-primary-text);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,8 +83,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.inactive .label {
|
.inactive .label {
|
||||||
|
/* Not dimmed with opacity: muted text already reads as inactive and keeps 4.5:1 */
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
opacity: 0.5;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Error state ──────────────────────────────────────────── */
|
/* ── Error state ──────────────────────────────────────────── */
|
||||||
|
|||||||
@@ -6,12 +6,13 @@ export type BadgeVariant = 'success' | 'error' | 'warning' | 'info' | 'neutral'
|
|||||||
export interface BadgeProps {
|
export interface BadgeProps {
|
||||||
variant?: BadgeVariant;
|
variant?: BadgeVariant;
|
||||||
dot?: boolean;
|
dot?: boolean;
|
||||||
|
className?: string;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Badge({ variant = 'neutral', dot = false, children }: BadgeProps) {
|
export function Badge({ variant = 'neutral', dot = false, className, children }: BadgeProps) {
|
||||||
return (
|
return (
|
||||||
<span className={[styles.badge, styles[variant]].join(' ')}>
|
<span className={[styles.badge, styles[variant], className].filter(Boolean).join(' ')}>
|
||||||
{dot && <span className={styles.dot} aria-hidden="true" />}
|
{dot && <span className={styles.dot} aria-hidden="true" />}
|
||||||
{children}
|
{children}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
|
|
||||||
.code :global(.hljs-comment),
|
.code :global(.hljs-comment),
|
||||||
.code :global(.hljs-quote) {
|
.code :global(.hljs-quote) {
|
||||||
color: var(--hl-comment, #6A8072);
|
color: var(--hl-comment);
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
.code :global(.hljs-built_in),
|
.code :global(.hljs-built_in),
|
||||||
.code :global(.hljs-name),
|
.code :global(.hljs-name),
|
||||||
.code :global(.hljs-tag) {
|
.code :global(.hljs-tag) {
|
||||||
color: var(--hl-keyword, #A67DCC);
|
color: var(--hl-keyword);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-string),
|
.code :global(.hljs-string),
|
||||||
@@ -39,32 +39,32 @@
|
|||||||
.code :global(.hljs-template-variable),
|
.code :global(.hljs-template-variable),
|
||||||
.code :global(.hljs-type),
|
.code :global(.hljs-type),
|
||||||
.code :global(.hljs-addition) {
|
.code :global(.hljs-addition) {
|
||||||
color: var(--hl-string, #9BB870);
|
color: var(--hl-string);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-number),
|
.code :global(.hljs-number),
|
||||||
.code :global(.hljs-regexp),
|
.code :global(.hljs-regexp),
|
||||||
.code :global(.hljs-link) {
|
.code :global(.hljs-link) {
|
||||||
color: var(--hl-number, #E8A85F);
|
color: var(--hl-number);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-function),
|
.code :global(.hljs-function),
|
||||||
.code :global(.hljs-title.hljs-function_) {
|
.code :global(.hljs-title.hljs-function_) {
|
||||||
color: var(--hl-function, #5BB8D4);
|
color: var(--hl-function);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-variable),
|
.code :global(.hljs-variable),
|
||||||
.code :global(.hljs-params) {
|
.code :global(.hljs-params) {
|
||||||
color: var(--hl-variable, #D4A0A0);
|
color: var(--hl-variable);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-property) {
|
.code :global(.hljs-property) {
|
||||||
color: var(--hl-property, #79C0C8);
|
color: var(--hl-property);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-deletion),
|
.code :global(.hljs-deletion),
|
||||||
.code :global(.hljs-meta) {
|
.code :global(.hljs-meta) {
|
||||||
color: var(--hl-meta, #A9A3C9);
|
color: var(--hl-meta);
|
||||||
}
|
}
|
||||||
|
|
||||||
.code :global(.hljs-emphasis) {
|
.code :global(.hljs-emphasis) {
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
.wrapper {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.placeholder {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Eye, EyeOff } from 'lucide-react';
|
||||||
|
import { Button } from '../Button/Button';
|
||||||
|
import { CodeBlock } from '../CodeBlock/CodeBlock';
|
||||||
|
import styles from './RevealableCodeBlock.module.css';
|
||||||
|
|
||||||
|
export interface RevealableCodeBlockProps {
|
||||||
|
code: string;
|
||||||
|
language?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A CodeBlock that starts hidden; the code is only rendered after the user reveals it. */
|
||||||
|
export function RevealableCodeBlock({ code, language }: RevealableCodeBlockProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [revealed, setRevealed] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={styles.wrapper}>
|
||||||
|
<div className={styles.content}>
|
||||||
|
{revealed ? (
|
||||||
|
<CodeBlock code={code} language={language} />
|
||||||
|
) : (
|
||||||
|
<p className={styles.placeholder}>{t('revealable.hidden')}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
aria-expanded={revealed}
|
||||||
|
onClick={() => setRevealed((r) => !r)}
|
||||||
|
>
|
||||||
|
{revealed ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||||
|
{revealed ? t('revealable.hide') : t('revealable.reveal')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -49,7 +49,7 @@
|
|||||||
|
|
||||||
.sortIconActive {
|
.sortIconActive {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
color: var(--color-primary);
|
color: var(--color-primary-text);
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-theme="dark"] .th {
|
[data-theme="dark"] .th {
|
||||||
|
|||||||
@@ -4,6 +4,23 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
transition: background var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge:hover {
|
||||||
|
background: color-mix(in srgb, var(--color-neutral-bg) 85%, white);
|
||||||
|
}
|
||||||
|
|
||||||
|
.swatch {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 1px solid currentColor;
|
||||||
|
box-sizing: border-box;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.button {
|
.button {
|
||||||
all: unset;
|
all: unset;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
|||||||
@@ -7,9 +7,15 @@ export interface UuidBadgeProps {
|
|||||||
id: string;
|
id: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function uuidColor(id: string): string | null {
|
||||||
|
const hex = id.replace(/-/g, '').slice(0, 6);
|
||||||
|
return /^[0-9a-f]{6}$/i.test(hex) ? `#${hex}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
export function UuidBadge({ id }: UuidBadgeProps) {
|
export function UuidBadge({ id }: UuidBadgeProps) {
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
const short = `${id.slice(0, 4)}…${id.slice(-4)}`;
|
const short = `${id.slice(0, 4)}…${id.slice(-4)}`;
|
||||||
|
const color = uuidColor(id);
|
||||||
|
|
||||||
const handleClick = (e: React.MouseEvent) => {
|
const handleClick = (e: React.MouseEvent) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
@@ -21,7 +27,10 @@ export function UuidBadge({ id }: UuidBadgeProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<span className={styles.wrapper} title={copied ? 'Copied!' : id}>
|
<span className={styles.wrapper} title={copied ? 'Copied!' : id}>
|
||||||
<Badge variant="neutral">
|
<Badge variant="neutral" className={styles.badge}>
|
||||||
|
{color && (
|
||||||
|
<span className={styles.swatch} style={{ background: color }} aria-hidden="true" />
|
||||||
|
)}
|
||||||
<button type="button" className={styles.button} onClick={handleClick}>
|
<button type="button" className={styles.button} onClick={handleClick}>
|
||||||
{short}
|
{short}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ export type { SearchProps } from './Search/Search';
|
|||||||
export { CodeBlock } from './CodeBlock/CodeBlock';
|
export { CodeBlock } from './CodeBlock/CodeBlock';
|
||||||
export type { CodeBlockProps } from './CodeBlock/CodeBlock';
|
export type { CodeBlockProps } from './CodeBlock/CodeBlock';
|
||||||
|
|
||||||
|
export { RevealableCodeBlock } from './RevealableCodeBlock/RevealableCodeBlock';
|
||||||
|
export type { RevealableCodeBlockProps } from './RevealableCodeBlock/RevealableCodeBlock';
|
||||||
|
|
||||||
export { CodeEditor } from './CodeEditor/CodeEditor';
|
export { CodeEditor } from './CodeEditor/CodeEditor';
|
||||||
export type { CodeEditorProps } from './CodeEditor/CodeEditor';
|
export type { CodeEditorProps } from './CodeEditor/CodeEditor';
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,8 @@
|
|||||||
--color-primary-hover: #8ABD2E;
|
--color-primary-hover: #8ABD2E;
|
||||||
--color-primary-active: #77A320;
|
--color-primary-active: #77A320;
|
||||||
--color-primary-fg: #2D3339; /* Outer Space on bright green */
|
--color-primary-fg: #2D3339; /* Outer Space on bright green */
|
||||||
|
/* Primary as text/icon color on light surfaces (Atlantis is too light for text) */
|
||||||
|
--color-primary-text: #496904;
|
||||||
|
|
||||||
/* Secondary — Kimberly tint */
|
/* Secondary — Kimberly tint */
|
||||||
--color-secondary: #EDEAF8;
|
--color-secondary: #EDEAF8;
|
||||||
@@ -19,8 +21,8 @@
|
|||||||
--color-secondary-fg: #6650C0; /* Kimberly */
|
--color-secondary-fg: #6650C0; /* Kimberly */
|
||||||
--color-secondary-border: #B8B0E0;
|
--color-secondary-border: #B8B0E0;
|
||||||
|
|
||||||
/* Danger */
|
/* Danger (white text needs >= 4.5:1) */
|
||||||
--color-danger: #D94F4F;
|
--color-danger: #CE4546;
|
||||||
--color-danger-hover: #C03A3A;
|
--color-danger-hover: #C03A3A;
|
||||||
--color-danger-fg: #ffffff;
|
--color-danger-fg: #ffffff;
|
||||||
|
|
||||||
@@ -43,11 +45,21 @@
|
|||||||
--color-link-hover: #3D2F80;
|
--color-link-hover: #3D2F80;
|
||||||
|
|
||||||
--color-text: #2D3339;
|
--color-text: #2D3339;
|
||||||
--color-text-muted: #6650C0; /* Kimberly */
|
--color-text-muted: #634DBD; /* Kimberly, a touch darker for 4.5:1 on bg-subtle */
|
||||||
--color-border: #AFBFB9; /* Powder Ash */
|
--color-border: #AFBFB9; /* Powder Ash */
|
||||||
--color-bg: #E6EDEA; /* Powder Ash tint */
|
--color-bg: #E6EDEA; /* Powder Ash tint */
|
||||||
--color-bg-subtle: #D8E2DE; /* Powder Ash tint, 1 step darker */
|
--color-bg-subtle: #D8E2DE; /* Powder Ash tint, 1 step darker */
|
||||||
|
|
||||||
|
/* Syntax highlighting (CodeBlock); each >= 4.5:1 on bg and bg-subtle */
|
||||||
|
--hl-comment: #4F6557;
|
||||||
|
--hl-keyword: #764E99;
|
||||||
|
--hl-string: #4F6821;
|
||||||
|
--hl-number: #895403;
|
||||||
|
--hl-function: #056980;
|
||||||
|
--hl-variable: #815354;
|
||||||
|
--hl-property: #1D6971;
|
||||||
|
--hl-meta: #615B7E;
|
||||||
|
|
||||||
/* Spacing */
|
/* Spacing */
|
||||||
--space-1: 4px;
|
--space-1: 4px;
|
||||||
--space-2: 8px;
|
--space-2: 8px;
|
||||||
@@ -112,6 +124,7 @@ a:hover {
|
|||||||
--color-primary-hover: #AEDE55;
|
--color-primary-hover: #AEDE55;
|
||||||
--color-primary-active: #8ABD2E;
|
--color-primary-active: #8ABD2E;
|
||||||
--color-primary-fg: #1A1F24;
|
--color-primary-fg: #1A1F24;
|
||||||
|
--color-primary-text: #9DD341;
|
||||||
|
|
||||||
/* Secondary — dark Kimberly tint */
|
/* Secondary — dark Kimberly tint */
|
||||||
--color-secondary: #2A2548;
|
--color-secondary: #2A2548;
|
||||||
@@ -122,7 +135,7 @@ a:hover {
|
|||||||
|
|
||||||
/* Danger */
|
/* Danger */
|
||||||
--color-danger: #E06060;
|
--color-danger: #E06060;
|
||||||
--color-danger-hover: #CC4A4A;
|
--color-danger-hover: #F06E6D; /* lighter, so the dark text keeps >= 4.5:1 */
|
||||||
--color-danger-fg: #1A1F24;
|
--color-danger-fg: #1A1F24;
|
||||||
|
|
||||||
/* Semantic */
|
/* Semantic */
|
||||||
@@ -148,4 +161,14 @@ a:hover {
|
|||||||
--color-border: #3D4850;
|
--color-border: #3D4850;
|
||||||
--color-bg: #1A1F24; /* deeper than Outer Space */
|
--color-bg: #1A1F24; /* deeper than Outer Space */
|
||||||
--color-bg-subtle: #2D3339; /* Outer Space */
|
--color-bg-subtle: #2D3339; /* Outer Space */
|
||||||
|
|
||||||
|
/* Syntax highlighting (CodeBlock); each >= 4.5:1 on bg and bg-subtle */
|
||||||
|
--hl-comment: #8AA192;
|
||||||
|
--hl-keyword: #B38ADA;
|
||||||
|
--hl-string: #9BB870;
|
||||||
|
--hl-number: #E8A85F;
|
||||||
|
--hl-function: #5BB8D4;
|
||||||
|
--hl-variable: #D4A0A0;
|
||||||
|
--hl-property: #79C0C8;
|
||||||
|
--hl-meta: #A9A3C9;
|
||||||
}
|
}
|
||||||
+6
-4
@@ -3,13 +3,15 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
ports:
|
ports:
|
||||||
# UI, REST API (/api/v1), MCP (/mcp) and Swagger (/docs)
|
# UI, REST API (/api/v1), MCP (/mcp) and Swagger (/docs).
|
||||||
|
# The production CORS origins (server/src/common/cors.ts) use this port;
|
||||||
|
# set CORS_ORIGINS in .env when publishing it elsewhere.
|
||||||
- "13000:3000"
|
- "13000:3000"
|
||||||
|
# Optional overrides (see .env.example); every setting has a default
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- path: .env
|
||||||
|
required: false
|
||||||
volumes:
|
volumes:
|
||||||
# persist SQLite database across restarts
|
# persist SQLite database across restarts
|
||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
# mount key files into the container
|
|
||||||
- ./keys:/app/keys
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
+66
-37
@@ -1,50 +1,79 @@
|
|||||||
# Architecture
|
# Architecture
|
||||||
|
|
||||||
```
|
```
|
||||||
┌──────────────────────────────────────────────────────┐
|
Browser (React SPA) MCP client (AI agent, IDE)
|
||||||
│ Browser (React SPA - client/) │
|
│ / and /api/v1 │ /mcp (Streamable HTTP)
|
||||||
│ │
|
└──────────────┬──────────────────┘
|
||||||
│ Environments Credentials Snippets │
|
▼
|
||||||
│ Sessions Scenarios Runs │
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
└─────────────────────────────┬────────────────────────┘
|
│ liqa container (:13000 → 3000) NestJS app, server/src/ │
|
||||||
│ HTTP REST (:13000)
|
│ │
|
||||||
│
|
│ Routes / built client (ServeStaticModule) │
|
||||||
MCP client (AI agent / VS Code Copilot)
|
│ /api/v1 REST API /docs Swagger UI │
|
||||||
│ HTTP /mcp (Streamable MCP)
|
│ /mcp MCP tools /health health check │
|
||||||
▼
|
│ │
|
||||||
┌──────────────────────────────────────────────────────┐
|
│ McpService MCP tools → services below │
|
||||||
│ NestJS app (server/src/) │
|
│ ScenarioService scenarios, steps, versions, runs │
|
||||||
│ │
|
│ ScenarioSchedulerService @Interval(1 s) run worker │
|
||||||
│ McpService all MCP tools │
|
│ E2eExportService standalone Playwright test zip │
|
||||||
│ SessionService session persistence │
|
│ SnippetService snippets + versions │
|
||||||
│ SessionContextService live browser contexts │
|
│ EnvironmentService environments │
|
||||||
│ EnvironmentService environment CRUD + import │
|
│ CredentialService credentials │
|
||||||
│ CredentialService credential CRUD + import │
|
│ ImportService central YAML import │
|
||||||
│ SnippetService snippet CRUD + import │
|
│ FileStorageService scenario files + run artifacts │
|
||||||
│ BrowserService ad-hoc open/exec │
|
│ SessionService saved browser sessions │
|
||||||
│ CodeExecutorService sandboxed JS runtime │
|
│ SessionContextService live Playwright contexts │
|
||||||
│ ScenarioService scenarios/steps/runs CRUD │
|
│ SessionSchedulerService @Interval(60 s) session cleanup │
|
||||||
│ ScenarioSchedulerService @Interval(1 s) run worker │
|
│ BrowserService ad-hoc open / exec │
|
||||||
└───────────────────────┬──────────────────────────────┘
|
│ CodeExecutorService runs step / snippet JS │
|
||||||
│ better-sqlite3 (TypeORM)
|
└───────────────┬─────────────────────────────┬───────────────┘
|
||||||
▼
|
│ TypeORM (better-sqlite3) │ Playwright
|
||||||
data/sessions.db
|
▼ ▼
|
||||||
|
data/liqa.db, data/files/ chromium-headless-shell
|
||||||
```
|
```
|
||||||
|
|
||||||
- **McpService** registers MCP tools and delegates to session, environment, browser, and scenario services.
|
Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it.
|
||||||
- **SessionService** persists session records in SQLite. **SessionContextService** manages live Playwright contexts for open sessions.
|
|
||||||
- **EnvironmentService**, **CredentialService**, and **SnippetService** provide CRUD plus import/export upserts.
|
## Server components (`server/src/`)
|
||||||
- **BrowserService** handles stateless ad-hoc automation (`/open`, `/exec`) and session-aware browsing.
|
|
||||||
- **CodeExecutorService** validates and executes user JS with `page`, `context`, and helper APIs.
|
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
|
||||||
- **ScenarioService** manages scenarios, steps, credential aliases, runs, logs, and scenario import/export.
|
- **ScenarioService** (`scenario/`) manages scenarios, steps, credential aliases, versions, runs, run logs, scenario/run files, and scenario export/import.
|
||||||
- **ScenarioSchedulerService** polls pending runs every second and executes step runs to completion.
|
- **ScenarioSchedulerService** picks up pending runs every second (up to 10 in parallel) and executes their steps in order in one Playwright browser per run. It handles step and scenario timeouts, failure page dumps (screenshot + HTML), Playwright traces, and saving the browser as a session (`saveSession`).
|
||||||
|
- **E2eExportService** builds a standalone Playwright test project (zip) from a scenario, bundling the snippets, credentials and files it uses.
|
||||||
|
- **SnippetService** (`snippet/`), **EnvironmentService** (`environment/`) and **CredentialService** (`credential/`) provide CRUD plus export/import.
|
||||||
|
- **ImportService** (`import/`) implements `POST /import`: validates a YAML stream of mixed items, then imports them in dependency order (environments, credentials, snippets, scenarios).
|
||||||
|
- **FileStorageService** (`file/`) stores uploaded scenario files and run artifacts under `FILES_DIR`, and deletes expired files on a cron schedule (`FILE_CLEANUP_CRON`).
|
||||||
|
- **SessionService** (`session/`) persists saved sessions (cookies, localStorage); **SessionContextService** keeps their live Playwright contexts; **SessionSchedulerService** closes idle sessions and deletes old closed ones every minute.
|
||||||
|
- **BrowserService** (`browser/`) handles ad-hoc automation (`POST /api/v1/open`, `POST /api/v1/exec`, and the `open_url` / `exec_code` MCP tools), optionally in a saved session.
|
||||||
|
- **CodeExecutorService** (`code-executor/`) checks step and snippet code with acorn, then runs it with the `context` API (page, environment values, credentials, snippets, files, assertions, logs). It is not a security sandbox: step code is trusted.
|
||||||
|
|
||||||
|
Cross-cutting pieces:
|
||||||
|
|
||||||
|
- `config/app.config.ts` - all settings, validated at startup (see `.env.example`).
|
||||||
|
- `database/` - the entity list, TypeORM data source options (shared by the app, the migration runner and the TypeORM CLI), the migration runner and the migrations.
|
||||||
|
- `common/app-package.ts` - app name and version, read from the workspace root `package.json`.
|
||||||
|
- `common/client-static.ts` - serving the built client, with the `index.html` fallback for client-side routes.
|
||||||
|
- `common/body-parsers.ts` - YAML request bodies (`application/yaml`) for the import endpoint.
|
||||||
|
- `interceptors/` - a trace id per request (kept in `AsyncLocalStorage` and added to log lines) and request/response logging; `filters/` - consistent error responses.
|
||||||
|
|
||||||
|
## Data
|
||||||
|
|
||||||
|
SQLite via TypeORM. The schema is managed by migrations (`server/src/database/migrations/`, registered in `migrations/index.ts`); `synchronize` is off. The Docker container applies pending migrations (`node dist/database/migrate`) before starting the server, and the server refuses to start while migrations are pending. See "Database migrations" in [development.md](development.md). The main tables:
|
||||||
|
|
||||||
|
- `scenarios` / `scenario_steps` hold the **latest** version of each scenario; `scenario_versions` holds a snapshot of every version (content + steps).
|
||||||
|
- `snippets` holds the latest version of each snippet; `snippet_versions` holds every version. Step code pins a version with `runSnippet("alias@N")`.
|
||||||
|
- `scenario_runs` record the scenario version, environment, trace mode and status; `scenario_run_steps` keep their own copy of each step's code, so a run always shows what it executed; `scenario_run_logs` hold ordered run logs.
|
||||||
|
- `files` + `scenario_files` / `scenario_run_files` map stored files to scenarios and runs.
|
||||||
|
- `environments`, `credentials`, `scenario_credentials` (alias → credential per scenario), `sessions`.
|
||||||
|
|
||||||
|
See [scenario.md](scenario.md) for versioning, runs and import/export rules.
|
||||||
|
|
||||||
## Client (`client/`)
|
## Client (`client/`)
|
||||||
|
|
||||||
A React 19 + TypeScript SPA served by the Vite dev server during development. In the Docker image the server serves the built client itself (`ServeStaticModule`, see `server/src/common/client-static.ts`), from the same origin as the API.
|
A React 19 + TypeScript SPA. During development it's served by the Vite dev server; in the Docker image the server serves the built client from the same origin as the API.
|
||||||
|
|
||||||
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses `BrowserRouter`; the server answers any GET outside `/api`, `/mcp`, `/docs` and `/health` with the client's `index.html`, so client-side routes survive a page refresh.
|
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses `BrowserRouter`; the server answers any GET outside `/api`, `/mcp`, `/docs` and `/health` with the client's `index.html`, so client-side routes survive a page refresh.
|
||||||
|
|
||||||
The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
|
Pages: scenarios (with steps, versions, credentials, used snippets and files), runs, snippets, credentials, environments, sessions, and the central import page. The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
|
||||||
|
|
||||||
See [development.md](development.md) for the full client tech stack and directory layout.
|
See [development.md](development.md) for the full client tech stack and directory layout.
|
||||||
+108
-28
@@ -16,20 +16,27 @@ Install all dependencies from the repo root:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npx playwright install chromium # first time only (server)
|
npx playwright install --only-shell chromium # first time only: headless Chromium for the server
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy `.env.example` to `.env` and fill in the required values before running.
|
No `.env` is needed: every setting below has a default. To override settings, copy `.env.example` to `.env` and uncomment the ones you need. Docker Compose loads `.env` when it exists.
|
||||||
|
|
||||||
### Environment variables (server)
|
### Environment variables (server)
|
||||||
|
|
||||||
|
All settings are validated at startup by `server/src/config/app.config.ts`.
|
||||||
|
|
||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins |
|
||||||
|
| `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) |
|
||||||
| `PORT` | `3000` | HTTP port |
|
| `PORT` | `3000` | HTTP port |
|
||||||
| `KEYS_DIR` | `keys` | Directory for key material used by credential/snippet workflows |
|
| `DB_PATH` | `data/liqa.db` | SQLite database file |
|
||||||
| `DB_PATH` | `data/sessions.db` | SQLite database file |
|
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
|
||||||
|
| `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept |
|
||||||
|
| `FILE_CLEANUP_CRON` | `0 3 * * *` | When expired files are deleted |
|
||||||
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
|
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
|
||||||
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
|
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
|
||||||
|
| `PLAYWRIGHT_TRACE_MODE` | `off` | Default Playwright trace mode for runs: `on`, `retain-on-failure` or `off` (see [scenario.md](scenario.md)) |
|
||||||
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
|
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
|
||||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
|
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
|
||||||
|
|
||||||
@@ -62,13 +69,12 @@ The server listens on port **3000** by default.
|
|||||||
npm -w client run dev
|
npm -w client run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
The Vite dev server runs on **http://localhost:5173** and proxies these API prefixes to `localhost:13000` (or `localhost:3000` when running server locally):
|
The Vite dev server runs on **http://localhost:5173**. It has no API proxy: the client calls `VITE_API_URL` (default `/api/v1` on its own origin), and the server allows CORS from `http://localhost:5173`. So point it at a running server:
|
||||||
|
|
||||||
- `/environments`
|
```bash
|
||||||
- `/credentials`
|
npm -w client run dev:compose-api # API of the compose container (localhost:13000)
|
||||||
- `/snippets`
|
VITE_API_URL=http://localhost:3000/api/v1 npm -w client run dev # API of a locally started server
|
||||||
- `/sessions`
|
```
|
||||||
- `/scenarios`
|
|
||||||
|
|
||||||
**Production build**:
|
**Production build**:
|
||||||
|
|
||||||
@@ -80,6 +86,36 @@ The built files are emitted to `client/dist/`.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Database migrations
|
||||||
|
|
||||||
|
The SQLite schema is managed by TypeORM migrations in `server/src/database/migrations/`; `synchronize` is off.
|
||||||
|
|
||||||
|
- **Docker:** the container applies pending migrations before starting the server.
|
||||||
|
- **Locally:** build, then apply them before starting the server (it refuses to start while migrations are pending):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm -w server run build
|
||||||
|
npm -w server run migration:run # apply pending migrations to DB_PATH
|
||||||
|
npm -w server run migration:show # list migrations and whether they're applied
|
||||||
|
```
|
||||||
|
|
||||||
|
The scripts run from `server/`, so `DB_PATH` (default `data/liqa.db`) is relative to it, and they read `server/.env` if present, like the server does.
|
||||||
|
|
||||||
|
**Changing the schema** (adding or changing an entity):
|
||||||
|
|
||||||
|
1. Change the entity and build (`npm -w server run build`).
|
||||||
|
2. Make sure your local database is on the latest migration (`migration:run`).
|
||||||
|
3. Generate a migration from the difference between the entities and that database:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm -w server run migration:generate -- src/database/migrations/AddSomething
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Review the generated file, then add its class to `MIGRATIONS` in `src/database/migrations/index.ts` (they're listed explicitly, oldest first).
|
||||||
|
5. Run the tests: `test/migrations.spec.ts` checks that the migrations produce exactly the schema the entities describe, and fails if an entity change has no migration.
|
||||||
|
|
||||||
|
The initial migration (`Initial…`) adopts databases created before migrations existed (by `synchronize`): if the tables already exist, it's only recorded as applied.
|
||||||
|
|
||||||
## Running tests
|
## Running tests
|
||||||
|
|
||||||
### Server (Jest)
|
### Server (Jest)
|
||||||
@@ -100,7 +136,7 @@ Watch mode:
|
|||||||
npm -w server run test:watch
|
npm -w server run test:watch
|
||||||
```
|
```
|
||||||
|
|
||||||
Enable verbose NestJS log output during tests:
|
Print the NestJS logs of the test app (they're silenced by default; `DEBUG=test`):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm -w server run test:debug
|
npm -w server run test:debug
|
||||||
@@ -168,6 +204,8 @@ The root `Dockerfile` builds a single image with the whole application: it build
|
|||||||
|
|
||||||
The runtime image uses Playwright's headless-only Chromium build (`chromium-headless-shell`) with just the shared libraries it links against, plus DejaVu and Liberation fonts (Liberation is metric-compatible with Arial/Times, so pages lay out as they would with those fonts). All browser launches are headless, so the full desktop Chromium isn't installed. If a new Playwright version needs another library, `ldd` on the `chrome-headless-shell` binary in the image lists what's missing.
|
The runtime image uses Playwright's headless-only Chromium build (`chromium-headless-shell`) with just the shared libraries it links against, plus DejaVu and Liberation fonts (Liberation is metric-compatible with Arial/Times, so pages lay out as they would with those fonts). All browser launches are headless, so the full desktop Chromium isn't installed. If a new Playwright version needs another library, `ldd` on the `chrome-headless-shell` binary in the image lists what's missing.
|
||||||
|
|
||||||
|
To keep the image small, production dependencies and the browser are installed in a separate `runtime-deps` stage, which drops what nothing loads at runtime (source maps, TypeScript sources and declarations, docs, TypeORM's browser build, better-sqlite3's C sources, and Playwright's ffmpeg, which is only used for video recording). The runtime stage is plain `debian:bookworm-slim` with only the `node` binary copied in, so the image has no `npm`, `npx`, `yarn` or `corepack`. If a package starts failing in the image only, check whether it reads one of the deleted file types at runtime.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose build
|
docker compose build
|
||||||
```
|
```
|
||||||
@@ -180,6 +218,43 @@ docker compose build --no-cache
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Licenses
|
||||||
|
|
||||||
|
The project is MIT-licensed ([LICENSE](../LICENSE)); the `license` field in all three `package.json` files says the same.
|
||||||
|
|
||||||
|
The image ships third-party code: the server's production dependencies, the client's production dependencies (bundled into its build), the Node.js binary, Chromium and Debian packages. Their notices are in the image as follows:
|
||||||
|
|
||||||
|
- **npm packages and Node.js**: the `licenses` stage of the Dockerfile runs `scripts/third-party-licenses.mjs`, which writes the project's LICENSE followed by every production dependency of both workspaces with its license files (or, for the few packages that ship none, the declared license, author and source). Node.js's LICENSE for the exact version in the image is fetched from GitHub and appended. The result is `/app/client/licenses.txt`, which the app serves at `/licenses.txt`. The build fails if a package has no license information at all.
|
||||||
|
- **Server packages' own license files** stay in `node_modules`: the slimming step deletes Markdown files except `LICENSE*`, `NOTICE*` and `COPYING*`.
|
||||||
|
- **Chromium**: `LICENSE.headless_shell` next to the binary under `/ms-playwright`.
|
||||||
|
- **Debian packages**: `/usr/share/doc/*/copyright`.
|
||||||
|
|
||||||
|
The image also has the OCI labels `org.opencontainers.image.licenses=MIT`, `source`, `title` and `version` (CI passes the version as the `VERSION` build arg).
|
||||||
|
|
||||||
|
To check the notices locally, or to review a new dependency's license, run from the repository root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node scripts/third-party-licenses.mjs > /tmp/licenses.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Before adding a dependency, check its license is compatible with MIT distribution (permissive licenses such as MIT, ISC, BSD, Apache-2.0 are; copyleft ones such as GPL or AGPL need a closer look).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CI (Gitea Actions)
|
||||||
|
|
||||||
|
`.gitea/workflows/ci.yml` runs on pushes to `master` and on pull requests:
|
||||||
|
|
||||||
|
- **server**: lint (no warnings allowed), type-check, tests, build.
|
||||||
|
- **client**: lint (no warnings allowed), build, Storybook tests in headless Chromium.
|
||||||
|
- **image** (pushes to `master` only): when the push changes `version` in the root `package.json`, and both check jobs pass, builds the Docker image and pushes it to the Gitea container registry set by `REGISTRY` at the top of the workflow (`git.hq.ars9.space`) as `<registry>/<owner>/<repo>:<version>` and `:latest`.
|
||||||
|
|
||||||
|
The image job logs in as the repository owner with the `REGISTRY_TOKEN` secret: a Gitea access token with package write access (Settings → Applications → token with `write:package`), added under the repository's Settings → Actions → Secrets. It runs `docker` on the runner, so the runner must give jobs access to a Docker daemon (act_runner mounts the host's Docker socket into job containers by default).
|
||||||
|
|
||||||
|
Jobs clone the repository from the address the runner was registered with. If that's an internal hostname (such as `http://gitea:3000` from Gitea's compose network), job containers can't resolve it: either register the runner with the public URL, or set `container.network` in the act_runner config to Gitea's Docker network so jobs join it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Running with Docker Compose
|
## Running with Docker Compose
|
||||||
|
|
||||||
Start (detached):
|
Start (detached):
|
||||||
@@ -198,7 +273,7 @@ Everything is served by the single `liqa` container at **http://localhost:13000*
|
|||||||
|
|
||||||
When switching from the old two-container setup (`server` + `client`), remove the old containers with `docker compose up -d --build --remove-orphans`.
|
When switching from the old two-container setup (`server` + `client`), remove the old containers with `docker compose up -d --build --remove-orphans`.
|
||||||
|
|
||||||
SQLite data is persisted in `./data/` and key files are mounted from `./keys/` — both directories are volume-mounted into the container.
|
The SQLite database and stored files are persisted in `./data/`, which is volume-mounted into the container.
|
||||||
|
|
||||||
Stop and remove containers:
|
Stop and remove containers:
|
||||||
|
|
||||||
@@ -216,7 +291,7 @@ docker compose logs -f
|
|||||||
|
|
||||||
## Client overview
|
## Client overview
|
||||||
|
|
||||||
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, credentials, snippets, sessions, scenarios, and runs.
|
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing scenarios, runs, snippets, credentials, environments and sessions, and for importing exported YAML.
|
||||||
|
|
||||||
### Tech stack
|
### Tech stack
|
||||||
|
|
||||||
@@ -224,9 +299,13 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
|
|||||||
|---|---|
|
|---|---|
|
||||||
| React 19 + TypeScript | UI framework |
|
| React 19 + TypeScript | UI framework |
|
||||||
| Vite 6 | Dev server and bundler |
|
| Vite 6 | Dev server and bundler |
|
||||||
| react-router-dom (HashRouter) | Client-side routing |
|
| react-router-dom 7 (`BrowserRouter`) | Client-side routing |
|
||||||
|
| @tanstack/react-query | Data fetching (cross-scenario runs list) |
|
||||||
| i18next + react-i18next | Internationalisation |
|
| i18next + react-i18next | Internationalisation |
|
||||||
| lucide-react | Icon library |
|
| lucide-react | Icon library |
|
||||||
|
| @monaco-editor/react | Code editor for steps and snippets |
|
||||||
|
| react-markdown + highlight.js | Markdown descriptions and code highlighting |
|
||||||
|
| yaml | YAML export of entities |
|
||||||
| moment | Relative timestamp formatting |
|
| moment | Relative timestamp formatting |
|
||||||
| ESLint 10 + Prettier | Linting and formatting |
|
| ESLint 10 + Prettier | Linting and formatting |
|
||||||
| Storybook 10 + Vitest | Component development and testing |
|
| Storybook 10 + Vitest | Component development and testing |
|
||||||
@@ -236,29 +315,30 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
|
|||||||
```
|
```
|
||||||
client/
|
client/
|
||||||
src/
|
src/
|
||||||
api/ API client modules (environments, credentials, snippets, sessions, scenarios)
|
api/ API client (client.ts) and types (types.ts)
|
||||||
hooks/ useTheme (light/dark persistence)
|
components/ modals/ - run, export, export logs and delete confirmation modals
|
||||||
|
hooks/ useTheme, usePageTitle, useRunDefaults, useImportFile
|
||||||
i18n/ i18next bootstrap + locales/en.json
|
i18n/ i18next bootstrap + locales/en.json
|
||||||
pages/ Environment/Credential/Snippet/Session/Scenario/Run pages
|
lib/ highlight.js setup, API error toast events
|
||||||
ui/ Reusable component library
|
pages/ scenario/, run/, snippet/, credential/, environment/, session/, import/
|
||||||
Badge, Breadcrumbs, Button, Card, Input, Select,
|
ui/ Reusable component library (Badge, Button, Card, CodeEditor, Modal,
|
||||||
SidePanel, Table, ThemeSwitcher, Timestamp
|
Select, SidePanel, Table, Toast, ... - see ui/index.ts)
|
||||||
.storybook/
|
.storybook/
|
||||||
stories/ *.stories.tsx for all ui/ components
|
stories/ *.stories.tsx for ui/ components
|
||||||
```
|
```
|
||||||
|
|
||||||
### Routing
|
### Routing
|
||||||
|
|
||||||
Hash-based routing (`/#/path`) avoids conflicts with the Vite dev-server proxy. Default route redirects to `/#/scenarios`.
|
`BrowserRouter` with plain paths. The root and unknown paths redirect to `/scenarios`. The server answers these paths with the client's `index.html` (see [architecture.md](architecture.md)), so they work on refresh.
|
||||||
|
|
||||||
| Route | Page |
|
| Route | Page |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `/#/environments` | Environment list |
|
| `/scenarios` | Scenario list |
|
||||||
| `/#/credentials` | Credential list |
|
| `/scenarios/:id` | Scenario details (steps, versions, credentials, used snippets, files) |
|
||||||
| `/#/snippets` | Snippet list |
|
| `/scenarios/:id/runs`, `/scenarios/:id/runs/:runId` | Runs of a scenario, run details |
|
||||||
| `/#/sessions` | Session list |
|
| `/runs` | Cross-scenario runs list |
|
||||||
| `/#/scenarios` | Scenario list |
|
| `/snippets`, `/credentials`, `/environments`, `/sessions` | Entity lists (plus `/:id`, `/new`, `/:id/edit` where applicable) |
|
||||||
| `/#/runs` | Cross-scenario runs list |
|
| `/import` | Central import |
|
||||||
|
|
||||||
### Theming
|
### Theming
|
||||||
|
|
||||||
|
|||||||
+66
-44
@@ -1,94 +1,116 @@
|
|||||||
# MCP tools
|
# MCP tools
|
||||||
|
|
||||||
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport).
|
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport), e.g. `http://localhost:13000/mcp` with the compose setup. Each request is served by a fresh MCP server, so there is no MCP session state between calls.
|
||||||
|
|
||||||
The server currently registers the following tools.
|
The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text.
|
||||||
|
|
||||||
## Sessions
|
## Sessions
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `list_sessions` | List stored sessions (paginated) |
|
| `list_sessions` | List saved browser sessions (`orderBy`/`orderDir`) |
|
||||||
| `delete_session` | Delete a session by UUID |
|
| `delete_session` | Delete a session by `id` |
|
||||||
|
|
||||||
## Environments
|
## Environments
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `list_environments` | List environments (paginated) |
|
| `list_environments` | List environments (`orderBy`/`orderDir`) |
|
||||||
| `get_environment` | Get one environment by UUID |
|
| `get_environment` | Get one environment by `id` |
|
||||||
| `create_environment` | Create environment (`name`, `urls`) |
|
| `create_environment` | Create an environment: `name`, optional `description`, `data` |
|
||||||
| `update_environment` | Update environment (`id`, optional `name`/`urls`) |
|
| `update_environment` | Update `name`, `description` and/or `data` of environment `id` |
|
||||||
| `delete_environment` | Delete environment by UUID |
|
| `delete_environment` | Delete an environment by `id` |
|
||||||
|
|
||||||
`urls` is a free-form key/value map. Common keys: `id_url`, `cabinet_url`, `admin_url`.
|
`data` is a free-form map of string keys to string values, read in step code with `context.getEnv(key)`.
|
||||||
|
|
||||||
|
## Credentials
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
|---|---|
|
||||||
|
| `list_credentials` | List credentials (`orderBy`/`orderDir`). Returns the full `data`, secrets included |
|
||||||
|
| `get_credential` | Get one credential by `id` (full `data`) |
|
||||||
|
| `create_credential` | Create a credential: `name`, optional `data` (JSON-encoded string) |
|
||||||
|
| `update_credential` | Update `name` and/or `data`; omitted fields are left unchanged |
|
||||||
|
| `delete_credential` | Delete a credential; also removes it from scenarios it's assigned to |
|
||||||
|
|
||||||
## Browser (ad-hoc)
|
## Browser (ad-hoc)
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
|
| `open_url` | Open `url`, optionally in saved session `sessionName`; returns title and content (`readerMode` for readable text, `selector` to limit to one element) |
|
||||||
| `exec_code` | Execute Playwright JS — script receives a single `context` argument (see `scenario.md`). Optional `environmentId` (UUID) resolves environment from DB for `context.getEnv()`. Optional `credentials` (`{ alias: credentialUUID }`) resolves credentials from DB for `context.getCredential(alias)`. |
|
| `exec_code` | Run Playwright JS that receives a single `context` argument (see [scenario.md](scenario.md)), optionally after opening `url` and/or in session `sessionName`. `environmentId` loads an environment for `context.getEnv()`; `credentials` (`{ alias: credentialId }`) loads credentials for `context.getCredential(alias)` |
|
||||||
|
|
||||||
## Scenarios
|
## Scenarios
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `list_scenarios` | List scenarios (paginated) |
|
| `list_scenarios` | List scenarios (`orderBy`/`orderDir`) |
|
||||||
| `get_scenario` | Get scenario with steps |
|
| `get_scenario` | Get a scenario (latest version) with its steps |
|
||||||
| `create_scenario` | Create scenario by `name` |
|
| `create_scenario` | Create a scenario: `name`, optional `description`, `environmentId` (default environment), `timeoutSeconds` |
|
||||||
| `update_scenario` | Rename scenario |
|
| `update_scenario` | Update scenario fields; bumps the version when content changes |
|
||||||
| `delete_scenario` | Delete scenario |
|
| `delete_scenario` | Delete a scenario with its steps, versions and runs |
|
||||||
| `create_scenario_step` | Add step to scenario |
|
| `create_scenario_step` | Append a step: `execCode`, optional `title` and `timeoutSeconds`. The schema also requires `order` and `type`, but both are ignored: new steps always go last (use `update_scenario_step` with `order` to move one) |
|
||||||
| `get_scenario_step` | Get one step |
|
| `get_scenario_step` | Get one step |
|
||||||
| `update_scenario_step` | Update step fields |
|
| `update_scenario_step` | Update step fields (including `order` to move it) |
|
||||||
| `delete_scenario_step` | Delete step |
|
| `delete_scenario_step` | Delete a step |
|
||||||
| `list_scenario_runs` | List runs for a scenario |
|
|
||||||
| `list_scenario_versions` | List a scenario's versions, newest first |
|
| `list_scenario_versions` | List a scenario's versions, newest first |
|
||||||
| `get_scenario_version` | Get one scenario version with its steps |
|
| `get_scenario_version` | Get one scenario version with its steps |
|
||||||
| `run_scenario` | Trigger run for scenario; optional `version` (defaults to latest) and `traceMode` |
|
| `list_scenario_credentials` | List credentials assigned to a scenario (alias → credential) |
|
||||||
| `get_scenario_run` | Get run with step runs and logs |
|
| `add_scenario_credential` | Assign credential `credentialId` to a scenario under `alias` |
|
||||||
| `wait_for_scenario_run` | Wait until run is `pass` or `fail` |
|
| `remove_scenario_credential` | Remove an assignment by `scenarioCredentialId` (the assignment id, not the credential id) |
|
||||||
| `export_scenario` | Export one scenario version (optional `version`, defaults to latest) |
|
| `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) |
|
||||||
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in `scenario.md`) |
|
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) |
|
||||||
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in `scenario.md`) |
|
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) |
|
||||||
|
| `export_e2e_test` | Export a scenario as a standalone Playwright test project (zip, base64) |
|
||||||
|
|
||||||
|
Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned.
|
||||||
|
|
||||||
|
## Runs
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
|---|---|
|
||||||
|
| `run_scenario` | Start a run of scenario `id` in `environmentId`; optional `version` (defaults to the latest), `saveSession`, `traceMode` (`on`, `retain-on-failure`, `off`; defaults to `PLAYWRIGHT_TRACE_MODE`) |
|
||||||
|
| `list_scenario_runs` | List runs of a scenario, optionally filtered by `status` |
|
||||||
|
| `list_all_runs` | List runs across all scenarios, optionally filtered by `status` |
|
||||||
|
| `get_scenario_run` | Get a run with its step runs (outputs) and logs |
|
||||||
|
| `wait_for_scenario_run` | Wait until a run is `pass` or `fail` (up to 5 minutes), then return it |
|
||||||
|
|
||||||
## Snippets
|
## Snippets
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `list_snippets` | List snippets (paginated) |
|
| `list_snippets` | List snippets (`orderBy`/`orderDir`) |
|
||||||
| `get_snippet` | Get one snippet (latest version) |
|
| `get_snippet` | Get one snippet (latest version) |
|
||||||
| `create_snippet` | Create snippet (`alias`, `title`, `code`) |
|
| `create_snippet` | Create a snippet: `alias`, `title`, `code`, optional `description` |
|
||||||
| `update_snippet` | Update snippet fields; bumps its version when content changes |
|
| `update_snippet` | Update snippet fields; bumps its version when content changes |
|
||||||
| `delete_snippet` | Delete snippet and all its versions |
|
| `delete_snippet` | Delete a snippet and all its versions |
|
||||||
| `list_snippet_versions` | List a snippet's versions, newest first |
|
| `list_snippet_versions` | List a snippet's versions, newest first |
|
||||||
| `get_snippet_version` | Get one snippet version |
|
| `get_snippet_version` | Get one snippet version |
|
||||||
|
|
||||||
## Scenario Files
|
Step code runs a snippet with `context.runSnippet("alias", ...args)` (latest version) or `context.runSnippet("alias@3", ...args)` (version 3).
|
||||||
|
|
||||||
|
## Scenario files
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `upload_scenario_file` | Upload a file to a scenario; accepts optional `expiresAt` (ISO 8601 date string) |
|
| `upload_scenario_file` | Upload a file to a scenario: `name`, base64 `contentBase64`, optional `mimeType` and `expiresAt` (ISO 8601) |
|
||||||
| `list_scenario_files` | List scenario files (paginated) |
|
| `list_scenario_files` | List a scenario's files (`limit`, `offset`) |
|
||||||
| `get_scenario_file_content` | Retrieve file content as base64 with metadata |
|
| `get_scenario_file_content` | Get a file's content as base64, with metadata |
|
||||||
|
|
||||||
## Run Artifact Files
|
## Run files
|
||||||
|
|
||||||
| Tool | Description |
|
| Tool | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `list_run_files` | List files (artifacts) created during a scenario run (paginated) |
|
| `list_run_files` | List files created during a run (`limit`, `offset`): downloads, failure screenshots/HTML, `trace.zip` |
|
||||||
| `get_run_file_content` | Retrieve run artifact content as base64 with metadata; run artifact content can't be modified and inherits expiry from the run artifact subsystem |
|
| `get_run_file_content` | Get a run file's content as base64, with metadata |
|
||||||
| `delete_run_file` | Delete a file from a run; the stored file is removed once no scenario or run references it (also `DELETE /scenarios/:id/runs/:runId/files/:fileId` and the delete button on the run detail page) |
|
| `delete_run_file` | Delete a file from a run; the stored file is removed once no scenario or run references it (also `DELETE /api/v1/scenarios/:id/runs/:runId/files/:fileId` and the delete button on the run detail page) |
|
||||||
|
|
||||||
## Binary Content Handling
|
## Binary content handling
|
||||||
|
|
||||||
File tools transport binary payloads as base64-encoded strings in a `contentBase64` field with an accompanying `encoding: "base64"` marker in the response. When retrieving file content via `get_scenario_file_content` or `get_run_file_content`, decode the base64 to recover the original bytes.
|
File tools carry binary content as base64 strings in a `contentBase64` field, with `encoding: "base64"` in the response. Decode it to get the original bytes.
|
||||||
|
|
||||||
Scenario files uploaded via `upload_scenario_file` must have their content pre-encoded as base64. Run artifacts are created implicitly through scenario execution (via `context.downloadFile()` during step execution) and cannot be uploaded via MCP.
|
Content for `upload_scenario_file` must be base64-encoded. Run files are only created by runs themselves (`context.downloadFile()`, failure page dumps, traces) and can't be uploaded.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
- Tool IDs and entity IDs are UUIDs.
|
- The step `type` field (`login`, `exec`, `sign`) in `create_scenario_step`, `update_scenario_step` and `import_scenario` is a legacy field kept for compatibility; it's ignored, and every step runs its `execCode`.
|
||||||
- `create_scenario_step` schema still accepts legacy `type`/`sessionName` fields for compatibility. Current scheduler executes `execCode` plus optional `validateCode` and does not branch by step type.
|
|
||||||
|
|
||||||
+32
-43
@@ -1,23 +1,23 @@
|
|||||||
# Scenario execution
|
# Scenario execution
|
||||||
|
|
||||||
When a scenario run is created, the server creates one `ScenarioRunStep` per scenario step.
|
API paths below are relative to the REST prefix `/api/v1` (e.g. `POST /api/v1/scenarios/:id/run`).
|
||||||
|
|
||||||
- Step runs are ordered by `step.order`.
|
## Runs
|
||||||
- First step run starts as `pending`; the rest start as `waiting`.
|
|
||||||
- Scheduler tick (`@Interval(1000)`) picks pending runs and processes steps in order.
|
|
||||||
- Steps in the same run share one Playwright browser/context/page.
|
|
||||||
|
|
||||||
## Execution model
|
Creating a run (`POST /scenarios/:id/run`, the Run button, or the `run_scenario` MCP tool) takes an environment, and optionally a scenario version (latest by default), `saveSession` and a trace mode.
|
||||||
|
|
||||||
Current scheduler behavior is exec-centric:
|
- The run gets one step run per step of that scenario version, each with its own copy of the step's title, code and timeout. Editing or deleting steps later doesn't change existing runs.
|
||||||
|
- The first step run starts as `pending`, the rest as `waiting`.
|
||||||
- `execCode` is required for a step to pass.
|
- A scheduler tick (`@Interval(1000)`) picks up pending runs (up to 10 at a time) and executes their steps in order. All steps of a run share one Playwright browser, context and page.
|
||||||
- `validateCode` is optional and runs after `execCode`.
|
- A step passes when its code returns, and fails when it throws or times out. Its return value is stored as the step output (JSON) and is available to later steps via `context.getStepOutput()`.
|
||||||
- Legacy step type metadata may still appear in MCP payloads, but run execution is not branched by step type.
|
- When a step fails, the run is marked `fail`, the remaining steps are `cancelled`, and a screenshot and the page HTML are saved to the run's files (`step-<order>-failure.png` / `.html`).
|
||||||
|
- Timeouts: each step gets its own `timeoutSeconds`, otherwise the scenario's `timeoutSeconds`, otherwise 60 s. The run as a whole fails once it has run longer than the scenario's `timeoutSeconds` (default 600 s); this is checked before each step.
|
||||||
|
- With `saveSession`, the run's browser is kept after the run as a saved session named `run-<runId>` (see Sessions in the UI), instead of being closed.
|
||||||
|
- Runs left `in_progress` when the server stops are marked `fail` on the next start.
|
||||||
|
|
||||||
## Script runtime
|
## Script runtime
|
||||||
|
|
||||||
`execCode` and `validateCode` execute as async JavaScript with a single `context` argument:
|
Step code (`execCode`) and snippet code run as an async JavaScript function body with a single `context` argument:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async (context) => {
|
async (context) => {
|
||||||
@@ -25,23 +25,29 @@ async (context) => {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Available in scope:
|
Available on `context`:
|
||||||
|
|
||||||
- `context.page`: Playwright `Page`
|
- `context.page`: Playwright `Page`
|
||||||
- `context.browser`: Playwright `BrowserContext`
|
- `context.browser`: Playwright `BrowserContext`
|
||||||
- `context.env`: shallow copy of environment key/value map
|
- `context.env`: shallow copy of the environment's key/value map
|
||||||
- `context.getEnv(key)`: required environment value lookup (throws if missing)
|
- `context.getEnv(key)`: environment value lookup (throws if missing)
|
||||||
- `context.getCredential(alias)`: credential payload assigned to the scenario alias
|
- `context.getCredential(alias)`: payload of the credential assigned to the scenario under `alias` (parsed JSON when the data is JSON; throws if missing)
|
||||||
- `context.getStepOutput(order)`: prior step output by absolute order (`1`, `2`, ...) or relative (`-1` = previous step)
|
- `context.getStepOutput(order)`: output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none
|
||||||
- `context.dumpDom(selector?)`: simplified DOM snapshot
|
- `context.dumpDom(selector?)`: simplified DOM snapshot of the page (or of one element)
|
||||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: structured step logs
|
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: run log entries
|
||||||
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
|
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
|
||||||
- `context.runSnippet(name, ...args)`: execute stored snippet code with the same context. `name` is the snippet alias for its latest version, or `alias@<version>` (e.g. `login@3`) to pin a specific version
|
- `context.runSnippet(name, ...args)`: runs stored snippet code with the same context; the snippet receives the extra arguments as `...args`. `name` is the snippet alias for its latest version, or `alias@<version>` (e.g. `login@3`) to pin a specific version. Snippet start/finish/failure is logged
|
||||||
- `context.getScenarioFiles(opts?)`: list files uploaded to the scenario (`limit`, `offset`)
|
- `context.getScenarioFiles(opts?)`: list files uploaded to the scenario (`limit`, `offset`), including their path on disk
|
||||||
- `context.downloadFile(url, opts?)`: fetch `url` and save the result as a run artifact (requires a real scenario run — throws when invoked ad hoc, e.g. via the `exec_code` MCP tool). `opts` may include `method`, `headers`, `body`, `filename`. `url` also accepts a `data:` URI (`data:<mediaType>;base64,<data>` or `data:<mediaType>,<percent-encoded data>`) to save content generated in-script (e.g. a credential JWT) directly, without an actual network fetch.
|
- `context.downloadFile(url, opts?)`: fetch `url` and save the result as a run file (requires a real scenario run — throws when invoked ad hoc, e.g. via the `exec_code` MCP tool). `opts` may include `method`, `headers`, `body`, `filename`. `url` also accepts a `data:` URI (`data:<mediaType>;base64,<data>` or `data:<mediaType>,<percent-encoded data>`) to save content generated in-script (e.g. a credential JWT) directly, without an actual network fetch.
|
||||||
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
|
||||||
|
|
||||||
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
|
Also in scope:
|
||||||
|
|
||||||
|
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
||||||
|
- `expect`: Playwright's `expect` (e.g. `await expect(context.page.locator("h1")).toHaveText("Done")`)
|
||||||
|
|
||||||
|
Code is syntax-checked before it runs, and executes in the server process: it's trusted code, not sandboxed.
|
||||||
|
|
||||||
|
Step run logs also include automatic "Step N started / passed / failed" entries.
|
||||||
|
|
||||||
## Versioning
|
## Versioning
|
||||||
|
|
||||||
@@ -71,7 +77,7 @@ Exports hold exactly one version and always include its `version` number (the la
|
|||||||
- Items are imported in dependency order - environments, credentials, snippets, scenarios - regardless of their order in the file, so a scenario can reference an environment or credential from the same file.
|
- Items are imported in dependency order - environments, credentials, snippets, scenarios - regardless of their order in the file, so a scenario can reference an environment or credential from the same file.
|
||||||
- The response lists what was imported: `{ imported: [{ kind, id, name, version? }] }`.
|
- The response lists what was imported: `{ imported: [{ kind, id, name, version? }] }`.
|
||||||
|
|
||||||
A scenario export (`GET /scenarios/:id/export`, optionally with its environment and credentials) is in this format, one document per entity, and can be imported back as is.
|
A scenario export (`GET /scenarios/:id/export`, optionally with its environment, credentials and used snippets) is in this format, one document per entity, and can be imported back as is. Query parameters: `includeEnvironment=true`, `credentialIds` and `snippetIds` (repeat the parameter or separate ids with commas) and `version`. A selected snippet is exported once per version the scenario uses: the latest for plain `runSnippet("alias")` calls, plus each version pinned with `alias@N`. Snippets used only through other snippets count as used.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
---
|
---
|
||||||
@@ -107,23 +113,6 @@ Traces are off by default because they often reach ~10 MB per run.
|
|||||||
|
|
||||||
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
|
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
|
||||||
|
|
||||||
## Validation contract
|
|
||||||
|
|
||||||
`validateCode` may return:
|
|
||||||
|
|
||||||
```js
|
|
||||||
return { success: true, description: 'ok' };
|
|
||||||
// or
|
|
||||||
return false;
|
|
||||||
```
|
|
||||||
|
|
||||||
Interpretation:
|
|
||||||
|
|
||||||
- Boolean: `true` = pass, `false` = fail
|
|
||||||
- Object: `success` controls pass/fail; `description` is persisted as step description
|
|
||||||
|
|
||||||
On validation failure, the step fails and the run is marked `fail`.
|
|
||||||
|
|
||||||
## Statuses
|
## Statuses
|
||||||
|
|
||||||
Run status:
|
Run status:
|
||||||
@@ -147,7 +136,7 @@ Run-step status:
|
|||||||
1. Create environment
|
1. Create environment
|
||||||
2. Create credentials and snippets (optional but common)
|
2. Create credentials and snippets (optional but common)
|
||||||
3. Create scenario
|
3. Create scenario
|
||||||
4. Add ordered steps (`execCode`, optional `validateCode`)
|
4. Add ordered steps (`execCode`, optional `title` and `timeoutSeconds`)
|
||||||
5. Assign credentials to scenario aliases when needed
|
5. Assign credentials to scenario aliases when needed
|
||||||
6. Run scenario
|
6. Run scenario
|
||||||
7. Wait for run completion and inspect run logs/outputs
|
7. Wait for run completion and inspect run logs/outputs
|
||||||
Generated
+4632
-3597
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -1,7 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "liqa",
|
"name": "liqa",
|
||||||
"version": "1.19.2",
|
"version": "1.22.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"author": "Andrii Arsenin",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=24"
|
"node": ">=24"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Writes the license notices for everything the app ships to stdout: the
|
||||||
|
// project's own LICENSE, then every production dependency of the client and
|
||||||
|
// server workspaces with its license text, as installed in node_modules.
|
||||||
|
//
|
||||||
|
// node scripts/third-party-licenses.mjs > licenses.txt
|
||||||
|
//
|
||||||
|
// Run it from the repository root after `npm ci` (dev dependencies may be
|
||||||
|
// installed too; only production dependencies are listed). Exits non-zero
|
||||||
|
// when a package's license can't be determined.
|
||||||
|
|
||||||
|
import { execFileSync } from "node:child_process";
|
||||||
|
import * as fs from "node:fs";
|
||||||
|
import * as path from "node:path";
|
||||||
|
|
||||||
|
const ROOT = process.cwd();
|
||||||
|
const LICENSE_FILE = /^(licen[cs]e|copying|notice)(\.|-|$)/i;
|
||||||
|
|
||||||
|
const tree = JSON.parse(
|
||||||
|
execFileSync("npm", ["ls", "--omit=dev", "--all", "--long", "--json"], {
|
||||||
|
cwd: ROOT,
|
||||||
|
encoding: "utf8",
|
||||||
|
maxBuffer: 256 * 1024 * 1024,
|
||||||
|
// npm ls exits non-zero on unmet optional peers; the JSON is still complete
|
||||||
|
stdio: ["ignore", "pipe", "ignore"],
|
||||||
|
}).toString() || "{}",
|
||||||
|
);
|
||||||
|
|
||||||
|
const workspaces = new Set(
|
||||||
|
(
|
||||||
|
JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"))
|
||||||
|
.workspaces ?? []
|
||||||
|
).map((w) => path.resolve(ROOT, w)),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** name@version → { name, version, license, dir } */
|
||||||
|
const packages = new Map();
|
||||||
|
const walk = (node) => {
|
||||||
|
for (const [name, dep] of Object.entries(node.dependencies ?? {})) {
|
||||||
|
// Unmet optional peers have no path
|
||||||
|
if (!dep.path) continue;
|
||||||
|
// Workspace packages are our own code: list only their dependencies
|
||||||
|
if (!workspaces.has(fs.realpathSync(dep.path))) {
|
||||||
|
const key = `${name}@${dep.version}`;
|
||||||
|
if (packages.has(key)) continue;
|
||||||
|
packages.set(key, { name, version: dep.version, dir: dep.path });
|
||||||
|
}
|
||||||
|
walk(dep);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(tree);
|
||||||
|
|
||||||
|
const manifestOf = (pkg) =>
|
||||||
|
JSON.parse(fs.readFileSync(path.join(pkg.dir, "package.json"), "utf8"));
|
||||||
|
|
||||||
|
const licenseOf = (pkg) => {
|
||||||
|
const manifest = manifestOf(pkg);
|
||||||
|
const field = manifest.license ?? manifest.licenses;
|
||||||
|
if (typeof field === "string") return field;
|
||||||
|
if (Array.isArray(field)) return field.map((l) => l.type ?? l).join(" OR ");
|
||||||
|
if (field?.type) return field.type;
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const licenseTexts = (pkg) =>
|
||||||
|
fs
|
||||||
|
.readdirSync(pkg.dir)
|
||||||
|
.filter(
|
||||||
|
(f) =>
|
||||||
|
LICENSE_FILE.test(f) && fs.statSync(path.join(pkg.dir, f)).isFile(),
|
||||||
|
)
|
||||||
|
.sort()
|
||||||
|
.map((f) => fs.readFileSync(path.join(pkg.dir, f), "utf8").trim());
|
||||||
|
|
||||||
|
// For packages that ship no license file, record who to attribute and where
|
||||||
|
// the full terms are
|
||||||
|
const withoutLicenseFile = (pkg, license) => {
|
||||||
|
const { author, repository, homepage } = manifestOf(pkg);
|
||||||
|
const authorName = typeof author === "string" ? author : author?.name;
|
||||||
|
const repo = typeof repository === "string" ? repository : repository?.url;
|
||||||
|
return [
|
||||||
|
`The package ships no license file; its package.json declares ${license}.`,
|
||||||
|
authorName && `Author: ${authorName}`,
|
||||||
|
(repo || homepage) && `Source: ${repo || homepage}`,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join("\n");
|
||||||
|
};
|
||||||
|
|
||||||
|
const missing = [];
|
||||||
|
const sections = [...packages.values()]
|
||||||
|
.sort(
|
||||||
|
(a, b) =>
|
||||||
|
a.name.localeCompare(b.name) || a.version.localeCompare(b.version),
|
||||||
|
)
|
||||||
|
.map((pkg) => {
|
||||||
|
const license = licenseOf(pkg);
|
||||||
|
const texts = licenseTexts(pkg);
|
||||||
|
if (!license && texts.length === 0)
|
||||||
|
missing.push(`${pkg.name}@${pkg.version}`);
|
||||||
|
const body =
|
||||||
|
texts.length > 0 ? texts.join("\n\n") : withoutLicenseFile(pkg, license);
|
||||||
|
return `${pkg.name}@${pkg.version}\nLicense: ${license ?? "see below"}\n\n${body}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (missing.length > 0) {
|
||||||
|
console.error(`No license information for: ${missing.join(", ")}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rule = "-".repeat(79);
|
||||||
|
process.stdout.write(
|
||||||
|
[
|
||||||
|
fs.readFileSync(path.join(ROOT, "LICENSE"), "utf8").trim(),
|
||||||
|
`${"=".repeat(79)}\n\nThird-party software\n\nThis application includes the following third-party packages (${sections.length}),\nunder their own licenses:`,
|
||||||
|
...sections,
|
||||||
|
].join(`\n\n${rule}\n\n`) + "\n",
|
||||||
|
);
|
||||||
@@ -12,4 +12,8 @@ module.exports = {
|
|||||||
'^@mozilla/readability$': '<rootDir>/test/__mocks__/readability.ts',
|
'^@mozilla/readability$': '<rootDir>/test/__mocks__/readability.ts',
|
||||||
},
|
},
|
||||||
testEnvironment: 'node',
|
testEnvironment: 'node',
|
||||||
|
// Each suite builds a full Nest app in beforeAll. That takes well under a
|
||||||
|
// second on an idle machine, but several seconds when every suite starts at
|
||||||
|
// once on a busy CI runner, past Jest's default 5 s.
|
||||||
|
testTimeout: 30_000,
|
||||||
};
|
};
|
||||||
+5
-2
@@ -7,6 +7,9 @@
|
|||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
"start:dev": "nest start --watch",
|
"start:dev": "nest start --watch",
|
||||||
"start:prod": "node dist/main",
|
"start:prod": "node dist/main",
|
||||||
|
"migration:run": "node dist/database/migrate",
|
||||||
|
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
|
||||||
|
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
@@ -15,8 +18,8 @@
|
|||||||
"test:watch": "jest --watch"
|
"test:watch": "jest --watch"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "Andrii Arsenin",
|
||||||
"license": "ISC",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||||
"@mozilla/readability": "^0.6.0",
|
"@mozilla/readability": "^0.6.0",
|
||||||
|
|||||||
@@ -5,29 +5,15 @@ import { ServeStaticModule } from "@nestjs/serve-static";
|
|||||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||||
import { BrowserModule } from "./browser/browser.module";
|
import { BrowserModule } from "./browser/browser.module";
|
||||||
import { clientStaticOptions } from "./common/client-static";
|
import { clientStaticOptions } from "./common/client-static";
|
||||||
|
import { dataSourceOptions } from "./database/data-source";
|
||||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||||
import { CredentialEntity } from "./credential/credential.entity";
|
|
||||||
import { CredentialModule } from "./credential/credential.module";
|
import { CredentialModule } from "./credential/credential.module";
|
||||||
import { EnvironmentEntity } from "./environment/environment.entity";
|
|
||||||
import { EnvironmentModule } from "./environment/environment.module";
|
import { EnvironmentModule } from "./environment/environment.module";
|
||||||
import { FileEntity } from "./file/file.entity";
|
|
||||||
import { FileModule } from "./file/file.module";
|
import { FileModule } from "./file/file.module";
|
||||||
import { ScenarioFileEntity } from "./file/scenario-file.entity";
|
|
||||||
import { ScenarioRunFileEntity } from "./file/scenario-run-file.entity";
|
|
||||||
import { HealthModule } from "./health/health.module";
|
import { HealthModule } from "./health/health.module";
|
||||||
import { ImportModule } from "./import/import.module";
|
import { ImportModule } from "./import/import.module";
|
||||||
import { McpModule } from "./mcp/mcp.module";
|
import { McpModule } from "./mcp/mcp.module";
|
||||||
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
|
|
||||||
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
|
|
||||||
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
|
|
||||||
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
|
|
||||||
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
|
|
||||||
import { ScenarioVersionEntity } from "./scenario/scenario-version.entity";
|
|
||||||
import { SnippetVersionEntity } from "./snippet/snippet-version.entity";
|
|
||||||
import { ScenarioEntity } from "./scenario/scenario.entity";
|
|
||||||
import { ScenarioModule } from "./scenario/scenario.module";
|
import { ScenarioModule } from "./scenario/scenario.module";
|
||||||
import { SessionEntity } from "./session/session.entity";
|
|
||||||
import { SnippetEntity } from "./snippet/snippet.entity";
|
|
||||||
import { SnippetModule } from "./snippet/snippet.module";
|
import { SnippetModule } from "./snippet/snippet.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@@ -45,28 +31,8 @@ import { SnippetModule } from "./snippet/snippet.module";
|
|||||||
}),
|
}),
|
||||||
TypeOrmModule.forRootAsync({
|
TypeOrmModule.forRootAsync({
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
useFactory: (config: ConfigService<AppConfig, true>) => ({
|
useFactory: (config: ConfigService<AppConfig, true>) =>
|
||||||
type: "better-sqlite3",
|
dataSourceOptions(config.get("DB_PATH")),
|
||||||
database: config.get("DB_PATH"),
|
|
||||||
entities: [
|
|
||||||
SessionEntity,
|
|
||||||
EnvironmentEntity,
|
|
||||||
CredentialEntity,
|
|
||||||
ScenarioEntity,
|
|
||||||
ScenarioStepEntity,
|
|
||||||
ScenarioVersionEntity,
|
|
||||||
ScenarioRunEntity,
|
|
||||||
ScenarioRunStepEntity,
|
|
||||||
ScenarioRunLogEntity,
|
|
||||||
ScenarioCredentialEntity,
|
|
||||||
SnippetEntity,
|
|
||||||
SnippetVersionEntity,
|
|
||||||
FileEntity,
|
|
||||||
ScenarioFileEntity,
|
|
||||||
ScenarioRunFileEntity,
|
|
||||||
],
|
|
||||||
synchronize: true,
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
BrowserModule,
|
BrowserModule,
|
||||||
EnvironmentModule,
|
EnvironmentModule,
|
||||||
|
|||||||
@@ -74,7 +74,6 @@ export interface ExecContext {
|
|||||||
credentials?: Record<string, unknown>;
|
credentials?: Record<string, unknown>;
|
||||||
environment?: EnvironmentData | null;
|
environment?: EnvironmentData | null;
|
||||||
snippets?: Record<string, string> | null;
|
snippets?: Record<string, string> | null;
|
||||||
result?: unknown;
|
|
||||||
scenarioId?: string;
|
scenarioId?: string;
|
||||||
runId?: string;
|
runId?: string;
|
||||||
fileService?: FileStorageService;
|
fileService?: FileStorageService;
|
||||||
@@ -115,7 +114,6 @@ export class CodeExecutorService {
|
|||||||
credentials,
|
credentials,
|
||||||
environment,
|
environment,
|
||||||
snippets,
|
snippets,
|
||||||
result,
|
|
||||||
scenarioId,
|
scenarioId,
|
||||||
runId,
|
runId,
|
||||||
fileService,
|
fileService,
|
||||||
@@ -278,12 +276,11 @@ export class CodeExecutorService {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// `console`, `result`, and `expect` are injected as named parameters so
|
// `console` and `expect` are injected as named parameters so scripts
|
||||||
// existing scripts that reference them directly still work.
|
// can reference them directly.
|
||||||
const fn = new Function(
|
const fn = new Function(
|
||||||
"context",
|
"context",
|
||||||
"console",
|
"console",
|
||||||
"result",
|
|
||||||
"expect",
|
"expect",
|
||||||
`return (async (context) => { ${code} })(context)`,
|
`return (async (context) => { ${code} })(context)`,
|
||||||
);
|
);
|
||||||
@@ -291,7 +288,6 @@ export class CodeExecutorService {
|
|||||||
const execResult = await fn(
|
const execResult = await fn(
|
||||||
scriptContext,
|
scriptContext,
|
||||||
fakeConsole,
|
fakeConsole,
|
||||||
result,
|
|
||||||
playwrightExpect,
|
playwrightExpect,
|
||||||
);
|
);
|
||||||
return { result: execResult };
|
return { result: execResult };
|
||||||
|
|||||||
@@ -46,11 +46,6 @@ export class ExecContextBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
result(result: unknown): this {
|
|
||||||
this.ctx.result = result;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
scenarioId(scenarioId: string): this {
|
scenarioId(scenarioId: string): this {
|
||||||
this.ctx.scenarioId = scenarioId;
|
this.ctx.scenarioId = scenarioId;
|
||||||
return this;
|
return this;
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/** Vite dev server (`npm -w client run dev`), calling the API cross-origin. */
|
||||||
|
const DEV_ORIGINS = ["http://localhost:5173", "http://127.0.0.1:5173"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The port compose.yaml publishes. The UI is served from the same origin in
|
||||||
|
* production, so these only matter for other tools calling the API from a
|
||||||
|
* page on that origin; keep in sync with compose.yaml.
|
||||||
|
*/
|
||||||
|
const PRODUCTION_ORIGINS = ["http://localhost:13000", "http://127.0.0.1:13000"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Origins allowed to call the API cross-origin. `CORS_ORIGINS` (comma
|
||||||
|
* separated) overrides the defaults, which depend on NODE_ENV: the compose
|
||||||
|
* port in production, the Vite dev server otherwise.
|
||||||
|
*/
|
||||||
|
export function corsOrigins(nodeEnv: string, override: string): string[] {
|
||||||
|
const configured = override
|
||||||
|
.split(",")
|
||||||
|
.map((origin) => origin.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (configured.length > 0) return configured;
|
||||||
|
return nodeEnv === "production" ? PRODUCTION_ORIGINS : DEV_ORIGINS;
|
||||||
|
}
|
||||||
@@ -17,9 +17,14 @@ export enum TraceMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class AppConfig {
|
export class AppConfig {
|
||||||
|
/** `production` in the Docker image; also selects the default CORS origins. */
|
||||||
@IsString()
|
@IsString()
|
||||||
NODE_ENV: string = "development";
|
NODE_ENV: string = "development";
|
||||||
|
|
||||||
|
/** Comma-separated origins allowed to call the API cross-origin; empty = default for NODE_ENV. */
|
||||||
|
@IsString()
|
||||||
|
CORS_ORIGINS: string = "";
|
||||||
|
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(1)
|
@Min(1)
|
||||||
@Max(65535)
|
@Max(65535)
|
||||||
@@ -31,9 +36,6 @@ export class AppConfig {
|
|||||||
@IsString()
|
@IsString()
|
||||||
APP_VERSION: string = appPackage().version;
|
APP_VERSION: string = appPackage().version;
|
||||||
|
|
||||||
@IsString()
|
|
||||||
KEYS_DIR: string = "keys";
|
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
DB_PATH: string = "data/liqa.db";
|
DB_PATH: string = "data/liqa.db";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import * as fs from "node:fs";
|
||||||
|
import { DataSource, type DataSourceOptions } from "typeorm";
|
||||||
|
import { validateAppConfig } from "../config/app.config";
|
||||||
|
import { ENTITIES } from "./entities";
|
||||||
|
import { MIGRATIONS } from "./migrations";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TypeORM options shared by the app, the migration runner and the TypeORM
|
||||||
|
* CLI. The schema is managed by migrations only (`synchronize: false`).
|
||||||
|
*/
|
||||||
|
export function dataSourceOptions(database: string): DataSourceOptions {
|
||||||
|
return {
|
||||||
|
type: "better-sqlite3",
|
||||||
|
database,
|
||||||
|
entities: ENTITIES,
|
||||||
|
migrations: MIGRATIONS,
|
||||||
|
synchronize: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outside Nest (migration runner, TypeORM CLI) nothing loads .env; load it
|
||||||
|
// like ConfigModule does: optional, and without overriding set variables
|
||||||
|
if (fs.existsSync(".env")) process.loadEnvFile(".env");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Data source for the TypeORM CLI and `migrate.ts`, using DB_PATH from the
|
||||||
|
* environment or .env (default `data/liqa.db`).
|
||||||
|
*/
|
||||||
|
export default new DataSource(
|
||||||
|
dataSourceOptions(validateAppConfig(process.env).DB_PATH),
|
||||||
|
);
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { CredentialEntity } from "../credential/credential.entity";
|
||||||
|
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||||
|
import { FileEntity } from "../file/file.entity";
|
||||||
|
import { ScenarioFileEntity } from "../file/scenario-file.entity";
|
||||||
|
import { ScenarioRunFileEntity } from "../file/scenario-run-file.entity";
|
||||||
|
import { ScenarioCredentialEntity } from "../scenario/scenario-credential.entity";
|
||||||
|
import { ScenarioRunLogEntity } from "../scenario/scenario-run-log.entity";
|
||||||
|
import { ScenarioRunStepEntity } from "../scenario/scenario-run-step.entity";
|
||||||
|
import { ScenarioRunEntity } from "../scenario/scenario-run.entity";
|
||||||
|
import { ScenarioStepEntity } from "../scenario/scenario-step.entity";
|
||||||
|
import { ScenarioVersionEntity } from "../scenario/scenario-version.entity";
|
||||||
|
import { ScenarioEntity } from "../scenario/scenario.entity";
|
||||||
|
import { SessionEntity } from "../session/session.entity";
|
||||||
|
import { SnippetVersionEntity } from "../snippet/snippet-version.entity";
|
||||||
|
import { SnippetEntity } from "../snippet/snippet.entity";
|
||||||
|
|
||||||
|
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
|
||||||
|
export const ENTITIES = [
|
||||||
|
SessionEntity,
|
||||||
|
EnvironmentEntity,
|
||||||
|
CredentialEntity,
|
||||||
|
ScenarioEntity,
|
||||||
|
ScenarioStepEntity,
|
||||||
|
ScenarioVersionEntity,
|
||||||
|
ScenarioRunEntity,
|
||||||
|
ScenarioRunStepEntity,
|
||||||
|
ScenarioRunLogEntity,
|
||||||
|
ScenarioCredentialEntity,
|
||||||
|
SnippetEntity,
|
||||||
|
SnippetVersionEntity,
|
||||||
|
FileEntity,
|
||||||
|
ScenarioFileEntity,
|
||||||
|
ScenarioRunFileEntity,
|
||||||
|
];
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import dataSource from "./data-source";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies pending migrations to the database at DB_PATH, then exits. Runs
|
||||||
|
* before the server in the Docker image (`node dist/database/migrate`).
|
||||||
|
*/
|
||||||
|
async function migrate(): Promise<void> {
|
||||||
|
await dataSource.initialize();
|
||||||
|
try {
|
||||||
|
const applied = await dataSource.runMigrations({ transaction: "each" });
|
||||||
|
console.log(
|
||||||
|
applied.length > 0
|
||||||
|
? `Applied ${applied.length} migration(s): ${applied.map((m) => m.name).join(", ")}`
|
||||||
|
: "Database schema is up to date",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await dataSource.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
migrate().catch((err: unknown) => {
|
||||||
|
console.error("Migration failed:", err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initial schema. Databases created before migrations existed (by TypeORM
|
||||||
|
* `synchronize`) already have this schema: for them this migration only gets
|
||||||
|
* recorded as applied, and later migrations run from there.
|
||||||
|
*/
|
||||||
|
export class Initial1790793447827 implements MigrationInterface {
|
||||||
|
name = "Initial1790793447827";
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
if (await queryRunner.hasTable("scenarios")) return;
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "credentials" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "data" text, "lastUsedAt" datetime, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "environments" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "data" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_9d00da4836959b86d7590f60c57" UNIQUE ("name"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "files" ("id" varchar PRIMARY KEY NOT NULL, "originalName" varchar NOT NULL, "mimeType" varchar NOT NULL, "size" integer NOT NULL, "sha256" varchar NOT NULL, "filePath" varchar NOT NULL, "expiresAt" datetime, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_credentials" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "credentialId" varchar NOT NULL, "alias" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_02756536236c408dbb58b3fc964" UNIQUE ("scenarioId", "alias"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_steps" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "order" integer NOT NULL DEFAULT (0), "title" text, "execCode" text, "timeoutSeconds" integer, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenarios" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" varchar, "timeoutSeconds" integer, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_files" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "sessions" ("id" varchar PRIMARY KEY NOT NULL, "sessionName" varchar NOT NULL, "token" text NOT NULL, "cookies" text NOT NULL, "localStorage" text NOT NULL DEFAULT ('{}'), "status" varchar NOT NULL DEFAULT ('closed'), "lastUsedAt" datetime, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_b8f17f1ce30f015f494188c50bb" UNIQUE ("sessionName"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_run_steps" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "scenarioStepId" varchar, "title" text, "execCode" text, "timeoutSeconds" integer, "status" text NOT NULL DEFAULT ('waiting'), "order" integer NOT NULL DEFAULT (0), "description" text, "output" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_runs" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "environmentId" varchar, "sessionId" varchar, "scenarioVersion" integer, "status" text NOT NULL DEFAULT ('pending'), "saveSession" boolean NOT NULL DEFAULT (0), "traceMode" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_run_files" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_run_logs" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "stepRunId" varchar, "level" text NOT NULL DEFAULT ('log'), "message" text NOT NULL, "seq" integer NOT NULL DEFAULT (0), "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_versions" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "version" integer NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" text, "timeoutSeconds" integer, "steps" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_e1a56dce2b7e0379bb5bbdf8c1f" UNIQUE ("scenarioId", "version"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "snippets" ("id" varchar PRIMARY KEY NOT NULL, "alias" varchar, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_bd062c68591ae917b720eb3427c" UNIQUE ("alias"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "snippet_versions" ("id" varchar PRIMARY KEY NOT NULL, "snippetId" varchar NOT NULL, "version" integer NOT NULL, "alias" varchar NOT NULL, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_2487f4aabeb20c4192ee30e09a2" UNIQUE ("snippetId", "version"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_credentials" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "credentialId" varchar NOT NULL, "alias" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_02756536236c408dbb58b3fc964" UNIQUE ("scenarioId", "alias"), CONSTRAINT "FK_37f19dadd8e524b22a807ece1a9" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_96676b988693d5ca2923782530c" FOREIGN KEY ("credentialId") REFERENCES "credentials" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_credentials"("id", "scenarioId", "credentialId", "alias", "createdAt") SELECT "id", "scenarioId", "credentialId", "alias", "createdAt" FROM "scenario_credentials"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_credentials"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_credentials" RENAME TO "scenario_credentials"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_steps" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "order" integer NOT NULL DEFAULT (0), "title" text, "execCode" text, "timeoutSeconds" integer, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_4bab3637cc3bf37677bb01c7446" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_steps"("id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt") SELECT "id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt" FROM "scenario_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_steps"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_steps" RENAME TO "scenario_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenarios" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" varchar, "timeoutSeconds" integer, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_ffdcf9186d95114f0dab068e20a" FOREIGN KEY ("environmentId") REFERENCES "environments" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenarios"("id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt") SELECT "id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt" FROM "scenarios"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenarios"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenarios" RENAME TO "scenarios"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_files" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_c41719984235f8984d1c6b92ef5" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_67013a49e7948fb530a7d956e2b" FOREIGN KEY ("fileId") REFERENCES "files" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_files"("id", "scenarioId", "fileId", "createdAt") SELECT "id", "scenarioId", "fileId", "createdAt" FROM "scenario_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_files"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_files" RENAME TO "scenario_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_run_steps" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "scenarioStepId" varchar, "title" text, "execCode" text, "timeoutSeconds" integer, "status" text NOT NULL DEFAULT ('waiting'), "order" integer NOT NULL DEFAULT (0), "description" text, "output" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_213c27405af3433011121babb58" FOREIGN KEY ("runId") REFERENCES "scenario_runs" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_e84cd4c7725bdc5dfd09d18d92f" FOREIGN KEY ("scenarioStepId") REFERENCES "scenario_steps" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_run_steps"("id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt") SELECT "id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt" FROM "scenario_run_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_run_steps"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_run_steps" RENAME TO "scenario_run_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_runs" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "environmentId" varchar, "sessionId" varchar, "scenarioVersion" integer, "status" text NOT NULL DEFAULT ('pending'), "saveSession" boolean NOT NULL DEFAULT (0), "traceMode" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_1d2c2595dfff133de062f9c692a" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_5076ffbd1b4fa71f5de011eba1f" FOREIGN KEY ("environmentId") REFERENCES "environments" ("id") ON DELETE SET NULL ON UPDATE NO ACTION, CONSTRAINT "FK_068b01cdfa49095433f245d6708" FOREIGN KEY ("sessionId") REFERENCES "sessions" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_runs"("id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt") SELECT "id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt" FROM "scenario_runs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_runs"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_runs" RENAME TO "scenario_runs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_run_files" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_5fc35a4bfc42d7566a0f7706902" FOREIGN KEY ("runId") REFERENCES "scenario_runs" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_637619025bdb0b6a89fae6e178d" FOREIGN KEY ("fileId") REFERENCES "files" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_run_files"("id", "runId", "fileId", "createdAt") SELECT "id", "runId", "fileId", "createdAt" FROM "scenario_run_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_run_files"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_run_files" RENAME TO "scenario_run_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_run_logs" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "stepRunId" varchar, "level" text NOT NULL DEFAULT ('log'), "message" text NOT NULL, "seq" integer NOT NULL DEFAULT (0), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "FK_dde48478a42823e583a360dd468" FOREIGN KEY ("runId") REFERENCES "scenario_runs" ("id") ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT "FK_62d82b9fce3a6a2947ed1136c67" FOREIGN KEY ("stepRunId") REFERENCES "scenario_run_steps" ("id") ON DELETE SET NULL ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_run_logs"("id", "runId", "stepRunId", "level", "message", "seq", "createdAt") SELECT "id", "runId", "stepRunId", "level", "message", "seq", "createdAt" FROM "scenario_run_logs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_run_logs"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_run_logs" RENAME TO "scenario_run_logs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_scenario_versions" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "version" integer NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" text, "timeoutSeconds" integer, "steps" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_e1a56dce2b7e0379bb5bbdf8c1f" UNIQUE ("scenarioId", "version"), CONSTRAINT "FK_f5ccfb45c7847cfab74cf4f17b6" FOREIGN KEY ("scenarioId") REFERENCES "scenarios" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_scenario_versions"("id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt") SELECT "id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt" FROM "scenario_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_versions"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_scenario_versions" RENAME TO "scenario_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "temporary_snippet_versions" ("id" varchar PRIMARY KEY NOT NULL, "snippetId" varchar NOT NULL, "version" integer NOT NULL, "alias" varchar NOT NULL, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_2487f4aabeb20c4192ee30e09a2" UNIQUE ("snippetId", "version"), CONSTRAINT "FK_0d3a004957c9553619be11635fd" FOREIGN KEY ("snippetId") REFERENCES "snippets" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "temporary_snippet_versions"("id", "snippetId", "version", "alias", "title", "description", "code", "createdAt") SELECT "id", "snippetId", "version", "alias", "title", "description", "code", "createdAt" FROM "snippet_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "snippet_versions"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "temporary_snippet_versions" RENAME TO "snippet_versions"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "snippet_versions" RENAME TO "temporary_snippet_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "snippet_versions" ("id" varchar PRIMARY KEY NOT NULL, "snippetId" varchar NOT NULL, "version" integer NOT NULL, "alias" varchar NOT NULL, "title" varchar NOT NULL DEFAULT (''), "description" text, "code" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_2487f4aabeb20c4192ee30e09a2" UNIQUE ("snippetId", "version"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "snippet_versions"("id", "snippetId", "version", "alias", "title", "description", "code", "createdAt") SELECT "id", "snippetId", "version", "alias", "title", "description", "code", "createdAt" FROM "temporary_snippet_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_snippet_versions"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_versions" RENAME TO "temporary_scenario_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_versions" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "version" integer NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" text, "timeoutSeconds" integer, "steps" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_e1a56dce2b7e0379bb5bbdf8c1f" UNIQUE ("scenarioId", "version"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_versions"("id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt") SELECT "id", "scenarioId", "version", "name", "description", "environmentId", "timeoutSeconds", "steps", "createdAt" FROM "temporary_scenario_versions"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_versions"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_run_logs" RENAME TO "temporary_scenario_run_logs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_run_logs" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "stepRunId" varchar, "level" text NOT NULL DEFAULT ('log'), "message" text NOT NULL, "seq" integer NOT NULL DEFAULT (0), "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_run_logs"("id", "runId", "stepRunId", "level", "message", "seq", "createdAt") SELECT "id", "runId", "stepRunId", "level", "message", "seq", "createdAt" FROM "temporary_scenario_run_logs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_run_logs"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_run_files" RENAME TO "temporary_scenario_run_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_run_files" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_run_files"("id", "runId", "fileId", "createdAt") SELECT "id", "runId", "fileId", "createdAt" FROM "temporary_scenario_run_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_run_files"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_runs" RENAME TO "temporary_scenario_runs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_runs" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "environmentId" varchar, "sessionId" varchar, "scenarioVersion" integer, "status" text NOT NULL DEFAULT ('pending'), "saveSession" boolean NOT NULL DEFAULT (0), "traceMode" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_runs"("id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt") SELECT "id", "scenarioId", "environmentId", "sessionId", "scenarioVersion", "status", "saveSession", "traceMode", "createdAt", "updatedAt" FROM "temporary_scenario_runs"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_runs"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_run_steps" RENAME TO "temporary_scenario_run_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_run_steps" ("id" varchar PRIMARY KEY NOT NULL, "runId" varchar NOT NULL, "scenarioStepId" varchar, "title" text, "execCode" text, "timeoutSeconds" integer, "status" text NOT NULL DEFAULT ('waiting'), "order" integer NOT NULL DEFAULT (0), "description" text, "output" text, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_run_steps"("id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt") SELECT "id", "runId", "scenarioStepId", "title", "execCode", "timeoutSeconds", "status", "order", "description", "output", "createdAt", "updatedAt" FROM "temporary_scenario_run_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_run_steps"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_files" RENAME TO "temporary_scenario_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_files" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "fileId" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_files"("id", "scenarioId", "fileId", "createdAt") SELECT "id", "scenarioId", "fileId", "createdAt" FROM "temporary_scenario_files"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_files"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenarios" RENAME TO "temporary_scenarios"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenarios" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, "description" text, "environmentId" varchar, "timeoutSeconds" integer, "version" integer NOT NULL DEFAULT (1), "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenarios"("id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt") SELECT "id", "name", "description", "environmentId", "timeoutSeconds", "version", "createdAt", "updatedAt" FROM "temporary_scenarios"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenarios"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_steps" RENAME TO "temporary_scenario_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_steps" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "order" integer NOT NULL DEFAULT (0), "title" text, "execCode" text, "timeoutSeconds" integer, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_steps"("id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt") SELECT "id", "scenarioId", "order", "title", "execCode", "timeoutSeconds", "createdAt", "updatedAt" FROM "temporary_scenario_steps"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_steps"`);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "scenario_credentials" RENAME TO "temporary_scenario_credentials"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "scenario_credentials" ("id" varchar PRIMARY KEY NOT NULL, "scenarioId" varchar NOT NULL, "credentialId" varchar NOT NULL, "alias" varchar NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_02756536236c408dbb58b3fc964" UNIQUE ("scenarioId", "alias"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`INSERT INTO "scenario_credentials"("id", "scenarioId", "credentialId", "alias", "createdAt") SELECT "id", "scenarioId", "credentialId", "alias", "createdAt" FROM "temporary_scenario_credentials"`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`DROP TABLE "temporary_scenario_credentials"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "snippet_versions"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "snippets"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_versions"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_run_logs"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_run_files"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_runs"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_run_steps"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "sessions"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_files"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenarios"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_steps"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "scenario_credentials"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "files"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "environments"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "credentials"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { Initial1790793447827 } from "./1790793447827-Initial";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
|
||||||
|
* same list works from compiled JS, ts-jest and the TypeORM CLI.
|
||||||
|
*/
|
||||||
|
export const MIGRATIONS = [Initial1790793447827];
|
||||||
+21
-2
@@ -1,11 +1,13 @@
|
|||||||
import { RequestMethod, ValidationPipe } from "@nestjs/common";
|
import { RequestMethod, ValidationPipe } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { NestFactory } from "@nestjs/core";
|
import { NestFactory } from "@nestjs/core";
|
||||||
|
import { DataSource } from "typeorm";
|
||||||
import type { NestExpressApplication } from "@nestjs/platform-express";
|
import type { NestExpressApplication } from "@nestjs/platform-express";
|
||||||
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
|
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
|
||||||
import { AppModule } from "./app.module";
|
import { AppModule } from "./app.module";
|
||||||
import { appPackage } from "./common/app-package";
|
import { appPackage } from "./common/app-package";
|
||||||
import { configureBodyParsers } from "./common/body-parsers";
|
import { configureBodyParsers } from "./common/body-parsers";
|
||||||
|
import { corsOrigins } from "./common/cors";
|
||||||
import { TraceLogger } from "./common/trace-logger";
|
import { TraceLogger } from "./common/trace-logger";
|
||||||
import { AppConfig } from "./config/app.config";
|
import { AppConfig } from "./config/app.config";
|
||||||
import { HttpExceptionFilter } from "./filters/http-exception.filter";
|
import { HttpExceptionFilter } from "./filters/http-exception.filter";
|
||||||
@@ -35,6 +37,15 @@ async function bootstrap() {
|
|||||||
logger: new TraceLogger("Bootstrap", { timestamp: true }),
|
logger: new TraceLogger("Bootstrap", { timestamp: true }),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The schema is managed by migrations; refuse to run against an outdated one.
|
||||||
|
// Checked before app.init(), i.e. before any module touches the tables.
|
||||||
|
if (await app.get(DataSource).showMigrations()) {
|
||||||
|
throw new Error(
|
||||||
|
"The database has pending migrations. Run `npm -w server run migration:run` " +
|
||||||
|
"(the Docker image runs them automatically before starting the server).",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
app.setGlobalPrefix(API_PREFIX, {
|
app.setGlobalPrefix(API_PREFIX, {
|
||||||
exclude: [
|
exclude: [
|
||||||
{ path: "health", method: RequestMethod.ALL },
|
{ path: "health", method: RequestMethod.ALL },
|
||||||
@@ -53,7 +64,7 @@ async function bootstrap() {
|
|||||||
const nodeEnv = config.get("NODE_ENV");
|
const nodeEnv = config.get("NODE_ENV");
|
||||||
|
|
||||||
app.enableCors({
|
app.enableCors({
|
||||||
origin: ["http://localhost:5173", "http://127.0.0.1:5173"],
|
origin: corsOrigins(nodeEnv, config.get("CORS_ORIGINS")),
|
||||||
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
|
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
|
||||||
credentials: true,
|
credentials: true,
|
||||||
});
|
});
|
||||||
@@ -76,4 +87,12 @@ async function bootstrap() {
|
|||||||
logger.log(`MCP endpoint available at http://localhost:${port}/mcp`);
|
logger.log(`MCP endpoint available at http://localhost:${port}/mcp`);
|
||||||
}
|
}
|
||||||
|
|
||||||
bootstrap();
|
// Startup failures (pending migrations, port in use, ...) must stop the
|
||||||
|
// process with an error code; the handlers above only keep a running server alive
|
||||||
|
bootstrap().catch((err: unknown) => {
|
||||||
|
processLogger.error(
|
||||||
|
`Startup failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
err instanceof Error ? err.stack : undefined,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from "class-validator";
|
} from "class-validator";
|
||||||
import { EnvironmentData } from "../../environment/environment.entity";
|
import { EnvironmentData } from "../../environment/environment.entity";
|
||||||
|
import { SnippetExportDto } from "../../snippet/dto/snippet-export.dto";
|
||||||
|
|
||||||
export class ScenarioStepExportDto {
|
export class ScenarioStepExportDto {
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
@@ -154,4 +155,5 @@ export class ScenarioExportDto {
|
|||||||
export type ExportEntity =
|
export type ExportEntity =
|
||||||
| EnvironmentExportInlineDto
|
| EnvironmentExportInlineDto
|
||||||
| CredentialExportDto
|
| CredentialExportDto
|
||||||
|
| SnippetExportDto
|
||||||
| ScenarioExportDto;
|
| ScenarioExportDto;
|
||||||
@@ -135,18 +135,17 @@ export class ScenarioController {
|
|||||||
@Param("id", ParseUUIDPipe) id: string,
|
@Param("id", ParseUUIDPipe) id: string,
|
||||||
@Query("includeEnvironment") includeEnvironment: string,
|
@Query("includeEnvironment") includeEnvironment: string,
|
||||||
@Query("credentialIds") credentialIds: string | string[] | undefined,
|
@Query("credentialIds") credentialIds: string | string[] | undefined,
|
||||||
|
@Query("snippetIds") snippetIds: string | string[] | undefined,
|
||||||
@Query("version", new ParseIntPipe({ optional: true }))
|
@Query("version", new ParseIntPipe({ optional: true }))
|
||||||
version: number | undefined,
|
version: number | undefined,
|
||||||
@Res({ passthrough: true }) res: Response,
|
@Res({ passthrough: true }) res: Response,
|
||||||
) {
|
) {
|
||||||
const credIds: string[] = credentialIds
|
const toIds = (ids: string | string[] | undefined): string[] =>
|
||||||
? Array.isArray(credentialIds)
|
ids ? (Array.isArray(ids) ? ids : ids.split(",").filter(Boolean)) : [];
|
||||||
? credentialIds
|
|
||||||
: credentialIds.split(",").filter(Boolean)
|
|
||||||
: [];
|
|
||||||
const entities = await this.scenarioService.exportScenario(id, {
|
const entities = await this.scenarioService.exportScenario(id, {
|
||||||
includeEnvironment: includeEnvironment === "true",
|
includeEnvironment: includeEnvironment === "true",
|
||||||
credentialIds: credIds,
|
credentialIds: toIds(credentialIds),
|
||||||
|
snippetIds: toIds(snippetIds),
|
||||||
version,
|
version,
|
||||||
});
|
});
|
||||||
res.setHeader("Content-Type", "application/yaml; charset=utf-8");
|
res.setHeader("Content-Type", "application/yaml; charset=utf-8");
|
||||||
@@ -155,12 +154,17 @@ export class ScenarioController {
|
|||||||
const kindLabels: Record<string, string> = {
|
const kindLabels: Record<string, string> = {
|
||||||
environment: "Environment",
|
environment: "Environment",
|
||||||
credential: "Credential",
|
credential: "Credential",
|
||||||
|
snippet: "Snippet",
|
||||||
scenario: "Scenario",
|
scenario: "Scenario",
|
||||||
};
|
};
|
||||||
return (entities as ExportEntity[])
|
return (entities as ExportEntity[])
|
||||||
.map((entity) => {
|
.map((entity) => {
|
||||||
const label = kindLabels[entity.kind ?? ""] ?? entity.kind ?? "Entity";
|
const label = kindLabels[entity.kind ?? ""] ?? entity.kind ?? "Entity";
|
||||||
const comment = `# ${label}: ${entity.name ?? entity.id ?? ""}`;
|
const title =
|
||||||
|
entity.kind === "snippet"
|
||||||
|
? `${entity.alias ?? entity.name} v${entity.version}`
|
||||||
|
: entity.name;
|
||||||
|
const comment = `# ${label}: ${title ?? entity.id ?? ""}`;
|
||||||
return `---\n${comment}\n${yamlStringify(entity)}`;
|
return `---\n${comment}\n${yamlStringify(entity)}`;
|
||||||
})
|
})
|
||||||
.join("");
|
.join("");
|
||||||
|
|||||||
@@ -486,11 +486,18 @@ export class ScenarioService implements OnModuleInit {
|
|||||||
*/
|
*/
|
||||||
async getUsedSnippets(scenarioId: string): Promise<UsedSnippet[]> {
|
async getUsedSnippets(scenarioId: string): Promise<UsedSnippet[]> {
|
||||||
const scenario = await this.findOne(scenarioId);
|
const scenario = await this.findOne(scenarioId);
|
||||||
const snippetMap = await this.snippetService.buildSnippetMap();
|
return this.resolveUsedSnippets(
|
||||||
const usedRefs = resolveUsedSnippetAliases(
|
|
||||||
scenario.steps.map((s) => s.execCode ?? ""),
|
scenario.steps.map((s) => s.execCode ?? ""),
|
||||||
snippetMap,
|
);
|
||||||
).map(parseSnippetRef);
|
}
|
||||||
|
|
||||||
|
private async resolveUsedSnippets(
|
||||||
|
execCodes: string[],
|
||||||
|
): Promise<UsedSnippet[]> {
|
||||||
|
const snippetMap = await this.snippetService.buildSnippetMap();
|
||||||
|
const usedRefs = resolveUsedSnippetAliases(execCodes, snippetMap).map(
|
||||||
|
parseSnippetRef,
|
||||||
|
);
|
||||||
if (usedRefs.length === 0) return [];
|
if (usedRefs.length === 0) return [];
|
||||||
const snippets = await this.snippetService.findByAliases([
|
const snippets = await this.snippetService.findByAliases([
|
||||||
...new Set(usedRefs.map((r) => r.alias)),
|
...new Set(usedRefs.map((r) => r.alias)),
|
||||||
@@ -699,6 +706,8 @@ export class ScenarioService implements OnModuleInit {
|
|||||||
options: {
|
options: {
|
||||||
includeEnvironment: boolean;
|
includeEnvironment: boolean;
|
||||||
credentialIds: string[];
|
credentialIds: string[];
|
||||||
|
/** Used snippets to include, at every version the scenario uses. */
|
||||||
|
snippetIds?: string[];
|
||||||
/** Version to export; defaults to the latest. */
|
/** Version to export; defaults to the latest. */
|
||||||
version?: number;
|
version?: number;
|
||||||
},
|
},
|
||||||
@@ -741,6 +750,25 @@ export class ScenarioService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Include selected snippets, once per used version (latest or pinned)
|
||||||
|
const snippetIds = options.snippetIds ?? [];
|
||||||
|
if (snippetIds.length > 0) {
|
||||||
|
const used = await this.resolveUsedSnippets(
|
||||||
|
content.steps.map((s) => s.execCode ?? ""),
|
||||||
|
);
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const snippet of used) {
|
||||||
|
if (!snippetIds.includes(snippet.id)) continue;
|
||||||
|
const version = snippet.pinnedVersion ?? snippet.version;
|
||||||
|
const key = `${snippet.id}@${version}`;
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
entities.push(
|
||||||
|
await this.snippetService.exportSnippet(snippet, version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Scenario is always last
|
// Scenario is always last
|
||||||
const allCreds = scenario.scenarioCredentials ?? [];
|
const allCreds = scenario.scenarioCredentials ?? [];
|
||||||
const credentialMappings = allCreds
|
const credentialMappings = allCreds
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type { NestExpressApplication } from "@nestjs/platform-express";
|
|||||||
import { ScheduleModule } from "@nestjs/schedule";
|
import { ScheduleModule } from "@nestjs/schedule";
|
||||||
|
|
||||||
import { configureBodyParsers } from "../src/common/body-parsers";
|
import { configureBodyParsers } from "../src/common/body-parsers";
|
||||||
|
import { dataSourceOptions } from "../src/database/data-source";
|
||||||
import { ImportModule } from "../src/import/import.module";
|
import { ImportModule } from "../src/import/import.module";
|
||||||
|
|
||||||
jest.mock("@nestjs/common", () => {
|
jest.mock("@nestjs/common", () => {
|
||||||
@@ -42,25 +43,10 @@ import { SessionModule } from "../src/session/session.module";
|
|||||||
import { EnvironmentModule } from "../src/environment/environment.module";
|
import { EnvironmentModule } from "../src/environment/environment.module";
|
||||||
import { ScenarioModule } from "../src/scenario/scenario.module";
|
import { ScenarioModule } from "../src/scenario/scenario.module";
|
||||||
import { McpModule } from "../src/mcp/mcp.module";
|
import { McpModule } from "../src/mcp/mcp.module";
|
||||||
import { SessionEntity } from "../src/session/session.entity";
|
|
||||||
import { EnvironmentEntity } from "../src/environment/environment.entity";
|
|
||||||
import { ScenarioEntity } from "../src/scenario/scenario.entity";
|
|
||||||
import { ScenarioStepEntity } from "../src/scenario/scenario-step.entity";
|
|
||||||
import { ScenarioVersionEntity } from "../src/scenario/scenario-version.entity";
|
|
||||||
import { SnippetVersionEntity } from "../src/snippet/snippet-version.entity";
|
|
||||||
import { ScenarioRunEntity } from "../src/scenario/scenario-run.entity";
|
|
||||||
import { ScenarioRunStepEntity } from "../src/scenario/scenario-run-step.entity";
|
|
||||||
import { ScenarioRunLogEntity } from "../src/scenario/scenario-run-log.entity";
|
|
||||||
import { ScenarioCredentialEntity } from "../src/scenario/scenario-credential.entity";
|
|
||||||
import { CredentialEntity } from "../src/credential/credential.entity";
|
|
||||||
import { SnippetEntity } from "../src/snippet/snippet.entity";
|
|
||||||
import { HealthController } from "../src/health/health.controller";
|
import { HealthController } from "../src/health/health.controller";
|
||||||
import { HttpExceptionFilter } from "../src/filters/http-exception.filter";
|
import { HttpExceptionFilter } from "../src/filters/http-exception.filter";
|
||||||
import { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
|
import { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
|
||||||
import { validateAppConfig } from "../src/config/app.config";
|
import { validateAppConfig } from "../src/config/app.config";
|
||||||
import { FileEntity } from "../src/file/file.entity";
|
|
||||||
import { ScenarioFileEntity } from "../src/file/scenario-file.entity";
|
|
||||||
import { ScenarioRunFileEntity } from "../src/file/scenario-run-file.entity";
|
|
||||||
|
|
||||||
export async function buildTestApp(): Promise<INestApplication> {
|
export async function buildTestApp(): Promise<INestApplication> {
|
||||||
// Each test app stores files in its own temp dir: suites run in parallel and
|
// Each test app stores files in its own temp dir: suites run in parallel and
|
||||||
@@ -75,27 +61,10 @@ export async function buildTestApp(): Promise<INestApplication> {
|
|||||||
ignoreEnvFile: true,
|
ignoreEnvFile: true,
|
||||||
validate: validateAppConfig,
|
validate: validateAppConfig,
|
||||||
}),
|
}),
|
||||||
|
// The real migrations, not synchronize, so tests use the schema production gets
|
||||||
TypeOrmModule.forRoot({
|
TypeOrmModule.forRoot({
|
||||||
type: "better-sqlite3",
|
...dataSourceOptions(":memory:"),
|
||||||
database: ":memory:",
|
migrationsRun: true,
|
||||||
entities: [
|
|
||||||
SessionEntity,
|
|
||||||
EnvironmentEntity,
|
|
||||||
ScenarioEntity,
|
|
||||||
ScenarioStepEntity,
|
|
||||||
ScenarioVersionEntity,
|
|
||||||
ScenarioRunEntity,
|
|
||||||
ScenarioRunStepEntity,
|
|
||||||
ScenarioRunLogEntity,
|
|
||||||
ScenarioCredentialEntity,
|
|
||||||
CredentialEntity,
|
|
||||||
SnippetEntity,
|
|
||||||
SnippetVersionEntity,
|
|
||||||
FileEntity,
|
|
||||||
ScenarioFileEntity,
|
|
||||||
ScenarioRunFileEntity,
|
|
||||||
],
|
|
||||||
synchronize: true,
|
|
||||||
}),
|
}),
|
||||||
ScheduleModule.forRoot(),
|
ScheduleModule.forRoot(),
|
||||||
BrowserModule,
|
BrowserModule,
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { corsOrigins } from "../src/common/cors";
|
||||||
|
|
||||||
|
describe("corsOrigins", () => {
|
||||||
|
it("allows the Vite dev server outside production", () => {
|
||||||
|
for (const env of ["development", "test", ""]) {
|
||||||
|
expect(corsOrigins(env, "")).toEqual([
|
||||||
|
"http://localhost:5173",
|
||||||
|
"http://127.0.0.1:5173",
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows the compose port in production", () => {
|
||||||
|
expect(corsOrigins("production", "")).toEqual([
|
||||||
|
"http://localhost:13000",
|
||||||
|
"http://127.0.0.1:13000",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses CORS_ORIGINS when set, in any environment", () => {
|
||||||
|
const override = " https://liqa.example.com , http://localhost:8080,";
|
||||||
|
for (const env of ["development", "production"]) {
|
||||||
|
expect(corsOrigins(env, override)).toEqual([
|
||||||
|
"https://liqa.example.com",
|
||||||
|
"http://localhost:8080",
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
/**
|
||||||
|
* The schema is managed by migrations. These tests fail when an entity
|
||||||
|
* changes without a matching migration, and cover adopting databases that
|
||||||
|
* were created by `synchronize` before migrations existed.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { DataSource } from "typeorm";
|
||||||
|
import { dataSourceOptions } from "../src/database/data-source";
|
||||||
|
import { MIGRATIONS } from "../src/database/migrations";
|
||||||
|
|
||||||
|
async function pendingSchemaChanges(dataSource: DataSource): Promise<string[]> {
|
||||||
|
const sql = await dataSource.driver.createSchemaBuilder().log();
|
||||||
|
return sql.upQueries.map((q) => q.query);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Database migrations", () => {
|
||||||
|
it("migrations produce exactly the schema the entities describe", async () => {
|
||||||
|
const dataSource = new DataSource(dataSourceOptions(":memory:"));
|
||||||
|
await dataSource.initialize();
|
||||||
|
try {
|
||||||
|
await dataSource.runMigrations();
|
||||||
|
expect(await dataSource.showMigrations()).toBe(false);
|
||||||
|
// If this fails, generate a migration: see "Database migrations" in docs/development.md
|
||||||
|
expect(await pendingSchemaChanges(dataSource)).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await dataSource.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adopts a database created by synchronize", async () => {
|
||||||
|
const dataSource = new DataSource({
|
||||||
|
...dataSourceOptions(":memory:"),
|
||||||
|
synchronize: true,
|
||||||
|
});
|
||||||
|
await dataSource.initialize();
|
||||||
|
try {
|
||||||
|
await dataSource.query(
|
||||||
|
`INSERT INTO scenarios (id, name, version) VALUES ('11111111-1111-4111-8111-111111111111', 'kept', 1)`,
|
||||||
|
);
|
||||||
|
const applied = await dataSource.runMigrations();
|
||||||
|
expect(applied.map((m) => m.name)).toEqual(MIGRATIONS.map((m) => m.name));
|
||||||
|
expect(await dataSource.showMigrations()).toBe(false);
|
||||||
|
expect(await pendingSchemaChanges(dataSource)).toEqual([]);
|
||||||
|
const [row] = await dataSource.query(`SELECT name FROM scenarios`);
|
||||||
|
expect(row.name).toBe("kept");
|
||||||
|
} finally {
|
||||||
|
await dataSource.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("can revert the initial migration", async () => {
|
||||||
|
const dataSource = new DataSource(dataSourceOptions(":memory:"));
|
||||||
|
await dataSource.initialize();
|
||||||
|
try {
|
||||||
|
await dataSource.runMigrations();
|
||||||
|
await dataSource.undoLastMigration();
|
||||||
|
const tables = await dataSource.query(
|
||||||
|
`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT IN ('migrations', 'sqlite_sequence')`,
|
||||||
|
);
|
||||||
|
expect(tables).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await dataSource.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -810,7 +810,10 @@ describe("ScenarioController", () => {
|
|||||||
.expect(200);
|
.expect(200);
|
||||||
|
|
||||||
expect(res.body.id).toBe(runId);
|
expect(res.body.id).toBe(runId);
|
||||||
expect(res.body.status).toBe("pending");
|
// The scheduler may already have picked the run up
|
||||||
|
expect(["pending", "in_progress", "pass", "fail"]).toContain(
|
||||||
|
res.body.status,
|
||||||
|
);
|
||||||
expect(Array.isArray(res.body.stepRuns)).toBe(true);
|
expect(Array.isArray(res.body.stepRuns)).toBe(true);
|
||||||
expect(res.body.stepRuns[0]).toHaveProperty("scenarioStep");
|
expect(res.body.stepRuns[0]).toHaveProperty("scenarioStep");
|
||||||
expect(Array.isArray(res.body.logs)).toBe(true);
|
expect(Array.isArray(res.body.logs)).toBe(true);
|
||||||
|
|||||||
@@ -277,6 +277,47 @@ describe("Versioning", () => {
|
|||||||
expect(first[first.length - 1]).toMatchObject({ version: 1, steps: [] });
|
expect(first[first.length - 1]).toMatchObject({ version: 1, steps: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("includes selected used snippets at the versions the scenario uses", async () => {
|
||||||
|
const alias = `exp-snip-${uniq()}`;
|
||||||
|
const sn = await snippetService.create({
|
||||||
|
alias,
|
||||||
|
title: "t",
|
||||||
|
code: "return 'one';",
|
||||||
|
});
|
||||||
|
await snippetService.update(sn.id, { code: "return 'two';" });
|
||||||
|
const other = await snippetService.create({
|
||||||
|
alias: `exp-other-${uniq()}`,
|
||||||
|
title: "t",
|
||||||
|
code: "return 3;",
|
||||||
|
});
|
||||||
|
|
||||||
|
const sc = await scenarioService.create({ name: `exp-sn-${uniq()}` });
|
||||||
|
await scenarioService.createStep(sc.id, {
|
||||||
|
execCode: `await context.runSnippet("${alias}"); await context.runSnippet("${alias}@1"); await context.runSnippet("${alias}"); return context.runSnippet("${other.alias}");`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const withSnippet = await scenarioService.exportScenario(sc.id, {
|
||||||
|
includeEnvironment: false,
|
||||||
|
credentialIds: [],
|
||||||
|
snippetIds: [sn.id],
|
||||||
|
});
|
||||||
|
expect(withSnippet.map((e) => e.kind)).toEqual([
|
||||||
|
"snippet",
|
||||||
|
"snippet",
|
||||||
|
"scenario",
|
||||||
|
]);
|
||||||
|
expect(withSnippet.slice(0, 2)).toMatchObject([
|
||||||
|
{ id: sn.id, version: 2, code: "return 'two';" },
|
||||||
|
{ id: sn.id, version: 1, code: "return 'one';" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const without = await scenarioService.exportScenario(sc.id, {
|
||||||
|
includeEnvironment: false,
|
||||||
|
credentialIds: [],
|
||||||
|
});
|
||||||
|
expect(without.map((e) => e.kind)).toEqual(["scenario"]);
|
||||||
|
});
|
||||||
|
|
||||||
it("restores exact versions by id + version", async () => {
|
it("restores exact versions by id + version", async () => {
|
||||||
const id = crypto.randomUUID();
|
const id = crypto.randomUUID();
|
||||||
const base = { kind: "scenario" as const, id, name: "imported" };
|
const base = { kind: "scenario" as const, id, name: "imported" };
|
||||||
|
|||||||
Reference in new issue
Block a user