aboutsummaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authoramankumarsingh77 <amankumarsingh7702@gmail.com>2026-07-28 01:19:58 +0530
committerAman Kumar <145339995+amankumarsingh77@users.noreply.github.com>2026-08-02 19:12:46 +0530
commitf9dcdf7f6dcdf2979693a9f179eda2b9995d57ae (patch)
tree763ca6f879a693f56572ab256d33769d6d6bb0ad /test
parentb9c77bb6f9b8b83574489344ef6efd207a611e98 (diff)
refactor: close the remaining unguarded type assertions
Types the event-queue iterator's TReturn as undefined so the terminal result needs no cast; declares the isError field the pi runtime reads by duck-typing; binds socket to a local const in the daemon transport; replaces the @ts-ignore on the optional sharp import with a non-literal specifier so src/ still typechecks where sharp was not installed. Adds src/util/guards.ts as the single home for narrowing over unknown — isRecord plus scalar/array readers — and converts the two private isObject copies in cdp/types.ts and daemon/protocol.ts along with every inline `as Record<string, unknown>` in domains/js.ts and domains/render.ts. Gives Accessibility.getFullAXTree a real result schema, closing the last unvalidated CDP boundary: only nodeId is required, every object carries additionalProperties, and each AX value stays Unknown, so the tree decodes as a whole or fails as a whole rather than being filtered. Guards the five tool-result `details` readers, the daemon attach response, the persisted session state, the browser-namespace flag, and the fs errno narrowing, each feeding an already-present failure path. The daemon-transport socket binding is not a bug fix: send() runs synchronously inside sendWithTimeout's promise executor, so socket cannot be reassigned between the check and the write. It removes the assertion and makes the write immune to a later refactor that adds an await. Two assertions survive by design and are documented in the task report: the never->unknown re-widening in util/tool.ts, which the type-erased tool registry makes unavoidable, and the AsyncFunction constructor lookup in domains/js.ts, which JavaScript exposes no typed binding for. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'test')
-rw-r--r--test/cdp/commands-test.ts59
-rw-r--r--test/cdp/event-queue-test.ts136
-rw-r--r--test/util/guards-test.ts95
3 files changed, 290 insertions, 0 deletions
diff --git a/test/cdp/commands-test.ts b/test/cdp/commands-test.ts
index b316f68..ad1b057 100644
--- a/test/cdp/commands-test.ts
+++ b/test/cdp/commands-test.ts
@@ -43,3 +43,62 @@ describe("cdp command table", () => {
assert.equal(r.success, false);
});
});
+
+describe("Accessibility.getFullAXTree schema", () => {
+ test("accepts a realistic Chrome AX node with unmodelled extra fields", () => {
+ const r = decodeResult("Accessibility.getFullAXTree", {
+ nodes: [
+ {
+ nodeId: "1",
+ ignored: false,
+ role: { type: "role", value: "RootWebArea" },
+ chromeRole: { type: "internalRole", value: 144 },
+ name: { type: "computedString", value: "Example", sources: [{ type: "relatedElement" }] },
+ properties: [
+ { name: "focusable", value: { type: "booleanOrUndefined", value: true } },
+ { name: "level", value: { type: "integer", value: 2 } },
+ ],
+ childIds: ["2", "3"],
+ backendDOMNodeId: 7,
+ frameId: "F1",
+ },
+ { nodeId: "2", parentId: "1", ignored: true, ignoredReasons: [{ name: "notRendered" }] },
+ ],
+ });
+ assert.equal(r.success, true);
+ if (r.success) {
+ assert.equal(r.data.nodes.length, 2);
+ assert.equal(r.data.nodes[0]?.role?.value, "RootWebArea");
+ assert.equal(r.data.nodes[0]?.backendDOMNodeId, 7);
+ assert.deepEqual(r.data.nodes[0]?.childIds, ["2", "3"]);
+ }
+ });
+
+ test("accepts an empty node list", () => {
+ const r = decodeResult("Accessibility.getFullAXTree", { nodes: [] });
+ assert.equal(r.success, true);
+ });
+
+ test("rejects a node whose nodeId is not a string", () => {
+ const r = decodeResult("Accessibility.getFullAXTree", { nodes: [{ nodeId: 5 }] });
+ assert.equal(r.success, false);
+ if (!r.success) assert.equal(r.error.kind, "invalid_response");
+ });
+
+ test("rejects childIds that are not strings", () => {
+ const r = decodeResult("Accessibility.getFullAXTree", { nodes: [{ nodeId: "1", childIds: [2] }] });
+ assert.equal(r.success, false);
+ });
+
+ test("rejects a missing nodes array", () => {
+ const r = decodeResult("Accessibility.getFullAXTree", {});
+ assert.equal(r.success, false);
+ });
+
+ test("keeps an AxValue's value untyped so any Chrome value type decodes", () => {
+ const r = decodeResult("Accessibility.getFullAXTree", {
+ nodes: [{ nodeId: "1", value: { type: "number", value: 42 } }, { nodeId: "2", name: { type: "x", value: null } }],
+ });
+ assert.equal(r.success, true);
+ });
+});
diff --git a/test/cdp/event-queue-test.ts b/test/cdp/event-queue-test.ts
new file mode 100644
index 0000000..cae8143
--- /dev/null
+++ b/test/cdp/event-queue-test.ts
@@ -0,0 +1,136 @@
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { makeEventQueue, rejectAllPending, sendWithTimeout, type Pending } from "../../src/cdp/event-queue";
+
+describe("event queue iteration", () => {
+ test("yields pushed events in order", async () => {
+ const q = makeEventQueue();
+ q.push({ method: "Page.loadEventFired", params: {} });
+ q.push({ method: "Page.frameNavigated", params: {} });
+ const seen: string[] = [];
+ for await (const ev of q.iter) {
+ seen.push(ev.method);
+ if (seen.length === 2) break;
+ }
+ assert.deepEqual(seen, ["Page.loadEventFired", "Page.frameNavigated"]);
+ });
+
+ test("ending the queue terminates the iteration after draining the buffer", async () => {
+ const q = makeEventQueue();
+ q.push({ method: "Page.loadEventFired", params: {} });
+ q.end();
+ const seen: string[] = [];
+ for await (const ev of q.iter) seen.push(ev.method);
+ assert.deepEqual(seen, ["Page.loadEventFired"]);
+ });
+
+ test("a waiter pending at end() is released", async () => {
+ const q = makeEventQueue();
+ const done = (async () => {
+ const seen: string[] = [];
+ for await (const ev of q.iter) seen.push(ev.method);
+ return seen;
+ })();
+ await Promise.resolve();
+ q.end();
+ assert.deepEqual(await done, []);
+ });
+
+ test("push after end() is dropped", async () => {
+ const q = makeEventQueue();
+ q.end();
+ q.push({ method: "Page.loadEventFired", params: {} });
+ const seen: string[] = [];
+ for await (const ev of q.iter) seen.push(ev.method);
+ assert.deepEqual(seen, []);
+ });
+
+ test("a waiter is handed the next pushed event directly", async () => {
+ const q = makeEventQueue();
+ const it = q.iter[Symbol.asyncIterator]();
+ const pending = it.next();
+ await Promise.resolve();
+ q.push({ method: "Runtime.consoleAPICalled", params: { a: 1 } });
+ const r = await pending;
+ assert.equal(r.done, false);
+ assert.deepEqual(r.value, { method: "Runtime.consoleAPICalled", params: { a: 1 } });
+ });
+
+ test("the terminal result reports done with an undefined value", async () => {
+ const q = makeEventQueue();
+ q.end();
+ const it = q.iter[Symbol.asyncIterator]();
+ const r = await it.next();
+ assert.equal(r.done, true);
+ assert.equal(r.value, undefined);
+ });
+
+ test("sessionId is preserved on yielded events", async () => {
+ const q = makeEventQueue();
+ q.push({ method: "Page.loadEventFired", params: {}, sessionId: "s1" });
+ q.end();
+ const seen: Array<string | undefined> = [];
+ for await (const ev of q.iter) seen.push(ev.sessionId);
+ assert.deepEqual(seen, ["s1"]);
+ });
+});
+
+describe("pending request bookkeeping", () => {
+ test("rejectAllPending settles every entry with transport_closed and clears the map", () => {
+ const pending = new Map<number, Pending>();
+ const settled: string[] = [];
+ for (const id of [1, 2]) {
+ pending.set(id, {
+ resolve: (r) => settled.push(r.success ? "ok" : r.error.kind),
+ timer: setTimeout(() => {}, 10_000),
+ method: `M.m${id}`,
+ });
+ }
+ rejectAllPending(pending, "gone");
+ assert.deepEqual(settled, ["transport_closed", "transport_closed"]);
+ assert.equal(pending.size, 0);
+ });
+
+ test("sendWithTimeout resolves transport_closed when send throws synchronously", async () => {
+ const pending = new Map<number, Pending>();
+ const r = await sendWithTimeout(pending, 7, "M.m", 10_000, "Test", () => {
+ throw new Error("socket gone");
+ });
+ assert.equal(r.success, false);
+ if (!r.success) {
+ assert.equal(r.error.kind, "transport_closed");
+ assert.equal(r.error.message, "socket gone");
+ assert.equal(r.error.method, "M.m");
+ }
+ assert.equal(pending.size, 0);
+ });
+
+ test("sendWithTimeout registers a pending entry the caller can resolve", async () => {
+ const pending = new Map<number, Pending>();
+ let sent = false;
+ const p = sendWithTimeout(pending, 9, "M.m", 10_000, "Test", () => {
+ sent = true;
+ });
+ assert.equal(sent, true);
+ const entry = pending.get(9);
+ assert.notEqual(entry, undefined);
+ if (entry) {
+ clearTimeout(entry.timer);
+ entry.resolve({ success: true, data: { hello: "world" } });
+ }
+ const r = await p;
+ assert.equal(r.success, true);
+ if (r.success) assert.deepEqual(r.data, { hello: "world" });
+ });
+
+ test("sendWithTimeout resolves a timeout error and drops the pending entry", async () => {
+ const pending = new Map<number, Pending>();
+ const r = await sendWithTimeout(pending, 11, "M.slow", 1, "Test", () => {});
+ assert.equal(r.success, false);
+ if (!r.success) {
+ assert.equal(r.error.kind, "timeout");
+ assert.match(r.error.message, /Test timeout after 1ms: M\.slow/);
+ }
+ assert.equal(pending.size, 0);
+ });
+});
diff --git a/test/util/guards-test.ts b/test/util/guards-test.ts
new file mode 100644
index 0000000..7c7b426
--- /dev/null
+++ b/test/util/guards-test.ts
@@ -0,0 +1,95 @@
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { asArrayOf, asBoolean, asNumber, asRecord, asString, errnoCode, isRecord } from "../../src/util/guards";
+
+describe("isRecord", () => {
+ test("accepts plain objects", () => {
+ assert.equal(isRecord({}), true);
+ assert.equal(isRecord({ a: 1 }), true);
+ });
+
+ test("rejects null, arrays and primitives", () => {
+ assert.equal(isRecord(null), false);
+ assert.equal(isRecord(undefined), false);
+ assert.equal(isRecord([]), false);
+ assert.equal(isRecord([{ a: 1 }]), false);
+ assert.equal(isRecord("s"), false);
+ assert.equal(isRecord(0), false);
+ assert.equal(isRecord(false), false);
+ });
+});
+
+describe("scalar readers", () => {
+ test("asString accepts only strings", () => {
+ assert.equal(asString(""), "");
+ assert.equal(asString("x"), "x");
+ assert.equal(asString(1), undefined);
+ assert.equal(asString(null), undefined);
+ assert.equal(asString(undefined), undefined);
+ assert.equal(asString({}), undefined);
+ });
+
+ test("asNumber accepts only numbers, including 0 and NaN", () => {
+ assert.equal(asNumber(0), 0);
+ assert.equal(asNumber(-1.5), -1.5);
+ assert.equal(Number.isNaN(asNumber(Number.NaN)), true);
+ assert.equal(asNumber("1"), undefined);
+ assert.equal(asNumber(null), undefined);
+ });
+
+ test("asBoolean accepts only booleans", () => {
+ assert.equal(asBoolean(false), false);
+ assert.equal(asBoolean(true), true);
+ assert.equal(asBoolean(0), undefined);
+ assert.equal(asBoolean("true"), undefined);
+ });
+
+ test("asRecord mirrors isRecord but yields the value", () => {
+ assert.deepEqual(asRecord({ a: 1 }), { a: 1 });
+ assert.equal(asRecord([]), undefined);
+ assert.equal(asRecord(null), undefined);
+ });
+});
+
+describe("asArrayOf", () => {
+ test("parses every element", () => {
+ assert.deepEqual(asArrayOf(["a", "b"], asString), ["a", "b"]);
+ assert.deepEqual(asArrayOf([], asString), []);
+ });
+
+ test("rejects the whole array when any element fails, rather than dropping it", () => {
+ assert.equal(asArrayOf(["a", 2], asString), undefined);
+ assert.equal(asArrayOf([1, "b"], asString), undefined);
+ });
+
+ test("rejects non-arrays", () => {
+ assert.equal(asArrayOf({ 0: "a" }, asString), undefined);
+ assert.equal(asArrayOf(undefined, asString), undefined);
+ assert.equal(asArrayOf("ab", asString), undefined);
+ });
+
+ test("treats an element parsed as undefined as a failure", () => {
+ assert.equal(asArrayOf([undefined], asString), undefined);
+ });
+});
+
+describe("errnoCode", () => {
+ test("reads .code off a real Error", () => {
+ const e = Object.assign(new Error("nope"), { code: "ENOENT" });
+ assert.equal(errnoCode(e), "ENOENT");
+ });
+
+ test("returns undefined for an Error without a code", () => {
+ assert.equal(errnoCode(new Error("plain")), undefined);
+ });
+
+ test("returns undefined for a non-string code", () => {
+ assert.equal(errnoCode(Object.assign(new Error("x"), { code: 13 })), undefined);
+ });
+
+ test("returns undefined for non-Errors that merely carry a code", () => {
+ assert.equal(errnoCode({ code: "ENOENT" }), undefined);
+ assert.equal(errnoCode("ENOENT"), undefined);
+ assert.equal(errnoCode(null), undefined);
+ });
+});