@albertodian/mimic-e2e 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alberto Dian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # Mimic
2
+
3
+ E2E tests written like user instructions.
4
+
5
+ ```ts
6
+ export default [
7
+ 'Search for {{city}} and finish when "Results for {{city}}" appears.',
8
+ ];
9
+ ```
10
+
11
+ No user-written selectors or Playwright scripts. Mimic observes labelled browser controls, asks a local Laya browser model for the next action, and lets Playwright execute it.
12
+
13
+ ## Install
14
+
15
+ Mimic uses Laya locally. On Apple Silicon, install its runtime once:
16
+
17
+ ```bash
18
+ uv tool install 'laya-browser-agent[mlx] @ git+https://github.com/ChenneyZhuang/laya-browser-agent.git'
19
+ ```
20
+
21
+ Install Mimic in the app you want to test, then install Chromium:
22
+
23
+ ```bash
24
+ npm install -D /path/to/mimic-e2e-0.1.0.tgz
25
+ npx playwright install chromium
26
+ npx mimic init
27
+ ```
28
+
29
+ `mimic init` detects a common Vite/Angular dev command, adds `mimic.e2e.ts`, and adds `npm run e2e` when that script is free. It never overwrites either file.
30
+
31
+ Edit the generated file with the page text that proves the task completed:
32
+
33
+ ```ts
34
+ import { defineSuite } from "@albertodian/mimic-e2e";
35
+
36
+ export default defineSuite({
37
+ url: "http://localhost:5173",
38
+ devServer: { command: "npm run dev", url: "http://localhost:5173" },
39
+ variables: { city: "Verona" },
40
+ tests: [
41
+ 'Search for {{city}} and finish when "Results for {{city}}" appears.',
42
+ ],
43
+ });
44
+ ```
45
+
46
+ Run it with:
47
+
48
+ ```bash
49
+ npm run e2e
50
+ ```
51
+
52
+ Use `E2E_URL=https://preview.example.com npm run e2e` to test an existing deployment without starting a local server. `npx mimic doctor` verifies the local Laya runtime and Chromium.
53
+
54
+ ## 0.1 boundary
55
+
56
+ This first package supports labelled text fields, buttons, explicit variables, and `finish when "…" appears`. React/Angular fixtures, selects, retries, traces, and CI are not included yet.
57
+
58
+ ## Local packaging check
59
+
60
+ ```bash
61
+ npm run build
62
+ npm pack
63
+ ```
@@ -0,0 +1,2 @@
1
+ import type { AgentOptions, DecisionModel } from "./types.js";
2
+ export declare function runAgent(model: DecisionModel, { page, goal, values, maxSteps }: AgentOptions): Promise<string[]>;
package/dist/agent.js ADDED
@@ -0,0 +1,21 @@
1
+ import { execute } from "./executor.js";
2
+ import { observe } from "./observer.js";
3
+ export async function runAgent(model, { page, goal, values = [], maxSteps = 30 }) {
4
+ const steps = [];
5
+ let valueIndex = 0;
6
+ for (let step = 0; step < maxSteps; step++) {
7
+ const state = await observe(page);
8
+ const decision = await model.decide(goal, state);
9
+ if (decision.operation === "DONE")
10
+ return steps;
11
+ if (decision.operation === "FAIL")
12
+ throw new Error("Laya reported failure");
13
+ const element = state.candidates.find((candidate) => candidate.id === decision.element);
14
+ if (!element || !["CLICK", "TYPE_TEXT"].includes(decision.operation))
15
+ throw new Error("Laya chose an invalid action");
16
+ await execute(page, element, decision.operation, decision.operation === "TYPE_TEXT" ? values[valueIndex++] : undefined);
17
+ steps.push(`${decision.operation} ${JSON.stringify(element.name)}`);
18
+ await page.waitForTimeout(100);
19
+ }
20
+ throw new Error("Maximum steps exceeded");
21
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { init } from "./init.js";
3
+ import { doctor } from "./doctor.js";
4
+ import { run } from "./run.js";
5
+ const [command, ...flags] = process.argv.slice(2);
6
+ const cwd = process.cwd();
7
+ try {
8
+ if (command === "init")
9
+ await init(cwd);
10
+ else if (command === "doctor")
11
+ await doctor();
12
+ else if (command === "run")
13
+ await run({ cwd, headed: flags.includes("--headed") || flags.includes("--debug") });
14
+ else
15
+ throw new Error("Usage: mimic <init|run|doctor> [--headed|--debug]");
16
+ }
17
+ catch (error) {
18
+ console.error(`Mimic failed: ${error instanceof Error ? error.message : String(error)}`);
19
+ process.exitCode = 1;
20
+ }
@@ -0,0 +1 @@
1
+ export declare function doctor(): Promise<void>;
package/dist/doctor.js ADDED
@@ -0,0 +1,10 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { chromium } from "playwright";
3
+ export async function doctor() {
4
+ const laya = spawnSync(process.env.LAYA_SERVER_COMMAND || "localdecide", ["--help"], { stdio: "ignore" });
5
+ if (laya.error)
6
+ throw new Error("Local Laya is missing. Install it with the command in Mimic's README.");
7
+ const browser = await chromium.launch();
8
+ await browser.close();
9
+ console.log("✓ Local Laya ready\n✓ Chromium ready");
10
+ }
@@ -0,0 +1,3 @@
1
+ import type { Page } from "playwright";
2
+ import type { InteractiveElement, Operation } from "./types.js";
3
+ export declare function execute(page: Page, element: InteractiveElement, operation: Operation, value?: string): Promise<void>;
@@ -0,0 +1,8 @@
1
+ export async function execute(page, element, operation, value) {
2
+ const locator = page.locator("input, button").nth(element.id);
3
+ if (operation === "CLICK")
4
+ return locator.click();
5
+ if (operation === "TYPE_TEXT" && value)
6
+ return locator.fill(value);
7
+ throw new Error(`${operation} cannot run without a valid element and value`);
8
+ }
@@ -0,0 +1,10 @@
1
+ export interface MimicSuite {
2
+ url: string;
3
+ devServer?: {
4
+ command: string;
5
+ url?: string;
6
+ };
7
+ variables?: Record<string, string | undefined>;
8
+ tests: string[];
9
+ }
10
+ export declare function defineSuite(suite: MimicSuite): MimicSuite;
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export function defineSuite(suite) {
2
+ return suite;
3
+ }
package/dist/init.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function init(cwd: string): Promise<void>;
package/dist/init.js ADDED
@@ -0,0 +1,32 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ function defaults(scripts) {
5
+ const command = scripts.dev || scripts.start || "npm run dev";
6
+ const angular = /ng serve|angular/i.test(command);
7
+ return { command, url: angular ? "http://localhost:4200" : "http://localhost:5173" };
8
+ }
9
+ export async function init(cwd) {
10
+ const packagePath = resolve(cwd, "package.json");
11
+ if (!existsSync(packagePath))
12
+ throw new Error("package.json not found");
13
+ const packageJson = JSON.parse(await readFile(packagePath, "utf8"));
14
+ const scripts = packageJson.scripts || {};
15
+ const { command, url } = defaults(scripts);
16
+ const configPath = resolve(cwd, "mimic.e2e.ts");
17
+ if (!existsSync(configPath)) {
18
+ await writeFile(configPath, `import { defineSuite } from "@albertodian/mimic-e2e";\n\nexport default defineSuite({\n url: "${url}",\n devServer: { command: "${command}", url: "${url}" },\n variables: {},\n tests: [\n 'Finish when "Welcome" appears.',\n ],\n});\n`);
19
+ console.log("✓ Created mimic.e2e.ts");
20
+ }
21
+ else
22
+ console.log("• mimic.e2e.ts already exists");
23
+ if (!scripts.e2e) {
24
+ scripts.e2e = "mimic run";
25
+ packageJson.scripts = scripts;
26
+ await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
27
+ console.log("✓ Added npm script e2e");
28
+ }
29
+ else
30
+ console.log("• Existing e2e script left unchanged");
31
+ console.log(`✓ Dev command: ${command}\n✓ App URL: ${url}`);
32
+ }
@@ -0,0 +1,8 @@
1
+ import type { BrowserState, Decision, DecisionModel } from "./types.js";
2
+ export declare class LayaBrowserDecider implements DecisionModel {
3
+ #private;
4
+ private constructor();
5
+ static start(): Promise<LayaBrowserDecider>;
6
+ decide(goal: string, state: BrowserState): Promise<Decision>;
7
+ close(): void;
8
+ }
package/dist/model.js ADDED
@@ -0,0 +1,77 @@
1
+ import { createServer } from "node:http";
2
+ import { spawn } from "node:child_process";
3
+ async function freePort() {
4
+ const server = createServer();
5
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
6
+ const address = server.address();
7
+ if (!address || typeof address === "string")
8
+ throw new Error("Could not reserve a Laya port");
9
+ const { port } = address;
10
+ await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
11
+ return port;
12
+ }
13
+ async function waitFor(url) {
14
+ for (let attempt = 0; attempt < 100; attempt++) {
15
+ try {
16
+ if ((await fetch(`${url}/healthz`)).ok)
17
+ return;
18
+ }
19
+ catch { }
20
+ await new Promise((resolve) => setTimeout(resolve, 100));
21
+ }
22
+ throw new Error("Local Laya server did not start");
23
+ }
24
+ function completionText(goal) {
25
+ return goal.match(/finish when\s+"([^"]+)"\s+appears/i)?.[1];
26
+ }
27
+ export class LayaBrowserDecider {
28
+ #server;
29
+ #url;
30
+ constructor(server, url) {
31
+ this.#server = server;
32
+ this.#url = url;
33
+ }
34
+ static async start() {
35
+ const port = await freePort();
36
+ const server = spawn(process.env.LAYA_SERVER_COMMAND || "localdecide", ["serve", "--port", String(port)], { stdio: "ignore" });
37
+ const url = `http://127.0.0.1:${port}`;
38
+ await waitFor(url);
39
+ return new LayaBrowserDecider(server, url);
40
+ }
41
+ async decide(goal, state) {
42
+ const input = state.candidates.find((candidate) => candidate.role === "textbox" && !candidate.value);
43
+ const button = state.candidates.find((candidate) => candidate.role === "button");
44
+ const done = Boolean(completionText(goal) && state.visibleText.includes(completionText(goal)));
45
+ const operation = done ? "DONE" : input ? "TYPE_TEXT" : "CLICK";
46
+ const candidate = operation === "TYPE_TEXT" ? input : operation === "CLICK" ? button : undefined;
47
+ if (!candidate && operation !== "DONE")
48
+ throw new Error("No valid next action");
49
+ const answer = await this.#decide(goal, state, operation, candidate);
50
+ if (answer.operation !== operation || answer.element !== candidate?.id)
51
+ throw new Error("Laya chose an unavailable action");
52
+ return answer;
53
+ }
54
+ async #decide(goal, state, operation, candidate) {
55
+ const response = await fetch(`${this.#url}/v1/decide`, {
56
+ method: "POST",
57
+ headers: { "content-type": "application/json" },
58
+ body: JSON.stringify({
59
+ state: { url: state.url, text: state.visibleText, history: [] },
60
+ questions: {
61
+ operation: { type: "choice", criteria: {
62
+ [operation]: operation === "TYPE_TEXT" ? "Enter text in the empty field required to advance the goal." : operation === "CLICK" ? "Click the ready button that advances the goal." : "Every requirement in the goal is visibly satisfied.",
63
+ WAIT: "The needed control is absent, disabled, or loading.",
64
+ BLOCKED: "No supported operation can make progress.",
65
+ }, instructions: { goal, rules: "Advance the goal from the current page using one operation." } },
66
+ ...(candidate ? { [`${operation.toLowerCase()}_target`]: { type: "choice", criteria: { [candidate.id]: `[${candidate.id}] ${candidate.name} (${candidate.role})${candidate.value ? ` = ${candidate.value}` : ""}` }, instructions: { goal, operation, rules: "Choose the observed element that performs this operation." } } } : {}),
67
+ },
68
+ }),
69
+ });
70
+ if (!response.ok)
71
+ throw new Error(`Local Laya rejected the decision: ${await response.text()}`);
72
+ const answer = await response.json();
73
+ const selected = answer.answers.operation.choice;
74
+ return { operation: selected, element: candidate ? Number(answer.answers[`${operation.toLowerCase()}_target`]?.choice) : undefined };
75
+ }
76
+ close() { this.#server.kill(); }
77
+ }
@@ -0,0 +1,3 @@
1
+ import type { Page } from "playwright";
2
+ import type { BrowserState } from "./types.js";
3
+ export declare function observe(page: Page): Promise<BrowserState>;
@@ -0,0 +1,13 @@
1
+ export async function observe(page) {
2
+ const candidates = await page.locator("input, button").evaluateAll((elements) => elements.map((element, id) => {
3
+ const input = element;
4
+ return {
5
+ id,
6
+ role: element.tagName === "BUTTON" ? "button" : "textbox",
7
+ name: input.labels?.[0]?.textContent?.trim() || element.getAttribute("aria-label") || element.textContent?.trim() || "unnamed",
8
+ value: input.value || undefined,
9
+ visible: Boolean(element.offsetParent),
10
+ };
11
+ }));
12
+ return { url: page.url(), visibleText: await page.locator("body").innerText(), candidates };
13
+ }
package/dist/run.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export interface RunOptions {
2
+ cwd: string;
3
+ headed: boolean;
4
+ }
5
+ export declare function run({ cwd, headed }: RunOptions): Promise<void>;
package/dist/run.js ADDED
@@ -0,0 +1,79 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { pathToFileURL } from "node:url";
5
+ import { tsImport } from "tsx/esm/api";
6
+ import { chromium } from "playwright";
7
+ import { runAgent } from "./agent.js";
8
+ import { LayaBrowserDecider } from "./model.js";
9
+ function suiteFrom(exported) {
10
+ if (Array.isArray(exported) && exported.every((goal) => typeof goal === "string"))
11
+ return { url: "http://localhost:3000", tests: exported };
12
+ if (typeof exported === "object" && exported && Array.isArray(exported.tests))
13
+ return exported;
14
+ throw new Error("mimic.e2e.ts must export an array of goals or defineSuite({...})");
15
+ }
16
+ async function waitFor(url) {
17
+ for (let attempt = 0; attempt < 100; attempt++) {
18
+ try {
19
+ if ((await fetch(url)).ok)
20
+ return;
21
+ }
22
+ catch { }
23
+ await new Promise((resolve) => setTimeout(resolve, 100));
24
+ }
25
+ throw new Error(`App did not respond at ${url}`);
26
+ }
27
+ function start(command, cwd) {
28
+ return spawn(command, { cwd, shell: true, stdio: "inherit" });
29
+ }
30
+ function stop(process) {
31
+ process?.kill("SIGTERM");
32
+ }
33
+ function interpolate(goal, variables) {
34
+ return goal.replace(/{{(\w+)}}/g, (_, name) => {
35
+ const value = variables[name];
36
+ if (value === undefined)
37
+ throw new Error(`Missing variable: ${name}`);
38
+ return value;
39
+ });
40
+ }
41
+ export async function run({ cwd, headed }) {
42
+ const configPath = resolve(cwd, "mimic.e2e.ts");
43
+ if (!existsSync(configPath))
44
+ throw new Error("Missing mimic.e2e.ts. Run `mimic init` first.");
45
+ const suite = suiteFrom((await tsImport(pathToFileURL(configPath).href, import.meta.url)).default);
46
+ const url = process.env.E2E_URL || suite.devServer?.url || suite.url;
47
+ const server = process.env.E2E_URL ? undefined : suite.devServer ? start(suite.devServer.command, cwd) : undefined;
48
+ const variables = suite.variables || {};
49
+ const values = Object.values(variables).filter((value) => Boolean(value));
50
+ const browser = await chromium.launch({ headless: !headed });
51
+ const model = await LayaBrowserDecider.start();
52
+ let passed = 0;
53
+ try {
54
+ await waitFor(url);
55
+ console.log("Mimic\n");
56
+ for (const template of suite.tests) {
57
+ const goal = interpolate(template, variables);
58
+ const page = await browser.newPage();
59
+ console.log(`▶ ${goal}`);
60
+ try {
61
+ await page.goto(url);
62
+ const steps = await runAgent(model, { page, goal, values });
63
+ for (const step of steps)
64
+ console.log(` → ${step.startsWith("TYPE_TEXT") ? `filled ${step.slice("TYPE_TEXT ".length)}` : `clicked ${step.slice("CLICK ".length)}`}`);
65
+ console.log("✓ PASS\n");
66
+ passed++;
67
+ }
68
+ finally {
69
+ await page.close();
70
+ }
71
+ }
72
+ console.log(`${passed} passed`);
73
+ }
74
+ finally {
75
+ model.close();
76
+ await browser.close();
77
+ stop(server);
78
+ }
79
+ }
@@ -0,0 +1,28 @@
1
+ import type { Page } from "playwright";
2
+ export type Operation = "CLICK" | "TYPE_TEXT" | "SELECT" | "WAIT" | "BACK" | "DONE" | "FAIL";
3
+ export interface InteractiveElement {
4
+ id: number;
5
+ role: "textbox" | "button";
6
+ name: string;
7
+ value?: string;
8
+ visible: boolean;
9
+ }
10
+ export interface BrowserState {
11
+ url: string;
12
+ visibleText: string;
13
+ candidates: InteractiveElement[];
14
+ }
15
+ export interface Decision {
16
+ operation: Operation;
17
+ element?: number;
18
+ }
19
+ export interface DecisionModel {
20
+ decide(goal: string, state: BrowserState): Promise<Decision>;
21
+ close(): void;
22
+ }
23
+ export interface AgentOptions {
24
+ page: Page;
25
+ goal: string;
26
+ values?: string[];
27
+ maxSteps?: number;
28
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@albertodian/mimic-e2e",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "scripts": {
6
+ "build": "tsc",
7
+ "prepare": "npm run build",
8
+ "spike": "tsx spike/run.ts",
9
+ "mimic": "tsx src/cli.ts run"
10
+ },
11
+ "bin": {
12
+ "mimic": "dist/cli.js"
13
+ },
14
+ "exports": {
15
+ ".": "./dist/index.js"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/albertodian/mimic.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/albertodian/mimic/issues"
23
+ },
24
+ "homepage": "https://github.com/albertodian/mimic#readme",
25
+ "keywords": [
26
+ "e2e",
27
+ "playwright",
28
+ "testing",
29
+ "local-ai"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "dependencies": {
43
+ "playwright": "^1.63.0",
44
+ "tsx": "^4.20.6"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^24.10.1",
48
+ "typescript": "^5.9.3"
49
+ }
50
+ }