@h-ai/core 1.0.0-beta.1 → 1.0.0-beta.11
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 +640 -473
- package/README.ja.md +639 -472
- package/README.md +640 -473
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/{chunk-BEGTB6GL.js → chunk-MYNB4HIZ.js} +42 -19
- package/dist/chunk-MYNB4HIZ.js.map +1 -0
- package/dist/{core-types-_JqVAGGT.d.ts → core-types-DM_AiIaS.d.ts} +154 -11
- package/dist/node.d.ts +2 -2
- package/dist/node.js +325 -99
- package/dist/node.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-BEGTB6GL.js.map +0 -1
package/README.en.md
CHANGED
|
@@ -6,647 +6,814 @@
|
|
|
6
6
|
|
|
7
7
|
## Introduction
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
`@h-ai/core` is the shared foundation of Hai Framework. It gives applications and framework modules consistent configuration, errors, logging, and internationalization. Utilities work directly; call `core.init()` when a Node application needs file configuration.
|
|
10
10
|
|
|
11
|
-
## Core
|
|
11
|
+
## Core capabilities
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
13
|
+
| Capability | Purpose | Main entry points |
|
|
14
|
+
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
|
|
15
|
+
| Configuration and startup | Load YAML, merge environment overrides, validate settings, and orchestrate module startup and shutdown | `core.config`, `core.init`, `core.module.createRuntime` |
|
|
16
|
+
| Results and errors | Express business success/failure, define error codes, and produce safe messages at API boundaries | `HaiResult`, `ok` / `err`, `core.error` |
|
|
17
|
+
| Logging and diagnostics | Structured logs, request correlation, credential masking, and log observation | `core.logger`, `core.context`, `core.sanitize` |
|
|
18
|
+
| Internationalization and validation messages | Manage message languages, isolate concurrent request locales, and localize Zod field errors | `core.i18n`, `core.zodValidation` |
|
|
19
|
+
| Request access control | Resolve trusted client addresses and check paths, methods, IPs, and time windows | `core.access` (Node only) |
|
|
20
|
+
| General utilities | Generate identifiers and reuse type, object, string, array, async, and time operations, plus consistent errors before module initialization | `core.id`, `core.typeUtils`, `core.object`, and others |
|
|
21
|
+
|
|
22
|
+
### Node and browser boundaries
|
|
23
|
+
|
|
24
|
+
Both environments use `import { core } from '@h-ai/core'`; the bundler selects the code for the target environment.
|
|
25
|
+
|
|
26
|
+
| Capability | Node.js | Browser |
|
|
27
|
+
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
28
|
+
| Logging, results/errors, messages, utilities, and ordered module startup/shutdown | Supported | Supported |
|
|
29
|
+
| YAML, dotenv, environment mapping, file watching | Reads and watches local configuration files | Cannot read or watch local files; loading methods return failure |
|
|
30
|
+
| Request correlation with `core.context.run` | Each request retains its own IDs after asynchronous work, without mixing them with other requests | Values exist only during synchronous callback code and are no longer available after `await` |
|
|
31
|
+
| Request locale with `core.i18n.runWithLocale` | Each request keeps its chosen language after asynchronous work; other requests do not change it | Throws; set the page language with `setGlobalLocale()` or pass a locale when getting a message |
|
|
32
|
+
| Request policies with `core.access` | Checks request addresses, paths, and time windows | This tool is unavailable |
|
|
33
|
+
|
|
34
|
+
`core.init()` configures Core settings and logging synchronously, returns `void`, and Core provides no `close()` method. Applications starting databases, caches, or other modules can manage them with `core.module.createRuntime()`: its returned object's `start()` initializes them in order, and `close()` cleans them up in reverse. A complete example follows under “Application startup and shutdown”.
|
|
22
35
|
|
|
23
36
|
## Getting started
|
|
24
37
|
|
|
25
|
-
|
|
38
|
+
Each Core feature below has a purpose, examples, and relevant limits. Start with initialization when loading configuration; logging, messages, and general utilities work directly.
|
|
26
39
|
|
|
27
|
-
|
|
40
|
+
Call runtime functions through `core.xxx()` or `core.<feature>.xxx()`. Import the result constructors `ok` / `err`, types, schemas, and error constants separately from the package entry. Their sections below show the usage.
|
|
28
41
|
|
|
29
|
-
```
|
|
30
|
-
|
|
42
|
+
```bash
|
|
43
|
+
pnpm add @h-ai/core
|
|
44
|
+
```
|
|
31
45
|
|
|
32
|
-
|
|
33
|
-
core.init({ configDir: './config', watchConfig: true })
|
|
46
|
+
The custom configuration and form-validation examples also use Zod; install it with `pnpm add zod` before running them. Database and cache examples list their additional dependencies in their section.
|
|
34
47
|
|
|
35
|
-
|
|
36
|
-
core.logger.info('Server started', { port: 3000 })
|
|
37
|
-
core.logger.warn('Slow query', { duration: 2500 })
|
|
38
|
-
core.logger.error('Connection failed', { error })
|
|
48
|
+
### Initialization: `core.init`
|
|
39
49
|
|
|
40
|
-
|
|
41
|
-
const dbLogger = core.logger.create({ name: 'db' })
|
|
42
|
-
dbLogger.info('Connected to PostgreSQL')
|
|
50
|
+
Load YAML and configure logging at Node startup, or configure logging in a browser. Initializing Core does not start databases or other modules.
|
|
43
51
|
|
|
44
|
-
|
|
45
|
-
const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
|
|
46
|
-
reqLogger.info('Request started') // 日志自动包含 requestId + userId
|
|
47
|
-
reqLogger.error('Request failed') // 同上
|
|
52
|
+
#### Node.js
|
|
48
53
|
|
|
49
|
-
|
|
50
|
-
const opLogger = reqLogger.child({ operation: 'createOrder' })
|
|
51
|
-
opLogger.info('Order created') // 包含 requestId + userId + operation
|
|
54
|
+
Create `config/_core.yml`:
|
|
52
55
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
```yaml
|
|
57
|
+
# 应用元信息,供启动代码和页面读取。
|
|
58
|
+
name: orders
|
|
59
|
+
version: 0.1.0
|
|
60
|
+
env: development
|
|
61
|
+
# 默认消息语言;启动代码读取后调用 setGlobalLocale 应用。
|
|
62
|
+
defaultLocale: zh-CN
|
|
63
|
+
logging:
|
|
64
|
+
level: info # 输出 info 及以上级别。
|
|
65
|
+
format: pretty # 本地开发使用便于阅读的日志。
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { core, CoreConfigSchema } from '@h-ai/core'
|
|
70
|
+
|
|
71
|
+
// 1. 读取 config 目录中的 YAML,_core.yml 对应名称 core。
|
|
72
|
+
core.init({ configDir: './config' }) // 返回 undefined;配置缓存中可读取 core。
|
|
73
|
+
|
|
74
|
+
// 2. 检查应用必需的配置;失败时停止启动,保留原始错误供排查。
|
|
75
|
+
const config = core.config.validate('core', CoreConfigSchema)
|
|
76
|
+
if (!config.success)
|
|
77
|
+
throw new Error(config.error.message, { cause: config.error })
|
|
60
78
|
|
|
61
|
-
//
|
|
62
|
-
const nanoid = core.id.generate()
|
|
63
|
-
const shortId = core.id.short()
|
|
64
|
-
const uuid = core.id.uuid()
|
|
65
|
-
const prefixed = core.id.withPrefix('order_')
|
|
79
|
+
// 成功时 config.success 为 true;config.data.name 为 'orders',defaultLocale 为 'zh-CN'。
|
|
66
80
|
|
|
67
|
-
//
|
|
68
|
-
core.
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
core.
|
|
72
|
-
core.array.chunk([1, 2, 3, 4, 5], 2) // [[1,2], [3,4], [5]]
|
|
73
|
-
await core.async.delay(1000)
|
|
74
|
-
await core.async.retry(() => fetchData(), { maxRetries: 3, delay: 1000 })
|
|
75
|
-
core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
|
|
76
|
-
core.typeUtils.isDefined(value)
|
|
81
|
+
// 3. 将配置中的语言应用到默认消息;读取 YAML 本身不会切换语言。
|
|
82
|
+
core.i18n.setGlobalLocale(config.data.defaultLocale) // 返回 undefined;后续默认消息使用中文。
|
|
83
|
+
|
|
84
|
+
// 4. 记录已验证的应用名称,确认启动完成。
|
|
85
|
+
core.logger.info('Application ready', { name: config.data.name }) // 返回 undefined;info 日志包含 name: 'orders'。
|
|
77
86
|
```
|
|
78
87
|
|
|
79
|
-
|
|
88
|
+
The startup boundary stops when required configuration is unavailable. `core.init()` logs individual load failures and continues, so completion does not mean every configuration is valid. Directory scanning and logger setup can still throw.
|
|
89
|
+
|
|
90
|
+
#### Browser
|
|
80
91
|
|
|
81
|
-
```
|
|
92
|
+
```ts
|
|
82
93
|
import { core } from '@h-ai/core'
|
|
83
94
|
|
|
84
|
-
//
|
|
85
|
-
core.init({ logging: { level: 'warn' } })
|
|
95
|
+
// 浏览器不读取 YAML;此处只设置日志,输出 warn 及以上级别。
|
|
96
|
+
core.init({ logging: { level: 'warn' } }) // 返回 undefined;之后 info 日志被过滤。
|
|
86
97
|
|
|
87
|
-
|
|
88
|
-
|
|
98
|
+
// 设置当前页面使用的默认消息语言。
|
|
99
|
+
core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;页面默认消息使用中文。
|
|
89
100
|
|
|
90
|
-
//
|
|
91
|
-
core.
|
|
92
|
-
core.
|
|
101
|
+
// 给一次请求生成编号,后续日志可用同一编号关联排查。
|
|
102
|
+
const requestId = core.id.request() // 返回随机字符串,如 'req-V1StGXR8_Z5jdHi6B-myT'。
|
|
103
|
+
core.logger.warn('Request needs attention', { requestId }) // 返回 undefined;浏览器输出 warn 消息及同一个 requestId。
|
|
93
104
|
```
|
|
94
105
|
|
|
95
|
-
The
|
|
106
|
+
The host supplies public configuration fields; never send complete server settings or secrets. Browser `core.config.get()` / `has()` / `keys()` return `undefined` / `false` / `[]`. `loadEnvFiles()`, `load()`, `validate()`, and `reload()` return `SERVICE_UNAVAILABLE`; `getOrThrow()` throws. `watch()` immediately calls back with the same unavailable error and returns a no-op unsubscribe function.
|
|
96
107
|
|
|
97
|
-
|
|
98
|
-
- `loadEnvFiles()` / `load()` / `validate()` / `reload()` return `HaiCommonError.SERVICE_UNAVAILABLE`.
|
|
99
|
-
- `watch()` immediately calls its callback with the same error and returns a safe no-op unsubscribe function.
|
|
100
|
-
- Read configuration on the server and deliver it through an API, or use `core.init({ logging })` only to configure browser logging.
|
|
108
|
+
### Files and environment settings: `core.config`
|
|
101
109
|
|
|
102
|
-
|
|
110
|
+
Read YAML, apply environment overrides, validate configuration types, and manage cached settings and file watchers. The file and environment operations below require Node.
|
|
103
111
|
|
|
104
|
-
####
|
|
112
|
+
#### Loading, validating, and reading
|
|
105
113
|
|
|
106
|
-
`core.
|
|
114
|
+
`core.init({ configDir, configSchemas?, watchConfig? })` scans direct `.yml` / `.yaml` children of the directory. `_core.yml` becomes `core`, `_db.yml` becomes `db`, and `app.yml` becomes `app`. The CLI reads build/deploy settings from root `hai.json`; they are separate from runtime YAML.
|
|
107
115
|
|
|
108
|
-
|
|
116
|
+
`_core.yml` is validated with `CoreConfigSchema`, accepting only `name`, `version`, `env`, `defaultLocale`, and `logging`. The metadata defaults are `hai Admin`, `0.1.0`, `development`, and `zh-CN`; `logging` is optional. Metadata does not set `NODE_ENV`, switch message languages, or register application translations. Configure logging here; explicit `core.init({ logging })` overrides the application of YAML logging settings during that initialization.
|
|
109
117
|
|
|
110
|
-
|
|
118
|
+
For other files, host-supplied `configSchemas` provide structural and type hints during scanning. Full business validation stays in module initialization or explicit `validate()`. A direct `load(name, file, schema)` validates immediately.
|
|
111
119
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
120
|
+
The following file examples use this `config/app.yml` with no additional environment overrides:
|
|
121
|
+
|
|
122
|
+
```yaml
|
|
123
|
+
# config/app.yml
|
|
124
|
+
port: 3000
|
|
116
125
|
```
|
|
117
126
|
|
|
118
|
-
|
|
127
|
+
load() reads a file and can validate it immediately; validate() validates cached settings. get() returns undefined for a missing entry, while getOrThrow() throws. Generic arguments help TypeScript and do not validate data. has()/keys() show which entries exist.
|
|
119
128
|
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
129
|
+
```ts
|
|
130
|
+
import { core } from '@h-ai/core'
|
|
131
|
+
import { z } from 'zod'
|
|
132
|
+
|
|
133
|
+
// 读取上方 config/app.yml;Schema 同时描述类型和校验规则。
|
|
134
|
+
const AppSchema = z.object({ port: z.number().int().min(1).max(65535) })
|
|
135
|
+
const loaded = core.config.load('app', './config/app.yml', AppSchema)
|
|
136
|
+
if (!loaded.success)
|
|
137
|
+
throw new Error(loaded.error.message, { cause: loaded.error })
|
|
125
138
|
|
|
126
|
-
|
|
139
|
+
// loaded:{ success: true, data: { port: 3000 } }。
|
|
127
140
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
reqLogger.warn('Slow response') // 同上
|
|
141
|
+
// validate 用于重新校验缓存;加载时未传 Schema 的配置也可在这里校验。
|
|
142
|
+
const validated = core.config.validate('app', AppSchema)
|
|
143
|
+
if (!validated.success)
|
|
144
|
+
throw new Error(validated.error.message, { cause: validated.error })
|
|
133
145
|
|
|
134
|
-
//
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
146
|
+
// validated:{ success: true, data: { port: 3000 } }。
|
|
147
|
+
|
|
148
|
+
// get 适合可选配置;getOrThrow 适合已确认存在的必需配置。
|
|
149
|
+
if (core.config.has('app')) { // true:上方已成功加载 app。
|
|
150
|
+
const optional = core.config.get<z.infer<typeof AppSchema>>('app') // { port: 3000 }。
|
|
151
|
+
const required = core.config.getOrThrow<z.infer<typeof AppSchema>>('app') // { port: 3000 };缺失则抛错。
|
|
152
|
+
core.logger.info('App config ready', { port: required.port, available: optional !== undefined })
|
|
153
|
+
}
|
|
154
|
+
core.config.keys() // 仅运行本节 load 示例时为 ['app']。
|
|
138
155
|
```
|
|
139
156
|
|
|
140
|
-
|
|
157
|
+
#### Reloading, watching, and cleanup
|
|
141
158
|
|
|
142
|
-
|
|
159
|
+
Use reload() to reread a file or watch() to receive new values and errors. Watching survives ordinary saves, atomic replacement, and file deletion/recreation. Failures retain the last successful cache. unwatch() stops watchers; clear() also removes the cache. Omitting the name affects all entries.
|
|
143
160
|
|
|
144
|
-
|
|
145
|
-
// 配置输出格式和级别(Node.js / Browser)
|
|
146
|
-
core.logger.configure({
|
|
147
|
-
level: 'info',
|
|
148
|
-
format: 'json', // 'json' | 'pretty'
|
|
149
|
-
context: { app: 'my-service' }, // 全局默认上下文
|
|
150
|
-
redact: ['password', 'token'], // 脱敏字段
|
|
151
|
-
})
|
|
161
|
+
watchConfig defaults to false. Reloading settings does not reinitialize running database modules. Use the cleanup calls below when the setting is no longer needed.
|
|
152
162
|
|
|
153
|
-
|
|
154
|
-
|
|
163
|
+
```ts
|
|
164
|
+
import { core } from '@h-ai/core'
|
|
165
|
+
|
|
166
|
+
// 前提:app 已由 init/load 加载。回调需先处理读取或校验失败。
|
|
167
|
+
const stop = core.config.watch('app', (_settings, error) => {
|
|
168
|
+
// 文件改成 port: 4000 后,成功回调收到 { port: 4000 }、error 为 undefined;失败时为 null 和错误对象。
|
|
169
|
+
if (error)
|
|
170
|
+
core.logger.error('Config reload failed', { error })
|
|
171
|
+
else
|
|
172
|
+
core.logger.info('Config reloaded')
|
|
173
|
+
})
|
|
174
|
+
// watch 返回取消函数 stop,不立即返回配置值。
|
|
175
|
+
core.config.isWatching('app') // true。
|
|
176
|
+
const reloaded = core.config.reload('app') // 文件仍为 port: 3000 时返回 { success: true, data: { port: 3000 } }。
|
|
177
|
+
if (!reloaded.success)
|
|
178
|
+
core.logger.warn('Manual reload failed', { error: reloaded.error })
|
|
179
|
+
|
|
180
|
+
stop() // 返回 undefined;取消当前回调,没有其他回调时停止底层监听。
|
|
181
|
+
core.config.unwatch('app') // 返回 undefined;isWatching('app') 变为 false。
|
|
182
|
+
core.config.clear('app') // 返回 undefined;get('app') 变为 undefined,has('app') 变为 false。
|
|
155
183
|
```
|
|
156
184
|
|
|
157
|
-
|
|
185
|
+
#### How environment variables change YAML settings
|
|
158
186
|
|
|
159
|
-
|
|
187
|
+
The framework derives environment override names from the configuration name and field path. For app.yml, port maps to HAI_APP_PORT and http.maxRetries maps to HAI_APP_HTTP_MAXRETRIES. Segments are uppercased and joined with underscores without splitting camelCase. YAML does not need a ${...} expression for this override to work.
|
|
160
188
|
|
|
161
|
-
|
|
189
|
+
For a fixed YAML value `port: 3000`, the result is 3000 without HAI_APP_PORT and 5000 after setting HAI_APP_PORT=5000.
|
|
162
190
|
|
|
163
|
-
|
|
191
|
+
Write `${VARIABLE}` in YAML to replace the expression with its environment value when loading. Text after the colon is the fallback when the variable is unset:
|
|
164
192
|
|
|
165
|
-
|
|
193
|
+
| YAML | Environment input | Result |
|
|
194
|
+
| ---------------------------- | ---------------------------- | ------------------------------------------------------- |
|
|
195
|
+
| `port: ${PORT}` | PORT=4000 | Uses 4000; an unset PORT returns CONFIG_ENV_VAR_MISSING |
|
|
196
|
+
| `port: ${PORT:3000}` | No PORT | Uses the expression's fallback, 3000 |
|
|
197
|
+
| `port: ${PORT:3000}` | PORT=4000, HAI_APP_PORT=5000 | Uses 5000: the convention variable wins |
|
|
198
|
+
| `label: server-${PORT:3000}` | PORT=4000 | Produces the string server-4000 |
|
|
166
199
|
|
|
167
|
-
|
|
168
|
-
| ------- | --------------------------------------------------- |
|
|
169
|
-
| `trace` | Detailed debugging data inside loops |
|
|
170
|
-
| `debug` | Function entry, parameter summaries, reads |
|
|
171
|
-
| `info` | Business events (initialized, write succeeded) |
|
|
172
|
-
| `warn` | Recoverable problems (validation failures, retries) |
|
|
173
|
-
| `error` | Operation failures requiring investigation |
|
|
174
|
-
| `fatal` | Fatal errors preventing continued service |
|
|
200
|
+
The loader first checks HAI_APP_PORT. If set, it replaces this field and does not evaluate its ${PORT...} expression. Otherwise it reads YAML: an expression looks up PORT, while a fixed value is used directly. Therefore PORT need not exist when HAI_APP_PORT already overrides the field.
|
|
175
201
|
|
|
176
|
-
|
|
202
|
+
Within one source, parent JSON can supply a base and child variables refine it. HAI_APP='{"port":3000,"label":"local"}' plus HAI_APP_PORT=4000 produces port=4000 and label=local regardless of line order. A higher-priority whole-object replacement removes lower-priority child overrides. Array JSON replaces the list; indexed variables only update existing items and out-of-range indexes fail.
|
|
177
203
|
|
|
178
|
-
|
|
204
|
+
#### Reading .env files
|
|
179
205
|
|
|
180
|
-
|
|
181
|
-
// 设置全局语言(所有 getMessage 函数自动响应)
|
|
182
|
-
core.i18n.setGlobalLocale('en-US')
|
|
183
|
-
const current = core.i18n.getGlobalLocale() // 'en-US'
|
|
206
|
+
core.init() does not read .env files. Call loadEnvFiles(), check success, assign its results to process.env, then load YAML. development/production map to dev/prod; missing files are skipped and duplicate keys in a file fail. Highest priority first: **process environment > `.env.<mode>.local` > `.env.local` > `.env.<mode>` > `.env` > YAML**. Keep private .local files out of Git.
|
|
184
207
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
'zh-CN': { welcome: '欢迎 {name}', error: '错误:{code}' },
|
|
188
|
-
'en-US': { welcome: 'Welcome {name}', error: 'Error: {code}' },
|
|
189
|
-
})
|
|
208
|
+
```ts
|
|
209
|
+
import { core } from '@h-ai/core'
|
|
190
210
|
|
|
191
|
-
//
|
|
192
|
-
|
|
211
|
+
// 前提:.env 写 HAI_APP_PORT=4000,没有其他来源覆盖这个变量。
|
|
212
|
+
// 先读取并合并 .env 文件与进程环境,失败时停止启动。
|
|
213
|
+
const result = core.config.loadEnvFiles({ mode: 'dev', envDir: '.' })
|
|
214
|
+
if (!result.success)
|
|
215
|
+
throw new Error(result.error.message, { cause: result.error })
|
|
216
|
+
// 成功时 result.success 为 true,result.data.HAI_APP_PORT 为 '4000';其他键来自合并后的环境。
|
|
217
|
+
// 返回值不会自动写入进程;显式应用后再初始化。
|
|
218
|
+
Object.assign(process.env, result.data)
|
|
219
|
+
core.init({ configDir: './config' }) // 返回 undefined;app.yml 中 port: 3000 被覆盖为数字 4000。
|
|
220
|
+
```
|
|
193
221
|
|
|
194
|
-
|
|
195
|
-
getMessage('welcome', { locale: 'zh-CN', params: { name: 'Alice' } }) // '欢迎 Alice'
|
|
222
|
+
#### What type does the replacement produce?
|
|
196
223
|
|
|
197
|
-
|
|
198
|
-
core.i18n.DEFAULT_LOCALES // [{ code: 'zh-CN', label: '简体中文' }, { code: 'en-US', label: 'English' }, { code: 'ja-JP', label: '日本語' }]
|
|
199
|
-
core.i18n.DEFAULT_LOCALE // 'zh-CN'
|
|
200
|
-
```
|
|
224
|
+
Environment variables start as text. Pass a Zod schema to `load()` / `resolve()` to convert replacements by field type: `z.number()` produces numbers, `z.boolean()` produces booleans, and `z.string()` preserves strings.
|
|
201
225
|
|
|
202
|
-
|
|
226
|
+
A full-value ${PORT:3000} can produce number 3000, and ${ENABLED:false} boolean false. Mixed text such as server-${PORT:3000} stays a string. A string field code preserves the fallback 00123 as '00123', including leading zeros. This example supplies the equivalent YAML values and environment in memory without reading a file:
|
|
203
227
|
|
|
204
|
-
|
|
228
|
+
```ts
|
|
229
|
+
import { core } from '@h-ai/core'
|
|
230
|
+
import { z } from 'zod'
|
|
205
231
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
232
|
+
// 用显式环境数据演示覆盖顺序、数值/布尔转换与字符串保留。
|
|
233
|
+
const AppSchema = z.object({ port: z.number(), enabled: z.boolean(), label: z.string(), code: z.string() })
|
|
234
|
+
const resolved = core.config.resolve({
|
|
235
|
+
name: 'app',
|
|
236
|
+
// eslint-disable-next-line no-template-curly-in-string -- 保留 YAML 中等待框架解析的字面表达式。
|
|
237
|
+
value: { port: '${PORT:3000}', enabled: '${ENABLED:false}', label: 'server-${PORT:3000}', code: '${APP_CODE:00123}' },
|
|
238
|
+
environment: { PORT: '4000', HAI_APP_PORT: '5000' },
|
|
239
|
+
schema: AppSchema,
|
|
212
240
|
})
|
|
213
|
-
|
|
241
|
+
if (!resolved.success)
|
|
242
|
+
throw new Error(resolved.error.message, { cause: resolved.error })
|
|
214
243
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
244
|
+
// resolved:{ success: true, data: { port: 5000, enabled: false, label: 'server-4000', code: '00123' } }。
|
|
245
|
+
|
|
246
|
+
// resolve 只做替换和类型还原;再用 Schema 确认最终数据符合要求。
|
|
247
|
+
const validated = AppSchema.safeParse(resolved.data)
|
|
248
|
+
if (!validated.success)
|
|
249
|
+
throw new Error(validated.error.message, { cause: validated.error })
|
|
250
|
+
core.logger.info('Config resolved', { settings: validated.data })
|
|
251
|
+
// settings: { port: 5000, enabled: false, label: 'server-4000', code: '00123' }
|
|
220
252
|
```
|
|
221
253
|
|
|
222
|
-
|
|
254
|
+
An empty string means the variable is set with no characters; it is not missing, null, false, or zero. APP_CODE='' leaves code as '' instead of using 00123. The schema decides whether this is allowed; numeric fields usually reject empty strings.
|
|
255
|
+
|
|
256
|
+
Substitution processes expressions in YAML; `server-${PORT}` inside an environment value or parent JSON remains literal text. For example, HAI_APP_LABEL='server-${PORT}' stays server-${PORT}. Put the expression in YAML when substitution is intended.
|
|
223
257
|
|
|
224
|
-
|
|
225
|
-
default English messages to the caller's own localized messages.
|
|
258
|
+
Without a schema, paths come from existing YAML/JSON structure and single expressions use YAML scalar rules for numbers/booleans. configSchemas can supply optional legal paths missing from YAML. Final business validation still belongs in validate() or module initialization.
|
|
226
259
|
|
|
227
|
-
|
|
260
|
+
#### Tools for generating configuration files
|
|
228
261
|
|
|
229
|
-
|
|
230
|
-
- `createPrefixedZodMessageGetter()`: derive keys such as `serv_validation*` / `kit_validation*` from module prefixes without a manual `KEY_MAP`.
|
|
231
|
-
- `mapZodErrorToFormErrors()`: extract, localize, and flatten in one step.
|
|
232
|
-
- Custom business messages are preserved; only Zod's default English messages are replaced.
|
|
262
|
+
resolve() also lets build/deploy tools calculate settings in memory. toEnv() converts objects to environment variables, mergeEnv() merges sources, and stringifyEnv()/parseEnv() encode/decode literal .env text. These tools do not mask secrets.
|
|
233
263
|
|
|
234
|
-
```
|
|
235
|
-
import type { ZodMessageGetter } from '@h-ai/core'
|
|
264
|
+
```ts
|
|
236
265
|
import { core } from '@h-ai/core'
|
|
237
|
-
import { z } from 'zod'
|
|
238
266
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
}
|
|
267
|
+
// 配置生成器把普通对象转成 HAI_APP_PORT 等变量;数组保留为 JSON。
|
|
268
|
+
const values = core.config.toEnv({ prefix: 'HAI_APP', value: { port: 3000, tags: ['local'] } })
|
|
269
|
+
// values:{ HAI_APP_PORT: '3000', HAI_APP_TAGS: '["local"]' }。
|
|
270
|
+
const merged = core.config.mergeEnv([values, { HAI_APP_PORT: '4000' }])
|
|
271
|
+
// merged:{ HAI_APP_PORT: '4000', HAI_APP_TAGS: '["local"]' }。
|
|
272
|
+
const text = core.config.stringifyEnv(merged) // 编码为可写入 .env 的文本。
|
|
273
|
+
// text 含以下两行,每行以换行符结尾:
|
|
274
|
+
// HAI_APP_PORT='4000'
|
|
275
|
+
// HAI_APP_TAGS='["local"]'
|
|
276
|
+
const restored = core.config.parseEnv(text) // 解析回字面字符串,不执行其中的变量。
|
|
277
|
+
// restored:{ HAI_APP_PORT: '4000', HAI_APP_TAGS: '["local"]' }。
|
|
278
|
+
core.logger.info('Generated config verified', { port: restored.HAI_APP_PORT })
|
|
279
|
+
```
|
|
244
280
|
|
|
245
|
-
|
|
246
|
-
switch (key) {
|
|
247
|
-
case 'validationEmail':
|
|
248
|
-
return '请输入合法邮箱地址'
|
|
249
|
-
case 'validationStringMin':
|
|
250
|
-
return `至少输入 ${params?.min} 个字符`
|
|
251
|
-
case 'validationRequired':
|
|
252
|
-
return '此项为必填项'
|
|
253
|
-
default:
|
|
254
|
-
return '输入不合法'
|
|
255
|
-
}
|
|
256
|
-
}
|
|
281
|
+
Plain objects expand by default; arrays, dynamic dictionaries, and empty objects retain JSON. See the [runtime configuration guide](../../docs/usage/configuration/runtime.md) for replacement generation rules, full precedence, and application integration.
|
|
257
282
|
|
|
258
|
-
|
|
259
|
-
email: 'bad',
|
|
260
|
-
password: '123',
|
|
261
|
-
nickname: '',
|
|
262
|
-
})
|
|
283
|
+
### Logging: `core.logger`
|
|
263
284
|
|
|
264
|
-
|
|
265
|
-
const getMessage = core.zodValidation.createPrefixedZodMessageGetter(
|
|
266
|
-
'kit',
|
|
267
|
-
(messageKey, params) => {
|
|
268
|
-
if (messageKey === 'kit_validationEmail')
|
|
269
|
-
return '请输入合法邮箱地址'
|
|
270
|
-
if (messageKey === 'kit_validationStringMin')
|
|
271
|
-
return `至少输入 ${params?.min} 个字符`
|
|
272
|
-
return '输入不合法'
|
|
273
|
-
},
|
|
274
|
-
)
|
|
275
|
-
const errors = core.zodValidation.mapZodErrorToFormErrors(result.error, getMessage)
|
|
276
|
-
|
|
277
|
-
errors[0]?.field // 'email'
|
|
278
|
-
errors[0]?.message // '请输入合法邮箱地址'
|
|
279
|
-
errors[2]?.message // '请填写昵称'(schema 自定义消息原样保留)
|
|
285
|
+
core.logger records structured logs. Levels progress from detail to severity: trace, debug, info, warn, error, fatal. fatal records a log; the application decides whether to exit.
|
|
280
286
|
|
|
281
|
-
|
|
282
|
-
|
|
287
|
+
`core.logger` supports `trace` / `debug` / `info` / `warn` / `error` / `fatal`. Node uses pino and browsers use loglevel. Unconfigured loggers default to `info` / `pretty`; a `logging` object parsed by `LoggingConfigSchema` defaults its format to `json`. Node falls back to JSON when optional `pino-pretty` is unavailable.
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
import { core } from '@h-ai/core'
|
|
291
|
+
|
|
292
|
+
// 先设置级别;低于当前级别的日志不会输出。
|
|
293
|
+
core.logger.setLevel('trace') // 返回 undefined;以下六个级别均会输出。
|
|
294
|
+
core.logger.trace('Processing detail', { step: 1 })
|
|
295
|
+
core.logger.debug('Read started')
|
|
296
|
+
core.logger.info('Order created', { orderId: 'order-1' })
|
|
297
|
+
core.logger.warn('Retry scheduled')
|
|
298
|
+
core.logger.error('Operation failed', { error: new Error('Example failure') })
|
|
299
|
+
core.logger.fatal('Service cannot continue')
|
|
300
|
+
// 六次日志调用均返回 undefined;分别输出对应级别、上面的消息及所传字段。
|
|
301
|
+
// 例如 info 日志的消息为 'Order created',字段 orderId 为 'order-1'。
|
|
283
302
|
```
|
|
284
303
|
|
|
285
|
-
|
|
304
|
+
create() makes a named logger; child() attaches fixed context. configure() sets output and extra redaction paths; setLevel()/getLevel() change or inspect the global level.
|
|
286
305
|
|
|
287
|
-
|
|
306
|
+
```ts
|
|
307
|
+
import { core } from '@h-ai/core'
|
|
288
308
|
|
|
289
|
-
|
|
309
|
+
// 全局配置可作用于已经创建的 Logger;redact 补充业务隐私字段。
|
|
310
|
+
core.logger.configure({ level: 'info', format: 'json', redact: ['customer.email'] }) // 返回 undefined;后续日志按此配置输出。
|
|
311
|
+
const orders = core.logger.create({ name: 'orders' }) // 返回 Logger 对象,可调用 info/warn 等方法。
|
|
312
|
+
const request = core.logger.child({ requestId: 'request-1' }) // 返回带固定 requestId 的 Logger。
|
|
313
|
+
orders.info('Order created', { customer: { email: 'user@example.com' } }) // 返回 undefined;输出中 customer.email 为 '[REDACTED]'。
|
|
314
|
+
request.warn('Request needs attention') // 返回 undefined;输出中 requestId 为 'request-1'。
|
|
315
|
+
core.logger.getLevel() // 'info'。
|
|
316
|
+
```
|
|
290
317
|
|
|
291
|
-
|
|
292
|
-
import { core, HaiConfigError } from '@h-ai/core'
|
|
293
|
-
import { z } from 'zod'
|
|
318
|
+
Existing default, module, and nested child loggers use current global settings on subsequent writes; `setLevel()` also takes effect immediately. Explicit `create()` level/format/context options take precedence; unspecified options inherit dynamically. Per-call context overrides fixed context, then `core.context` adds current request correlation fields. Browser JSON includes `level` / `msg`; pretty output includes readable text and context.
|
|
294
319
|
|
|
295
|
-
|
|
296
|
-
core.init({
|
|
297
|
-
configDir: './config', // 扫描配置目录内所有 .yml / .yaml
|
|
298
|
-
watchConfig: true, // 监听变更并自动重载
|
|
299
|
-
})
|
|
320
|
+
observe() supports diagnostics collection, receiving records after level filtering and masking and returning an unsubscribe function. Collect bounded memory data in the callback and persist asynchronously elsewhere. Observation is not persistence; exceptions and synchronous reentry are isolated.
|
|
300
321
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
name: z.string(),
|
|
304
|
-
port: z.number().default(3000),
|
|
305
|
-
})
|
|
306
|
-
const result = core.config.load('app', './config/app.yml', AppSchema)
|
|
307
|
-
if (result.success) {
|
|
308
|
-
core.logger.info('Config loaded', { name: result.data.name })
|
|
309
|
-
}
|
|
310
|
-
else {
|
|
311
|
-
core.logger.error('Config load failed', { code: result.error.code })
|
|
312
|
-
}
|
|
322
|
+
```ts
|
|
323
|
+
import { core } from '@h-ai/core'
|
|
313
324
|
|
|
314
|
-
//
|
|
315
|
-
const
|
|
325
|
+
// 观察经过级别过滤和脱敏的记录;内存收集设置上限。
|
|
326
|
+
const recentMessages: string[] = []
|
|
327
|
+
const stop = core.logger.observe((record) => {
|
|
328
|
+
if (recentMessages.length === 100)
|
|
329
|
+
recentMessages.shift()
|
|
330
|
+
recentMessages.push(record.message)
|
|
331
|
+
})
|
|
332
|
+
// observe 返回取消函数 stop;本例 warn 日志触发一次回调,record.message 为 'Observed event'。
|
|
333
|
+
core.logger.warn('Observed event')
|
|
334
|
+
recentMessages // ['Observed event']。
|
|
335
|
+
stop() // 返回 undefined;后续日志不再进入这个回调。
|
|
336
|
+
```
|
|
316
337
|
|
|
317
|
-
|
|
318
|
-
if (core.config.has('app')) {
|
|
319
|
-
const cfg = core.config.get<z.infer<typeof AppSchema>>('app') // undefined 或配置
|
|
320
|
-
const cfg2 = core.config.getOrThrow<z.infer<typeof AppSchema>>('app') // 未加载时抛异常
|
|
321
|
-
}
|
|
322
|
-
core.config.keys() // ['core', 'app', 'db', ...]
|
|
338
|
+
### Request correlation: `core.context`
|
|
323
339
|
|
|
324
|
-
|
|
325
|
-
const reloadResult = core.config.reload('app')
|
|
340
|
+
run() gives a request/task its requestId, userId, scopeId, jobId, and other correlation fields; get() reads them. On Node they remain available after database or other asynchronous work, without another request overwriting them. Existing loggers automatically include these fields.
|
|
326
341
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
if (error) {
|
|
330
|
-
core.logger.error('Config reload failed', { error })
|
|
331
|
-
return
|
|
332
|
-
}
|
|
333
|
-
core.logger.info('Config updated', { config: newConfig })
|
|
334
|
-
})
|
|
335
|
-
unwatch() // 取消监听
|
|
342
|
+
```ts
|
|
343
|
+
import { core } from '@h-ai/core'
|
|
336
344
|
|
|
337
|
-
//
|
|
338
|
-
core.
|
|
339
|
-
core.
|
|
345
|
+
// Node 示例:同一请求等待异步处理后,仍能取得自己的编号。
|
|
346
|
+
await core.context.run({ requestId: 'request-1', userId: 'user-1' }, async () => {
|
|
347
|
+
await core.async.delay(1)
|
|
348
|
+
const current = core.context.get() // 包含 requestId: 'request-1'、traceId: 'request-1'、userId: 'user-1';其他字段为 undefined。
|
|
349
|
+
core.logger.info('Request continued', { requestId: current.requestId })
|
|
350
|
+
return current.requestId
|
|
351
|
+
}) // run 返回回调的结果;此处 await 后得到 'request-1'。
|
|
352
|
+
core.context.get() // {},回到外层后不保留上面请求的上下文。
|
|
353
|
+
|
|
354
|
+
// 采集器自身写日志时,可暂停观察回调,正常日志输出仍然执行。
|
|
355
|
+
core.context.run({ suppressLogObservers: true }, () => core.logger.warn('Collector diagnostic'))
|
|
356
|
+
// 返回 undefined;输出 warn 日志,但不会触发日志观察回调。
|
|
340
357
|
```
|
|
341
358
|
|
|
342
|
-
|
|
359
|
+
In browsers values exist only in synchronous callback code and are not retained after await. Correlation IDs do not authorize access; trusted server code must provide identity and tenant scope.
|
|
360
|
+
|
|
361
|
+
### Cleaning diagnostic data: `core.sanitize`
|
|
343
362
|
|
|
344
|
-
|
|
363
|
+
Clean credentials before logs, diagnostic exports, or public errors. Check sensitive names, mask a single value or object tree, clean URL credentials, or remove labeled/known secrets from text.
|
|
345
364
|
|
|
346
365
|
```ts
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
core.
|
|
366
|
+
import { core } from '@h-ai/core'
|
|
367
|
+
|
|
368
|
+
core.sanitize.isSensitiveKey('apiKey') // true。
|
|
369
|
+
core.sanitize.sanitizeSensitiveValue('example-only', 'password') // '[REDACTED]'。
|
|
370
|
+
const safe = core.sanitize.sanitizeSensitiveFields({ password: 'example-only', email: 'user@example.com' })
|
|
371
|
+
// safe:{ password: '[REDACTED]', email: 'user@example.com' },原对象不变。
|
|
372
|
+
// 默认仅遮蔽凭据;额外业务隐私可在已处理凭据的副本上继续清理。
|
|
373
|
+
core.sanitize.sanitizeSensitiveFields(safe, { matcher: ['email'], replacement: '***' })
|
|
374
|
+
// => { password: '[REDACTED]', email: '***' }
|
|
375
|
+
core.sanitize.sanitizeUrl('https://user:example-only@example.com/?token=example-only')
|
|
376
|
+
// => 'https://[REDACTED]:[REDACTED]@example.com/?token=[REDACTED]'
|
|
377
|
+
core.sanitize.sanitizeText('Bearer example-only') // '[REDACTED]'。
|
|
378
|
+
core.sanitize.sanitizeText('Request failed with a known private value', ['private value'])
|
|
379
|
+
// => 'Request failed with a known [REDACTED]'
|
|
352
380
|
```
|
|
353
381
|
|
|
354
|
-
|
|
382
|
+
defaultSensitiveKeyRegex/defaultSensitiveReplacement expose the default matching rule and [REDACTED] value. A custom matcher replaces the default rule, so retain default credential masking before applying extra business privacy rules.
|
|
355
383
|
|
|
356
|
-
`
|
|
357
|
-
environment variable named `HAI_<CONFIG_NAME>_<YAML_PATH>`. Configuration names and keys are uppercased, levels are separated by `_`,
|
|
358
|
-
and camelCase is not split. For example, `ai.llm.apiKey` maps to `HAI_AI_LLM_APIKEY`,
|
|
359
|
-
and `ai.llm.maxTokens` to `HAI_AI_LLM_MAXTOKENS`. Array indexes are also levels:
|
|
360
|
-
`ai.llm.models[0].temperature` maps to `HAI_AI_LLM_MODELS_0_TEMPERATURE`.
|
|
384
|
+
Logs mask credential fields such as password/passwordHash, token, secretKey, and privateKey, plus URL userinfo, sensitive query parameters, and OAuth key-value fragments. Invalid URLs return `(invalid url)`. `redact` adds business privacy paths using dots, brackets, and single-level `*`, case sensitively. Email addresses and phone numbers remain visible by default.
|
|
361
385
|
|
|
362
|
-
|
|
363
|
-
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.
|
|
386
|
+
Native `Error` values are copied with name/message/stack/cause, aggregate errors, and enumerable context before masking; originals are unchanged. Error-subgraph cycles and the 32-level depth limit use `[Circular]` / `[MaxDepth]`. Ordinary object cycles remain and may prevent JSON serialization. Message and error text masking handles explicit credential labels and URLs, not arbitrary unlabeled secrets; callers must clean these or redact the whole path.
|
|
364
387
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
388
|
+
Masked results contain data only. Plain objects and class instances contribute their own enumerable data properties; prototypes, accessors, and custom `toJSON()` methods are not retained or invoked. Dates become ISO strings and URLs become masked strings, without changing the original. Still select only useful diagnostic fields from SDK/business objects and explicitly clean unlabeled secrets and business privacy data.
|
|
389
|
+
|
|
390
|
+
### Results and errors: `core.error`
|
|
391
|
+
|
|
392
|
+
core.error defines module errors, creates failure instances, and builds safe HTTP/UI messages. Codes stay stable and messages can follow the current locale. Serv/Kit or another HTTP framework handles response status and headers.
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
import { core } from '@h-ai/core'
|
|
396
|
+
|
|
397
|
+
// 定义稳定错误码,消息在创建实例时根据当前语言获取。
|
|
398
|
+
const OrderError = core.error.buildHaiErrorsDef('orders', { NOT_FOUND: '300:404' })
|
|
399
|
+
// OrderError.NOT_FOUND:{ code: 'hai:orders:300', httpStatus: 404, system: 'hai', module: 'orders' }。
|
|
400
|
+
const failure = core.error.buildHaiErrorInst(OrderError.NOT_FOUND, core.i18n.coreM('core_errorNotFound', { locale: 'zh-CN' }))
|
|
401
|
+
// failure:上面的错误定义加上 message: '资源不存在'。
|
|
402
|
+
const publicError = core.error.toPublic(failure, 'request-1')
|
|
403
|
+
// publicError:保留 code/httpStatus/system/module,增加 traceId: 'request-1';
|
|
404
|
+
// message 为 '资源不存在 (traceId: request-1)'。
|
|
405
|
+
const message = core.error.formatMessage(publicError) // '资源不存在 (traceId: request-1)',编号不会重复追加。
|
|
406
|
+
core.logger.warn('Order unavailable', { error: failure, publicMessage: message })
|
|
372
407
|
```
|
|
373
408
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
409
|
+
#### Shared result type and standalone constructors
|
|
410
|
+
|
|
411
|
+
`HaiResult<T>` uses success to distinguish data from error. Import `ok` / `err` to construct successful or failed results. Check success after business operations. Getters, utilities, and factories follow their direct-value or throwing signatures.
|
|
412
|
+
|
|
413
|
+
```ts
|
|
414
|
+
import type { HaiResult } from '@h-ai/core'
|
|
415
|
+
import { core, err, HaiCommonError, ok } from '@h-ai/core'
|
|
416
|
+
|
|
417
|
+
// 业务失败返回 err,成功返回 ok;共用构造器保持独立导入。
|
|
418
|
+
function divide(a: number, b: number): HaiResult<number> {
|
|
419
|
+
if (b === 0)
|
|
420
|
+
return err(HaiCommonError.VALIDATION_ERROR, core.i18n.coreM('core_errorValidation', { locale: 'zh-CN' }))
|
|
421
|
+
return ok(a / b) // 如 ok(5) 返回 { success: true, data: 5 }。
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// 先检查 success,再读取 data 或 error。
|
|
425
|
+
const result = divide(10, 2) // { success: true, data: 5 }。
|
|
426
|
+
if (!result.success)
|
|
427
|
+
core.logger.warn('Calculation failed', { error: result.error })
|
|
428
|
+
else
|
|
429
|
+
core.logger.info('Calculation completed', { value: result.data })
|
|
430
|
+
|
|
431
|
+
const failed = divide(10, 0)
|
|
432
|
+
// failed:{ success: false, error: { code: 'hai:common:200', httpStatus: 400,
|
|
433
|
+
// system: 'hai', module: 'common', message: '验证失败' } },无 data。
|
|
434
|
+
if (!failed.success)
|
|
435
|
+
core.logger.warn('Calculation rejected', { code: failed.error.code })
|
|
377
436
|
```
|
|
378
437
|
|
|
379
|
-
|
|
380
|
-
Convention-based environment variables > explicit environment variables > YAML defaults.
|
|
438
|
+
Use `core.error.toPublic(error, traceId?, locale?)` at HTTP/UI boundaries. It replaces 5xx details with a localized generic message, removes known credentials from other messages, and retains safe fields. Correlation IDs are selected from the explicit argument, context traceId/requestId, or the error's traceId, otherwise generated. `formatMessage()` appends a valid ID without duplicating the same suffix.
|
|
381
439
|
|
|
382
|
-
|
|
383
|
-
- `${VAR:default}`: read `process.env.VAR`; use the value after the colon if absent.
|
|
440
|
+
Internal `cause` / `ext` are private by default. Field errors for 400/422 can retain `field` / `message`; explicitly approved, business-schema-validated `publicExt` is masked and exposed as `ext`. Core does not validate its business safety automatically. Serv/Kit/UI hosts handle HTTP status, headers, and message components.
|
|
384
441
|
|
|
385
|
-
|
|
442
|
+
| Configuration error | Code | Meaning |
|
|
443
|
+
| ------------------------- | -------------- | -------------------------------------------- |
|
|
444
|
+
| `CONFIG_FILE_NOT_FOUND` | `hai:core:010` | Missing file |
|
|
445
|
+
| `CONFIG_PARSE_ERROR` | `hai:core:011` | YAML/dotenv reading or parsing failed |
|
|
446
|
+
| `CONFIG_VALIDATION_ERROR` | `hai:core:012` | Invalid schema input or environment override |
|
|
447
|
+
| `CONFIG_ENV_VAR_MISSING` | `hai:core:013` | Required interpolation variable missing |
|
|
448
|
+
| `CONFIG_NOT_LOADED` | `hai:core:014` | Configuration not loaded |
|
|
386
449
|
|
|
387
|
-
|
|
450
|
+
These constants belong to `HaiConfigError`; cross-module failures use `HaiCommonError`.
|
|
388
451
|
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
url: http://${HOST}:${PORT} # → string(混合文本)
|
|
395
|
-
```
|
|
396
|
-
|
|
397
|
-
#### ID generation
|
|
398
|
-
|
|
399
|
-
```typescript
|
|
400
|
-
const id = core.id.generate() // nanoid 21 字符
|
|
401
|
-
const id8 = core.id.generate(8) // 自定义长度
|
|
402
|
-
const shortId = core.id.short() // 10 字符短 ID
|
|
403
|
-
const prefixed = core.id.withPrefix('user_') // 'user_V1StGXR...'
|
|
404
|
-
const traceId = core.id.trace() // 'trace-V1StGXR...'
|
|
405
|
-
const reqId = core.id.request() // 'req-V1StGXR...'
|
|
406
|
-
const uuid = core.id.uuid() // UUID v4
|
|
407
|
-
|
|
408
|
-
// 校验
|
|
409
|
-
core.id.isValidUUID('f47ac10b-...') // true/false
|
|
410
|
-
core.id.isValidNanoId('abc123', 6) // true/false
|
|
411
|
-
```
|
|
412
|
-
|
|
413
|
-
UUID generation requires cryptographic randomUUID/getRandomValues and throws if neither is available; it never falls back to Math.random.
|
|
414
|
-
|
|
415
|
-
#### Utilities
|
|
416
|
-
|
|
417
|
-
```typescript
|
|
418
|
-
// 类型检查
|
|
419
|
-
core.typeUtils.isDefined(x) // x !== undefined
|
|
420
|
-
core.typeUtils.isObject(x) // plain object
|
|
421
|
-
core.typeUtils.isFunction(x)
|
|
422
|
-
core.typeUtils.isPromise(x)
|
|
423
|
-
core.typeUtils.isString(x)
|
|
424
|
-
core.typeUtils.isNumber(x)
|
|
425
|
-
core.typeUtils.isBoolean(x)
|
|
426
|
-
core.typeUtils.isArray(x)
|
|
427
|
-
|
|
428
|
-
// 对象操作
|
|
429
|
-
core.object.deepClone(obj)
|
|
430
|
-
core.object.deepMerge(a, b) // 递归合并(防原型污染)
|
|
431
|
-
core.object.deepMerge(a, b, c) // 支持多个对象
|
|
432
|
-
core.object.pick(obj, ['a', 'b'])
|
|
433
|
-
core.object.omit(obj, ['c', 'd'])
|
|
434
|
-
core.object.keys(obj) // typed Object.keys
|
|
435
|
-
core.object.values(obj)
|
|
436
|
-
core.object.entries(obj)
|
|
437
|
-
core.object.fromEntries(entries)
|
|
438
|
-
|
|
439
|
-
// 字符串操作
|
|
440
|
-
core.string.capitalize('hello') // 'Hello'
|
|
441
|
-
core.string.kebabCase('helloWorld') // 'hello-world'
|
|
442
|
-
core.string.camelCase('hello-world') // 'helloWorld'
|
|
443
|
-
core.string.snakeCase('helloWorld') // 'hello_world'
|
|
444
|
-
core.string.pascalCase('hello-world') // 'HelloWorld'
|
|
445
|
-
core.string.truncate('long text', 5) // 'long ...'
|
|
446
|
-
core.string.trim(' hello ') // 'hello'
|
|
447
|
-
core.string.isBlank('') // true
|
|
448
|
-
core.string.isNotBlank('x') // true
|
|
449
|
-
core.string.padStart('5', 3, '0') // '005'
|
|
450
|
-
core.string.padEnd('5', 3, '0') // '500'
|
|
451
|
-
core.string.constantTimeEqual(a, b) // Node 使用原生等长比较;浏览器不保证恒时
|
|
452
|
-
|
|
453
|
-
// 数组操作
|
|
454
|
-
core.array.unique([1, 1, 2]) // [1, 2]
|
|
455
|
-
core.array.chunk([1, 2, 3, 4], 2) // [[1,2], [3,4]]
|
|
456
|
-
core.array.groupBy(items, item => item.type) // Record<string, T[]>
|
|
457
|
-
core.array.first([1, 2, 3]) // 1
|
|
458
|
-
core.array.last([1, 2, 3]) // 3
|
|
459
|
-
core.array.flatten([[1], [2, 3]]) // [1, 2, 3]
|
|
460
|
-
core.array.compact([1, null, 2]) // [1, 2]
|
|
461
|
-
core.array.shuffle([1, 2, 3]) // 随机排列
|
|
462
|
-
core.array.intersection([1, 2], [2, 3]) // [2]
|
|
463
|
-
core.array.difference([1, 2], [2, 3]) // [1]
|
|
464
|
-
|
|
465
|
-
// 异步操作
|
|
466
|
-
await core.async.delay(1000)
|
|
467
|
-
await core.async.withTimeout(fetch('/api'), 5000)
|
|
468
|
-
await core.async.retry(fn, { maxRetries: 3, delay: 1000 })
|
|
469
|
-
await core.async.parallel(items, processFn, 5) // 并发限制
|
|
470
|
-
await core.async.serial(items, processFn)
|
|
471
|
-
const debouncedFn = core.async.debounce(fn, 300)
|
|
472
|
-
const throttledFn = core.async.throttle(fn, 200)
|
|
473
|
-
|
|
474
|
-
// 时间操作
|
|
475
|
-
core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
|
|
476
|
-
core.time.timeAgo(new Date(Date.now() - 60000)) // '1 分钟前'
|
|
477
|
-
core.time.now() // Date.now()
|
|
478
|
-
core.time.nowSeconds() // Math.floor(Date.now() / 1000)
|
|
479
|
-
core.time.parseDate('2024-01-01')
|
|
480
|
-
core.time.isValidDate(date)
|
|
481
|
-
core.time.addDays(date, 7)
|
|
482
|
-
core.time.addHours(date, 2)
|
|
483
|
-
core.time.startOfDay(date)
|
|
484
|
-
core.time.endOfDay(date)
|
|
485
|
-
```
|
|
486
|
-
|
|
487
|
-
The Node entry uses node:crypto.timingSafeEqual over equal-length UTF-16LE code units. Different lengths return false; length is not hidden. The browser implementation avoids content-based early returns but has no JavaScript-engine timing guarantee and is not a server credential boundary. Surrounding branches, encoding and request handling are not made timing-safe by this helper.
|
|
488
|
-
|
|
489
|
-
#### Module utilities (module)
|
|
490
|
-
|
|
491
|
-
Shared initialization error handling for modules:
|
|
492
|
-
|
|
493
|
-
```typescript
|
|
452
|
+
### Messages and locales: `core.i18n`
|
|
453
|
+
|
|
454
|
+
Create message getters with parameter interpolation, read built-in Core messages, and manage locale selection. Constants list framework locales and do not register application translations.
|
|
455
|
+
|
|
456
|
+
```ts
|
|
494
457
|
import { core } from '@h-ai/core'
|
|
495
458
|
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
)
|
|
459
|
+
// 页面语言或服务进程的启动默认值;请求中使用 runWithLocale 单独选择语言。
|
|
460
|
+
core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;后续默认消息使用中文。
|
|
461
|
+
core.i18n.getGlobalLocale() // 'zh-CN'。
|
|
462
|
+
core.i18n.coreM('core_errorNotFound') // '资源不存在'。
|
|
463
|
+
core.i18n.DEFAULT_LOCALE // zh-CN。
|
|
464
|
+
core.i18n.DEFAULT_LOCALES // [{ code: 'zh-CN', label: '简体中文' }, { code: 'en-US', label: 'English' }, { code: 'ja-JP', label: '日本語' }]。
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
Message locales are `zh-CN`, `en-US`, and `ja-JP`; `zh` / `en` / `ja` aliases are normalized. Explicit locale takes priority over Node request locale and then the application default. Unsupported locales fall back to `zh-CN`; missing keys return the key itself.
|
|
468
|
+
|
|
469
|
+
```ts
|
|
470
|
+
import { core } from '@h-ai/core'
|
|
500
471
|
|
|
501
|
-
//
|
|
502
|
-
const
|
|
503
|
-
|
|
504
|
-
|
|
472
|
+
// 业务字典按语言组织;占位参数在取消息时传入。
|
|
473
|
+
const message = core.i18n.createMessageGetter({
|
|
474
|
+
'zh-CN': { welcome: '欢迎 {name}' },
|
|
475
|
+
'en-US': { welcome: 'Welcome {name}' },
|
|
476
|
+
'ja-JP': { welcome: 'ようこそ {name}' },
|
|
477
|
+
})
|
|
478
|
+
// createMessageGetter 返回消息函数;如 message('welcome', { locale: 'zh-CN', params: { name: 'Alice' } }) 得到 '欢迎 Alice'。
|
|
479
|
+
const greeting = await core.i18n.runWithLocale('en-US', async () => {
|
|
480
|
+
await Promise.resolve()
|
|
481
|
+
return message('welcome', { params: { name: 'Alice' } })
|
|
482
|
+
})
|
|
483
|
+
// greeting:'Welcome Alice';runWithLocale 返回回调的结果,此处等待 Promise 得到字符串。
|
|
484
|
+
core.logger.info('Greeting prepared', { greeting })
|
|
505
485
|
```
|
|
506
486
|
|
|
507
|
-
|
|
487
|
+
Wrap actual asynchronous Node request/SSR work in `runWithLocale()`. Serv establishes the request locale automatically; Kit provides the same entry point. Within a request, `setGlobalLocale()` changes only that request. Outside it, use it only for startup defaults. Browsers use application-level `setGlobalLocale()` or explicit locales. SSR UI stores should not modify process defaults.
|
|
508
488
|
|
|
509
|
-
|
|
489
|
+
### Field validation messages: `core.zodValidation`
|
|
510
490
|
|
|
511
|
-
|
|
491
|
+
Convert Zod errors into { field, message }[] for form hints. createPrefixedZodMessageGetter() selects translation keys by prefix; mapZodErrorToFormErrors() extracts, translates, and flattens field paths.
|
|
512
492
|
|
|
513
|
-
```
|
|
514
|
-
import
|
|
515
|
-
import {
|
|
493
|
+
```ts
|
|
494
|
+
import { core } from '@h-ai/core'
|
|
495
|
+
import { z } from 'zod'
|
|
516
496
|
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
497
|
+
// 此例复用 Core 已有翻译;业务表单可注入自己的消息获取器。
|
|
498
|
+
const message = core.zodValidation.createPrefixedZodMessageGetter('core', key =>
|
|
499
|
+
key === 'core_validationEmail'
|
|
500
|
+
? core.i18n.coreM('core_validationEmail', { locale: 'zh-CN' })
|
|
501
|
+
: core.i18n.coreM('core_errorValidation', { locale: 'zh-CN' }))
|
|
502
|
+
// 返回消息函数;message('validationEmail') 得到 '请输入有效的邮箱地址'。
|
|
503
|
+
const parsed = z.object({ email: z.email() }).safeParse({ email: 'invalid' })
|
|
504
|
+
if (!parsed.success) {
|
|
505
|
+
const errors = core.zodValidation.mapZodErrorToFormErrors(parsed.error, message)
|
|
506
|
+
// errors:[{ field: 'email', message: '请输入有效的邮箱地址' }]。
|
|
507
|
+
core.logger.info('Validation failed', { errors })
|
|
521
508
|
}
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
Supports Zod v3/v4 issues/errors. Default English messages are translated; explicit business messages remain unchanged. Paths use dots and global errors use _. Unknown fields in strict schemas use validationUnexpectedFields without exposing internal names.
|
|
512
|
+
|
|
513
|
+
### Module startup and helpers: `core.module`
|
|
514
|
+
|
|
515
|
+
Applications and module implementations can reuse these helpers to manage several modules or return consistent failures before initialization. The application chooses its actual modules.
|
|
516
|
+
|
|
517
|
+
#### Application startup and shutdown
|
|
518
|
+
|
|
519
|
+
Applications using several modules need to initialize resources such as databases before handling business work, then release them afterward. `core.module.createRuntime()` accepts each module's startup and cleanup functions and returns an object the application can call. Creating it does not start the modules.
|
|
522
520
|
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
521
|
+
This local development example additionally requires `@h-ai/reldb` and `@h-ai/cache`. Both use in-memory settings for demonstration; production must use the shared backends required by each module.
|
|
522
|
+
|
|
523
|
+
```ts
|
|
524
|
+
import { cache } from '@h-ai/cache'
|
|
525
|
+
import { core } from '@h-ai/core'
|
|
526
|
+
import { reldb } from '@h-ai/reldb'
|
|
527
|
+
|
|
528
|
+
// 按需要的启动顺序,列出各模块的初始化和关闭函数。
|
|
529
|
+
const runtime = core.module.createRuntime([
|
|
530
|
+
{
|
|
531
|
+
name: 'database',
|
|
532
|
+
start: () => reldb.init({ type: 'sqlite', database: ':memory:' }),
|
|
533
|
+
close: () => reldb.close(),
|
|
534
|
+
},
|
|
535
|
+
{
|
|
536
|
+
name: 'cache',
|
|
537
|
+
start: () => cache.init({ type: 'memory' }),
|
|
538
|
+
close: () => cache.close(),
|
|
539
|
+
},
|
|
540
|
+
])
|
|
541
|
+
|
|
542
|
+
// createRuntime 返回带 start()/close() 的对象;到这里数据库和缓存尚未启动。
|
|
543
|
+
|
|
544
|
+
// 依次启动数据库、缓存;失败时自动清理已尝试启动的模块。
|
|
545
|
+
const started = await runtime.start() // 成功为 { success: true, data: undefined };两个模块均已初始化。
|
|
546
|
+
if (!started.success)
|
|
547
|
+
throw new Error(started.error.message, { cause: started.error })
|
|
548
|
+
|
|
549
|
+
try {
|
|
550
|
+
// 启动成功后再执行应用业务;这里演示记录启动结果。
|
|
551
|
+
core.logger.info('Application modules ready')
|
|
526
552
|
}
|
|
527
|
-
|
|
528
|
-
|
|
553
|
+
finally {
|
|
554
|
+
// 演示结束后先关闭缓存,再关闭数据库,并检查清理结果。
|
|
555
|
+
const closed = await runtime.close() // 成功为 { success: true, data: undefined };两个模块均已关闭。
|
|
556
|
+
if (!closed.success)
|
|
557
|
+
core.logger.error('Application cleanup failed', { error: closed.error })
|
|
529
558
|
}
|
|
530
559
|
```
|
|
531
560
|
|
|
532
|
-
|
|
561
|
+
Startup here is database → cache; shutdown is cache → database. This demonstration cleans up immediately afterward. A long-running service should call the same `runtime.close()` when exiting.
|
|
533
562
|
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
563
|
+
A startup failure cleans up modules whose startup was attempted. A shutdown failure stops cleanup at that module and retains dependencies it still needs; the next `close()` or `start()` retries cleanup. Simultaneous `start()` calls do not initialize twice. An optional `enabled()` returning false skips its step.
|
|
564
|
+
|
|
565
|
+
Both methods return `HaiResult`; check `success`. Errors include the module, phase, code, and necessary configuration field hints while keeping configuration secrets and raw SDK exceptions out of public startup errors.
|
|
537
566
|
|
|
538
|
-
|
|
539
|
-
const DbErrorInfo = {
|
|
540
|
-
NOT_INITIALIZED: '001:500',
|
|
541
|
-
CONNECTION_FAILED: '010:500',
|
|
542
|
-
QUERY_FAILED: '011:500',
|
|
543
|
-
} as const satisfies ErrorInfo
|
|
567
|
+
#### Returning errors before initialization
|
|
544
568
|
|
|
545
|
-
|
|
546
|
-
export const DbError = core.error.buildHaiErrorsDef('db', DbErrorInfo)
|
|
547
|
-
// DbError.CONNECTION_FAILED → { code: 'hai:db:010', httpStatus: 500, system: 'hai', module: 'db' }
|
|
569
|
+
createNotInitializedKit() provides error/result/proxy forms. Proxies return a consistent sync/async failure until the implementation switches to real operations. The message function reads the locale at call time.
|
|
548
570
|
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
'
|
|
555
|
-
|
|
571
|
+
```ts
|
|
572
|
+
import type { HaiResult } from '@h-ai/core'
|
|
573
|
+
import { core, HaiCommonError } from '@h-ai/core'
|
|
574
|
+
|
|
575
|
+
const message = core.i18n.createMessageGetter({
|
|
576
|
+
'zh-CN': { notReady: '请先初始化模块' },
|
|
577
|
+
'en-US': { notReady: 'Initialize the module first' },
|
|
578
|
+
'ja-JP': { notReady: '先にモジュールを初期化してください' },
|
|
579
|
+
})
|
|
580
|
+
// 本例固定使用中文消息,便于观察返回值。
|
|
581
|
+
core.i18n.setGlobalLocale('zh-CN') // 返回 undefined。
|
|
582
|
+
const waiting = core.module.createNotInitializedKit(HaiCommonError.NOT_INITIALIZED, () => message('notReady'))
|
|
583
|
+
// waiting 是带 error/result/proxy 的对象。
|
|
584
|
+
waiting.error() // { code: 'hai:common:001', httpStatus: 500, system: 'hai', module: 'common', message: '请先初始化模块' }。
|
|
585
|
+
waiting.result<string>() // { success: false, error: 上方错误对象 },无 data。
|
|
586
|
+
|
|
587
|
+
// 模块实现可把尚未就绪的操作暂时指向这些代理。
|
|
588
|
+
const asyncOperations = waiting.proxy<{ read: () => Promise<HaiResult<string>> }>()
|
|
589
|
+
const syncOperations = waiting.proxy<{ read: () => HaiResult<string> }>('sync')
|
|
590
|
+
// 两次 proxy 调用分别返回异步和同步操作对象。
|
|
591
|
+
const result = await asyncOperations.read() // { success: false, error: 上方错误对象 }。
|
|
592
|
+
if (!result.success)
|
|
593
|
+
core.logger.warn('Read before initialization', { error: result.error })
|
|
594
|
+
syncOperations.read() // 直接返回 { success: false, error: 上方错误对象 },不返回 Promise。
|
|
556
595
|
```
|
|
557
596
|
|
|
558
|
-
####
|
|
597
|
+
#### Checking shared-state requirements
|
|
598
|
+
|
|
599
|
+
requiresSharedState() decides whether a production process should reject backends limited to one host. It only returns a decision; it does not connect or switch databases. Server code supplies the real environment.
|
|
559
600
|
|
|
560
|
-
```
|
|
561
|
-
import {
|
|
601
|
+
```ts
|
|
602
|
+
import { core } from '@h-ai/core'
|
|
562
603
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
HaiConfigError.CONFIG_ENV_VAR_MISSING // hai:core:013 - 环境变量缺失
|
|
567
|
-
HaiConfigError.CONFIG_NOT_LOADED // hai:core:014 - 配置未加载
|
|
604
|
+
// 此例用显式数据演示;服务端实际使用时传入 process.env。
|
|
605
|
+
core.module.requiresSharedState({ NODE_ENV: 'production' }) // true:应使用跨主机共享后端。
|
|
606
|
+
core.module.requiresSharedState({ NODE_ENV: 'production', HAI_E2E: '1' }) // false:显式 E2E 例外。
|
|
568
607
|
```
|
|
569
608
|
|
|
570
|
-
### Request
|
|
609
|
+
### Request access checks: `core.access` (Node)
|
|
571
610
|
|
|
572
|
-
|
|
611
|
+
At HTTP entry points, resolve a trusted client IP and check addresses, paths, methods, and time windows. Core returns decisions; Serv http.access or Kit createHandle({ access }) connects them to request processing.
|
|
573
612
|
|
|
574
|
-
|
|
613
|
+
#### Resolving and checking client addresses
|
|
575
614
|
|
|
576
|
-
|
|
615
|
+
```ts
|
|
616
|
+
import { AccessConditionSchema, core } from '@h-ai/core'
|
|
617
|
+
|
|
618
|
+
core.access.normalizeClientIp('::ffff:198.51.100.23') // 198.51.100.23。
|
|
619
|
+
const resolve = core.access.createClientIpResolver(['192.0.2.10']) // 返回 IP 解析函数,只信任这个代理。
|
|
620
|
+
const request = new Request('https://example.test/api/orders', { headers: { 'x-forwarded-for': '198.51.100.23' } })
|
|
621
|
+
// 第二参数必须来自真实 socket/可信平台;这里用测试地址模拟代理对端。
|
|
622
|
+
const clientIp = resolve(request, '192.0.2.10') // '198.51.100.23',读取受信代理的转发头。
|
|
623
|
+
const check = core.access.createConditionCheck(AccessConditionSchema.parse({ allowIps: ['198.51.100.0/24'] }))
|
|
624
|
+
// createConditionCheck 返回检查函数;check(clientIp) 得到 { allowed: true }。
|
|
625
|
+
core.logger.info('Address checked', { allowed: check(clientIp).allowed })
|
|
626
|
+
```
|
|
577
627
|
|
|
578
|
-
|
|
628
|
+
#### Loading policies and checking requests
|
|
579
629
|
|
|
580
630
|
```ts
|
|
581
631
|
import { core } from '@h-ai/core'
|
|
582
632
|
|
|
583
|
-
|
|
584
|
-
|
|
633
|
+
// 可改为 loadPolicy({ file: './config/security/request-access.yml' }) 在启动时读独立文件。
|
|
634
|
+
const policy = core.access.loadPolicy({
|
|
635
|
+
rules: [{ id: 'external-api', paths: ['/api/external/**'], methods: ['POST'], allowIps: ['192.0.2.0/24'], encryption: 'disabled' }],
|
|
585
636
|
})
|
|
586
|
-
|
|
587
|
-
const
|
|
637
|
+
// policy.rules[0] 保留上方规则,并补 denyIps: []、windows: []、timezone: 'UTC'。
|
|
638
|
+
const check = core.access.createRequestCheck(policy) // 返回请求检查函数,另带 encryption 方法和 requiresEncryption 属性。
|
|
639
|
+
const decision = check('/api/external/sync', 'POST', '192.0.2.10') // { allowed: true }。
|
|
640
|
+
check.encryption('/api/external/sync', 'POST') // disabled,供 HTTP 框架选择传输模式。
|
|
641
|
+
check.requiresEncryption // false;本例没有 required 规则。
|
|
642
|
+
core.logger.info('Request access checked', { allowed: decision.allowed })
|
|
588
643
|
```
|
|
589
644
|
|
|
590
|
-
|
|
645
|
+
- Creating a checker validates and compiles rules. `loadPolicy({ file })` reads independent YAML at startup, limited to 1 MiB. Invalid configuration throws and must stop the host. File references cannot be mixed with inline rules.
|
|
646
|
+
- Global conditions and all matching rules must pass; deny addresses take priority. Empty IP/time lists leave that dimension unrestricted, and timezone defaults to UTC. Paths include deployment prefixes, match exactly or end in `/**`, and GET does not imply HEAD.
|
|
647
|
+
- Default `auto` in `createClientIpResolver()` ignores forwarded headers on ordinary hosts; only managed private Compose uses the container subnet. `[]` disables proxy trust. Self-managed hosts explicitly list proxy IPs/CIDRs; peer addresses must come from sockets or trusted platforms.
|
|
648
|
+
- Path `encryption` can be `required` / `disabled`; omission inherits the host setting. Opposing modes on overlapping paths and methods fail at creation. Hosts use `check.encryption()` / `requiresEncryption` to wire transport behavior. Core does not hold keys or encrypt/decrypt; HTTPS and authentication are still required.
|
|
591
649
|
|
|
592
|
-
|
|
650
|
+
See the [request access guide](../../docs/usage/configuration/request-access.md) for defaults, policy files, proxy topology, and deployment steps.
|
|
593
651
|
|
|
594
|
-
|
|
652
|
+
### Creating and checking identifiers: `core.id`
|
|
595
653
|
|
|
596
|
-
|
|
654
|
+
Create business identifiers and log correlation IDs, or validate UUID v4/nanoid inputs.
|
|
597
655
|
|
|
598
|
-
|
|
656
|
+
```ts
|
|
657
|
+
import { core } from '@h-ai/core'
|
|
599
658
|
|
|
600
|
-
|
|
659
|
+
// 以下随机值仅展示格式,每次执行都不同。
|
|
660
|
+
core.id.generate() // 如 'V1StGXR8_Z5jdHi6B-myT',默认 21 字符;generate(8) 返回 8 字符。
|
|
661
|
+
const shortId = core.id.short() // 如 'V1StGXR8_Z',10 字符。
|
|
662
|
+
core.id.withPrefix('order_') // 如 'order_V1StGXR8_Z5jdHi6B-myT',前缀后接 21 字符。
|
|
663
|
+
core.id.trace() // 如 'trace-V1StGXR8_Z5jdHi6B-myT'。
|
|
664
|
+
core.id.request() // 如 'req-V1StGXR8_Z5jdHi6B-myT'。
|
|
665
|
+
const uuid = core.id.uuid() // 如 '550e8400-e29b-41d4-a716-446655440000',UUID v4。
|
|
666
|
+
core.id.isValidUUID(uuid) // true。
|
|
667
|
+
core.id.isValidNanoId(shortId, 10) // true。
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
IDs are not secrets. UUID requires cryptographic randomness and throws if unavailable. _core.yml has no global ID length/prefix settings; pass options per call.
|
|
671
|
+
|
|
672
|
+
### Checking value types: `core.typeUtils`
|
|
601
673
|
|
|
602
|
-
|
|
674
|
+
Check boundary values and narrow their TypeScript types in branches. These checks do not replace business schema validation.
|
|
675
|
+
|
|
676
|
+
```ts
|
|
677
|
+
import { core } from '@h-ai/core'
|
|
603
678
|
|
|
604
|
-
|
|
679
|
+
core.typeUtils.isDefined(null) // false,同时排除 null 和 undefined。
|
|
680
|
+
core.typeUtils.isObject({ name: 'orders' }) // true;排除 null/数组,但也接受 Date 和类实例。
|
|
681
|
+
core.typeUtils.isFunction(() => {}) // true。
|
|
682
|
+
core.typeUtils.isPromise(Promise.resolve('ready')) // true。
|
|
683
|
+
core.typeUtils.isString('orders') // true。
|
|
684
|
+
core.typeUtils.isNumber(3000) // true;传 NaN 返回 false。
|
|
685
|
+
core.typeUtils.isBoolean(false) // true。
|
|
686
|
+
core.typeUtils.isArray([1, 2]) // true。
|
|
687
|
+
```
|
|
605
688
|
|
|
606
|
-
`core.
|
|
689
|
+
### Objects: `core.object`
|
|
607
690
|
|
|
608
|
-
|
|
691
|
+
Clone, merge, and select object fields, with typed keys/values/entries and fromEntries.
|
|
609
692
|
|
|
610
693
|
```ts
|
|
611
|
-
import type { LogRecord } from '@h-ai/core'
|
|
612
694
|
import { core } from '@h-ai/core'
|
|
613
695
|
|
|
614
|
-
const
|
|
615
|
-
const
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
}
|
|
624
|
-
unsubscribe()
|
|
696
|
+
const defaults = { name: 'orders', port: 3000 }
|
|
697
|
+
const copy = core.object.deepClone(defaults) // { name: 'orders', port: 3000 },新副本。
|
|
698
|
+
// 合并局部覆盖时,显式保留包含 name/port 的完整配置类型。
|
|
699
|
+
const settings = core.object.deepMerge<typeof defaults>(copy, { port: 4000 }) // { name: 'orders', port: 4000 }。
|
|
700
|
+
core.object.pick(settings, ['name']) // { name: 'orders' }。
|
|
701
|
+
core.object.omit(settings, ['port']) // { name: 'orders' }。
|
|
702
|
+
core.object.keys(settings) // ['name', 'port'],元素类型为 'name' | 'port'。
|
|
703
|
+
core.object.values(settings) // ['orders', 4000]。
|
|
704
|
+
core.object.entries(settings) // [['name', 'orders'], ['port', 4000]]。
|
|
705
|
+
core.object.fromEntries([['mode', 'local']]) // { mode: 'local' }。
|
|
625
706
|
```
|
|
626
707
|
|
|
627
|
-
|
|
708
|
+
deepClone uses structuredClone for cloneable Date/Map/Set/cyclic values and throws for unsupported values such as functions. deepMerge recursively merges plain objects only; later arrays, dates, collections, and class instances replace earlier values without modifying inputs. It does not clone instances.
|
|
628
709
|
|
|
629
|
-
`core.
|
|
710
|
+
### Strings: `core.string`
|
|
630
711
|
|
|
631
|
-
|
|
712
|
+
Convert naming formats, prepare display strings, detect whitespace, and compare strings.
|
|
632
713
|
|
|
633
|
-
|
|
714
|
+
```ts
|
|
715
|
+
import { core } from '@h-ai/core'
|
|
716
|
+
|
|
717
|
+
core.string.capitalize('hello') // 'Hello'。
|
|
718
|
+
core.string.kebabCase('helloWorld') // 'hello-world'。
|
|
719
|
+
core.string.camelCase('hello-world') // 'helloWorld'。
|
|
720
|
+
core.string.snakeCase('helloWorld') // 'hello_world'。
|
|
721
|
+
core.string.pascalCase('hello-world') // 'HelloWorld'。
|
|
722
|
+
core.string.truncate('abcdef', 3) // 'abc...'。
|
|
723
|
+
core.string.trim(' hello ') // 'hello'。
|
|
724
|
+
core.string.isBlank(' ') // true。
|
|
725
|
+
core.string.isNotBlank('hello') // true。
|
|
726
|
+
core.string.padStart('5', 3, '0') // '005'。
|
|
727
|
+
core.string.padEnd('5', 3, '0') // '500'。
|
|
728
|
+
core.string.constantTimeEqual('same', 'same') // true;安全边界见下方说明。
|
|
729
|
+
```
|
|
634
730
|
|
|
635
|
-
|
|
731
|
+
Node constantTimeEqual uses native timingSafeEqual on equal-length UTF-16 bytes and rejects unequal lengths immediately. Browser engines provide no constant-time guarantee; do not use this for server credential checks.
|
|
636
732
|
|
|
637
|
-
|
|
733
|
+
### Arrays: `core.array`
|
|
638
734
|
|
|
639
|
-
|
|
735
|
+
Deduplicate, chunk, group, remove nullish values, or calculate intersections/differences while retaining the input array.
|
|
640
736
|
|
|
641
|
-
|
|
737
|
+
```ts
|
|
738
|
+
import { core } from '@h-ai/core'
|
|
739
|
+
|
|
740
|
+
core.array.unique([1, 1, 2]) // [1, 2]。
|
|
741
|
+
core.array.chunk([1, 2, 3], 2) // [[1, 2], [3]]。
|
|
742
|
+
core.array.groupBy([{ role: 'admin' }, { role: 'user' }], item => item.role)
|
|
743
|
+
// => { admin: [{ role: 'admin' }], user: [{ role: 'user' }] }
|
|
744
|
+
core.array.first([1, 2, 3]) // 1;空数组为 undefined。
|
|
745
|
+
core.array.last([1, 2, 3]) // 3;空数组为 undefined。
|
|
746
|
+
core.array.flatten([[1], [2, 3]]) // [1, 2, 3],只展开一层。
|
|
747
|
+
core.array.compact([0, null, 1, undefined]) // [0, 1],保留 0/false/空字符串。
|
|
748
|
+
core.array.shuffle([1, 2, 3]) // 如 [2, 3, 1],次序随机;新数组不修改输入。
|
|
749
|
+
core.array.intersection([1, 2], [2, 3]) // [2]。
|
|
750
|
+
core.array.difference([1, 2], [2, 3]) // [1]。
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
groupBy supports prototype names such as `constructor` and `__proto__`. chunk expects a positive integer size and returns an empty array for size<=0.
|
|
754
|
+
|
|
755
|
+
### Asynchronous work: `core.async`
|
|
756
|
+
|
|
757
|
+
Schedule delays, timeouts, retries, bounded/serial work, or debounce/throttle input and scroll events.
|
|
758
|
+
|
|
759
|
+
```ts
|
|
760
|
+
import { core } from '@h-ai/core'
|
|
761
|
+
|
|
762
|
+
await core.async.delay(1) // 等待约 1ms 后得到 undefined;计时以运行环境为准。
|
|
763
|
+
await core.async.withTimeout(Promise.resolve('ready'), 1000) // 'ready';超时则 reject 为 Error。
|
|
764
|
+
await core.async.retry(async () => 'ready', { maxRetries: 3, delay: 10 }) // 'ready',本例首次即成功。
|
|
765
|
+
await core.async.parallel([1, 2, 3], async value => value * 2, 2) // [2, 4, 6],最多同时执行两项。
|
|
766
|
+
await core.async.serial([1, 2, 3], async value => value * 2) // [2, 4, 6],按输入顺序逐项执行。
|
|
767
|
+
|
|
768
|
+
// 两种包装保留回调参数类型;调用 search/scroll 时传入同样类型的参数。
|
|
769
|
+
const search = core.async.debounce((term: string) => core.logger.debug('Search requested', { term }), 100)
|
|
770
|
+
const scroll = core.async.throttle((position: number) => core.logger.debug('Scroll position', { position }), 100)
|
|
771
|
+
// debounce/throttle 均返回包装函数,调用时返回 undefined。
|
|
772
|
+
core.logger.setLevel('debug') // 返回 undefined;确保下面的 debug 日志可见。
|
|
773
|
+
search('orders') // 约 100ms 后回调收到 'orders';100ms 内连续调用只处理最后一次。
|
|
774
|
+
scroll(100) // 本例第一次调用立即回调,position 为 100;100ms 内最多执行一次。
|
|
775
|
+
```
|
|
776
|
+
|
|
777
|
+
withTimeout limits waiting but does not cancel work. retry handles throws/rejections, not failed HaiResult values; current maxRetries includes the first attempt, so 3 means at most three executions. parallel requires positive safe integer concurrency; invalid values reject with RangeError before any task runs. Result order follows input order.
|
|
778
|
+
|
|
779
|
+
### Dates and time: `core.time`
|
|
780
|
+
|
|
781
|
+
Convert timestamps, Date values, and display text, and calculate local calendar boundaries or relative time.
|
|
782
|
+
|
|
783
|
+
```ts
|
|
784
|
+
import { core } from '@h-ai/core'
|
|
785
|
+
|
|
786
|
+
// date 与以下日期运算使用本机时区;parseDate 中的 Z 表示 UTC。
|
|
787
|
+
const date = new Date(2026, 0, 1, 12, 0, 0)
|
|
788
|
+
core.time.formatDate(date, 'YYYY-MM-DD HH:mm:ss') // '2026-01-01 12:00:00'。
|
|
789
|
+
core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;相对时间使用中文。
|
|
790
|
+
core.time.timeAgo(new Date(Date.now() - 60_000)) // '1 分钟前'(立即执行时)。
|
|
791
|
+
core.time.now() // 当前毫秒时间戳,如 1767268800000;每次执行随时间变化。
|
|
792
|
+
core.time.nowSeconds() // 当前秒时间戳,如 1767268800;相当于当前毫秒时间戳除以 1000 后向下取整。
|
|
793
|
+
const parsed = core.time.parseDate('2026-01-01T00:00:00Z') // Date 对象,toISOString() 为 '2026-01-01T00:00:00.000Z'。
|
|
794
|
+
core.time.isValidDate(parsed) // true;Invalid Date 返回 false。
|
|
795
|
+
core.time.addDays(date, 7) // 新 Date,本机时间 2026-01-08 12:00:00。
|
|
796
|
+
core.time.addHours(date, 2) // 新 Date,本机时间 2026-01-01 14:00:00。
|
|
797
|
+
core.time.startOfDay(date) // 新 Date,本机时间 2026-01-01 00:00:00.000。
|
|
798
|
+
core.time.endOfDay(date) // 新 Date,本机时间 2026-01-01 23:59:59.999。
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
formatDate supports YYYY/MM/DD/HH/mm/ss tokens and defaults to YYYY-MM-DD. Date arithmetic returns new Date values. Invalid parseDate input produces an invalid date rather than automatically throwing; check isValidDate.
|
|
802
|
+
|
|
803
|
+
See the [Core reference](../cli/templates/skills/hai-core/reference.md) for complete parameters and less common options. Current published declarations define the contract.
|
|
642
804
|
|
|
643
805
|
## Development and testing
|
|
644
806
|
|
|
807
|
+
Run from the repository root (use `pnpm.cmd` in PowerShell):
|
|
808
|
+
|
|
645
809
|
```bash
|
|
810
|
+
pnpm --filter @h-ai/core typecheck
|
|
811
|
+
pnpm --filter @h-ai/core lint
|
|
812
|
+
pnpm --filter @h-ai/core build
|
|
646
813
|
pnpm --filter @h-ai/core test
|
|
647
814
|
```
|
|
648
815
|
|
|
649
|
-
See the [module JSDoc conventions
|
|
816
|
+
See the [module JSDoc conventions](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证) for declaration and example checks.
|
|
650
817
|
|
|
651
818
|
## License
|
|
652
819
|
|