@h-ai/core 0.1.0-alpha.56 → 0.1.0-alpha.58
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/README.en.md +550 -0
- package/README.ja.md +550 -0
- package/README.md +9 -1
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +50 -19
- package/dist/browser.js.map +1 -1
- package/dist/{chunk-MWGBPJOG.js → chunk-RXNSRXYF.js} +7208 -2058
- package/dist/chunk-RXNSRXYF.js.map +1 -0
- package/dist/{core-function-config.node-DMHeZn-R.d.ts → core-function-config.node-CwXAT7fW.d.ts} +42 -39
- package/dist/node.d.ts +2 -2
- package/dist/node.js +46 -27
- package/dist/node.js.map +1 -1
- package/package.json +12 -12
- package/dist/chunk-MWGBPJOG.js.map +0 -1
package/README.ja.md
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
# @h-ai/core
|
|
2
|
+
|
|
3
|
+
[简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
|
|
4
|
+
|
|
5
|
+
[フレームワークのホーム](../../README.ja.md)
|
|
6
|
+
|
|
7
|
+
> hai Agent Framework の中核モジュール。共通ツール、型定義、設定管理、ログ機能を提供します。
|
|
8
|
+
|
|
9
|
+
## 主な機能
|
|
10
|
+
|
|
11
|
+
- **HaiResult 型**:関数型のエラー処理(`ok` / `err`)とモジュール共通の戻り値形式。
|
|
12
|
+
- **統一ログ**:Node.js は pino、ブラウザーは loglevel を使い、API は共通。
|
|
13
|
+
- **国際化(i18n)**:一元化された locale 管理と型安全なメッセージ取得。
|
|
14
|
+
- **Zod 検証エラーの変換**:Zod v3/v4 の issue 抽出と、既定の英語メッセージのローカライズ。
|
|
15
|
+
- **設定管理**:YAML 読み込み、規約に沿う環境変数マッピング、明示的な変数展開、Zod 検証、ファイル監視(Node.js 専用)。
|
|
16
|
+
- **ID 生成**:nanoid と UUID v4。
|
|
17
|
+
- **エラー定義**:標準化されたコードと、モジュール共通のエラー定義・インスタンス生成。
|
|
18
|
+
- **モジュールツール**:NotInitializedKit のプロキシと共通のライフサイクル基盤。
|
|
19
|
+
- **ツール関数**:型確認、オブジェクト・文字列・配列・非同期・時刻の操作。
|
|
20
|
+
|
|
21
|
+
## クイックスタート
|
|
22
|
+
|
|
23
|
+
### Node.js 環境
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { core } from '@h-ai/core'
|
|
27
|
+
|
|
28
|
+
// 初始化:加载配置目录(可选)
|
|
29
|
+
core.init({ configDir: './config', watchConfig: true })
|
|
30
|
+
|
|
31
|
+
// 日志
|
|
32
|
+
core.logger.info('Server started', { port: 3000 })
|
|
33
|
+
core.logger.warn('Slow query', { duration: 2500 })
|
|
34
|
+
core.logger.error('Connection failed', { error })
|
|
35
|
+
|
|
36
|
+
// 创建模块级 logger(独立名称空间)
|
|
37
|
+
const dbLogger = core.logger.create({ name: 'db' })
|
|
38
|
+
dbLogger.info('Connected to PostgreSQL')
|
|
39
|
+
|
|
40
|
+
// 创建子 logger(自动携带固定上下文,适合请求级/操作级追踪)
|
|
41
|
+
const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
|
|
42
|
+
reqLogger.info('Request started') // 日志自动包含 requestId + userId
|
|
43
|
+
reqLogger.error('Request failed') // 同上
|
|
44
|
+
|
|
45
|
+
// 子 logger 可嵌套
|
|
46
|
+
const opLogger = reqLogger.child({ operation: 'createOrder' })
|
|
47
|
+
opLogger.info('Order created') // 包含 requestId + userId + operation
|
|
48
|
+
|
|
49
|
+
// i18n
|
|
50
|
+
core.i18n.setGlobalLocale('zh-CN')
|
|
51
|
+
const getMessage = core.i18n.createMessageGetter({
|
|
52
|
+
'zh-CN': { welcome: '欢迎 {name}', error: '发生错误:{msg}' },
|
|
53
|
+
'en-US': { welcome: 'Welcome {name}', error: 'Error: {msg}' },
|
|
54
|
+
})
|
|
55
|
+
getMessage('welcome', { params: { name: 'Alice' } }) // '欢迎 Alice'
|
|
56
|
+
|
|
57
|
+
// ID 生成
|
|
58
|
+
const nanoid = core.id.generate()
|
|
59
|
+
const shortId = core.id.short()
|
|
60
|
+
const uuid = core.id.uuid()
|
|
61
|
+
const prefixed = core.id.withPrefix('order_')
|
|
62
|
+
|
|
63
|
+
// 工具函数
|
|
64
|
+
core.object.deepMerge(objA, objB)
|
|
65
|
+
core.sanitize.sanitizeSensitiveFields({ password: 'secret', email: 'user@example.com' })
|
|
66
|
+
core.string.capitalize('hello')
|
|
67
|
+
core.array.unique([1, 1, 2, 3])
|
|
68
|
+
core.array.chunk([1, 2, 3, 4, 5], 2) // [[1,2], [3,4], [5]]
|
|
69
|
+
await core.async.delay(1000)
|
|
70
|
+
await core.async.retry(() => fetchData(), { maxRetries: 3, delay: 1000 })
|
|
71
|
+
core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
|
|
72
|
+
core.typeUtils.isDefined(value)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### ブラウザー環境
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import { core } from '@h-ai/core'
|
|
79
|
+
|
|
80
|
+
// 初始化日志级别(浏览器不支持配置加载)
|
|
81
|
+
core.init({ logging: { level: 'warn' } })
|
|
82
|
+
|
|
83
|
+
core.logger.info('Page ready')
|
|
84
|
+
const id = core.id.generate()
|
|
85
|
+
|
|
86
|
+
// 其他工具函数与 Node.js 相同
|
|
87
|
+
core.string.capitalize('hello')
|
|
88
|
+
core.array.unique([1, 1, 2])
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
ブラウザー版は型定義に合わせて `core.config` の API 形状を保持しますが、ファイル設定には対応しません:
|
|
92
|
+
|
|
93
|
+
- `core.config.get()` は `undefined`、`has()` は `false`、`keys()` は `[]` を返します。
|
|
94
|
+
- `load()` / `validate()` / `reload()` は `HaiCommonError.SERVICE_UNAVAILABLE` を返します。
|
|
95
|
+
- `watch()` は同じエラーで直ちにコールバックを呼び、安全な no-op の監視解除関数を返します。
|
|
96
|
+
- 設定が必要な場合はサーバーで読み込み API で渡すか、ブラウザーでは `core.init({ logging })` でログのみ設定してください。
|
|
97
|
+
|
|
98
|
+
## API の詳細
|
|
99
|
+
|
|
100
|
+
### ログ(Logger)
|
|
101
|
+
|
|
102
|
+
`core.logger` は既定の Logger インスタンスであり、ログ管理の共通入口でもあります。
|
|
103
|
+
|
|
104
|
+
#### ログの記録
|
|
105
|
+
|
|
106
|
+
6 つのレベル:`trace` / `debug` / `info` / `warn` / `error` / `fatal`。
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
core.logger.info('User created', { userId: '123' })
|
|
110
|
+
core.logger.error('Failed to connect', { error })
|
|
111
|
+
core.logger.debug('Processing item', { id, step: 'validation' })
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
#### モジュール用 logger の作成
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
// 独立名称空间,适合模块内全局使用
|
|
118
|
+
const logger = core.logger.create({ name: 'payment' })
|
|
119
|
+
logger.info('Payment processed')
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
#### 子 logger(child)
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
// 携带固定上下文,每条日志自动附带这些字段
|
|
126
|
+
const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
|
|
127
|
+
reqLogger.info('Request started') // 输出包含 requestId + userId
|
|
128
|
+
reqLogger.warn('Slow response') // 同上
|
|
129
|
+
|
|
130
|
+
// 嵌套 child:子上下文递归合并
|
|
131
|
+
const opLogger = reqLogger.child({ operation: 'login' })
|
|
132
|
+
opLogger.info('Login succeeded') // 输出包含 requestId + userId + operation
|
|
133
|
+
opLogger.error('Login failed', { reason: 'invalid_password' })
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
> **典型的な使い方**:リクエスト入口で `reqLogger` を作成してサービス層に渡し、サービス層で `child` に操作コンテキストを追加します。ログに処理全体のコンテキストが自動的に含まれます。
|
|
137
|
+
|
|
138
|
+
#### ログの管理
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
// 配置输出格式和级别(Node.js / Browser)
|
|
142
|
+
core.logger.configure({
|
|
143
|
+
level: 'info',
|
|
144
|
+
format: 'json', // 'json' | 'pretty'
|
|
145
|
+
context: { app: 'my-service' }, // 全局默认上下文
|
|
146
|
+
redact: ['password', 'token'], // 脱敏字段
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
core.logger.setLevel('debug')
|
|
150
|
+
const level = core.logger.getLevel() // 'debug'
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`core.init()` で `_core.yml.logging` を読み込んだ後、または `configure` / `setLevel` の後は、既定・モジュール・ネストした child Logger の次の出力に現在の共通設定を適用します。初期化前に作成したインスタンスも対象です。`create({ level, format, context })` の明示指定は優先され、省略項目は共通設定を動的に継承します。呼び出し時の context は固定 context を上書きし、追加 `redact` 規則も全インスタンスに適用するため、モジュール Logger の再作成は不要です。
|
|
154
|
+
|
|
155
|
+
ブラウザーでは引き続き DevTools console に出力します。`pretty` は読みやすいメッセージと context、`json` は `level` / `msg` を含む JSON 文字列です。既定の認証情報マスキングと設定したパスのマスキングを併用し、ネストしたドット・括弧パスと `*` に対応します。メッセージ本文の機密情報は呼び出し側で除去してください。
|
|
156
|
+
|
|
157
|
+
`core.logger` は既定でログの機密情報をマスクします。`password`、`token`、`secret`、`privateKey`、`apiV3Key` などは `[REDACTED]` に置換されます。`url` / `baseUrl` / `endpoint` は URL 内のユーザー名・パスワードのみをマスクします。メールアドレス・電話番号は既定では隠しません。
|
|
158
|
+
|
|
159
|
+
#### ログレベルの規約
|
|
160
|
+
|
|
161
|
+
| レベル | 用途 |
|
|
162
|
+
| ------- | ---------------------------------------- |
|
|
163
|
+
| `trace` | ループ内の詳細なデバッグデータ |
|
|
164
|
+
| `debug` | 関数開始、引数の概要、読み取り操作 |
|
|
165
|
+
| `info` | 業務イベント(初期化完了、書き込み成功) |
|
|
166
|
+
| `warn` | 回復可能な問題(検証失敗、再試行) |
|
|
167
|
+
| `error` | 調査が必要な操作の失敗 |
|
|
168
|
+
| `fatal` | サービス継続不能の致命的エラー |
|
|
169
|
+
|
|
170
|
+
### 国際化(i18n)
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
// 设置全局语言(所有 getMessage 函数自动响应)
|
|
174
|
+
core.i18n.setGlobalLocale('en-US')
|
|
175
|
+
const current = core.i18n.getGlobalLocale() // 'en-US'
|
|
176
|
+
|
|
177
|
+
// 为每个模块创建消息获取器
|
|
178
|
+
const getMessage = core.i18n.createMessageGetter({
|
|
179
|
+
'zh-CN': { welcome: '欢迎 {name}', error: '错误:{code}' },
|
|
180
|
+
'en-US': { welcome: 'Welcome {name}', error: 'Error: {code}' },
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
// 使用:自动读取全局 locale,支持参数插值
|
|
184
|
+
getMessage('welcome', { params: { name: 'Alice' } }) // 'Welcome Alice'
|
|
185
|
+
|
|
186
|
+
// 支持 locale 参数覆盖
|
|
187
|
+
getMessage('welcome', { locale: 'zh-CN', params: { name: 'Alice' } }) // '欢迎 Alice'
|
|
188
|
+
|
|
189
|
+
// 常量
|
|
190
|
+
core.i18n.DEFAULT_LOCALES // [{ code: 'zh-CN', label: '简体中文' }, { code: 'en-US', label: 'English' }]
|
|
191
|
+
core.i18n.DEFAULT_LOCALE // 'zh-CN'
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### 機密情報のマスク
|
|
195
|
+
|
|
196
|
+
`core.sanitize.sanitizeSensitiveFields()` はオブジェクト・配列内の機密情報を再帰的にマスクします。既定では password、token、secret、privateKey、apiV3Key などを処理し、`url` / `baseUrl` / `endpoint` の認証情報もマスクします。独自の matcher も指定できます。
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
core.sanitize.sanitizeSensitiveFields({
|
|
200
|
+
email: 'user@example.com',
|
|
201
|
+
password: 'secret',
|
|
202
|
+
baseUrl: 'https://user:pass@example.com/api/v1',
|
|
203
|
+
profile: { token: 'jwt-token' },
|
|
204
|
+
})
|
|
205
|
+
// => { email: 'user@example.com', password: '[REDACTED]', baseUrl: 'https://[REDACTED]:[REDACTED]@example.com/api/v1', profile: { token: '[REDACTED]' } }
|
|
206
|
+
|
|
207
|
+
core.sanitize.sanitizeSensitiveFields({ email: 'user@example.com' }, {
|
|
208
|
+
matcher: /email/i,
|
|
209
|
+
replacement: '***',
|
|
210
|
+
})
|
|
211
|
+
// => { email: '***' }
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Zod 検証エラーの i18n 変換
|
|
215
|
+
|
|
216
|
+
`core.zodValidation` は Zod の `SafeParseError` / `ZodError` をフラットなフォームエラーに変換し、
|
|
217
|
+
Zod の既定の英語メッセージを呼び出し元の i18n 文言に変換します。
|
|
218
|
+
|
|
219
|
+
- 公開入口は 2 つです:
|
|
220
|
+
- `createPrefixedZodMessageGetter()`:モジュールの接頭辞から `serv_validation*` / `kit_validation*` などの key を生成し、手書きの `KEY_MAP` を省略。
|
|
221
|
+
- `mapZodErrorToFormErrors()`:抽出・ローカライズ・フラット化を一度に実行。
|
|
222
|
+
- 独自の業務メッセージは保持し、Zod の既定の英語メッセージのみを置換します。
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
import type { ZodMessageGetter } from '@h-ai/core'
|
|
226
|
+
import { core } from '@h-ai/core'
|
|
227
|
+
import { z } from 'zod'
|
|
228
|
+
|
|
229
|
+
const LoginSchema = z.object({
|
|
230
|
+
email: z.string().email(),
|
|
231
|
+
password: z.string().min(8),
|
|
232
|
+
nickname: z.string().min(1, '请填写昵称'),
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
const getMessage: ZodMessageGetter = (key, params) => {
|
|
236
|
+
switch (key) {
|
|
237
|
+
case 'validationEmail':
|
|
238
|
+
return '请输入合法邮箱地址'
|
|
239
|
+
case 'validationStringMin':
|
|
240
|
+
return `至少输入 ${params?.min} 个字符`
|
|
241
|
+
case 'validationRequired':
|
|
242
|
+
return '此项为必填项'
|
|
243
|
+
default:
|
|
244
|
+
return '输入不合法'
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const result = LoginSchema.safeParse({
|
|
249
|
+
email: 'bad',
|
|
250
|
+
password: '123',
|
|
251
|
+
nickname: '',
|
|
252
|
+
})
|
|
253
|
+
|
|
254
|
+
if (!result.success) {
|
|
255
|
+
const getMessage = core.zodValidation.createPrefixedZodMessageGetter(
|
|
256
|
+
'kit',
|
|
257
|
+
(messageKey, params) => {
|
|
258
|
+
if (messageKey === 'kit_validationEmail')
|
|
259
|
+
return '请输入合法邮箱地址'
|
|
260
|
+
if (messageKey === 'kit_validationStringMin')
|
|
261
|
+
return `至少输入 ${params?.min} 个字符`
|
|
262
|
+
return '输入不合法'
|
|
263
|
+
},
|
|
264
|
+
)
|
|
265
|
+
const errors = core.zodValidation.mapZodErrorToFormErrors(result.error, getMessage)
|
|
266
|
+
|
|
267
|
+
errors[0]?.field // 'email'
|
|
268
|
+
errors[0]?.message // '请输入合法邮箱地址'
|
|
269
|
+
errors[2]?.message // '请填写昵称'(schema 自定义消息原样保留)
|
|
270
|
+
|
|
271
|
+
core.logger.info('Validation failed', { errors })
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### 設定管理(Node.js 専用)
|
|
276
|
+
|
|
277
|
+
> ブラウザーにはファイルシステムがないため、`core.config` は代替 API の形状のみを提供します。ファイル関連メソッドは `SERVICE_UNAVAILABLE` を返し、YAML を読み込みません。
|
|
278
|
+
|
|
279
|
+
```typescript
|
|
280
|
+
import { core, HaiConfigError } from '@h-ai/core'
|
|
281
|
+
import { z } from 'zod'
|
|
282
|
+
|
|
283
|
+
// 方式 1:init 时自动加载整个配置目录
|
|
284
|
+
core.init({
|
|
285
|
+
configDir: './config', // 扫描该目录所有 .yml 文件
|
|
286
|
+
watchConfig: true, // 监听变更并自动重载
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
// 方式 2:手动加载单个文件(可选 Schema 校验)
|
|
290
|
+
const AppSchema = z.object({
|
|
291
|
+
name: z.string(),
|
|
292
|
+
port: z.number().default(3000),
|
|
293
|
+
})
|
|
294
|
+
const result = core.config.load('app', './config/app.yml', AppSchema)
|
|
295
|
+
if (result.success) {
|
|
296
|
+
core.logger.info('Config loaded', { name: result.data.name })
|
|
297
|
+
}
|
|
298
|
+
else {
|
|
299
|
+
core.logger.error('Config load failed', { code: result.error.code })
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// 校验已加载的配置
|
|
303
|
+
const validResult = core.config.validate('app', AppSchema)
|
|
304
|
+
|
|
305
|
+
// 查询和获取
|
|
306
|
+
if (core.config.has('app')) {
|
|
307
|
+
const cfg = core.config.get<typeof AppSchema>('app') // undefined 或配置
|
|
308
|
+
const cfg2 = core.config.getOrThrow<typeof AppSchema>('app') // 未加载时抛异常
|
|
309
|
+
}
|
|
310
|
+
core.config.keys() // ['core', 'app', 'db', ...]
|
|
311
|
+
|
|
312
|
+
// 重新加载
|
|
313
|
+
const reloadResult = core.config.reload('app')
|
|
314
|
+
|
|
315
|
+
// 监听文件变更
|
|
316
|
+
const unwatch = core.config.watch('app', (newConfig, error) => {
|
|
317
|
+
if (error) {
|
|
318
|
+
core.logger.error('Config reload failed', { error })
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
core.logger.info('Config updated', { config: newConfig })
|
|
322
|
+
})
|
|
323
|
+
unwatch() // 取消监听
|
|
324
|
+
|
|
325
|
+
// 清除缓存(同时停止对应监听)
|
|
326
|
+
core.config.clear('app') // 清除单个
|
|
327
|
+
core.config.clear() // 清除全部
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
#### 環境変数のマッピングと展開
|
|
331
|
+
|
|
332
|
+
`core.config.load(name, ...)` は YAML の各末端設定を
|
|
333
|
+
`HAI_<CONFIG_NAME>_<YAML_PATH>` の環境変数に自動対応付けします。設定名・各 key は大文字化し、階層は `_` で区切り、
|
|
334
|
+
camelCase の単語は分割しません。例:`ai.llm.apiKey` は `HAI_AI_LLM_APIKEY`、
|
|
335
|
+
`ai.llm.maxTokens` は `HAI_AI_LLM_MAXTOKENS`。配列の添字も 1 階層として扱い、
|
|
336
|
+
`ai.llm.models[0].temperature` は `HAI_AI_LLM_MODELS_0_TEMPERATURE` です。
|
|
337
|
+
|
|
338
|
+
環境変数が存在すれば YAML を上書きし、YAML のスカラー規則で number / boolean などに変換します。
|
|
339
|
+
変数がなければ YAML 値を保持します。オブジェクト・配列全体も同名の JSON 変数で置換でき、HAI_DB は接続設定全体、HAI_REACH_PROVIDERS は配信チャネル配列を置換します。親ノード全体の上書きが子フィールド変数より優先され、置換後も Schema 検証を行います。
|
|
340
|
+
|
|
341
|
+
```yaml
|
|
342
|
+
# config/_ai.yml(core.init 扫描后配置名为 ai)
|
|
343
|
+
llm:
|
|
344
|
+
apiKey: ''
|
|
345
|
+
baseUrl: https://api.xiaomimimo.com/v1
|
|
346
|
+
model: mimo-v2.5
|
|
347
|
+
maxTokens: 4096
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
```dotenv
|
|
351
|
+
HAI_AI_LLM_APIKEY=your-api-key
|
|
352
|
+
HAI_AI_LLM_MAXTOKENS=8192
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
特殊な変数名が必要な場合は明示的な `${VAR}` を使用します。優先順位は固定です:
|
|
356
|
+
規約に沿う環境変数 > 明示的な環境変数 > YAML の既定値。
|
|
357
|
+
|
|
358
|
+
- `${VAR}`:`process.env.VAR` を読み、存在しなければ `CONFIG_ENV_VAR_MISSING`。
|
|
359
|
+
- `${VAR:default}`:`process.env.VAR` を読み、存在しなければコロン以降の既定値を使用。
|
|
360
|
+
|
|
361
|
+
**型の復元:** 値全体が単一の変数式(`${PORT:3000}` など)の場合、YAML 規則で number / boolean などの型に戻します。文字列との混在は常に文字列です。
|
|
362
|
+
|
|
363
|
+
`${VAR:}` や空文字列の `${VAR}` は `''` を保持し、YAML の `null` には変換しません。空文字列を未設定として扱うモジュールは、自身の Schema で `undefined` に正規化してください。
|
|
364
|
+
|
|
365
|
+
```yaml
|
|
366
|
+
# config/app.yml
|
|
367
|
+
debug: ${DEBUG:false} # → boolean false
|
|
368
|
+
port: ${PORT:3000} # → number 3000
|
|
369
|
+
database: ${DB_CONNECTION} # → 环境变量缺失时报错
|
|
370
|
+
url: http://${HOST}:${PORT} # → string(混合文本)
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
### ID 生成
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
const id = core.id.generate() // nanoid 21 字符
|
|
377
|
+
const id8 = core.id.generate(8) // 自定义长度
|
|
378
|
+
const shortId = core.id.short() // 10 字符短 ID
|
|
379
|
+
const prefixed = core.id.withPrefix('user_') // 'user_V1StGXR...'
|
|
380
|
+
const traceId = core.id.trace() // 'trace-V1StGXR...'
|
|
381
|
+
const reqId = core.id.request() // 'req-V1StGXR...'
|
|
382
|
+
const uuid = core.id.uuid() // UUID v4
|
|
383
|
+
|
|
384
|
+
// 校验
|
|
385
|
+
core.id.isValidUUID('f47ac10b-...') // true/false
|
|
386
|
+
core.id.isValidNanoId('abc123', 6) // true/false
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
### ツール関数
|
|
390
|
+
|
|
391
|
+
```typescript
|
|
392
|
+
// 类型检查
|
|
393
|
+
core.typeUtils.isDefined(x) // x !== undefined
|
|
394
|
+
core.typeUtils.isObject(x) // plain object
|
|
395
|
+
core.typeUtils.isFunction(x)
|
|
396
|
+
core.typeUtils.isPromise(x)
|
|
397
|
+
core.typeUtils.isString(x)
|
|
398
|
+
core.typeUtils.isNumber(x)
|
|
399
|
+
core.typeUtils.isBoolean(x)
|
|
400
|
+
core.typeUtils.isArray(x)
|
|
401
|
+
|
|
402
|
+
// 对象操作
|
|
403
|
+
core.object.deepClone(obj)
|
|
404
|
+
core.object.deepMerge(a, b) // 递归合并(防原型污染)
|
|
405
|
+
core.object.deepMerge(a, b, c) // 支持多个对象
|
|
406
|
+
core.object.pick(obj, ['a', 'b'])
|
|
407
|
+
core.object.omit(obj, ['c', 'd'])
|
|
408
|
+
core.object.keys(obj) // typed Object.keys
|
|
409
|
+
core.object.values(obj)
|
|
410
|
+
core.object.entries(obj)
|
|
411
|
+
core.object.fromEntries(entries)
|
|
412
|
+
|
|
413
|
+
// 字符串操作
|
|
414
|
+
core.string.capitalize('hello') // 'Hello'
|
|
415
|
+
core.string.kebabCase('helloWorld') // 'hello-world'
|
|
416
|
+
core.string.camelCase('hello-world') // 'helloWorld'
|
|
417
|
+
core.string.snakeCase('helloWorld') // 'hello_world'
|
|
418
|
+
core.string.pascalCase('hello-world') // 'HelloWorld'
|
|
419
|
+
core.string.truncate('long text', 5) // 'long ...'
|
|
420
|
+
core.string.trim(' hello ') // 'hello'
|
|
421
|
+
core.string.isBlank('') // true
|
|
422
|
+
core.string.isNotBlank('x') // true
|
|
423
|
+
core.string.padStart('5', 3, '0') // '005'
|
|
424
|
+
core.string.padEnd('5', 3, '0') // '500'
|
|
425
|
+
core.string.constantTimeEqual(a, b) // 防时序攻击比较
|
|
426
|
+
|
|
427
|
+
// 数组操作
|
|
428
|
+
core.array.unique([1, 1, 2]) // [1, 2]
|
|
429
|
+
core.array.chunk([1, 2, 3, 4], 2) // [[1,2], [3,4]]
|
|
430
|
+
core.array.groupBy(items, item => item.type) // Record<string, T[]>
|
|
431
|
+
core.array.first([1, 2, 3]) // 1
|
|
432
|
+
core.array.last([1, 2, 3]) // 3
|
|
433
|
+
core.array.flatten([[1], [2, 3]]) // [1, 2, 3]
|
|
434
|
+
core.array.compact([1, null, 2]) // [1, 2]
|
|
435
|
+
core.array.shuffle([1, 2, 3]) // 随机排列
|
|
436
|
+
core.array.intersection([1, 2], [2, 3]) // [2]
|
|
437
|
+
core.array.difference([1, 2], [2, 3]) // [1]
|
|
438
|
+
|
|
439
|
+
// 异步操作
|
|
440
|
+
await core.async.delay(1000)
|
|
441
|
+
await core.async.withTimeout(fetch('/api'), 5000)
|
|
442
|
+
await core.async.retry(fn, { maxRetries: 3, delay: 1000 })
|
|
443
|
+
await core.async.parallel(items, processFn, 5) // 并发限制
|
|
444
|
+
await core.async.serial(items, processFn)
|
|
445
|
+
const debouncedFn = core.async.debounce(fn, 300)
|
|
446
|
+
const throttledFn = core.async.throttle(fn, 200)
|
|
447
|
+
|
|
448
|
+
// 时间操作
|
|
449
|
+
core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
|
|
450
|
+
core.time.timeAgo(new Date(Date.now() - 60000)) // '1 分钟前'
|
|
451
|
+
core.time.now() // Date.now()
|
|
452
|
+
core.time.nowSeconds() // Math.floor(Date.now() / 1000)
|
|
453
|
+
core.time.parseDate('2024-01-01')
|
|
454
|
+
core.time.isValidDate(date)
|
|
455
|
+
core.time.addDays(date, 7)
|
|
456
|
+
core.time.addHours(date, 2)
|
|
457
|
+
core.time.startOfDay(date)
|
|
458
|
+
core.time.endOfDay(date)
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
### モジュール共通ツール(module)
|
|
462
|
+
|
|
463
|
+
モジュール共通の初期化エラー処理:
|
|
464
|
+
|
|
465
|
+
```typescript
|
|
466
|
+
import { core } from '@h-ai/core'
|
|
467
|
+
|
|
468
|
+
const notInitialized = core.module.createNotInitializedKit(
|
|
469
|
+
HaiDbError.NOT_INITIALIZED,
|
|
470
|
+
() => dbM('db_notInitialized'),
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
// 创建占位 Proxy(异步接口,默认)
|
|
474
|
+
const currentDdl: DdlOperations = notInitialized.proxy<DdlOperations>()
|
|
475
|
+
// 创建占位 Proxy(同步接口)
|
|
476
|
+
const currentHash: HashOperations = notInitialized.proxy<HashOperations>('sync')
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
## エラー処理
|
|
480
|
+
|
|
481
|
+
### HaiResult 型
|
|
482
|
+
|
|
483
|
+
失敗する可能性がある操作は `HaiResult<T>` を返します:
|
|
484
|
+
|
|
485
|
+
```typescript
|
|
486
|
+
import type { HaiResult } from '@h-ai/core'
|
|
487
|
+
import { core, err, HaiCommonError, ok } from '@h-ai/core'
|
|
488
|
+
|
|
489
|
+
function divide(a: number, b: number): HaiResult<number> {
|
|
490
|
+
if (b === 0)
|
|
491
|
+
return err(HaiCommonError.VALIDATION_ERROR, 'Division by zero')
|
|
492
|
+
return ok(a / b)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const result = divide(10, 2)
|
|
496
|
+
if (result.success) {
|
|
497
|
+
core.logger.info('Result', { data: result.data })
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
core.logger.error('Error', { error: result.error })
|
|
501
|
+
}
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
### 独自のエラーコード(モジュール単位)
|
|
505
|
+
|
|
506
|
+
```typescript
|
|
507
|
+
import type { ErrorInfo } from '@h-ai/core'
|
|
508
|
+
import { core } from '@h-ai/core'
|
|
509
|
+
|
|
510
|
+
// 定义错误码(格式 'code:httpStatus')
|
|
511
|
+
const DbErrorInfo = {
|
|
512
|
+
NOT_INITIALIZED: '001:500',
|
|
513
|
+
CONNECTION_FAILED: '010:500',
|
|
514
|
+
QUERY_FAILED: '011:500',
|
|
515
|
+
} as const satisfies ErrorInfo
|
|
516
|
+
|
|
517
|
+
// 生成错误定义对象
|
|
518
|
+
export const DbError = core.error.buildHaiErrorsDef('db', DbErrorInfo)
|
|
519
|
+
// DbError.CONNECTION_FAILED → { code: 'hai:db:010', httpStatus: 500, system: 'hai', module: 'db' }
|
|
520
|
+
|
|
521
|
+
// 创建错误实例
|
|
522
|
+
const errorInst = core.error.buildHaiErrorInst(
|
|
523
|
+
DbError.CONNECTION_FAILED,
|
|
524
|
+
'Unable to connect to PostgreSQL',
|
|
525
|
+
originalError, // cause(可选)
|
|
526
|
+
'Check connection string', // suggestion(可选)
|
|
527
|
+
)
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
### 設定エラーコード
|
|
531
|
+
|
|
532
|
+
```typescript
|
|
533
|
+
import { HaiConfigError } from '@h-ai/core'
|
|
534
|
+
|
|
535
|
+
HaiConfigError.CONFIG_FILE_NOT_FOUND // hai:core:010 - 配置文件不存在
|
|
536
|
+
HaiConfigError.CONFIG_PARSE_ERROR // hai:core:011 - YAML 解析失败
|
|
537
|
+
HaiConfigError.CONFIG_VALIDATION_ERROR // hai:core:012 - Schema 校验失败
|
|
538
|
+
HaiConfigError.CONFIG_ENV_VAR_MISSING // hai:core:013 - 环境变量缺失
|
|
539
|
+
HaiConfigError.CONFIG_NOT_LOADED // hai:core:014 - 配置未加载
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
## テスト
|
|
543
|
+
|
|
544
|
+
```bash
|
|
545
|
+
pnpm --filter @h-ai/core test
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
## License
|
|
549
|
+
|
|
550
|
+
Apache-2.0
|
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @h-ai/core
|
|
2
2
|
|
|
3
|
+
[简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
|
|
4
|
+
|
|
5
|
+
[框架首页](../../README.md)
|
|
6
|
+
|
|
3
7
|
> hai Agent Framework 核心模块 — 提供统一的基础工具、类型定义、配置管理和日志功能。
|
|
4
8
|
|
|
5
9
|
## 支持的能力
|
|
@@ -134,7 +138,7 @@ opLogger.error('Login failed', { reason: 'invalid_password' })
|
|
|
134
138
|
#### 日志管理
|
|
135
139
|
|
|
136
140
|
```typescript
|
|
137
|
-
// 配置输出格式和级别(Node.js)
|
|
141
|
+
// 配置输出格式和级别(Node.js / Browser)
|
|
138
142
|
core.logger.configure({
|
|
139
143
|
level: 'info',
|
|
140
144
|
format: 'json', // 'json' | 'pretty'
|
|
@@ -146,6 +150,10 @@ core.logger.setLevel('debug')
|
|
|
146
150
|
const level = core.logger.getLevel() // 'debug'
|
|
147
151
|
```
|
|
148
152
|
|
|
153
|
+
`core.init()` 加载 `_core.yml.logging` 后,或调用 `configure` / `setLevel` 后,默认、模块和嵌套 child Logger 会在后续输出中使用当前全局配置,即使这些实例在初始化前创建。`create({ level, format, context })` 的显式级别、格式和本地上下文仍优先;未指定的选项动态继承全局配置,调用时上下文覆盖固定上下文。附加 `redact` 对这些实例统一生效,不需要重建模块 Logger。
|
|
154
|
+
|
|
155
|
+
浏览器仍输出到 DevTools console:`pretty` 使用可读消息与上下文,`json` 输出包含 `level` / `msg` 的 JSON 字符串。默认凭据脱敏与配置的字段路径脱敏同时生效,支持嵌套点/括号路径和 `*`;消息文本本身需调用方脱敏。
|
|
156
|
+
|
|
149
157
|
`core.logger` 默认会对日志上下文执行安全脱敏:`password`、`token`、`secret`、`privateKey`、`apiV3Key` 等凭证类字段会替换为 `[REDACTED]`,`url` / `baseUrl` / `endpoint` 这类字段只会掩码 URL 中内嵌的用户名和密码;邮箱、手机号默认不会被遮盖。
|
|
150
158
|
|
|
151
159
|
#### 日志级别规范
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { H as HaiResult, W as WatchCallback, C as CoreOptions, a as CoreLogger, I as I18nFn, z as zodValidation, b as IdFn, T as TypeUtilFn, O as ObjectFn, S as SanitizeFn, c as StringFn, A as ArrayFn, d as AsyncFn, e as TimeFn, E as ErrorFn, M as ModuleFn } from './core-function-config.node-CwXAT7fW.js';
|
|
2
|
+
export { f as CoreConfig, g as CoreConfigSchema, h as CoreFunctions, i as Env, j as EnvSchema, k as ErrorInfo, l as ErrorInfoValue, m as HaiCommonError, n as HaiConfigError, o as HaiError, p as HaiErrorDef, q as IdConfig, r as IdConfigSchema, s as InterpolationParams, L as Locale, t as LocaleInfo, u as LocaleMessages, v as LogContext, w as LogFormat, x as LogFormatSchema, y as LogLevel, B as LogLevelSchema, D as Logger, F as LoggerFunctions, G as LoggerOptions, J as LoggingConfig, K as LoggingConfigSchema, N as MatchHandlers, P as MessageDictionary, Q as MessageOptions, R as PaginatedResult, U as PaginationOptions, V as PaginationOptionsInput, X as ValidationFormError, Z as ZodMessageGetter, Y as ZodValidationFn, _ as ZodValidationMessageKey, $ as err, a0 as ok } from './core-function-config.node-CwXAT7fW.js';
|
|
3
3
|
import * as zod from 'zod';
|
|
4
4
|
|
|
5
5
|
/**
|