@h-ai/core 0.1.0-alpha9 → 1.0.0-beta.10

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 ADDED
@@ -0,0 +1,820 @@
1
+ # @h-ai/core
2
+
3
+ [简体中文](./README.md) | [English](./README.en.md) | [日本語](./README.ja.md)
4
+
5
+ [Framework home](../../README.en.md)
6
+
7
+ ## Introduction
8
+
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
+
11
+ ## Core capabilities
12
+
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”.
35
+
36
+ ## Getting started
37
+
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.
39
+
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.
41
+
42
+ ```bash
43
+ pnpm add @h-ai/core
44
+ ```
45
+
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.
47
+
48
+ ### Initialization: `core.init`
49
+
50
+ Load YAML and configure logging at Node startup, or configure logging in a browser. Initializing Core does not start databases or other modules.
51
+
52
+ #### Node.js
53
+
54
+ Create `config/_core.yml`:
55
+
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 })
78
+
79
+ // 成功时 config.success 为 true;config.data.name 为 'orders',defaultLocale 为 'zh-CN'。
80
+
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'。
86
+ ```
87
+
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
91
+
92
+ ```ts
93
+ import { core } from '@h-ai/core'
94
+
95
+ // 浏览器不读取 YAML;此处只设置日志,输出 warn 及以上级别。
96
+ core.init({ logging: { level: 'warn' } }) // 返回 undefined;之后 info 日志被过滤。
97
+
98
+ // 设置当前页面使用的默认消息语言。
99
+ core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;页面默认消息使用中文。
100
+
101
+ // 给一次请求生成编号,后续日志可用同一编号关联排查。
102
+ const requestId = core.id.request() // 返回随机字符串,如 'req-V1StGXR8_Z5jdHi6B-myT'。
103
+ core.logger.warn('Request needs attention', { requestId }) // 返回 undefined;浏览器输出 warn 消息及同一个 requestId。
104
+ ```
105
+
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.
107
+
108
+ ### Files and environment settings: `core.config`
109
+
110
+ Read YAML, apply environment overrides, validate configuration types, and manage cached settings and file watchers. The file and environment operations below require Node.
111
+
112
+ #### Loading, validating, and reading
113
+
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.
115
+
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.
117
+
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.
119
+
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
125
+ ```
126
+
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.
128
+
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 })
138
+
139
+ // loaded:{ success: true, data: { port: 3000 } }。
140
+
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 })
145
+
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']。
155
+ ```
156
+
157
+ #### Reloading, watching, and cleanup
158
+
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.
160
+
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.
162
+
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。
183
+ ```
184
+
185
+ #### How environment variables change YAML settings
186
+
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.
188
+
189
+ For a fixed YAML value `port: 3000`, the result is 3000 without HAI_APP_PORT and 5000 after setting HAI_APP_PORT=5000.
190
+
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:
192
+
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 |
199
+
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.
201
+
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.
203
+
204
+ #### Reading .env files
205
+
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.
207
+
208
+ ```ts
209
+ import { core } from '@h-ai/core'
210
+
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
+ ```
221
+
222
+ #### What type does the replacement produce?
223
+
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.
225
+
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:
227
+
228
+ ```ts
229
+ import { core } from '@h-ai/core'
230
+ import { z } from 'zod'
231
+
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,
240
+ })
241
+ if (!resolved.success)
242
+ throw new Error(resolved.error.message, { cause: resolved.error })
243
+
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' }
252
+ ```
253
+
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.
257
+
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.
259
+
260
+ #### Tools for generating configuration files
261
+
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.
263
+
264
+ ```ts
265
+ import { core } from '@h-ai/core'
266
+
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
+ ```
280
+
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.
282
+
283
+ ### Logging: `core.logger`
284
+
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.
286
+
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'。
302
+ ```
303
+
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.
305
+
306
+ ```ts
307
+ import { core } from '@h-ai/core'
308
+
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
+ ```
317
+
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.
319
+
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.
321
+
322
+ ```ts
323
+ import { core } from '@h-ai/core'
324
+
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
+ ```
337
+
338
+ ### Request correlation: `core.context`
339
+
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.
341
+
342
+ ```ts
343
+ import { core } from '@h-ai/core'
344
+
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 日志,但不会触发日志观察回调。
357
+ ```
358
+
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`
362
+
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.
364
+
365
+ ```ts
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]'
380
+ ```
381
+
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.
383
+
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.
385
+
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.
387
+
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 })
407
+ ```
408
+
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 })
436
+ ```
437
+
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.
439
+
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.
441
+
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 |
449
+
450
+ These constants belong to `HaiConfigError`; cross-module failures use `HaiCommonError`.
451
+
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
457
+ import { core } from '@h-ai/core'
458
+
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'
471
+
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 })
485
+ ```
486
+
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.
488
+
489
+ ### Field validation messages: `core.zodValidation`
490
+
491
+ Convert Zod errors into { field, message }[] for form hints. createPrefixedZodMessageGetter() selects translation keys by prefix; mapZodErrorToFormErrors() extracts, translates, and flattens field paths.
492
+
493
+ ```ts
494
+ import { core } from '@h-ai/core'
495
+ import { z } from 'zod'
496
+
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 })
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.
520
+
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')
552
+ }
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 })
558
+ }
559
+ ```
560
+
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.
562
+
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.
566
+
567
+ #### Returning errors before initialization
568
+
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.
570
+
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。
595
+ ```
596
+
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.
600
+
601
+ ```ts
602
+ import { core } from '@h-ai/core'
603
+
604
+ // 此例用显式数据演示;服务端实际使用时传入 process.env。
605
+ core.module.requiresSharedState({ NODE_ENV: 'production' }) // true:应使用跨主机共享后端。
606
+ core.module.requiresSharedState({ NODE_ENV: 'production', HAI_E2E: '1' }) // false:显式 E2E 例外。
607
+ ```
608
+
609
+ ### Request access checks: `core.access` (Node)
610
+
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.
612
+
613
+ #### Resolving and checking client addresses
614
+
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
+ ```
627
+
628
+ #### Loading policies and checking requests
629
+
630
+ ```ts
631
+ import { core } from '@h-ai/core'
632
+
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' }],
636
+ })
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 })
643
+ ```
644
+
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.
649
+
650
+ See the [request access guide](../../docs/usage/configuration/request-access.md) for defaults, policy files, proxy topology, and deployment steps.
651
+
652
+ ### Creating and checking identifiers: `core.id`
653
+
654
+ Create business identifiers and log correlation IDs, or validate UUID v4/nanoid inputs.
655
+
656
+ ```ts
657
+ import { core } from '@h-ai/core'
658
+
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`
673
+
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'
678
+
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
+ ```
688
+
689
+ ### Objects: `core.object`
690
+
691
+ Clone, merge, and select object fields, with typed keys/values/entries and fromEntries.
692
+
693
+ ```ts
694
+ import { core } from '@h-ai/core'
695
+
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' }。
706
+ ```
707
+
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.
709
+
710
+ ### Strings: `core.string`
711
+
712
+ Convert naming formats, prepare display strings, detect whitespace, and compare strings.
713
+
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
+ ```
730
+
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.
732
+
733
+ ### Arrays: `core.array`
734
+
735
+ Deduplicate, chunk, group, remove nullish values, or calculate intersections/differences while retaining the input array.
736
+
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.
804
+
805
+ ## Development and testing
806
+
807
+ Run from the repository root (use `pnpm.cmd` in PowerShell):
808
+
809
+ ```bash
810
+ pnpm --filter @h-ai/core typecheck
811
+ pnpm --filter @h-ai/core lint
812
+ pnpm --filter @h-ai/core build
813
+ pnpm --filter @h-ai/core test
814
+ ```
815
+
816
+ See the [module JSDoc conventions](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证) for declaration and example checks.
817
+
818
+ ## License
819
+
820
+ Apache-2.0