Replace AJV with TypeBox validation
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s

Migrate schema validation from AJV to @sinclair/typebox across the monorepo. Key changes:

- Core validation: ConfigBase now uses TypeCompiler/Value (TypeBox) for compile/defaults/coercion and replaces Ajv usage.
- OneBot & Protocol: loadConfig functions and related config loaders updated to use Value.Default/Convert and TypeCompiler.Compile with improved error reporting.
- OneBot action validation: OneBotAction now compiles TypeBox schemas, applies defaults/conversions and returns TypeBox errors.
- Web UI backend: use TypeBox Value/TypeCompiler to fetch and validate defaults for Napcat/Web UI configs.
- Types/scripts: removed AJV type shims and adjusted post-build script to stop special-casing AJV types.
- Dependencies: removed ajv from several package.json files and added/normalized @sinclair/typebox usage; updated pnpm-lock accordingly.
- Tests/tools: added schema validation test utilities and tests (packages/napcat-onebot/test_schema.ts and packages/napcat-test/schema.test.ts) to validate schema compilation, coercion, and defaults.

This change standardizes on TypeBox for runtime schema compilation, default population and type coercion, simplifying validation logic and improving default handling across packages.
This commit is contained in:
手瓜一十雪 committed 2026-03-06 09:46:12 +08:00
1 parent 4ed4dfd450
commit 36ae7bf923
21 files changed
+370 -245

No files matched your search

