workers-port 0.0.0-stage → 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 Techkeyy
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 CHANGED
@@ -1,3 +1,236 @@
1
- # Temporary Holding Version
1
+ # Workers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Workers ports your Playwright suite to Kane CLI tests and proves the new tests catch the same bugs, by breaking your app on purpose. When a ported test is weaker, your coding agent rewrites it from Kane's own result.
4
+
5
+ **[GitHub repo](https://github.com/Techkeyy/workers)** <!-- placeholder until the repo is created --> · **Demo video: TODO** · **Sample report: TODO**
6
+
7
+ Teams want off brittle selector tests. Rewriting a suite by hand takes weeks, and nobody trusts an AI rewrite they cannot check. TestMu's own [*State of AI in Quality Engineering 2026*](https://www.testmuai.com/research/state-of-ai-in-quality-engineering.md) puts the median trust in AI-generated tests at 54 out of 100, and finds teams spend 50% of their AI testing budget on generating tests but only 17% on verifying them.
8
+
9
+ > *"The agent says the new tests are equivalent. Would they actually catch the bug the old ones caught?"*
10
+
11
+ Workers answers that question with a run, not with the agent's word. Every ported test is checked against deliberate breaks of your app (mutants), side by side with the original Playwright test. **The differentiator: a ported test is only accepted if it catches the same bugs, and it avoids the false alarms the selector tests raise.**
12
+
13
+ Built for the Kane CLI hackathon.
14
+
15
+ ## Why this exists
16
+
17
+ Playwright tests pin to selectors and `data-testid`s. A harmless markup change breaks them, so teams look at Kane CLI, where tests are plain English steps. The move is the hard part:
18
+
19
+ - A hand rewrite is weeks of work.
20
+ - An agent rewrite is fast, but a test that passes on the clean app proves nothing. A test that asserts nothing passes too.
21
+ - Kane's own recording can also be weaker than it looks (see platform feedback below: it rebuilt "N items left" from a bare number).
22
+
23
+ What is missing is a check on the port itself. Workers supplies it.
24
+
25
+ ```
26
+ old Playwright test new Kane test
27
+ | |
28
+ +---------- same app --------+
29
+ |
30
+ clean app: both must pass
31
+ bug mutant: both must FAIL <- the new test is as strong
32
+ refactor mutant: Playwright fails, Kane passes <- the false alarm is gone
33
+ ```
34
+
35
+ ## What it does
36
+
37
+ 1. **Lists** the Playwright tests (Playwright's own `--list` JSON).
38
+ 2. **Translates** each test with your coding agent into a Kane `_test.md` in plain English, following `src/rules.md`. Every `expect` becomes an explicit "Verify" line. The agent returns text; Workers writes the files.
39
+ 3. **Runs Playwright** on the clean app, then on every mutant. Each mutant is applied to the app, the suite runs, and the mutant is reverted (also on errors and Ctrl+C).
40
+ 4. **Runs Kane**: authors each test on the clean app, then runs it on every mutant with Kane's default self-healing, the way it runs in CI. The test's local recordings are restored from a clean snapshot before and after every run.
41
+ 5. **Diffs parity** with plain code, no LLM. Verdicts come from Playwright's JSON and Kane's exit code and `run_end` status.
42
+ 6. **Repairs** weak tests. For each test Kane is weaker on, the agent gets what the old test asserted and what Kane did, rewrites it, and Workers re-runs it, up to 2 rounds. The agent never sees the mutant. A test still weak after the cap is marked "needs human".
43
+ 7. **Reports** `report.html` and `report.json`: the matrix, findings, repair log with a real line diff, Kane dashboard links, before/after line counts.
44
+
45
+ Cell classes:
46
+
47
+ | Class | Meaning |
48
+ |---|---|
49
+ | `ok` | passes on the clean app in both suites |
50
+ | `broken-on-clean` | the Kane test fails on the clean app, so it needs a repair |
51
+ | `parity-caught` | bug mutant: Playwright and Kane both fail it |
52
+ | `parity-missed` | bug mutant: neither suite fails it (this test does not check that behaviour) |
53
+ | `kane-weaker` | bug mutant: Playwright fails it, Kane passes. Repair round |
54
+ | `kane-stronger` | bug mutant: Kane fails it, Playwright passes |
55
+ | `parity` | refactor mutant: both pass |
56
+ | `false-alarm-avoided` | refactor mutant: Playwright fails, Kane passes |
57
+ | `kane-false-alarm` | refactor mutant: Kane fails |
58
+
59
+ The pitch is plain English and no selectors. It is not fewer lines: in run 2 the six `_test.md` files total 116 lines against 79 for the Playwright originals.
60
+
61
+ ## Results: run 2 on the bundled TodoMVC demo
62
+
63
+ Six tests from Playwright's example spec, 7 mutants (5 bugs B1 to B5, 2 refactors R1, R2), Kane with self-healing on, local recordings restored per run. Source: `workers-out/report.json`.
64
+
65
+ | | 6 tests, 7 mutants |
66
+ |---|---|
67
+ | Bugs caught, old suite | 7 |
68
+ | Bugs caught, new suite | 7 |
69
+ | False alarms avoided | 2 |
70
+ | Kane weaker | 0 |
71
+ | Needs human | 0 |
72
+ | Bugs that slipped past both suites | 1 (B2) |
73
+ | Repaired tests | 1 (2 rounds) |
74
+ | Kane credits | 389.8 |
75
+
76
+ Mutants: B1 active count counts completed items, B2 counter always says "items", B3 counter always says "item", B4 "Clear completed" removes active items, B5 Escape saves the edit, R1 counter test-id renamed, R2 extra class on the clear button.
77
+
78
+ `C` = bug caught by both Playwright and Kane. `.` = both pass (the test does not check that). `A` = refactor, Playwright fails, Kane passes (false alarm avoided). `ok` = both pass on the clean app.
79
+
80
+ | Test | clean | B1 | B2 | B3 | B4 | B5 | R1 | R2 |
81
+ |---|---|---|---|---|---|---|---|---|
82
+ | add todo items | ok | . | . | . | . | . | . | . |
83
+ | append new items to the bottom (repaired) | ok | C | . | C | . | . | A | . |
84
+ | cancel edits on escape | ok | . | . | . | . | C | . | . |
85
+ | display the current number of todo items | ok | C | . | . | . | . | A | . |
86
+ | remove completed items when clicked | ok | . | . | . | C | . | . | . |
87
+ | hidden when there are no completed items | ok | C | . | . | C | . | . | . |
88
+
89
+ Four of the five bugs (B1, B3, B4, B5) are caught by at least one test in both suites. B2 is caught by neither.
90
+
91
+ ### The repair story
92
+
93
+ "should append new items to the bottom of the list" asserts `toHaveText('3 items left')`.
94
+
95
+ - **First translation:** `kane-weaker` on B3 (the counter shows "3 item left"). Playwright caught it, Kane did not. In an earlier run the same test caught B3 first time, so Kane's authoring is not deterministic. That is why the port has to be verified.
96
+ - **Round 1:** the agent rewrote the test. The rewrite broke on the clean app (`broken-on-clean`) and was rejected. The agent's word was not trusted, the run was.
97
+ - **Round 2:** the agent fixed it, using the wording "exact visible text of the todo counter ... is '3 items left'". Kane re-authored it, caught B3, and every other cell held. Final status `repaired`.
98
+
99
+ ## Quickstart
100
+
101
+ Prerequisites:
102
+
103
+ - Node 22 or newer (`engines` in `package.json`)
104
+ - Chrome
105
+ - `kane-cli` (`npm install -g @testmuai/kane-cli`), logged in, with credits
106
+ - `claude` or `codex` CLI, logged in
107
+
108
+ From npm, in any empty folder (the demo app and its Playwright suite are copied to `./workers-demo`):
109
+
110
+ ```bash
111
+ npm install workers-port
112
+ npx playwright install chromium
113
+
114
+ # everything except Kane: list, translate, run Playwright on every mutant, print a credit estimate
115
+ npx workers-port demo --dry-run --max-tests 1
116
+
117
+ # the real run (spends Kane credits)
118
+ npx workers-port demo --max-tests 3
119
+ ```
120
+
121
+ Or from a clone of this repo:
122
+
123
+ <!-- quickstart verified on a fresh clone: pending -->
124
+
125
+ ```bash
126
+ git clone https://github.com/Techkeyy/workers
127
+ cd workers
128
+ npm ci
129
+ npx playwright install chromium
130
+
131
+ # everything except Kane: list, translate, run Playwright on every mutant, print a credit estimate
132
+ node bin/workers.js demo --dry-run --max-tests 1
133
+
134
+ # the real run (spends Kane credits)
135
+ node bin/workers.js demo --max-tests 3
136
+ ```
137
+
138
+ The claude adapter is the default (`--agent claude`, falling back to codex if claude is not logged in and codex is). To use Codex: `--agent codex --agent-model <model>`.
139
+
140
+ `--grep "title one|title two"` ports only tests whose title contains one of the strings. Run 2 used it to pick the six tests that cover every mutant. Without `--max-tests` or `--grep`, the demo ports the whole 24-test spec.
141
+
142
+ Credits, as I measured them: about 40 per authored test, 0 per clean replay, 10 to 30 per mutant run where self-healing kicks in. Run 2 cost 389.8 credits for 6 tests.
143
+
144
+ ## Using it on your own project
145
+
146
+ ```bash
147
+ node bin/workers.js port --config playwright.config.ts --app ./my-app --mutants workers.mutants.json
148
+ ```
149
+
150
+ Options: `--url`, `--out`, `--grep`, `--max-tests`, `--repair-rounds`, `--agent`, `--agent-model`, `--dry-run`. Run `node bin/workers.js --help` for the full list. Run `--dry-run` first.
151
+
152
+ The mutants file is a JSON array. Each mutant edits one file in `--app` with an exact find and replace, temporarily:
153
+
154
+ ```json
155
+ [
156
+ {
157
+ "id": "B3",
158
+ "kind": "bug",
159
+ "description": "Counter always says \"item\" (so \"3 item left\")",
160
+ "file": "app.js",
161
+ "find": "const itemWord = activeCount === 1 ? 'item' : 'items';",
162
+ "replace": "const itemWord = 'item';"
163
+ }
164
+ ]
165
+ ```
166
+
167
+ `kind` is `bug` (behaviour changes, both suites should fail) or `refactor` (markup changes, behaviour stays, Playwright may fail and Kane should pass). The bundled file is `demo/workers.mutants.json`. Originals are kept in `<file>.workers-backup` and restored when the run ends, fails, is interrupted, or at the next startup.
168
+
169
+ ## Claude Code skill
170
+
171
+ `skill/workers/` lets you say "port my Playwright tests to Kane" inside Claude Code. Install it by copying the folder:
172
+
173
+ ```bash
174
+ mkdir -p ~/.claude/skills
175
+ cp -r skill/workers ~/.claude/skills/
176
+ ```
177
+
178
+ Use `.claude/skills/` instead for a single project, then start a new Claude Code session. See `skill/README.md`.
179
+
180
+ ## How I tried to break it
181
+
182
+ | Attack | Result |
183
+ |---|---|
184
+ | The agent sees the mutant and tunes the test to it | It cannot. The repair prompt holds the old test's Playwright error and source plus Kane's step results, never the mutant's id, description, file or diff. A unit test pins this. |
185
+ | The agent writes a test that asserts nothing | It has to fail the mutants the old test fails. In run 2, round 1's weaker rewrite of the append test did not survive the runs: it broke on the clean app and was rejected. I have not yet fed Workers a deliberately empty `_test.md`. |
186
+ | Kane heals around a bug and passes it | A heal that passes a bug mutant still counts as a miss (`kane-weaker`). A heal that passes a refactor counts as a false alarm avoided, with the heal flagged. |
187
+ | Strict replay hides the brittleness story | In strict replay Kane's recorded checks use `data-testid` selectors like Playwright does (R1 was a `kane-false-alarm` with healing off). So Workers runs Kane the way CI does, with self-healing on, and restores the clean recordings before every run. |
188
+ | Kane authoring changes between runs | It does. The same test caught B3 in run 1 and missed it in run 2 before repair. That is the case for verifying every port. |
189
+ | A bug neither suite catches | B2 ("1 items left") slipped past both suites. It is reported as missed, not hidden. |
190
+ | Mutant left in the app after a crash | Reverted on errors and SIGINT, and at next startup. `demo/app` was clean after run 2. |
191
+
192
+ **A bug-mutant cell is only `parity-caught` when both suites actually failed. Verdicts come from exit codes and JSON, never from the agent.** Rules decide, the agent only writes tests.
193
+
194
+ The Workers code itself has 71 unit tests (`npm test`, `node --test`), plus the real runs above.
195
+
196
+ ## Architecture
197
+
198
+ | File | Job |
199
+ |---|---|
200
+ | `bin/workers.js` | CLI entry: `port` and `demo` |
201
+ | `src/port.js` | Orchestrates the full run: translate, baseline, mutants, parity, repair, report |
202
+ | `src/inventory.js` | Lists Playwright tests from `--list` JSON |
203
+ | `src/translate.js` | Extracts a test's source, asks the agent, validates the `_test.md` |
204
+ | `src/rules.md` | The translation rules the agent follows |
205
+ | `src/agents.js` | Adapters for claude and codex |
206
+ | `src/run-playwright.js` | Parses Playwright results into per-test verdicts |
207
+ | `src/run-kane.js` | Runs Kane and parses its NDJSON into a result |
208
+ | `src/kane-cache.js` | Snapshots and restores Kane's per-test recordings |
209
+ | `src/mutants.js` | Loads, applies and reverts mutants |
210
+ | `src/parity.js` | Pure function: verdicts to cell class |
211
+ | `src/loop.js` | Builds the repair prompt (no mutant details) and runs the rounds |
212
+ | `src/diff.js` | Line-based LCS diff for the repair log |
213
+ | `src/report.js` | Renders `report.html` and `report.json` |
214
+ | `src/server.js` | Makes sure the app is being served |
215
+ | `src/util.js` | Runs child processes |
216
+
217
+ ## Platform feedback for Kane CLI
218
+
219
+ I built on `kane-cli` 0.10.4 (`testmd run`, NDJSON `--agent` output, `output-<stem>/` recordings, self-healing). Mutation checks turn up things normal use rarely does. These are observations, with evidence from `director.md`; I have not filed them as issues yet.
220
+
221
+ - **K1, plural label rebuilt in extraction.** The recorded `code_js` for "Verify the counter reads '1 item left'" reads only the number and rebuilds the text: ``const n=Number(strong.textContent); return `${n} item${n===1?'':'s'} left` ``. A replay with `--no-adaptive-heal` on B2 passed, while Playwright's read of the DOM gave "1 items left". So a label or plural bug cannot be caught by that check. Wording like "the exact visible text of X is ..." helps (B3 was caught), and Workers uses it, but the recorded check can still differ between authoring runs.
222
+ - **T1, localStorage reads time out.** Authoring a test that verified localStorage failed with "verification setup repeatedly timed out reading browser storage". Workers translates those checks into reload then verify what is visible.
223
+ - **K2, a failed healed run replaced the local recordings.** A failed run with healing on set `artifacts.replaced: true` for B1. The next run (B2) had 0 replay decisions and re-authored on the mutant, about 49 credits, committing that version. Restoring `output-<stem>/` from a snapshot fixed it locally (a clean replay after restore cost 0 credits). It would help if a failed run left the recordings alone.
224
+
225
+ ## Limitations
226
+
227
+ - Mutants are hand-written. Workers does not generate them.
228
+ - The claude adapter has not been exercised end to end on this machine. The runs above used codex (model `gpt-5.6-terra`).
229
+ - Kane runs sequentially, about a minute each.
230
+ - Desktop web only.
231
+ - Tests run against a local app.
232
+ - One planted bug (B2) slipped past both suites in the demo.
233
+
234
+ ## License
235
+
236
+ MIT, see [LICENSE](LICENSE). `demo/tests/demo-todo-app.spec.ts` is Playwright's example spec from the `create-playwright` package (version 1.17.130, Microsoft, MIT). Only its URL was changed, see [`demo/tests/NOTICE.md`](demo/tests/NOTICE.md).
package/bin/workers.js ADDED
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { cpSync, existsSync, symlinkSync } from 'node:fs';
6
+ import { createRequire } from 'node:module';
7
+ import { port } from '../src/port.js';
8
+
9
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..');
10
+
11
+ // Installed from npm, the demo lives under node_modules, where Node will not run TypeScript and where
12
+ // Workers should not edit files. So copy it to ./workers-demo and work on the copy. The copy gets a
13
+ // node_modules link to the folder that holds this package's @playwright/test.
14
+ function prepareDemo() {
15
+ const src = join(root, 'demo');
16
+ if (!/[\\/]node_modules[\\/]/.test(src)) return src;
17
+ const dest = join(process.cwd(), 'workers-demo');
18
+ if (!existsSync(dest)) {
19
+ cpSync(src, dest, { recursive: true });
20
+ console.log(`Copied the demo app and its Playwright tests to ${dest}`);
21
+ }
22
+ const link = join(dest, 'node_modules');
23
+ if (!existsSync(link)) {
24
+ const pwEntry = createRequire(import.meta.url).resolve('@playwright/test');
25
+ symlinkSync(join(dirname(pwEntry), '..', '..'), link, 'junction');
26
+ }
27
+ return dest;
28
+ }
29
+
30
+ const HELP = `workers: port a Playwright suite to Kane CLI tests and prove they catch the same bugs.
31
+
32
+ Usage:
33
+ workers port --config <playwright.config> --app <dir> --mutants <file.json> [options]
34
+ workers demo [options] port with the bundled TodoMVC demo defaults
35
+
36
+ Options:
37
+ --config <file> Playwright config to read tests from
38
+ --app <dir> directory of the app whose files the mutants edit (temporarily)
39
+ --mutants <file> mutants JSON: [{id, kind: "bug"|"refactor", description, file, find, replace}]
40
+ --url <url> app URL for the tests (default: the config's webServer.url)
41
+ --out <dir> output folder for _test.md files and the report (default: workers-out)
42
+ --grep <text> only port tests whose title contains this text (several: "a|b")
43
+ --max-tests <n> port at most n tests
44
+ --repair-rounds <n> agent repair rounds per weak test (default: 2)
45
+ --agent claude|codex coding agent that writes the tests (default: claude; falls back to
46
+ codex if claude is not logged in and codex is)
47
+ --agent-model <name> model name passed to the agent
48
+ --dry-run everything except Kane: list, translate, run Playwright on every
49
+ mutant, then print the plan and a credit estimate
50
+ -h, --help show this help
51
+
52
+ Kane credit estimate: authoring is about 40 credits per test. A clean replay costs 0.
53
+ A mutant run where Kane's self-healing kicks in costs about 10-30 credits.
54
+ Mutant runs use Kane's default (self-healing on); the test's local Kane cache is restored before
55
+ and after every mutant run.`;
56
+
57
+ const options = {
58
+ config: { type: 'string' },
59
+ app: { type: 'string' },
60
+ mutants: { type: 'string' },
61
+ url: { type: 'string' },
62
+ out: { type: 'string', default: 'workers-out' },
63
+ grep: { type: 'string' },
64
+ 'max-tests': { type: 'string' },
65
+ 'repair-rounds': { type: 'string', default: '2' },
66
+ agent: { type: 'string', default: 'claude' },
67
+ 'agent-model': { type: 'string' },
68
+ 'dry-run': { type: 'boolean', default: false },
69
+ help: { type: 'boolean', short: 'h', default: false },
70
+ };
71
+
72
+ async function main() {
73
+ let parsed;
74
+ try {
75
+ parsed = parseArgs({ args: process.argv.slice(2), options, allowPositionals: true });
76
+ } catch (e) {
77
+ console.error(`${e.message}\n\n${HELP}`);
78
+ process.exit(2);
79
+ }
80
+ const { values: v, positionals } = parsed;
81
+ const [cmd] = positionals;
82
+ if (v.help || !cmd) {
83
+ console.log(HELP);
84
+ process.exit(v.help || !cmd ? 0 : 2);
85
+ }
86
+ if (cmd !== 'port' && cmd !== 'demo') {
87
+ console.error(`Unknown command "${cmd}".\n\n${HELP}`);
88
+ process.exit(2);
89
+ }
90
+ const demo = cmd === 'demo';
91
+ const demoDir = demo ? prepareDemo() : null;
92
+ const opts = {
93
+ config: v.config ?? (demo ? join(demoDir, 'playwright.config.ts') : undefined),
94
+ app: v.app ?? (demo ? join(demoDir, 'app') : undefined),
95
+ mutants: v.mutants ?? (demo ? join(demoDir, 'workers.mutants.json') : undefined),
96
+ url: v.url,
97
+ out: v.out,
98
+ grep: v.grep,
99
+ maxTests: v['max-tests'] ? Number(v['max-tests']) : undefined,
100
+ repairRounds: Number(v['repair-rounds']),
101
+ agent: v.agent,
102
+ agentModel: v['agent-model'],
103
+ dryRun: v['dry-run'],
104
+ };
105
+ for (const k of ['config', 'app', 'mutants']) {
106
+ if (!opts[k]) {
107
+ console.error(`Missing --${k}.\n\n${HELP}`);
108
+ process.exit(2);
109
+ }
110
+ }
111
+ try {
112
+ await port(opts);
113
+ } catch (e) {
114
+ console.error(`\nworkers: ${e.message}`);
115
+ process.exit(1);
116
+ }
117
+ }
118
+
119
+ main();
@@ -0,0 +1,181 @@
1
+ // Plain vanilla TodoMVC. Data lives in localStorage under STORAGE_KEY as
2
+ // an array of { id, title, completed }.
3
+ const STORAGE_KEY = 'react-todos';
4
+
5
+ let todos = loadTodos();
6
+ let filter = 'all';
7
+ let editingId = null;
8
+
9
+ const newTodoInput = document.querySelector('.new-todo');
10
+ const mainSection = document.querySelector('.main');
11
+ const footerSection = document.querySelector('.footer');
12
+ const toggleAllInput = document.querySelector('.toggle-all');
13
+ const todoListEl = document.querySelector('.todo-list');
14
+ const todoCountEl = document.querySelector('.todo-count');
15
+ const clearCompletedButton = document.querySelector('.clear-completed');
16
+ const filterLinks = document.querySelectorAll('.filters a');
17
+
18
+ function loadTodos() {
19
+ try {
20
+ return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
21
+ } catch (error) {
22
+ return [];
23
+ }
24
+ }
25
+
26
+ function saveTodos() {
27
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
28
+ }
29
+
30
+ function addTodo(title) {
31
+ const cleanTitle = title.trim();
32
+ if (cleanTitle === '') return;
33
+ todos.push({ id: Date.now() + Math.random(), title: cleanTitle, completed: false });
34
+ saveTodos();
35
+ render();
36
+ }
37
+
38
+ function toggleTodo(id) {
39
+ const todo = todos.find((item) => item.id === id);
40
+ todo.completed = !todo.completed;
41
+ saveTodos();
42
+ render();
43
+ }
44
+
45
+ function toggleAll(completed) {
46
+ todos.forEach((todo) => {
47
+ todo.completed = completed;
48
+ });
49
+ saveTodos();
50
+ render();
51
+ }
52
+
53
+ function removeTodo(id) {
54
+ todos = todos.filter((item) => item.id !== id);
55
+ saveTodos();
56
+ render();
57
+ }
58
+
59
+ function clearCompleted() {
60
+ todos = todos.filter((item) => !item.completed);
61
+ saveTodos();
62
+ render();
63
+ }
64
+
65
+ function startEditing(id) {
66
+ editingId = id;
67
+ render();
68
+ const input = todoListEl.querySelector('.edit');
69
+ input.focus();
70
+ input.setSelectionRange(input.value.length, input.value.length);
71
+ }
72
+
73
+ function saveEdit(id, title) {
74
+ if (editingId !== id) return;
75
+ editingId = null;
76
+ const cleanTitle = title.trim();
77
+ if (cleanTitle === '') {
78
+ removeTodo(id);
79
+ return;
80
+ }
81
+ const todo = todos.find((item) => item.id === id);
82
+ todo.title = cleanTitle;
83
+ saveTodos();
84
+ render();
85
+ }
86
+
87
+ function cancelEdit() {
88
+ editingId = null;
89
+ render();
90
+ }
91
+
92
+ function getVisibleTodos() {
93
+ if (filter === 'active') return todos.filter((item) => !item.completed);
94
+ if (filter === 'completed') return todos.filter((item) => item.completed);
95
+ return todos;
96
+ }
97
+
98
+ function createTodoElement(todo) {
99
+ const li = document.createElement('li');
100
+ li.setAttribute('data-testid', 'todo-item');
101
+ const classes = [];
102
+ if (todo.completed) classes.push('completed');
103
+ if (todo.id === editingId) classes.push('editing');
104
+ li.className = classes.join(' ');
105
+
106
+ const view = document.createElement('div');
107
+ view.className = 'view';
108
+
109
+ const checkbox = document.createElement('input');
110
+ checkbox.className = 'toggle';
111
+ checkbox.type = 'checkbox';
112
+ checkbox.setAttribute('aria-label', 'Toggle Todo');
113
+ checkbox.checked = todo.completed;
114
+ checkbox.addEventListener('change', () => toggleTodo(todo.id));
115
+
116
+ const label = document.createElement('label');
117
+ label.setAttribute('data-testid', 'todo-title');
118
+ label.textContent = todo.title;
119
+ label.addEventListener('dblclick', () => startEditing(todo.id));
120
+
121
+ const destroy = document.createElement('button');
122
+ destroy.className = 'destroy';
123
+ destroy.setAttribute('aria-label', 'Delete');
124
+ destroy.addEventListener('click', () => removeTodo(todo.id));
125
+
126
+ view.append(checkbox, label, destroy);
127
+ li.append(view);
128
+
129
+ const editInput = document.createElement('input');
130
+ editInput.className = 'edit';
131
+ editInput.setAttribute('aria-label', 'Edit');
132
+ editInput.value = todo.title;
133
+ editInput.addEventListener('keydown', (event) => {
134
+ if (event.key === 'Enter') saveEdit(todo.id, editInput.value);
135
+ if (event.key === 'Escape') cancelEdit();
136
+ });
137
+ editInput.addEventListener('blur', () => saveEdit(todo.id, editInput.value));
138
+ li.append(editInput);
139
+
140
+ return li;
141
+ }
142
+
143
+ function render() {
144
+ todoListEl.replaceChildren(...getVisibleTodos().map(createTodoElement));
145
+
146
+ const activeCount = todos.filter((item) => !item.completed).length;
147
+ const completedCount = todos.length - activeCount;
148
+
149
+ mainSection.hidden = todos.length === 0;
150
+ footerSection.hidden = todos.length === 0;
151
+ toggleAllInput.checked = todos.length > 0 && activeCount === 0;
152
+ clearCompletedButton.hidden = completedCount === 0;
153
+
154
+ const itemWord = activeCount === 1 ? 'item' : 'items';
155
+ todoCountEl.innerHTML = '<strong>' + activeCount + '</strong> ' + itemWord + ' left';
156
+
157
+ filterLinks.forEach((link) => {
158
+ if (link.dataset.filter === filter) {
159
+ link.className = 'selected';
160
+ } else {
161
+ link.removeAttribute('class');
162
+ }
163
+ });
164
+ }
165
+
166
+ function readFilterFromHash() {
167
+ const hash = location.hash.replace('#/', '');
168
+ filter = hash === 'active' || hash === 'completed' ? hash : 'all';
169
+ render();
170
+ }
171
+
172
+ newTodoInput.addEventListener('keydown', (event) => {
173
+ if (event.key !== 'Enter') return;
174
+ addTodo(newTodoInput.value);
175
+ newTodoInput.value = '';
176
+ });
177
+ toggleAllInput.addEventListener('change', () => toggleAll(toggleAllInput.checked));
178
+ clearCompletedButton.addEventListener('click', clearCompleted);
179
+ window.addEventListener('hashchange', readFilterFromHash);
180
+
181
+ readFilterFromHash();
@@ -0,0 +1,31 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>TodoMVC</title>
6
+ <link rel="stylesheet" href="style.css">
7
+ </head>
8
+ <body>
9
+ <section class="todoapp">
10
+ <header class="header">
11
+ <h1>todos</h1>
12
+ <input class="new-todo" placeholder="What needs to be done?" autofocus>
13
+ </header>
14
+ <main class="main" hidden>
15
+ <input id="toggle-all" class="toggle-all" type="checkbox">
16
+ <label for="toggle-all">Mark all as complete</label>
17
+ <ul class="todo-list"></ul>
18
+ </main>
19
+ <footer class="footer" hidden>
20
+ <span class="todo-count" data-testid="todo-count"></span>
21
+ <ul class="filters">
22
+ <li><a href="#/" data-filter="all">All</a></li>
23
+ <li><a href="#/active" data-filter="active">Active</a></li>
24
+ <li><a href="#/completed" data-filter="completed">Completed</a></li>
25
+ </ul>
26
+ <button class="clear-completed" hidden>Clear completed</button>
27
+ </footer>
28
+ </section>
29
+ <script src="app.js"></script>
30
+ </body>
31
+ </html>
@@ -0,0 +1,28 @@
1
+ body { font: 14px/1.4 Helvetica, Arial, sans-serif; background: #f5f5f5; color: #111; margin: 0; }
2
+ [hidden] { display: none !important; }
3
+ .todoapp { background: #fff; margin: 130px auto 40px; max-width: 550px; position: relative; box-shadow: 0 2px 4px rgba(0,0,0,.2); }
4
+ h1 { position: absolute; top: -110px; width: 100%; text-align: center; font-size: 80px; font-weight: 200; color: #b83f45; margin: 0; }
5
+ .new-todo, .edit { width: 100%; box-sizing: border-box; font-size: 24px; padding: 16px 16px 16px 60px; border: 0; outline: none; background: rgba(0,0,0,.003); box-shadow: inset 0 -2px 1px rgba(0,0,0,.03); }
6
+ .main { position: relative; border-top: 1px solid #e6e6e6; }
7
+ .toggle-all { position: absolute; top: -52px; left: 0; width: 50px; height: 34px; margin: 0; opacity: 0; z-index: 2; cursor: pointer; }
8
+ .toggle-all + label { position: absolute; top: -52px; left: 0; width: 50px; height: 34px; font-size: 0; }
9
+ .toggle-all + label::before { content: "\276F"; display: block; font-size: 22px; color: #949494; padding: 10px 27px; transform: rotate(90deg); }
10
+ .toggle-all:checked + label::before { color: #484848; }
11
+ .todo-list { margin: 0; padding: 0; list-style: none; }
12
+ .todo-list li { position: relative; font-size: 24px; border-bottom: 1px solid #ededed; }
13
+ .todo-list li .toggle { position: absolute; top: 0; bottom: 0; left: 12px; margin: auto 0; width: 40px; height: 40px; }
14
+ .todo-list li label { display: block; padding: 15px 15px 15px 60px; word-break: break-all; }
15
+ .todo-list li.completed label { color: #949494; text-decoration: line-through; }
16
+ .todo-list li .destroy { display: none; position: absolute; top: 0; right: 10px; bottom: 0; width: 40px; height: 40px; margin: auto 0; font-size: 30px; color: #949494; background: none; border: 0; cursor: pointer; }
17
+ .todo-list li:hover .destroy { display: block; }
18
+ .todo-list li.editing .view { display: none; }
19
+ .todo-list li.editing .edit { display: block; padding: 15px 15px 15px 60px; }
20
+ .todo-list li .edit { display: none; }
21
+ .footer { padding: 10px 15px; height: 20px; text-align: center; border-top: 1px solid #e6e6e6; color: #777; position: relative; }
22
+ .todo-count { float: left; text-align: left; }
23
+ .filters { margin: 0; padding: 0; list-style: none; position: absolute; right: 0; left: 0; }
24
+ .filters li { display: inline; }
25
+ .filters li a { margin: 3px; padding: 3px 7px; color: inherit; text-decoration: none; border: 1px solid transparent; border-radius: 3px; }
26
+ .filters li a.selected { border-color: #ce4646; }
27
+ .clear-completed { float: right; position: relative; z-index: 1; border: 0; background: none; color: inherit; cursor: pointer; font: inherit; }
28
+ .todo-list li .destroy::after { content: "\00d7"; }
@@ -0,0 +1,13 @@
1
+ import { defineConfig, devices } from '@playwright/test';
2
+
3
+ export default defineConfig({
4
+ testDir: './tests',
5
+ reporter: 'list',
6
+ use: { baseURL: 'http://localhost:4173' },
7
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
8
+ webServer: {
9
+ command: 'node serve.js',
10
+ url: 'http://localhost:4173',
11
+ reuseExistingServer: true,
12
+ },
13
+ });
package/demo/serve.js ADDED
@@ -0,0 +1,32 @@
1
+ // Tiny zero-dependency static file server for demo/app on port 4173.
2
+ import { createServer } from 'node:http';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { extname, join, normalize, dirname } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), 'app');
8
+ const port = Number(process.env.PORT) || 4173;
9
+ const types = {
10
+ '.html': 'text/html; charset=utf-8',
11
+ '.js': 'text/javascript; charset=utf-8',
12
+ '.css': 'text/css; charset=utf-8',
13
+ '.svg': 'image/svg+xml',
14
+ '.ico': 'image/x-icon',
15
+ };
16
+
17
+ createServer(async (req, res) => {
18
+ const urlPath = decodeURIComponent(new URL(req.url, 'http://x').pathname);
19
+ const rel = normalize(urlPath === '/' ? '/index.html' : urlPath);
20
+ const file = join(root, rel);
21
+ if (!file.startsWith(root)) {
22
+ res.writeHead(403).end('Forbidden');
23
+ return;
24
+ }
25
+ try {
26
+ const body = await readFile(file);
27
+ res.writeHead(200, { 'Content-Type': types[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store' });
28
+ res.end(body);
29
+ } catch {
30
+ res.writeHead(404).end('Not found');
31
+ }
32
+ }).listen(port, () => console.log(`Demo app on http://localhost:${port}`));