1
0

chore: 强化代码质量与风格检查体系

ESLint 升级到 recommended-type-checked + stylistic-type-checked,
引入 perfectionist 导入排序和 import 插件导入验证。

Prettier 显式声明全部格式化参数,消除跨环境差异。
TypeScript 启用 noUnusedLocals 和 noPropertyAccessFromIndexSignature。
完善 ignore 列表,排除 .agents/、bun.lock、data/ 等。
引入 husky + lint-staged(pre-commit)+ commitlint(commit-msg)。
更新 DEVELOPMENT.md 代码质量章节。
修复所有新增规则检测到的类型和风格违规。
This commit is contained in:
2026-05-12 18:44:59 +08:00
parent ce8baae3d1
commit a5cf6065c2
83 changed files with 2654 additions and 1824 deletions

View File

@@ -1,18 +1,19 @@
import { mismatchFailure } from "../shared/failure";
import type { ExpectResult } from "../shared/duration";
import { mismatchFailure } from "../shared/failure";
export function checkExitCode(exitCode: number, allowed: number[]): ExpectResult {
if (!allowed.includes(exitCode)) {
return {
matched: false,
failure: mismatchFailure(
"exitCode",
"exitCode",
allowed,
exitCode,
`exitCode ${exitCode} not in [${allowed}]`,
`exitCode ${exitCode} not in [${allowed.join(", ")}]`,
),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}

View File

@@ -1,26 +1,227 @@
import { isError } from "es-toolkit";
import type { CheckResult } from "../../types";
import type { Checker, CheckerContext, ResolveContext } from "../types";
import { resolve } from "node:path";
import type {
CommandExpectConfig,
CheckResult,
CommandTargetConfig,
ResolvedCommandTarget,
ResolvedTarget,
TargetConfig,
} from "../../types";
import type { Checker, CheckerContext, ResolveContext } from "../types";
import { parseSize } from "../../size";
import { checkExitCode } from "./expect";
import { checkDuration } from "../shared/duration";
import { checkTextRules } from "../shared/text";
import { errorFailure } from "../shared/failure";
import { resolve } from "node:path";
import { checkTextRules } from "../shared/text";
import { checkExitCode } from "./expect";
export class CommandChecker implements Checker {
readonly type = "command";
async execute(target: ResolvedTarget, ctx: CheckerContext): Promise<CheckResult> {
const t = target as ResolvedCommandTarget;
const timestamp = new Date().toISOString();
const start = performance.now();
let proc: ReturnType<typeof Bun.spawn>;
try {
proc = Bun.spawn([t.command.exec, ...t.command.args], {
cwd: t.command.cwd,
env: t.command.env,
stderr: "pipe",
stdin: "ignore",
stdout: "pipe",
});
} catch (error) {
const durationMs = Math.round(performance.now() - start);
return {
durationMs,
failure: errorFailure("exitCode", "spawn", isError(error) ? error.message : String(error)),
matched: false,
statusDetail: null,
targetName: t.name,
timestamp,
};
}
ctx.signal.addEventListener(
"abort",
() => {
try {
proc.kill();
} catch {
/* best-effort kill */
}
},
{ once: true },
);
let outputResult: { exceeded: boolean; stderr: string; stdout: string };
try {
outputResult = await readOutput(
proc.stdout as ReadableStream<Uint8Array>,
proc.stderr as ReadableStream<Uint8Array>,
() => proc.kill(),
t.command.maxOutputBytes,
);
} catch {
const durationMs = Math.round(performance.now() - start);
return {
durationMs,
failure: errorFailure("exitCode", "execution", "输出读取失败"),
matched: false,
statusDetail: null,
targetName: t.name,
timestamp,
};
}
await proc.exited;
const durationMs = Math.round(performance.now() - start);
const exitCode = proc.exitCode ?? 1;
if (outputResult.exceeded) {
return {
durationMs,
failure: errorFailure("exitCode", "output", `输出超过限制 ${t.command.maxOutputBytes} 字节`),
matched: false,
statusDetail: `exitCode=${exitCode}`,
targetName: t.name,
timestamp,
};
}
if (ctx.signal.aborted) {
return {
durationMs,
failure: errorFailure("exitCode", "timeout", `命令执行超时 (${t.timeoutMs}ms)`),
matched: false,
statusDetail: null,
targetName: t.name,
timestamp,
};
}
const exitCodeResult = checkExitCode(exitCode, t.expect?.exitCode ?? [0]);
if (!exitCodeResult.matched) {
return {
durationMs,
failure: exitCodeResult.failure,
matched: false,
statusDetail: `exitCode=${exitCode}`,
targetName: t.name,
timestamp,
};
}
const durationResult = checkDuration(durationMs, t.expect?.maxDurationMs);
if (!durationResult.matched) {
return {
durationMs,
failure: durationResult.failure,
matched: false,
statusDetail: `exitCode=${exitCode}`,
targetName: t.name,
timestamp,
};
}
if (t.expect?.stdout && t.expect.stdout.length > 0) {
const stdoutResult = checkTextRules(outputResult.stdout, t.expect.stdout, "stdout");
if (!stdoutResult.matched) {
return {
durationMs,
failure: stdoutResult.failure,
matched: false,
statusDetail: `exitCode=${exitCode}`,
targetName: t.name,
timestamp,
};
}
}
if (t.expect?.stderr && t.expect.stderr.length > 0) {
const stderrResult = checkTextRules(outputResult.stderr, t.expect.stderr, "stderr");
if (!stderrResult.matched) {
return {
durationMs,
failure: stderrResult.failure,
matched: false,
statusDetail: `exitCode=${exitCode}`,
targetName: t.name,
timestamp,
};
}
}
return {
durationMs,
failure: null,
matched: true,
statusDetail: `exitCode=${exitCode}`,
targetName: t.name,
timestamp,
};
}
resolve(target: TargetConfig, context: ResolveContext): ResolvedTarget {
const t = target as TargetConfig & { command: CommandTargetConfig; type: "command" };
const commandDefaults = context.defaults.command;
if (!t.command.exec || t.command.exec.trim() === "") {
throw new Error(`target "${t.name}" 缺少 command.exec 字段`);
}
const cwd = t.command.cwd ?? commandDefaults?.cwd ?? ".";
const resolvedCwd = resolve(context.configDir, cwd);
const maxOutputBytes = parseSize(t.command.maxOutputBytes ?? commandDefaults?.maxOutputBytes ?? "100MB");
const env = { ...process.env, ...(t.command.env ?? {}) } as Record<string, string>;
return {
command: {
args: t.command.args ?? [],
cwd: resolvedCwd,
env,
exec: t.command.exec,
maxOutputBytes,
},
expect: target.expect,
group: target.group ?? "default",
intervalMs: context.defaultIntervalMs,
name: t.name,
timeoutMs: context.defaultTimeoutMs,
type: "command",
} satisfies ResolvedCommandTarget;
}
serialize(target: ResolvedTarget): { config: string; target: string } {
const t = target as ResolvedCommandTarget;
const parts = [t.command.exec, ...t.command.args];
return {
config: JSON.stringify({
args: t.command.args,
cwd: t.command.cwd,
env: t.command.env,
exec: t.command.exec,
maxOutputBytes: t.command.maxOutputBytes,
}),
target: `exec ${parts.join(" ")}`,
};
}
}
async function readOutput(
stdout: ReadableStream<Uint8Array>,
stderr: ReadableStream<Uint8Array>,
kill: () => void,
maxBytes: number,
): Promise<{ stdout: string; stderr: string; exceeded: boolean }> {
): Promise<{ exceeded: boolean; stderr: string; stdout: string }> {
let totalBytes = 0;
let exceeded = false;
let killed = false;
@@ -61,203 +262,5 @@ async function readOutput(
const [out, err] = await Promise.all([readStream(stdout), readStream(stderr)]);
return { stdout: out, stderr: err, exceeded };
}
export class CommandChecker implements Checker {
readonly type = "command";
resolve(target: TargetConfig, context: ResolveContext): ResolvedTarget {
const t = target as TargetConfig & { type: "command"; command: CommandTargetConfig };
const commandDefaults = context.defaults.command;
if (!t.command.exec || t.command.exec.trim() === "") {
throw new Error(`target "${t.name}" 缺少 command.exec 字段`);
}
const cwd = t.command.cwd ?? commandDefaults?.cwd ?? ".";
const resolvedCwd = resolve(context.configDir, cwd);
const maxOutputBytes = parseSize(
t.command.maxOutputBytes ?? commandDefaults?.maxOutputBytes ?? "100MB",
);
const env = { ...process.env, ...(t.command.env ?? {}) } as Record<string, string>;
return {
type: "command",
name: t.name,
group: target.group ?? "default",
command: {
exec: t.command.exec,
args: t.command.args ?? [],
cwd: resolvedCwd,
env,
maxOutputBytes,
},
intervalMs: context.defaultIntervalMs,
timeoutMs: context.defaultTimeoutMs,
expect: target.expect as CommandExpectConfig | undefined,
} satisfies ResolvedCommandTarget;
}
async execute(target: ResolvedTarget, ctx: CheckerContext): Promise<CheckResult> {
const t = target as ResolvedCommandTarget;
const timestamp = new Date().toISOString();
const start = performance.now();
let proc: ReturnType<typeof Bun.spawn>;
try {
proc = Bun.spawn([t.command.exec, ...t.command.args], {
cwd: t.command.cwd,
env: t.command.env,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
} catch (error) {
const durationMs = Math.round(performance.now() - start);
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: null,
failure: errorFailure("exitCode", "spawn", isError(error) ? error.message : String(error)),
};
}
ctx.signal.addEventListener("abort", () => {
try {
proc.kill();
} catch {
/* best-effort kill */
}
}, { once: true });
let outputResult: { stdout: string; stderr: string; exceeded: boolean };
try {
outputResult = await readOutput(
proc.stdout as ReadableStream<Uint8Array>,
proc.stderr as ReadableStream<Uint8Array>,
() => proc.kill(),
t.command.maxOutputBytes,
);
} catch {
const durationMs = Math.round(performance.now() - start);
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: null,
failure: errorFailure("exitCode", "execution", "输出读取失败"),
};
}
await proc.exited;
const durationMs = Math.round(performance.now() - start);
const exitCode = proc.exitCode ?? 1;
if (outputResult.exceeded) {
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: `exitCode=${exitCode}`,
failure: errorFailure("exitCode", "output", `输出超过限制 ${t.command.maxOutputBytes} 字节`),
};
}
if (ctx.signal.aborted) {
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: null,
failure: errorFailure("exitCode", "timeout", `命令执行超时 (${t.timeoutMs}ms)`),
};
}
const exitCodeResult = checkExitCode(exitCode, t.expect?.exitCode ?? [0]);
if (!exitCodeResult.matched) {
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: `exitCode=${exitCode}`,
failure: exitCodeResult.failure,
};
}
const durationResult = checkDuration(durationMs, t.expect?.maxDurationMs);
if (!durationResult.matched) {
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: `exitCode=${exitCode}`,
failure: durationResult.failure,
};
}
if (t.expect?.stdout && t.expect.stdout.length > 0) {
const stdoutResult = checkTextRules(outputResult.stdout, t.expect.stdout, "stdout");
if (!stdoutResult.matched) {
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: `exitCode=${exitCode}`,
failure: stdoutResult.failure,
};
}
}
if (t.expect?.stderr && t.expect.stderr.length > 0) {
const stderrResult = checkTextRules(outputResult.stderr, t.expect.stderr, "stderr");
if (!stderrResult.matched) {
return {
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: `exitCode=${exitCode}`,
failure: stderrResult.failure,
};
}
}
return {
targetName: t.name,
timestamp,
matched: true,
durationMs,
statusDetail: `exitCode=${exitCode}`,
failure: null,
};
}
serialize(target: ResolvedTarget): { target: string; config: string } {
const t = target as ResolvedCommandTarget;
const parts = [t.command.exec, ...t.command.args];
return {
target: `exec ${parts.join(" ")}`,
config: JSON.stringify({
exec: t.command.exec,
args: t.command.args,
cwd: t.command.cwd,
env: t.command.env,
maxOutputBytes: t.command.maxOutputBytes,
}),
};
}
return { exceeded, stderr: err, stdout: out };
}