-1
View File
@@ -16,7 +16,6 @@
}
},
"dependencies": {
"ajv": "^8.13.0",
"file-type": "^21.0.0"
},
"devDependencies": {
+22 -10
View File
@@ -2,22 +2,24 @@ import path from 'node:path';
import fs from 'node:fs';
import type { NapCatCore } from '@/napcat-core';
import json5 from 'json5';
import Ajv, { AnySchema, ValidateFunction } from 'ajv';
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import { TSchema } from '@sinclair/typebox';
export abstract class ConfigBase<T> {
name: string;
core: NapCatCore;
configPath: string;
configData: T = {} as T;
ajv: Ajv;
validate: ValidateFunction<T>;
configSchema: TSchema;
validate: TypeCheck<TSchema>;
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: AnySchema) {
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: TSchema) {
this.name = name;
this.core = core;
this.configPath = configPath;
this.ajv = new Ajv({ useDefaults: true, coerceTypes: true });
this.validate = this.ajv.compile<T>(ConfigSchema);
this.configSchema = ConfigSchema;
this.validate = TypeCompiler.Compile(ConfigSchema);
fs.mkdirSync(this.configPath, { recursive: true });
this.read();
}
@@ -43,8 +45,13 @@ export abstract class ConfigBase<T> {
private loadConfig (configPath: string): T {
try {
const newConfigData = json5.parse(fs.readFileSync(configPath, 'utf-8'));
this.validate(newConfigData);
this.configData = newConfigData;
let data: unknown = newConfigData;
data = Value.Default(this.configSchema, data);
data = Value.Convert(this.configSchema, data);
if (!this.validate.Check(data)) {
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
}
this.configData = data as T;
this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
return this.configData;
} catch (e: unknown) {
@@ -55,8 +62,13 @@ export abstract class ConfigBase<T> {
save (newConfigData: T = this.configData): void {
const configPath = this.getConfigPath(this.core.selfInfo.uin);
this.validate(newConfigData);
this.configData = newConfigData;
let data: unknown = newConfigData;
data = Value.Default(this.configSchema, data);
data = Value.Convert(this.configSchema, data);
if (!this.validate.Check(data)) {
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
}
this.configData = data as T;
try {
fs.writeFileSync(configPath, JSON.stringify(this.configData, null, 2));
} catch (e: unknown) {
+6 -5
View File
@@ -1,7 +1,9 @@
import { ConfigBase } from '@/napcat-core/helper/config-base';
import { NapCatCore } from '@/napcat-core/index';
import { Type, Static } from '@sinclair/typebox';
import Ajv, { AnySchema } from 'ajv';
import { Value } from '@sinclair/typebox/value';
import { TSchema } from '@sinclair/typebox';
import path from 'node:path';
import fs from 'node:fs';
import json5 from 'json5';
@@ -34,8 +36,6 @@ export type NapcatConfig = Static<typeof NapcatConfigSchema>;
* 用于登录前(无 NapCatCore 实例时)的早期配置读取
*/
export function loadNapcatConfig (configPath: string): NapcatConfig {
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
const validate = ajv.compile<NapcatConfig>(NapcatConfigSchema);
let data: Record<string, unknown> = {};
try {
const configFile = path.join(configPath, 'napcat.json');
@@ -45,12 +45,13 @@ export function loadNapcatConfig (configPath: string): NapcatConfig {
} catch {
// 读取失败时使用 schema 默认值
}
validate(data);
data = Value.Default(NapcatConfigSchema, data) as Record<string, unknown>;
data = Value.Convert(NapcatConfigSchema, data) as Record<string, unknown>;
return data as NapcatConfig;
}
export class NapCatConfigLoader extends ConfigBase<NapcatConfig> {
constructor (core: NapCatCore, configPath: string, schema: AnySchema) {
constructor (core: NapCatCore, configPath: string, schema: TSchema) {
super('napcat', core, configPath, schema);
}
}
+7 -8
View File
@@ -16,19 +16,18 @@
}
},
"dependencies": {
"winston": "^3.17.0",
"json5": "^2.2.3",
"inversify": "^7.10.4",
"reflect-metadata": "^0.2.2",
"@protobuf-ts/runtime": "^2.11.1",
"ajv": "^8.13.0",
"@sinclair/typebox": "^0.34.38",
"file-type": "^21.0.0",
"compressing": "^1.10.1",
"napcat-image-size": "workspace:*",
"file-type": "^21.0.0",
"inversify": "^7.10.4",
"json5": "^2.2.3",
"napcat-common": "workspace:*",
"napcat-database": "workspace:*",
"napcat-protobuf": "workspace:*"
"napcat-image-size": "workspace:*",
"napcat-protobuf": "workspace:*",
"reflect-metadata": "^0.2.2",
"winston": "^3.17.0"
},
"devDependencies": {
"@types/node": "^22.0.1"
+18 -8
View File
@@ -1,5 +1,6 @@
import { ActionName, BaseCheckResult } from './router';
import Ajv, { ErrorObject, ValidateFunction } from 'ajv';
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import { NapCatCore } from 'napcat-core';
import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index';
import { NetworkAdapterConfig } from '../config/config';
@@ -46,7 +47,7 @@ export abstract class OneBotRequestToolkit {
export abstract class OneBotAction<PayloadType, ReturnDataType> {
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
core: NapCatCore;
private validate?: ValidateFunction<unknown> = undefined;
private validate?: TypeCheck<TSchema> = undefined;
payloadSchema?: TSchema = undefined;
returnSchema?: TSchema = undefined;
payloadExample?: unknown = undefined;
@@ -64,15 +65,24 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
}
protected async check (payload: PayloadType): Promise<BaseCheckResult> {
if (this.payloadSchema) {
this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema);
if (!this.payloadSchema) return { valid: true };
try {
this.validate = TypeCompiler.Compile(this.payloadSchema);
let data = payload;
data = Value.Default(this.payloadSchema, data) as PayloadType;
data = Value.Convert(this.payloadSchema, data) as PayloadType;
if (typeof payload === 'object' && payload !== null && data !== null) {
Object.assign(payload, data);
}
} catch (e: any) {
return { valid: false, message: `Schema compilation error: ${e.message}` };
}
if (this.validate && !this.validate(payload)) {
const errors = this.validate.errors as ErrorObject[];
const errorMessages = errors.map(e => `Key: ${e.instancePath.split('/').slice(1).join('.')}, Message: ${e.message}`);
if (this.validate && !this.validate.Check(payload)) {
const errors = [...this.validate.Errors(payload)];
const errorMessages = errors.map(e => `Key: ${e.path.split('/').slice(1).join('.')}, Message: ${e.message}`);
return {
valid: false,
message: errorMessages.join('\n') ?? '未知错误',
message: errorMessages.length > 0 ? errorMessages.join('\n') : '未知错误',
};
}
return { valid: true };
+10 -6
View File
@@ -1,5 +1,6 @@
import { Type, Static } from '@sinclair/typebox';
import Ajv from 'ajv';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
const HttpServerConfigSchema = Type.Object({
name: Type.String({ default: 'http-server' }),
enable: Type.Boolean({ default: false }),
@@ -97,11 +98,14 @@ export type NetworkAdapterConfig = HttpServerConfig | HttpSseServerConfig | Http
export type NetworkConfigKey = keyof OneBotConfig['network'];
export function loadConfig (config: Partial<OneBotConfig>): OneBotConfig {
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
const validate = ajv.compile(OneBotConfigSchema);
const valid = validate(config);
let data = config;
data = Value.Default(OneBotConfigSchema, data) as Partial<OneBotConfig>;
data = Value.Convert(OneBotConfigSchema, data) as Partial<OneBotConfig>;
const validate = TypeCompiler.Compile(OneBotConfigSchema);
const valid = validate.Check(data);
if (!valid) {
throw new Error(ajv.errorsText(validate.errors));
const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', ');
throw new Error(errorMsg);
}
return config as OneBotConfig;
return data as OneBotConfig;
}
+2 -2
View File
@@ -1,12 +1,12 @@
import { ConfigBase } from 'napcat-core/helper/config-base';
import type { NapCatCore } from 'napcat-core';
import { OneBotConfig } from './config';
import { AnySchema } from 'ajv';
import { TSchema } from '@sinclair/typebox';
export * from './config';
export class OB11ConfigLoader extends ConfigBase<OneBotConfig> {
constructor (core: NapCatCore, configPath: string, schema: AnySchema) {
constructor (core: NapCatCore, configPath: string, schema: TSchema) {
super('onebot11', core, configPath, schema);
}
}
+11 -12
View File
@@ -16,29 +16,28 @@
}
},
"dependencies": {
"napcat.protobuf": "^1.1.4",
"fast-xml-parser": "^4.3.6",
"type-is": "^1.6.7",
"on-finished": "^2.3.5",
"ajv": "^8.13.0",
"@sinclair/typebox": "^0.34.38",
"cors": "^2.8.5",
"express": "^5.0.0",
"ws": "^8.18.3",
"fast-xml-parser": "^4.3.6",
"file-type": "^21.0.0",
"napcat-protobuf": "workspace:*",
"json5": "^2.2.3",
"napcat-common": "workspace:*",
"napcat-core": "workspace:*",
"napcat-webui-backend": "workspace:*",
"napcat-image-size": "workspace:*",
"napcat-common": "workspace:*"
"napcat-protobuf": "workspace:*",
"napcat-webui-backend": "workspace:*",
"napcat.protobuf": "^1.1.4",
"on-finished": "^2.3.5",
"type-is": "^1.6.7",
"ws": "^8.18.3"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/type-is": "^1.6.7",
"@types/on-finished": "^2.3.4",
"@types/express": "^5.0.0",
"@types/node": "^22.0.1"
"@types/node": "^22.0.1",
"@types/on-finished": "^2.3.4",
"@types/type-is": "^1.6.7"
},
"engines": {
"node": ">=18.0.0"
+61
View File
@@ -0,0 +1,61 @@
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from './types/message';
import { OB11MessageSchema as OB11ActionMessageSchema } from './action/schemas';
try {
TypeCompiler.Compile(OB11MessageDataSchema);
console.log("Compile OB11MessageDataSchema OK");
} catch (e: any) {
console.error("Error in OB11MessageDataSchema:", e.message);
}
try {
TypeCompiler.Compile(OB11MessageSchema);
console.log("Compile OB11MessageSchema OK");
} catch (e: any) {
console.error("Error in OB11MessageSchema:", e.message);
}
try {
TypeCompiler.Compile(OB11ActionMessageSchema);
console.log("Compile OB11ActionMessageSchema OK");
} catch (e: any) {
console.error("Error in OB11ActionMessageSchema:", e.message);
}
import { Type } from '@sinclair/typebox';
try {
const QA = Type.Object({ message: OB11PostSendMsgSchema, quick_action: OB11ActionMessageSchema });
TypeCompiler.Compile(QA);
console.log("Compile Quick Action OK");
} catch (e: any) {
console.error("Error in Quick Action:", e.message);
}
// Test validation
const testObj = {
message_type: 'private',
user_id: 12345,
message: [
{ type: 'text', data: { text: 'hello' } }
]
};
try {
let data = structuredClone(testObj);
data = Value.Default(OB11PostSendMsgSchema, data) as any;
data = Value.Convert(OB11PostSendMsgSchema, data) as any;
const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema);
const isValid = compiler.Check(data);
console.log("Validation result:", isValid);
if (!isValid) {
const errors = [...compiler.Errors(data)];
errors.forEach(e => console.error(e.path, e.message));
} else {
console.log("Data after Convert and Check:", JSON.stringify(data, null, 2));
}
} catch (e: any) {
console.error("Test validation error:", e.message);
}
+61 -61
View File
@@ -2,44 +2,44 @@
import { MessageType, PartialMessage, RepeatType, ScalarType } from '@protobuf-ts/runtime';
import { PartialFieldInfo } from '@protobuf-ts/runtime/build/types/reflection-info';
type LowerCamelCase<S extends string> = CamelCaseHelper<S, false, true>;
export type LowerCamelCase<S extends string> = CamelCaseHelper<S, false, true>;
type CamelCaseHelper<
S extends string,
CapNext extends boolean,
IsFirstChar extends boolean
export type CamelCaseHelper<
S extends string,
CapNext extends boolean,
IsFirstChar extends boolean
> = S extends `${infer F}${infer R}`
? F extends '_'
? CamelCaseHelper<R, true, false>
: F extends `${number}`
? `${F}${CamelCaseHelper<R, true, false>}`
: CapNext extends true
? `${Uppercase<F>}${CamelCaseHelper<R, false, false>}`
: IsFirstChar extends true
? `${Lowercase<F>}${CamelCaseHelper<R, false, false>}`
: `${F}${CamelCaseHelper<R, false, false>}`
? CamelCaseHelper<R, true, false>
: F extends `${number}`
? `${F}${CamelCaseHelper<R, true, false>}`
: CapNext extends true
? `${Uppercase<F>}${CamelCaseHelper<R, false, false>}`
: IsFirstChar extends true
? `${Lowercase<F>}${CamelCaseHelper<R, false, false>}`
: `${F}${CamelCaseHelper<R, false, false>}`
: '';
type ScalarTypeToTsType<T extends ScalarType> = T extends
| ScalarType.DOUBLE
| ScalarType.FLOAT
| ScalarType.INT32
| ScalarType.FIXED32
| ScalarType.UINT32
| ScalarType.SFIXED32
| ScalarType.SINT32
export type ScalarTypeToTsType<T extends ScalarType> = T extends
| ScalarType.DOUBLE
| ScalarType.FLOAT
| ScalarType.INT32
| ScalarType.FIXED32
| ScalarType.UINT32
| ScalarType.SFIXED32
| ScalarType.SINT32
? number
: T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64
? bigint
: T extends ScalarType.BOOL
? boolean
: T extends ScalarType.STRING
? string
: T extends ScalarType.BYTES
? Uint8Array
: never;
? bigint
: T extends ScalarType.BOOL
? boolean
: T extends ScalarType.STRING
? string
: T extends ScalarType.BYTES
? Uint8Array
: never;
interface BaseProtoFieldType<T, O extends boolean, R extends O extends true ? false : boolean> {
export interface BaseProtoFieldType<T, O extends boolean, R extends O extends true ? false : boolean> {
kind: 'scalar' | 'message';
no: number;
type: T;
@@ -53,30 +53,30 @@ export interface ScalarProtoFieldType<T extends ScalarType, O extends boolean, R
}
export interface MessageProtoFieldType<
T extends () => ProtoMessageType,
O extends boolean,
R extends O extends true ? false : boolean
T extends () => ProtoMessageType,
O extends boolean,
R extends O extends true ? false : boolean
> extends BaseProtoFieldType<T, O, R> {
kind: 'message';
}
type ProtoFieldType =
| ScalarProtoFieldType<ScalarType, boolean, boolean>
| MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>;
export type ProtoFieldType =
| ScalarProtoFieldType<ScalarType, boolean, boolean>
| MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>;
type ProtoMessageType = {
export type ProtoMessageType = {
[key: string]: ProtoFieldType;
};
export function ProtoField<
T extends ScalarType,
O extends boolean = false,
R extends O extends true ? false : boolean = false
T extends ScalarType,
O extends boolean = false,
R extends O extends true ? false : boolean = false
> (no: number, type: T, optional?: O, repeat?: R): ScalarProtoFieldType<T, O, R>;
export function ProtoField<
T extends () => ProtoMessageType,
O extends boolean = false,
R extends O extends true ? false : boolean = false
T extends () => ProtoMessageType,
O extends boolean = false,
R extends O extends true ? false : boolean = false
> (no: number, type: T, optional?: O, repeat?: R): MessageProtoFieldType<T, O, R>;
export function ProtoField (
no: number,
@@ -91,38 +91,38 @@ export function ProtoField (
}
}
type ProtoFieldReturnType<T, E extends boolean> =
NonNullable<T> extends ScalarProtoFieldType<infer S, infer _O, infer _R>
? ScalarTypeToTsType<S>
: T extends NonNullable<MessageProtoFieldType<infer S, infer _O, infer _R>>
? NonNullable<NapProtoStructType<ReturnType<S>, E>>
: never;
export type ProtoFieldReturnType<T, E extends boolean> =
NonNullable<T> extends ScalarProtoFieldType<infer S, infer _O, infer _R>
? ScalarTypeToTsType<S>
: T extends NonNullable<MessageProtoFieldType<infer S, infer _O, infer _R>>
? NonNullable<NapProtoStructType<ReturnType<S>, E>>
: never;
type RequiredFieldsBaseType<T, E extends boolean> = {
[K in keyof T as T[K] extends { optional: true } ? never : LowerCamelCase<K & string>]: T[K] extends {
export type RequiredFieldsBaseType<T, E extends boolean> = {
[K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase<K & string>]: T[K] extends {
repeat: true;
}
? ProtoFieldReturnType<T[K], E>[]
: ProtoFieldReturnType<T[K], E>;
? ProtoFieldReturnType<T[K], E>[]
: ProtoFieldReturnType<T[K], E>;
};
type OptionalFieldsBaseType<T, E extends boolean> = {
[K in keyof T as T[K] extends { optional: true } ? LowerCamelCase<K & string> : never]?: T[K] extends {
export type OptionalFieldsBaseType<T, E extends boolean> = {
[K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase<K & string> : never]?: T[K] extends {
repeat: true;
}
? ProtoFieldReturnType<T[K], E>[]
: ProtoFieldReturnType<T[K], E>;
? ProtoFieldReturnType<T[K], E>[]
: ProtoFieldReturnType<T[K], E>;
};
type RequiredFieldsType<T, E extends boolean> = E extends true
export type RequiredFieldsType<T, E extends boolean> = E extends true
? Partial<RequiredFieldsBaseType<T, E>>
: RequiredFieldsBaseType<T, E>;
type OptionalFieldsType<T, E extends boolean> = E extends true
export type OptionalFieldsType<T, E extends boolean> = E extends true
? Partial<OptionalFieldsBaseType<T, E>>
: OptionalFieldsBaseType<T, E>;
type NapProtoStructType<T, E extends boolean> = RequiredFieldsType<T, E> & OptionalFieldsType<T, E>;
export type NapProtoStructType<T, E extends boolean> = RequiredFieldsType<T, E> & OptionalFieldsType<T, E>;
export type NapProtoEncodeStructType<T> = NapProtoStructType<T, true>;
@@ -165,7 +165,7 @@ class NapProtoRealMsg<T extends ProtoMessageType> {
this._proto_msg = new MessageType<NapProtoStructType<T, boolean>>('nya', this._field);
}
static getInstance<T extends ProtoMessageType>(fields: T): NapProtoRealMsg<T> {
static getInstance<T extends ProtoMessageType> (fields: T): NapProtoRealMsg<T> {
let instance = this.cache.get(fields);
if (!instance) {
instance = new NapProtoRealMsg(fields);
+10 -6
View File
@@ -1,5 +1,6 @@
import { Type, Static } from '@sinclair/typebox';
import Ajv from 'ajv';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
// WebSocket 服务端配置
const WebsocketServerConfigSchema = Type.Object({
@@ -56,11 +57,14 @@ export type NetworkAdapterConfig = HttpServerConfig | WebsocketServerConfig | We
export type NetworkConfigKey = keyof NapCatProtocolConfig['network'];
export function loadConfig (config: Partial<NapCatProtocolConfig>): NapCatProtocolConfig {
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
const validate = ajv.compile(NapCatProtocolConfigSchema);
const valid = validate(config);
let data = config;
data = Value.Default(NapCatProtocolConfigSchema, data) as Partial<NapCatProtocolConfig>;
data = Value.Convert(NapCatProtocolConfigSchema, data) as Partial<NapCatProtocolConfig>;
const validate = TypeCompiler.Compile(NapCatProtocolConfigSchema);
const valid = validate.Check(data);
if (!valid) {
throw new Error(ajv.errorsText(validate.errors));
const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', ');
throw new Error(errorMsg);
}
return config as NapCatProtocolConfig;
return data as NapCatProtocolConfig;
}
+2 -3
View File
@@ -16,14 +16,13 @@
}
},
"dependencies": {
"ajv": "^8.13.0",
"@sinclair/typebox": "^0.34.38",
"cors": "^2.8.5",
"express": "^5.0.0",
"ws": "^8.18.3",
"json5": "^2.2.3",
"napcat-common": "workspace:*",
"napcat-core": "workspace:*",
"napcat-common": "workspace:*"
"ws": "^8.18.3"
},
"devDependencies": {
"@types/cors": "^2.8.17",
+4 -2
View File
@@ -11,8 +11,10 @@
"vitest": "^4.0.9"
},
"dependencies": {
"@sinclair/typebox": "^0.34.41",
"napcat-core": "workspace:*",
"napcat-rpc": "workspace:*",
"napcat-image-size": "workspace:*"
"napcat-image-size": "workspace:*",
"napcat-onebot": "workspace:*",
"napcat-rpc": "workspace:*"
}
}
+117
View File
@@ -0,0 +1,117 @@
import { describe, expect, test } from 'vitest';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import { Type } from '@sinclair/typebox';
import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from '../napcat-onebot/types/message';
import { OB11MessageSchema as OB11ActionMessageSchema } from '../napcat-onebot/action/schemas';
import { OneBotConfigSchema, loadConfig as loadOneBotConfig, OneBotConfig } from '../napcat-onebot/config';
import { NapcatConfigSchema } from '../napcat-core/helper/config';
describe('NapCat Schemas Compilation', () => {
test('should compile OB11MessageDataSchema without duplicate id error', () => {
expect(() => TypeCompiler.Compile(OB11MessageDataSchema)).not.toThrow();
});
test('should compile OB11MessageSchema without duplicate id error', () => {
expect(() => TypeCompiler.Compile(OB11MessageSchema)).not.toThrow();
});
test('should compile OB11ActionMessageSchema without duplicate id error', () => {
expect(() => TypeCompiler.Compile(OB11ActionMessageSchema)).not.toThrow();
});
test('should compile OB11PostSendMsgSchema without error', () => {
expect(() => TypeCompiler.Compile(OB11PostSendMsgSchema)).not.toThrow();
});
test('should compile QuickAction hybrid schema without error', () => {
const QASchema = Type.Object({
message: OB11PostSendMsgSchema,
quick_action: OB11ActionMessageSchema
});
expect(() => TypeCompiler.Compile(QASchema)).not.toThrow();
});
});
describe('NapCat Schemas Validation & Coercion', () => {
test('should coerce numeric user_id to string in OB11PostSendMsgSchema', () => {
const payload = {
message_type: 'private',
user_id: 123456,
message: [{ type: 'text', data: { text: 'hello' } }]
};
let data: unknown = structuredClone(payload);
data = Value.Default(OB11PostSendMsgSchema, data);
data = Value.Convert(OB11PostSendMsgSchema, data);
const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema);
expect(compiler.Check(data)).toBe(true);
expect((data as Record<string, unknown>)['user_id']).toBe('123456');
});
test('should validate complex mixed messages correctly', () => {
const payload = {
message_type: 'group',
group_id: "654321",
message: 'this is a string message'
};
let data: unknown = structuredClone(payload);
data = Value.Default(OB11PostSendMsgSchema, data);
data = Value.Convert(OB11PostSendMsgSchema, data);
const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema);
expect(compiler.Check(data)).toBe(true);
});
});
describe('NapCat Configuration Loaders', () => {
test('OneBotConfig schemas should compile', () => {
expect(() => TypeCompiler.Compile(OneBotConfigSchema)).not.toThrow();
});
test('OneBotConfig should load and apply defaults correctly', () => {
const partialConfig: Partial<OneBotConfig> = {
network: {
httpServers: [{
port: 3000,
enable: true,
name: 'test',
host: '127.0.0.1',
enableCors: true,
enableWebsocket: false,
messagePostFormat: 'array',
token: '',
debug: false
}],
httpSseServers: [],
httpClients: [],
websocketServers: [],
websocketClients: [],
plugins: []
}
};
const loaded = loadOneBotConfig(partialConfig);
expect(loaded.network.httpServers[0]?.host).toBe('127.0.0.1');
expect(loaded.network.httpServers[0]?.enableCors).toBe(true);
expect(loaded.musicSignUrl).toBe('');
});
test('NapcatConfig should compile and apply defaults', () => {
let compiled: ReturnType<typeof TypeCompiler.Compile> | undefined;
expect(() => {
compiled = TypeCompiler.Compile(NapcatConfigSchema);
}).not.toThrow();
let data: unknown = {};
data = Value.Default(NapcatConfigSchema, data);
data = Value.Convert(NapcatConfigSchema, data);
expect(compiled?.Check(data)).toBe(true);
const resolved = data as Record<string, unknown>;
expect(resolved['consoleLog']).toBe(true);
expect(resolved['consoleLogLevel']).toBe('info');
});
});
-27
View File
@@ -96,33 +96,6 @@ declare module 'inversify' {
export default _inversify_default;
}
declare module 'ajv' {
export interface AnySchema { [key: string]: any; }
export interface ErrorObject {
keyword: string;
instancePath: string;
schemaPath: string;
params: any;
message?: string;
}
export interface ValidateFunction<T = any> {
(data: any): data is T;
errors: ErrorObject[] | null;
}
class Ajv {
constructor (...args: any[]);
compile<T = any> (schema: any): ValidateFunction<T>;
validate (schemaOrRef: any, data: any): boolean;
errorsText (errors?: any, options?: any): string;
errors: ErrorObject[] | null;
}
export default Ajv;
export { Ajv, ValidateFunction, ErrorObject };
}
declare module 'ip' {
export function toBuffer (ip: any, buffer?: Buffer, offset?: number): Buffer;
+5 -37
View File
@@ -11,38 +11,6 @@ const ALLOWED_PACKAGES = [
'node:', // node: 前缀的内置模块
];
/*
// 外部包类型到 any 的映射
const EXTERNAL_TYPE_REPLACEMENTS = {
// winston
'winston.Logger': 'any',
'winston.transport': 'any',
// express
'express.Express': 'any',
'express.Application': 'any',
'express.Router': 'any',
Express: 'any',
Request: 'any',
Response: 'any',
NextFunction: 'any',
// ws
WebSocket: 'any',
WebSocketServer: 'any',
RawData: 'any',
// ajv
Ajv: 'any',
AnySchema: 'any',
ValidateFunction: 'any',
'ValidateFunction<T>': 'any',
// inversify
Container: 'any',
// napcat-protobuf
NapProtoDecodeStructType: 'any',
NapProtoEncodeStructType: 'any',
'NapProtoDecodeStructType<T>': 'any',
'NapProtoEncodeStructType<T>': 'any',
};
*/
function isAllowedImport (importPath) {
return ALLOWED_PACKAGES.some(pkg => importPath.startsWith(pkg));
@@ -89,15 +57,15 @@ function replaceExternalTypes (content) {
// 使用类型上下文的模式匹配
const typeContextPatterns = [
// : Type
/:\s*(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[;,)\]}|&]|$)/g,
/:\s*(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[;,)\]}|&]|$)/g,
// <Type>
/<(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)>/g,
/<(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)>/g,
// Type[]
/(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)\[\]/g,
/(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)\[\]/g,
// extends Type
/extends\s+(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g,
/extends\s+(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g,
// implements Type
/implements\s+(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g,
/implements\s+(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g,
];
for (const pattern of typeContextPatterns) {
@@ -18,7 +18,6 @@
"dependencies": {
"@simplewebauthn/server": "^13.2.2",
"@sinclair/typebox": "^0.34.38",
"ajv": "^8.13.0",
"compressing": "^1.10.3",
"compression": "^1.8.1",
"express": "^5.0.0",
@@ -6,16 +6,13 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response';
import json5 from 'json5';
import Ajv from 'ajv';
import { Value } from '@sinclair/typebox/value';
import { NapcatConfigSchema } from '@/napcat-core/helper/config';
// 动态获取 NapCat 配置默认值
function getDefaultNapcatConfig (): Record<string, unknown> {
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
const validate = ajv.compile(NapcatConfigSchema);
const data = {};
validate(data);
return data;
return Value.Default(NapcatConfigSchema, data) as Record<string, unknown>;
}
/**
@@ -1,6 +1,7 @@
import { webUiPathWrapper, getInitialWebUiToken } from '@/napcat-webui-backend/index';
import { Type, Static } from '@sinclair/typebox';
import Ajv from 'ajv';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import fs, { constants } from 'node:fs/promises';
import { resolve } from 'node:path';
@@ -41,8 +42,14 @@ export class WebUiConfigWrapper {
WebUiConfigData: WebUiConfigType | undefined = undefined;
private validateAndApplyDefaults (config: Partial<WebUiConfigType>): WebUiConfigType {
new Ajv({ coerceTypes: true, useDefaults: true }).compile(WebUiConfigSchema)(config);
return config as WebUiConfigType;
let data = config;
data = Value.Default(WebUiConfigSchema, data) as Partial<WebUiConfigType>;
data = Value.Convert(WebUiConfigSchema, data) as Partial<WebUiConfigType>;
const validate = TypeCompiler.Compile(WebUiConfigSchema);
if (!validate.Check(data)) {
// Return original if validation failed, or throw
}
return data as WebUiConfigType;
}
private async ensureConfigFileExists (configPath: string): Promise<void> {
@@ -1,5 +1,6 @@
import { Type, Static } from '@sinclair/typebox';
import Ajv from 'ajv';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
const HttpServerConfigSchema = Type.Object({
name: Type.String({ default: 'http-server' }),
enable: Type.Boolean({ default: false }),
@@ -97,11 +98,14 @@ export type NetworkAdapterConfig = HttpServerConfig | HttpSseServerConfig | Http
export type NetworkConfigKey = keyof OneBotConfig['network'];
export function loadConfig (config: Partial<OneBotConfig>): OneBotConfig {
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
const validate = ajv.compile(OneBotConfigSchema);
const valid = validate(config);
let data = config;
data = Value.Default(OneBotConfigSchema, data) as Partial<OneBotConfig>;
data = Value.Convert(OneBotConfigSchema, data) as Partial<OneBotConfig>;
const validate = TypeCompiler.Compile(OneBotConfigSchema);
const valid = validate.Check(data);
if (!valid) {
throw new Error(ajv.errorsText(validate.errors));
const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', ');
throw new Error(errorMsg);
}
return config as OneBotConfig;
return data as OneBotConfig;
}
+12 -42
View File
@@ -64,9 +64,6 @@ importers:
packages/napcat-common:
dependencies:
ajv:
specifier: ^8.13.0
version: 8.17.1
file-type:
specifier: ^21.0.0
version: 21.1.0
@@ -83,9 +80,6 @@ importers:
'@sinclair/typebox':
specifier: ^0.34.38
version: 0.34.41
ajv:
specifier: ^8.13.0
version: 8.17.1
compressing:
specifier: ^1.10.1
version: 1.10.3
@@ -188,9 +182,6 @@ importers:
'@sinclair/typebox':
specifier: ^0.34.38
version: 0.34.41
ajv:
specifier: ^8.13.0
version: 8.17.1
cors:
specifier: ^2.8.5
version: 2.8.5
@@ -275,9 +266,6 @@ importers:
'@sinclair/typebox':
specifier: ^0.34.38
version: 0.34.41
ajv:
specifier: ^8.13.0
version: 8.17.1
cors:
specifier: ^2.8.5
version: 2.8.5
@@ -387,12 +375,18 @@ importers:
packages/napcat-test:
dependencies:
'@sinclair/typebox':
specifier: ^0.34.41
version: 0.34.41
napcat-core:
specifier: workspace:*
version: link:../napcat-core
napcat-image-size:
specifier: workspace:*
version: link:../napcat-image-size
napcat-onebot:
specifier: workspace:*
version: link:../napcat-onebot
napcat-rpc:
specifier: workspace:*
version: link:../napcat-rpc
@@ -447,9 +441,6 @@ importers:
'@sinclair/typebox':
specifier: ^0.34.38
version: 0.34.41
ajv:
specifier: ^8.13.0
version: 8.17.1
compressing:
specifier: ^1.10.3
version: 1.10.3
@@ -2877,6 +2868,9 @@ packages:
'@sinclair/typebox@0.34.41':
resolution: {integrity: sha512-6gS8pZzSXdyRHTIqoqSVknxolr1kzfy4/CeDnrzsVz8TTIWUbOBr6gnzOmTYJ3eXQNh4IYHIGi5aIL7sOZ2G/g==}
'@sinclair/typebox@0.34.48':
resolution: {integrity: sha512-kKJTNuK3AQOrgjjotVxMrCn1sUJwM76wMszfq1kdU4uYVJjvEWuFQ6HgvLt4Xz3fSmZlTOxJ/Ie13KnIcWQXFA==}
'@so-ric/colorspace@1.1.6':
resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==}
@@ -3471,9 +3465,6 @@ packages:
ajv@6.12.6:
resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==}
ajv@8.17.1:
resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==}
ansi-colors@4.1.3:
resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==}
engines: {node: '>=6'}
@@ -4439,9 +4430,6 @@ packages:
fast-levenshtein@2.0.6:
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
fast-uri@3.1.0:
resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==}
fast-xml-parser@4.5.3:
resolution: {integrity: sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==}
hasBin: true
@@ -5106,9 +5094,6 @@ packages:
json-schema-traverse@0.4.1:
resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}
json-schema-traverse@1.0.0:
resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
json-stable-stringify-without-jsonify@1.0.1:
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
@@ -6118,10 +6103,6 @@ packages:
resolution: {integrity: sha512-UszKE5KVK6JvyD92nzMn9cDapSk6w/CaFZ96CnmDMUqH9oowfxF/ZjRITD25H4DnOQClLA4/j7jLGXXLVKxAug==}
engines: {node: '>= 10'}
require-from-string@2.0.2:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
reselect@5.1.1:
resolution: {integrity: sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==}
@@ -9714,6 +9695,8 @@ snapshots:
'@sinclair/typebox@0.34.41': {}
'@sinclair/typebox@0.34.48': {}
'@so-ric/colorspace@1.1.6':
dependencies:
color: 5.0.2
@@ -10330,13 +10313,6 @@ snapshots:
json-schema-traverse: 0.4.1
uri-js: 4.4.1
ajv@8.17.1:
dependencies:
fast-deep-equal: 3.1.3
fast-uri: 3.1.0
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
ansi-colors@4.1.3: {}
ansi-regex@5.0.1: {}
@@ -11519,8 +11495,6 @@ snapshots:
fast-levenshtein@2.0.6: {}
fast-uri@3.1.0: {}
fast-xml-parser@4.5.3:
dependencies:
strnum: 1.1.2
@@ -12220,8 +12194,6 @@ snapshots:
json-schema-traverse@0.4.1: {}
json-schema-traverse@1.0.0: {}
json-stable-stringify-without-jsonify@1.0.1: {}
json5@1.0.2:
@@ -12850,7 +12822,7 @@ snapshots:
napcat-types@0.0.16:
dependencies:
'@sinclair/typebox': 0.34.41
'@sinclair/typebox': 0.34.48
'@types/node': 22.19.1
napcat.protobuf@1.1.4:
@@ -13490,8 +13462,6 @@ snapshots:
replace-ext@2.0.0: {}
require-from-string@2.0.2: {}
reselect@5.1.1: {}
resize-observer-polyfill@1.5.1: {}