chore(repo): restructure as monorepo with server and client workspaces

- move NestJS app into server/ subdirectory
- add client/ React+TypeScript (Vite) app with Hello World
- update docker-compose to build and run both services
- add root package.json declaring npm workspaces
- update .gitignore to cover node_modules and dist at all depths
This commit is contained in:
ars9 committed 2026-04-08 21:28:01 +03:00
1 parent afc4627353
commit 5cc16725fb
88 files changed
+12637 -405

No files matched your search

@@ -0,0 +1,8 @@
import { Module } from "@nestjs/common";
import { CodeExecutorService } from "./code-executor.service";
@Module({
providers: [CodeExecutorService],
exports: [CodeExecutorService],
})
export class CodeExecutorModule {}
@@ -0,0 +1,93 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { parse } from "acorn";
import type { Page, BrowserContext } from "playwright";
import { dumpDom } from "./dom-helpers";
export interface ExecResult {
result: unknown;
}
export type ScriptLogger = (
level: "log" | "warn" | "error",
message: string,
) => void;
@Injectable()
export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name);
/**
* Validates `code` by wrapping it in an async function body and attempting
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
throw new BadRequestException(
`Code parse error: ${(err as Error).message}`,
{ cause: err },
);
}
}
/**
* Executes `code` as an async function body with `page` and `context` in
* scope. Always call `validate()` before this method.
*/
async execute(
page: Page,
context: BrowserContext,
code: string,
log?: ScriptLogger,
getStepOutput?: (order: number) => Promise<unknown>,
): Promise<ExecResult> {
const scriptLog: ScriptLogger =
log ?? ((level, msg) => this.logger[level](msg));
const toStr = (args: unknown[]) =>
args
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
.join(" ");
try {
const pageHelpers = {
dumpDom: (selector?: string) => dumpDom(page, selector),
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
};
const fakeConsole = {
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
info: (...args: unknown[]) => scriptLog("log", toStr(args)),
debug: (...args: unknown[]) => scriptLog("log", toStr(args)),
};
// Passing `console` as a named parameter shadows the global in the script scope.
const fn = new Function(
"page",
"context",
"helpers",
"console",
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
);
this.logger.debug("Executing user code");
const result = await fn(page, context, pageHelpers, fakeConsole);
return { result };
} catch (err) {
throw new InternalServerErrorException(
`Code execution failed: ${(err as Error).message}`,
{ cause: err },
);
}
}
}
+204
View File
@@ -0,0 +1,204 @@
import type { Page } from "playwright";
export interface DomNode {
tag: string;
role?: string;
testid?: string;
qa?: string;
action?: string;
elementId?: string;
id?: string;
type?: string;
name?: string;
text?: string;
href?: string;
checked?: boolean;
disabled?: boolean;
children: DomNode[];
truncated?: boolean;
}
/**
* Dumps a logical component tree of the live DOM scoped to `rootSelector`.
* Filters out decorative/layout noise — keeps only structural landmarks,
* interactive elements, and elements with semantic attributes
* (role, data-testid, data-qa, data-action, data-element-id).
*
* Useful for debugging Playwright selectors without screenshotting.
*/
export async function dumpDom(
page: Page,
rootSelector = "body",
): Promise<DomNode> {
return page.evaluate(
([sel, maxDepth]) => {
const root = document.querySelector(sel as string);
if (!root)
return {
tag: "ERROR",
text: `selector not found: ${sel}`,
children: [],
};
const STRUCTURAL_TAGS = new Set([
"BODY",
"MAIN",
"HEADER",
"FOOTER",
"NAV",
"ASIDE",
"SECTION",
"FORM",
"DIALOG",
"DETAILS",
"SUMMARY",
"TABLE",
"THEAD",
"TBODY",
"TR",
"FIELDSET",
"LEGEND",
]);
const INTERACTIVE_TAGS = new Set([
"A",
"BUTTON",
"INPUT",
"SELECT",
"TEXTAREA",
"LABEL",
"TH",
"TD",
]);
const IGNORED_TAGS = new Set([
"SCRIPT",
"STYLE",
"SVG",
"PATH",
"DEFS",
"USE",
"CIRCLE",
"RECT",
"POLYGON",
"POLYLINE",
"LINE",
"ELLIPSE",
"G",
"CLIPPATH",
"IMAGE",
]);
function trimText(el: Element): string | undefined {
const t =
(el as HTMLElement).innerText?.trim() ?? el.textContent?.trim() ?? "";
// Only include if short enough to be meaningful, not a dump of all child text
const ownText = Array.from(el.childNodes)
.filter((n) => n.nodeType === Node.TEXT_NODE)
.map((n) => n.textContent?.trim() ?? "")
.filter(Boolean)
.join(" ");
const candidate = ownText || t;
return candidate.length > 0 ? candidate.substring(0, 80) : undefined;
}
function isVisible(el: Element): boolean {
const s = window.getComputedStyle(el);
return (
s.display !== "none" &&
s.visibility !== "hidden" &&
(el as HTMLElement).offsetParent !== null
);
}
function isSignificant(el: Element): boolean {
if (STRUCTURAL_TAGS.has(el.tagName)) return true;
if (INTERACTIVE_TAGS.has(el.tagName)) return true;
if (el.getAttribute("role")) return true;
if (el.getAttribute("data-testid")) return true;
if (el.getAttribute("data-qa")) return true;
if (el.getAttribute("data-action")) return true;
if (el.getAttribute("data-element-id")) return true;
return false;
}
function build(el: Element, depth: number): DomNode | null {
if (IGNORED_TAGS.has(el.tagName)) return null;
if (!isVisible(el)) return null;
const significant = isSignificant(el);
const childResults: DomNode[] = [];
if (depth < (maxDepth as number)) {
for (const child of Array.from(el.children)) {
const node = build(child, depth + 1);
if (node) childResults.push(node);
}
} else if (el.children.length > 0) {
return significant
? { tag: el.tagName.toLowerCase(), children: [], truncated: true }
: null;
}
// If not significant and no meaningful children, discard
if (!significant && childResults.length === 0) return null;
// If not significant but has exactly one child, pass through (unwrap)
if (!significant && childResults.length === 1) return childResults[0];
// If not significant but has children, keep as anonymous group only if > 1 child
if (!significant)
return { tag: el.tagName.toLowerCase(), children: childResults };
const node: DomNode = {
tag: el.tagName.toLowerCase(),
children: childResults,
};
const role = el.getAttribute("role");
if (role) node.role = role;
const testid = el.getAttribute("data-testid");
if (testid) node.testid = testid;
const qa = el.getAttribute("data-qa");
if (qa) node.qa = qa;
const action = el.getAttribute("data-action");
if (action) node.action = action;
const elementId = el.getAttribute("data-element-id");
if (elementId) node.elementId = elementId;
const id = el.id;
if (id) node.id = id;
const type = (el as HTMLInputElement).type;
if (type && type !== "submit" && el.tagName !== "BUTTON")
node.type = type;
const name = (el as HTMLInputElement).name;
if (name) node.name = name;
const href = (el as HTMLAnchorElement).href;
if (href && el.tagName === "A")
node.href = href.replace(window.location.origin, "");
if ("checked" in el) node.checked = (el as HTMLInputElement).checked;
if ((el as HTMLButtonElement).disabled) node.disabled = true;
const text = trimText(el);
if (text) node.text = text;
return node;
}
const result = build(root, 0);
return result ?? { tag: "empty", children: [] };
},
[rootSelector, 12] as [string, number],
);
}
export const helpers = { dumpDom };
export type Helpers = typeof helpers;