@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.en.md
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
# @h-ai/core
|
|
2
|
+
|
|
3
|
+
[简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
|
|
4
|
+
|
|
5
|
+
[Framework home](../../README.en.md)
|
|
6
|
+
|
|
7
|
+
> The core of hai Agent Framework: shared utilities, types, configuration management, and logging.
|
|
8
|
+
|
|
9
|
+
## Capabilities
|
|
10
|
+
|
|
11
|
+
- **HaiResult types**: functional error handling (`ok` / `err`) with a shared result format across modules.
|
|
12
|
+
- **Unified logging**: pino on Node.js and loglevel in browsers, with the same API.
|
|
13
|
+
- **Internationalization (i18n)**: centralized locale management and typed message getters.
|
|
14
|
+
- **Zod validation error mapping**: Zod v3/v4 issue extraction and localization of default English messages.
|
|
15
|
+
- **Configuration management**: YAML loading, convention-based environment mapping, explicit interpolation, Zod validation, and file watching (Node.js only).
|
|
16
|
+
- **ID generation**: nanoid and UUID v4.
|
|
17
|
+
- **Error definitions**: standardized codes and consistent error definitions and instances across modules.
|
|
18
|
+
- **Module utilities**: NotInitializedKit proxies and shared lifecycle infrastructure.
|
|
19
|
+
- **Utility library**: type checks and object / string / array / async / time operations.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
### Node.js environment
|
|
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
|
+
### Browser environment
|
|
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
|
+
The browser retains the `core.config` API shape for type compatibility, but does not support file configuration:
|
|
92
|
+
|
|
93
|
+
- `core.config.get()` returns `undefined`, `has()` returns `false`, and `keys()` returns `[]`.
|
|
94
|
+
- `load()` / `validate()` / `reload()` return `HaiCommonError.SERVICE_UNAVAILABLE`.
|
|
95
|
+
- `watch()` immediately calls its callback with the same error and returns a safe no-op unsubscribe function.
|
|
96
|
+
- Read configuration on the server and deliver it through an API, or use `core.init({ logging })` only to configure browser logging.
|
|
97
|
+
|
|
98
|
+
## Detailed API
|
|
99
|
+
|
|
100
|
+
### Logging (Logger)
|
|
101
|
+
|
|
102
|
+
`core.logger` is both the default Logger instance and the shared entry point for logger management.
|
|
103
|
+
|
|
104
|
+
#### Write logs
|
|
105
|
+
|
|
106
|
+
Six levels: `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
|
+
#### Create a module logger
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
// 独立名称空间,适合模块内全局使用
|
|
118
|
+
const logger = core.logger.create({ name: 'payment' })
|
|
119
|
+
logger.info('Payment processed')
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
#### Child loggers
|
|
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
|
+
> **Typical usage**: create `reqLogger` at the request entry, pass it to the service layer, and add operation context with `child`. Logs then include the complete request context.
|
|
137
|
+
|
|
138
|
+
#### Logger management
|
|
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
|
+
After `core.init()` loads `_core.yml.logging`, or after `configure` / `setLevel`, default, module and nested child loggers use current global configuration for subsequent output, including instances created before initialization. Explicit `create({ level, format, context })` options retain priority; omitted options inherit global configuration dynamically, and per-call context overrides fixed context. Additional `redact` rules apply to all these instances without recreating module loggers.
|
|
154
|
+
|
|
155
|
+
Browser logs still use the DevTools console: `pretty` prints readable messages with context, while `json` prints a JSON string containing `level` / `msg`. Default credential masking and configured path redaction both apply, including nested dot/bracket paths and `*`. Callers remain responsible for redacting message text.
|
|
156
|
+
|
|
157
|
+
`core.logger` redacts log context by default: credentials such as `password`, `token`, `secret`, `privateKey`, and `apiV3Key` become `[REDACTED]`. Fields such as `url` / `baseUrl` / `endpoint` mask only embedded usernames/passwords. Email addresses and phone numbers are not masked by default.
|
|
158
|
+
|
|
159
|
+
#### Log level conventions
|
|
160
|
+
|
|
161
|
+
| Level | Use case |
|
|
162
|
+
| ------- | --------------------------------------------------- |
|
|
163
|
+
| `trace` | Detailed debugging data inside loops |
|
|
164
|
+
| `debug` | Function entry, parameter summaries, reads |
|
|
165
|
+
| `info` | Business events (initialized, write succeeded) |
|
|
166
|
+
| `warn` | Recoverable problems (validation failures, retries) |
|
|
167
|
+
| `error` | Operation failures requiring investigation |
|
|
168
|
+
| `fatal` | Fatal errors preventing continued service |
|
|
169
|
+
|
|
170
|
+
### Internationalization (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
|
+
### Redaction utilities
|
|
195
|
+
|
|
196
|
+
`core.sanitize.sanitizeSensitiveFields()` recursively redacts objects and arrays. By default it handles password, token, secret, privateKey, apiV3Key, and similar credentials, and masks embedded credentials in `url` / `baseUrl` / `endpoint`. Modules can supply custom matchers.
|
|
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 validation error localization
|
|
215
|
+
|
|
216
|
+
`core.zodValidation` converts Zod `SafeParseError` / `ZodError` into flat form errors and maps Zod's
|
|
217
|
+
default English messages to the caller's own localized messages.
|
|
218
|
+
|
|
219
|
+
- Two public entry points:
|
|
220
|
+
- `createPrefixedZodMessageGetter()`: derive keys such as `serv_validation*` / `kit_validation*` from module prefixes without a manual `KEY_MAP`.
|
|
221
|
+
- `mapZodErrorToFormErrors()`: extract, localize, and flatten in one step.
|
|
222
|
+
- Custom business messages are preserved; only Zod's default English messages are replaced.
|
|
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
|
+
### Configuration management (Node.js only)
|
|
276
|
+
|
|
277
|
+
> Browsers have no filesystem access. `core.config` offers placeholder APIs only: file-related methods return `SERVICE_UNAVAILABLE` and do not load 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
|
+
#### Environment variable mapping and interpolation
|
|
331
|
+
|
|
332
|
+
`core.config.load(name, ...)` automatically maps each YAML leaf to an
|
|
333
|
+
environment variable named `HAI_<CONFIG_NAME>_<YAML_PATH>`. Configuration names and keys are uppercased, levels are separated by `_`,
|
|
334
|
+
and camelCase is not split. For example, `ai.llm.apiKey` maps to `HAI_AI_LLM_APIKEY`,
|
|
335
|
+
and `ai.llm.maxTokens` to `HAI_AI_LLM_MAXTOKENS`. Array indexes are also levels:
|
|
336
|
+
`ai.llm.models[0].temperature` maps to `HAI_AI_LLM_MODELS_0_TEMPERATURE`.
|
|
337
|
+
|
|
338
|
+
Existing environment variables override YAML and are parsed with YAML scalar rules into numbers, booleans, and other native types.
|
|
339
|
+
Absent variables leave YAML unchanged. Object/array nodes can also be replaced wholesale with same-name JSON variables, such as HAI_DB for connection configuration or HAI_REACH_PROVIDERS for channel arrays. A parent replacement takes precedence over child variables; schema validation still runs afterward.
|
|
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
|
+
For special variable names, use explicit `${VAR}` interpolation. Precedence is fixed:
|
|
356
|
+
Convention-based environment variables > explicit environment variables > YAML defaults.
|
|
357
|
+
|
|
358
|
+
- `${VAR}`: read `process.env.VAR`; return `CONFIG_ENV_VAR_MISSING` if absent.
|
|
359
|
+
- `${VAR:default}`: read `process.env.VAR`; use the value after the colon if absent.
|
|
360
|
+
|
|
361
|
+
**Type restoration:** when the whole value is one variable expression (such as `${PORT:3000}`), YAML rules restore native types (number / boolean, etc.). Mixed text always stays a string.
|
|
362
|
+
|
|
363
|
+
`${VAR:}` or `${VAR}` resolving to an empty string stays `''`, rather than becoming YAML `null`. Modules that treat empty strings as unset should normalize them to `undefined` in their own schemas.
|
|
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 generation
|
|
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
|
+
### Utilities
|
|
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 utilities (module)
|
|
462
|
+
|
|
463
|
+
Shared initialization error handling for modules:
|
|
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
|
+
## Error handling
|
|
480
|
+
|
|
481
|
+
### HaiResult types
|
|
482
|
+
|
|
483
|
+
All operations that may fail return `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
|
+
### Custom error codes (per module)
|
|
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
|
+
### Configuration error codes
|
|
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
|
+
## Tests
|
|
543
|
+
|
|
544
|
+
```bash
|
|
545
|
+
pnpm --filter @h-ai/core test
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
## License
|
|
549
|
+
|
|
550
|
+
Apache-2.0
|