View File

@@ -1,31 +1,16 @@
import type { HeaderExpect, HttpExpectConfig } from "../../types";
import { mismatchFailure, errorFailure } from "../shared/failure";
import { applyOperator } from "../shared/operator";
import { checkDuration } from "../shared/duration";
import { checkBodyExpect } from "../shared/body";
import type { ExpectResult } from "../shared/duration";
export function checkStatus(statusCode: number, allowed: number[]): ExpectResult {
if (!allowed.includes(statusCode)) {
return {
matched: false,
failure: mismatchFailure(
"status",
"status",
allowed,
statusCode,
`status ${statusCode} not in [${allowed}]`,
),
};
}
return { matched: true, failure: null };
}
import { checkBodyExpect } from "../shared/body";
import { checkDuration } from "../shared/duration";
import { errorFailure, mismatchFailure } from "../shared/failure";
import { applyOperator } from "../shared/operator";
export function checkHeaders(
headers: Record<string, string>,
headerExpects?: Record<string, HeaderExpect>,
): ExpectResult {
if (!headerExpects) return { matched: true, failure: null };
if (!headerExpects) return { failure: null, matched: true };
for (const [key, expected] of Object.entries(headerExpects)) {
const actualValue = headers[key.toLowerCase()];
@@ -34,36 +19,36 @@ export function checkHeaders(
if (typeof expected === "string") {
if (actualValue !== expected) {
return {
matched: false,
failure: mismatchFailure("headers", path, expected, actualValue, `header ${key} mismatch`),
matched: false,
};
}
} else {
if (actualValue === undefined) {
if (expected.exists !== false) {
return {
matched: false,
failure: mismatchFailure("headers", path, "defined", undefined, `header ${key} not found`),
matched: false,
};
}
continue;
}
if (!applyOperator(actualValue, expected)) {
return {
matched: false,
failure: mismatchFailure("headers", path, expected, actualValue, `header ${key} mismatch`),
matched: false,
};
}
}
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
export function checkHttpExpect(
statusCode: number,
headers: Record<string, string>,
body: string | null,
body: null | string,
durationMs: number,
expect?: HttpExpectConfig,
): ExpectResult {
@@ -83,13 +68,29 @@ export function checkHttpExpect(
if (expect.body && expect.body.length > 0) {
if (body === null) {
return {
matched: false,
failure: errorFailure("body", "body", "body is null but body rules are configured"),
matched: false,
};
}
const bodyResult = checkBodyExpect(body, expect.body);
if (!bodyResult.matched) return bodyResult;
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
export function checkStatus(statusCode: number, allowed: number[]): ExpectResult {
if (!allowed.includes(statusCode)) {
return {
failure: mismatchFailure(
"status",
"status",
allowed,
statusCode,
`status ${statusCode} not in [${allowed.join(", ")}]`,
),
matched: false,
};
}
return { failure: null, matched: true };
}

View File

@@ -1,51 +1,15 @@
import type { CheckResult } from "../../types";
import { isError } from "es-toolkit";
import type {
Checker,
CheckerContext,
ResolveContext,
} from "../types";
import type {
HttpExpectConfig,
HttpTargetConfig,
ResolvedHttpTarget,
ResolvedTarget,
TargetConfig,
} from "../../types";
import type { CheckResult, HttpTargetConfig, ResolvedHttpTarget, ResolvedTarget, TargetConfig } from "../../types";
import type { Checker, CheckerContext, ResolveContext } from "../types";
import { parseSize } from "../../size";
import { checkHttpExpect } from "./expect";
import { errorFailure } from "../shared/failure";
import { checkHttpExpect } from "./expect";
export class HttpChecker implements Checker {
readonly type = "http";
resolve(target: TargetConfig, context: ResolveContext): ResolvedTarget {
const t = target as TargetConfig & { type: "http"; http: HttpTargetConfig };
const httpDefaults = context.defaults.http;
if (!t.http.url || t.http.url.trim() === "") {
throw new Error(`target "${t.name}" 缺少 http.url 字段`);
}
const maxBodyBytes = parseSize(t.http.maxBodyBytes ?? httpDefaults?.maxBodyBytes ?? "100MB");
return {
type: "http",
name: t.name,
group: target.group ?? "default",
http: {
url: t.http.url,
method: t.http.method ?? httpDefaults?.method ?? "GET",
headers: { ...(httpDefaults?.headers ?? {}), ...(t.http.headers ?? {}) },
body: t.http.body,
maxBodyBytes,
},
intervalMs: context.defaultIntervalMs,
timeoutMs: context.defaultTimeoutMs,
expect: target.expect as HttpExpectConfig | undefined,
} satisfies ResolvedHttpTarget;
}
async execute(target: ResolvedTarget, ctx: CheckerContext): Promise<CheckResult> {
const t = target as ResolvedHttpTarget;
const timestamp = new Date().toISOString();
@@ -54,9 +18,9 @@ export class HttpChecker implements Checker {
const start = performance.now();
const response = await fetch(t.http.url, {
method: t.http.method,
headers: t.http.headers,
body: t.http.method !== "GET" && t.http.method !== "HEAD" ? t.http.body : undefined,
headers: t.http.headers,
method: t.http.method,
signal: ctx.signal,
});
@@ -67,19 +31,19 @@ export class HttpChecker implements Checker {
const hasBodyRules = !!(t.expect?.body && t.expect.body.length > 0);
const preBodyExpect = t.expect
? { status: t.expect.status, maxDurationMs: t.expect.maxDurationMs, headers: t.expect.headers }
? { headers: t.expect.headers, maxDurationMs: t.expect.maxDurationMs, status: t.expect.status }
: undefined;
const preBodyResult = checkHttpExpect(statusCode, responseHeaders, null, durationMs, preBodyExpect);
if (!hasBodyRules || !preBodyResult.matched) {
return {
durationMs,
failure: preBodyResult.failure,
matched: preBodyResult.matched,
statusDetail: `HTTP ${statusCode}`,
targetName: t.name,
timestamp,
matched: preBodyResult.matched,
durationMs,
statusDetail: `HTTP ${statusCode}`,
failure: preBodyResult.failure,
};
}
@@ -87,16 +51,12 @@ export class HttpChecker implements Checker {
if (bodyBuffer.byteLength > t.http.maxBodyBytes) {
return {
durationMs,
failure: errorFailure("body", "body", `响应体大小 ${bodyBuffer.byteLength} 超过限制 ${t.http.maxBodyBytes}`),
matched: false,
statusDetail: `HTTP ${statusCode}`,
targetName: t.name,
timestamp,
matched: false,
durationMs,
statusDetail: `HTTP ${statusCode}`,
failure: errorFailure(
"body",
"body",
`响应体大小 ${bodyBuffer.byteLength} 超过限制 ${t.http.maxBodyBytes}`,
),
};
}
@@ -104,42 +64,69 @@ export class HttpChecker implements Checker {
const fullResult = checkHttpExpect(statusCode, responseHeaders, body, durationMs, t.expect);
return {
durationMs,
failure: fullResult.failure,
matched: fullResult.matched,
statusDetail: `HTTP ${statusCode}`,
targetName: t.name,
timestamp,
matched: fullResult.matched,
durationMs,
statusDetail: `HTTP ${statusCode}`,
failure: fullResult.failure,
};
} catch (error) {
const isTimeout = ctx.signal.aborted || (error instanceof DOMException && error.name === "AbortError");
return {
targetName: t.name,
timestamp,
matched: false,
durationMs: null,
statusDetail: null,
failure: errorFailure(
"status",
"request",
isTimeout ? `请求超时 (${t.timeoutMs}ms)` : isError(error) ? error.message : String(error),
),
matched: false,
statusDetail: null,
targetName: t.name,
timestamp,
};
}
}
serialize(target: ResolvedTarget): { target: string; config: string } {
resolve(target: TargetConfig, context: ResolveContext): ResolvedTarget {
const t = target as TargetConfig & { http: HttpTargetConfig; type: "http" };
const httpDefaults = context.defaults.http;
if (!t.http.url || t.http.url.trim() === "") {
throw new Error(`target "${t.name}" 缺少 http.url 字段`);
}
const maxBodyBytes = parseSize(t.http.maxBodyBytes ?? httpDefaults?.maxBodyBytes ?? "100MB");
return {
expect: target.expect,
group: target.group ?? "default",
http: {
body: t.http.body,
headers: { ...(httpDefaults?.headers ?? {}), ...(t.http.headers ?? {}) },
maxBodyBytes,
method: t.http.method ?? httpDefaults?.method ?? "GET",
url: t.http.url,
},
intervalMs: context.defaultIntervalMs,
name: t.name,
timeoutMs: context.defaultTimeoutMs,
type: "http",
} satisfies ResolvedHttpTarget;
}
serialize(target: ResolvedTarget): { config: string; target: string } {
const t = target as ResolvedHttpTarget;
return {
target: t.http.url,
config: JSON.stringify({
url: t.http.url,
method: t.http.method,
headers: t.http.headers,
body: t.http.body,
headers: t.http.headers,
maxBodyBytes: t.http.maxBodyBytes,
method: t.http.method,
url: t.http.url,
}),
target: t.http.url,
};
}
}

View File

@@ -1,6 +1,6 @@
import { checkerRegistry } from "./registry";
import { HttpChecker } from "./http/runner";
import { CommandChecker } from "./command/runner";
import { HttpChecker } from "./http/runner";
import { checkerRegistry } from "./registry";
export function registerCheckers(): void {
checkerRegistry.register(new HttpChecker());

View File

@@ -1,15 +1,12 @@
import type { Checker } from "./types";
export class CheckerRegistry {
private checkers = new Map<string, Checker>();
register(checker: Checker): void {
if (this.checkers.has(checker.type)) {
throw new Error(`Checker type "${checker.type}" 已注册`);
}
this.checkers.set(checker.type, checker);
get supportedTypes(): string[] {
return [...this.checkers.keys()];
}
private checkers = new Map<string, Checker>();
get(type: string): Checker {
const checker = this.checkers.get(type);
if (!checker) {
@@ -18,8 +15,11 @@ export class CheckerRegistry {
return checker;
}
get supportedTypes(): string[] {
return [...this.checkers.keys()];
register(checker: Checker): void {
if (this.checkers.has(checker.type)) {
throw new Error(`Checker type "${checker.type}" 已注册`);
}
this.checkers.set(checker.type, checker);
}
}

View File

@@ -1,58 +1,26 @@
import type { BodyRule, CssRule, JsonRule, XpathRule } from "../../types";
import { DOMParser } from "@xmldom/xmldom";
import * as cheerio from "cheerio";
import * as xpath from "xpath";
import { DOMParser } from "@xmldom/xmldom";
import { mismatchFailure, errorFailure } from "./failure";
import { applyOperator, evaluateJsonPath } from "./operator";
import type { BodyRule, CssRule, JsonRule, XpathRule } from "../../types";
import type { ExpectResult } from "./duration";
function checkJsonRule(
body: string,
rule: JsonRule,
rulePath: string,
): ExpectResult {
const { path, ...operators } = rule;
const fullPath = `${rulePath}.json(${path})`;
import { errorFailure, mismatchFailure } from "./failure";
import { applyOperator, evaluateJsonPath } from "./operator";
let json: unknown;
try {
json = JSON.parse(body);
} catch {
return {
matched: false,
failure: errorFailure("body", fullPath, "body is not valid JSON"),
};
export function checkBodyExpect(body: string, rules?: BodyRule[]): ExpectResult {
if (!rules || rules.length === 0) return { failure: null, matched: true };
for (let i = 0; i < rules.length; i++) {
const result = checkSingleBodyRule(body, rules[i]!, i);
if (!result.matched) return result;
}
const actual = evaluateJsonPath(json, path);
const opKeys = Object.keys(operators);
if (opKeys.length === 0) {
if (actual === undefined) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, "defined", actual, `path ${path} is undefined`),
};
}
return { matched: true, failure: null };
}
const matched = applyOperator(actual, operators);
if (!matched) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, operators, actual, `json path ${path} mismatch`),
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
function checkCssRule(
body: string,
rule: CssRule,
rulePath: string,
): ExpectResult {
const { selector, attr, ...operators } = rule;
function checkCssRule(body: string, rule: CssRule, rulePath: string): ExpectResult {
const { attr, selector, ...operators } = rule;
const fullPath = `${rulePath}.css(${selector}${attr ? `@${attr}` : ""})`;
let $: cheerio.CheerioAPI;
@@ -60,8 +28,8 @@ function checkCssRule(
$ = cheerio.load(body);
} catch {
return {
matched: false,
failure: errorFailure("body", fullPath, "failed to parse HTML"),
matched: false,
};
}
@@ -72,44 +40,44 @@ function checkCssRule(
if (attr !== undefined) {
if (el.attr(attr) === undefined) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, "attr present", undefined, `attribute ${attr} not found`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
if (el.length === 0) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, "element found", "no match", `selector ${selector} not found`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
if (operators.exists === true) {
if (el.length === 0) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, true, false, `selector ${selector} not found`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
if (operators.exists === false) {
if (el.length > 0) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, false, true, `selector ${selector} exists`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
if (el.length === 0) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, "element found", "no match", `selector ${selector} not found`),
matched: false,
};
}
@@ -117,84 +85,73 @@ function checkCssRule(
const matched = applyOperator(actual ?? "", operators);
if (!matched) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, operators, actual, `css selector ${selector} mismatch`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
function checkXpathRule(
body: string,
rule: XpathRule,
rulePath: string,
): ExpectResult {
function checkJsonRule(body: string, rule: JsonRule, rulePath: string): ExpectResult {
const { path, ...operators } = rule;
const fullPath = `${rulePath}.xpath(${path})`;
const fullPath = `${rulePath}.json(${path})`;
let doc: ReturnType<DOMParser["parseFromString"]>;
let json: unknown;
try {
doc = new DOMParser().parseFromString(body, "text/xml");
json = JSON.parse(body);
} catch {
return {
failure: errorFailure("body", fullPath, "body is not valid JSON"),
matched: false,
failure: errorFailure("body", fullPath, "failed to parse XML/HTML"),
};
}
const nodes = xpath.select(path, doc as unknown as Node);
if (!nodes || !Array.isArray(nodes) || nodes.length === 0) {
return {
matched: false,
failure: mismatchFailure("body", fullPath, "node found", "no match", `xpath ${path} not found`),
};
}
const node = nodes[0]!;
const actual = node.nodeValue ?? (node as unknown as Element).textContent ?? "";
const actual = evaluateJsonPath(json, path);
const opKeys = Object.keys(operators);
if (opKeys.length === 0) {
return { matched: true, failure: null };
if (actual === undefined) {
return {
failure: mismatchFailure("body", fullPath, "defined", actual, `path ${path} is undefined`),
matched: false,
};
}
return { failure: null, matched: true };
}
const matched = applyOperator(actual, operators);
if (!matched) {
return {
failure: mismatchFailure("body", fullPath, operators, actual, `json path ${path} mismatch`),
matched: false,
failure: mismatchFailure("body", fullPath, operators, actual, `xpath ${path} mismatch`),
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
function checkSingleBodyRule(
body: string,
rule: BodyRule,
index: number,
): ExpectResult {
function checkSingleBodyRule(body: string, rule: BodyRule, index: number): ExpectResult {
const rulePath = `body[${index}]`;
if ("contains" in rule) {
const matched = body.includes(rule.contains);
if (!matched) {
return {
matched: false,
failure: mismatchFailure("body", rulePath, rule.contains, body, `body does not contain "${rule.contains}"`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
if ("regex" in rule) {
const matched = new RegExp(rule.regex).test(body);
if (!matched) {
return {
matched: false,
failure: mismatchFailure("body", rulePath, `/${rule.regex}/`, body, `body does not match /${rule.regex}/`),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
if ("json" in rule) {
@@ -209,16 +166,45 @@ function checkSingleBodyRule(
return checkXpathRule(body, rule.xpath, rulePath);
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}
export function checkBodyExpect(body: string, rules?: BodyRule[]): ExpectResult {
if (!rules || rules.length === 0) return { matched: true, failure: null };
function checkXpathRule(body: string, rule: XpathRule, rulePath: string): ExpectResult {
const { path, ...operators } = rule;
const fullPath = `${rulePath}.xpath(${path})`;
for (let i = 0; i < rules.length; i++) {
const result = checkSingleBodyRule(body, rules[i]!, i);
if (!result.matched) return result;
let doc: ReturnType<DOMParser["parseFromString"]>;
try {
doc = new DOMParser().parseFromString(body, "text/xml");
} catch {
return {
failure: errorFailure("body", fullPath, "failed to parse XML/HTML"),
matched: false,
};
}
return { matched: true, failure: null };
const nodes = xpath.select(path, doc as unknown as Node);
if (!nodes || !Array.isArray(nodes) || nodes.length === 0) {
return {
failure: mismatchFailure("body", fullPath, "node found", "no match", `xpath ${path} not found`),
matched: false,
};
}
const node = nodes[0]!;
const actual = node.nodeValue ?? (node as unknown as Element).textContent ?? "";
const opKeys = Object.keys(operators);
if (opKeys.length === 0) {
return { failure: null, matched: true };
}
const matched = applyOperator(actual, operators);
if (!matched) {
return {
failure: mismatchFailure("body", fullPath, operators, actual, `xpath ${path} mismatch`),
matched: false,
};
}
return { failure: null, matched: true };
}

View File

@@ -1,16 +1,16 @@
import type { CheckFailure } from "../../types";
import { mismatchFailure } from "./failure";
export interface ExpectResult {
matched: boolean;
failure: CheckFailure | null;
matched: boolean;
}
export function checkDuration(durationMs: number, maxDurationMs?: number): ExpectResult {
if (maxDurationMs === undefined) return { matched: true, failure: null };
if (maxDurationMs === undefined) return { failure: null, matched: true };
if (durationMs > maxDurationMs) {
return {
matched: false,
failure: mismatchFailure(
"duration",
"duration",
@@ -18,7 +18,8 @@ export function checkDuration(durationMs: number, maxDurationMs?: number): Expec
durationMs,
`duration ${durationMs}ms > ${maxDurationMs}ms`,
),
matched: false,
};
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}

View File

@@ -1,10 +1,12 @@
import type { CheckFailure } from "../../types";
export function truncateActual(value: unknown, maxLen = 200): unknown {
if (value === undefined || value === null) return value;
const str = String(value);
if (str.length <= maxLen) return value;
return str.slice(0, maxLen) + "...";
export function errorFailure(phase: CheckFailure["phase"], path: string, message: string): CheckFailure {
return {
kind: "error",
message,
path,
phase,
};
}
export function mismatchFailure(
@@ -15,20 +17,18 @@ export function mismatchFailure(
message: string,
): CheckFailure {
return {
kind: "mismatch",
phase,
path,
expected,
actual: truncateActual(actual),
expected,
kind: "mismatch",
message,
path,
phase,
};
}
export function errorFailure(phase: CheckFailure["phase"], path: string, message: string): CheckFailure {
return {
kind: "error",
phase,
path,
message,
};
export function truncateActual(value: unknown, maxLen = 200): unknown {
if (value === undefined || value === null) return value;
const str = typeof value === "string" ? value : JSON.stringify(value);
if (str.length <= maxLen) return value;
return str.slice(0, maxLen) + "...";
}

View File

@@ -1,6 +1,59 @@
import { isNil, isEmptyObject, isEqual, isPlainObject } from "es-toolkit";
import { isEmptyObject, isEqual, isNil, isPlainObject } from "es-toolkit";
import type { ExpectOperator, ExpectValue } from "../../types";
export function applyOperator(actual: unknown, op: ExpectOperator): boolean {
for (const [key, expected] of Object.entries(op)) {
if (expected === undefined) continue;
switch (key) {
case "contains":
if (!String(actual).includes(expected as string)) return false;
break;
case "empty": {
const isEmpty =
isNil(actual) || actual === "" || (Array.isArray(actual) && actual.length === 0) || isEmptyObject(actual);
if (expected !== isEmpty) return false;
break;
}
case "equals":
if (!isEqual(actual, expected)) return false;
break;
case "exists":
if (expected) {
if (actual === undefined) return false;
} else {
if (actual !== undefined) return false;
}
break;
case "gt":
if (!(Number(actual) > (expected as number))) return false;
break;
case "gte":
if (!(Number(actual) >= (expected as number))) return false;
break;
case "lt":
if (!(Number(actual) < (expected as number))) return false;
break;
case "lte":
if (!(Number(actual) <= (expected as number))) return false;
break;
case "match":
if (!new RegExp(expected as string).test(String(actual))) return false;
break;
}
}
return true;
}
export function checkExpectValue(actual: unknown, expected: ExpectValue): boolean {
if (isPlainObject(expected)) {
return applyOperator(actual, expected);
}
return applyOperator(actual, { equals: expected });
}
export function evaluateJsonPath(json: unknown, path: string): unknown {
if (!path.startsWith("$.")) return undefined;
@@ -22,55 +75,3 @@ export function evaluateJsonPath(json: unknown, path: string): unknown {
return current;
}
export function applyOperator(actual: unknown, op: ExpectOperator): boolean {
for (const [key, expected] of Object.entries(op)) {
if (expected === undefined) continue;
switch (key) {
case "equals":
if (!isEqual(actual, expected)) return false;
break;
case "contains":
if (!String(actual).includes(expected as string)) return false;
break;
case "match":
if (!new RegExp(expected as string).test(String(actual))) return false;
break;
case "empty": {
const isEmpty =
isNil(actual) || actual === "" || (Array.isArray(actual) && actual.length === 0) || isEmptyObject(actual);
if (expected !== isEmpty) return false;
break;
}
case "exists":
if (expected) {
if (actual === undefined) return false;
} else {
if (actual !== undefined) return false;
}
break;
case "gte":
if (!(Number(actual) >= (expected as number))) return false;
break;
case "lte":
if (!(Number(actual) <= (expected as number))) return false;
break;
case "gt":
if (!(Number(actual) > (expected as number))) return false;
break;
case "lt":
if (!(Number(actual) < (expected as number))) return false;
break;
}
}
return true;
}
export function checkExpectValue(actual: unknown, expected: ExpectValue): boolean {
if (isPlainObject(expected)) {
return applyOperator(actual, expected as ExpectOperator);
}
return applyOperator(actual, { equals: expected as string | number | boolean | null });
}

View File

@@ -1,18 +1,19 @@
import type { TextRule } from "../../types";
import { applyOperator } from "./operator";
import { mismatchFailure } from "./failure";
import type { ExpectResult } from "./duration";
import { mismatchFailure } from "./failure";
import { applyOperator } from "./operator";
export function checkTextRules(text: string, rules: TextRule[], phase: string): ExpectResult {
for (let i = 0; i < rules.length; i++) {
const rule = rules[i]!;
const path = `${phase}[${i}]`;
if (!applyOperator(text, rule)) {
return {
matched: false,
failure: mismatchFailure(phase, path, rule, text, `${phase} rule at index ${i} mismatch`),
matched: false,
};
}
}
return { matched: true, failure: null };
return { failure: null, matched: true };
}

View File

@@ -1,20 +1,19 @@
import type { CheckResult } from "../types";
import type { DefaultsConfig, ResolvedTarget, TargetConfig } from "../types";
import type { CheckResult, DefaultsConfig, ResolvedTarget, TargetConfig } from "../types";
export interface Checker {
execute(target: ResolvedTarget, ctx: CheckerContext): Promise<CheckResult>;
resolve(target: TargetConfig, context: ResolveContext): ResolvedTarget;
serialize(target: ResolvedTarget): { config: string; target: string };
readonly type: string;
}
export interface CheckerContext {
signal: AbortSignal;
}
export interface ResolveContext {
defaults: DefaultsConfig;
configDir: string;
defaultIntervalMs: number;
defaults: DefaultsConfig;
defaultTimeoutMs: number;
}
export interface Checker {
readonly type: string;
resolve(target: TargetConfig, context: ResolveContext): ResolvedTarget;
execute(target: ResolvedTarget, ctx: CheckerContext): Promise<CheckResult>;
serialize(target: ResolvedTarget): { target: string; config: string };
}