@h-ai/core 0.1.0-alpha.66 → 0.1.0-alpha.68

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.
@@ -9,10 +9,10 @@ import { z, ZodType } from 'zod';
9
9
 
10
10
  /**
11
11
  * 环境类型 Schema。
12
- *
13
12
  * @example
14
13
  * ```ts
15
- * EnvSchema.parse('development')
14
+ * import { EnvSchema } from '@h-ai/core'
15
+ * const config = EnvSchema.parse('production')
16
16
  * ```
17
17
  */
18
18
  declare const EnvSchema: z.ZodEnum<{
@@ -21,13 +21,21 @@ declare const EnvSchema: z.ZodEnum<{
21
21
  test: "test";
22
22
  staging: "staging";
23
23
  }>;
24
+ /**
25
+ * 运行环境标识;不会自行设置进程环境或初始化模块。
26
+ * @example
27
+ * ```ts
28
+ * import type { Env } from '@h-ai/core'
29
+ * const value: Env = 'production'
30
+ * ```
31
+ */
24
32
  type Env = z.infer<typeof EnvSchema>;
25
33
  /**
26
34
  * 日志级别 Schema。
27
- *
28
35
  * @example
29
36
  * ```ts
30
- * LogLevelSchema.parse('info')
37
+ * import { LogLevelSchema } from '@h-ai/core'
38
+ * const config = LogLevelSchema.parse('info')
31
39
  * ```
32
40
  */
33
41
  declare const LogLevelSchema: z.ZodEnum<{
@@ -38,56 +46,42 @@ declare const LogLevelSchema: z.ZodEnum<{
38
46
  error: "error";
39
47
  fatal: "fatal";
40
48
  }>;
49
+ /**
50
+ * 日志输出级别;未显式配置的 Logger 动态继承全局级别。
51
+ * @example
52
+ * ```ts
53
+ * import type { LogLevel } from '@h-ai/core'
54
+ * const value: LogLevel = 'warn'
55
+ * ```
56
+ */
41
57
  type LogLevel = z.infer<typeof LogLevelSchema>;
42
58
  /**
43
59
  * 日志格式 Schema。
44
- *
45
60
  * @example
46
61
  * ```ts
47
- * LogFormatSchema.parse('json')
62
+ * import { LogFormatSchema } from '@h-ai/core'
63
+ * const config = LogFormatSchema.parse('json')
48
64
  * ```
49
65
  */
50
66
  declare const LogFormatSchema: z.ZodEnum<{
51
67
  json: "json";
52
68
  pretty: "pretty";
53
69
  }>;
54
- type LogFormat = z.infer<typeof LogFormatSchema>;
55
70
  /**
56
- * 日志配置 Schema。
57
- *
58
- * @example 最小配置(全部使用默认值)
59
- * ```ts
60
- * LoggingConfigSchema.parse({})
61
- * // => { level: 'info', format: 'json', redact: [] }
62
- * ```
63
- *
64
- * @example 开发环境(pretty 格式 + debug 级别)
71
+ * 日志输出格式:JSON 或适合终端阅读的 pretty。
72
+ * @example
65
73
  * ```ts
66
- * LoggingConfigSchema.parse({ level: 'debug', format: 'pretty' })
67
- * // => { level: 'debug', format: 'pretty', redact: [] }
74
+ * import type { LogFormat } from '@h-ai/core'
75
+ * const value: LogFormat = 'json'
68
76
  * ```
69
- *
70
- * @example 带上下文与脱敏
77
+ */
78
+ type LogFormat = z.infer<typeof LogFormatSchema>;
79
+ /**
80
+ * 日志配置 Schema。
81
+ * @example
71
82
  * ```ts
72
- * LoggingConfigSchema.parse({
73
- * level: 'warn',
74
- * format: 'json',
75
- * context: { service: 'api-gateway', region: 'us-east-1' },
76
- * redact: ['password', 'token', 'headers.authorization'],
77
- * })
78
- * // => { level: 'warn', format: 'json', context: { service: 'api-gateway', region: 'us-east-1' }, redact: ['password', 'token', 'headers.authorization'] }
79
- * ```
80
- *
81
- * @example 在 _core.yml 中配置
82
- * ```yaml
83
- * logging:
84
- * level: info
85
- * format: json
86
- * context:
87
- * service: my-app
88
- * redact:
89
- * - password
90
- * - token
83
+ * import { LoggingConfigSchema } from '@h-ai/core'
84
+ * const config = LoggingConfigSchema.parse({ level: 'warn', format: 'json', redact: ['password'] })
91
85
  * ```
92
86
  */
93
87
  declare const LoggingConfigSchema: z.ZodObject<{
@@ -106,33 +100,25 @@ declare const LoggingConfigSchema: z.ZodObject<{
106
100
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
107
101
  redact: z.ZodDefault<z.ZodArray<z.ZodString>>;
108
102
  }, z.core.$strip>;
109
- type LoggingConfig = z.infer<typeof LoggingConfigSchema>;
110
103
  /**
111
- * ID 生成器配置 Schema。
112
- *
104
+ * 经过默认值填充的 Logger 配置;redact 是输出脱敏路径。
113
105
  * @example
114
106
  * ```ts
115
- * IdConfigSchema.parse({ length: 12 })
116
- * // => { length: 12 }
117
- *
118
- * IdConfigSchema.parse({ prefix: 'usr_', length: 16 })
119
- * // => { prefix: 'usr_', length: 16 }
107
+ * import { LoggingConfigSchema, type LoggingConfig } from '@h-ai/core'
108
+ * const config: LoggingConfig = LoggingConfigSchema.parse({})
120
109
  * ```
121
110
  */
122
- declare const IdConfigSchema: z.ZodObject<{
123
- prefix: z.ZodOptional<z.ZodString>;
124
- length: z.ZodDefault<z.ZodNumber>;
125
- }, z.core.$strip>;
126
- type IdConfig = z.infer<typeof IdConfigSchema>;
111
+ type LoggingConfig = z.infer<typeof LoggingConfigSchema>;
127
112
  /**
128
113
  * Core 配置 Schema。
129
114
  *
130
- * 描述应用的基础配置,通常通过 `_core.yml` 加载。
131
- *
115
+ * 描述应用的基础元数据和日志配置,通常通过 `_core.yml` 加载。
116
+ * 未声明的字段拒绝加载;业务配置放独立 app.yml 并使用应用 Schema 校验。
117
+ * ID 长度/前缀由每次 core.id 调用参数决定,不存在全局 ID 配置。
132
118
  * @example
133
119
  * ```ts
134
- * CoreConfigSchema.parse({ name: 'demo', env: 'production' })
135
- * // => { name: 'demo', version: '0.1.0', env: 'production', debug: false, defaultLocale: 'zh-CN' }
120
+ * import { CoreConfigSchema } from '@h-ai/core'
121
+ * const config = CoreConfigSchema.parse({ name: 'orders', env: 'production', logging: { level: 'info' } })
136
122
  * ```
137
123
  */
138
124
  declare const CoreConfigSchema: z.ZodObject<{
@@ -144,7 +130,6 @@ declare const CoreConfigSchema: z.ZodObject<{
144
130
  test: "test";
145
131
  staging: "staging";
146
132
  }>>;
147
- debug: z.ZodDefault<z.ZodBoolean>;
148
133
  logging: z.ZodOptional<z.ZodObject<{
149
134
  level: z.ZodDefault<z.ZodEnum<{
150
135
  trace: "trace";
@@ -161,12 +146,16 @@ declare const CoreConfigSchema: z.ZodObject<{
161
146
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
162
147
  redact: z.ZodDefault<z.ZodArray<z.ZodString>>;
163
148
  }, z.core.$strip>>;
164
- id: z.ZodOptional<z.ZodObject<{
165
- prefix: z.ZodOptional<z.ZodString>;
166
- length: z.ZodDefault<z.ZodNumber>;
167
- }, z.core.$strip>>;
168
149
  defaultLocale: z.ZodDefault<z.ZodString>;
169
- }, z.core.$strip>;
150
+ }, z.core.$strict>;
151
+ /**
152
+ * 严格校验后的 Core 配置;业务配置使用独立 Schema。
153
+ * @example
154
+ * ```ts
155
+ * import { CoreConfigSchema, type CoreConfig } from '@h-ai/core'
156
+ * const config: CoreConfig = CoreConfigSchema.parse({})
157
+ * ```
158
+ */
170
159
  type CoreConfig = z.infer<typeof CoreConfigSchema>;
171
160
 
172
161
  /**
@@ -228,16 +217,11 @@ declare function mapZodErrorToFormErrors(error: unknown, getMessage: ZodMessageG
228
217
  * 按最小知识原则,仅暴露调用方真正需要的两个入口:
229
218
  * 1. `createPrefixedZodMessageGetter()`:把模块前缀与消息获取器适配起来
230
219
  * 2. `mapZodErrorToFormErrors()`:一步完成 ZodError → 本地化扁平错误列表
231
- *
232
220
  * @example
233
221
  * ```ts
234
- * const getMessage = zodValidation.createPrefixedZodMessageGetter(
235
- * 'kit',
236
- * (messageKey, params) => messageKey === 'kit_validationEmail'
237
- * ? '请输入合法邮箱地址'
238
- * : `至少输入 ${params?.min} 个字符`,
239
- * )
240
- * const errors = zodValidation.mapZodErrorToFormErrors(zodError, getMessage)
222
+ * import { core } from '@h-ai/core'
223
+ * const tools = core.zodValidation
224
+ * tools.mapZodErrorToFormErrors({ issues: [{ path: ['name'], code: 'invalid_type', expected: 'string', message: 'Invalid input' }] }, key => key)
241
225
  * ```
242
226
  */
243
227
  declare const zodValidation: {
@@ -321,11 +305,27 @@ declare function buildHaiErrorsDef<T extends Record<string, string>>(module: str
321
305
  * ```
322
306
  */
323
307
  declare function buildHaiErrorInst(def: HaiErrorDef, message: string, cause?: unknown, suggestion?: string): HaiError;
308
+ /**
309
+ * 错误定义生成及错误实例组装工具;通过 core.error 使用。
310
+ * @example
311
+ * ```ts
312
+ * import { core } from '@h-ai/core'
313
+ * const tools = core.error
314
+ * tools.buildHaiErrorsDef('orders', { NOT_FOUND: '001:404' })
315
+ * ```
316
+ */
324
317
  declare const error: {
325
318
  buildHaiErrorsDef: typeof buildHaiErrorsDef;
326
319
  buildHaiErrorInst: typeof buildHaiErrorInst;
327
320
  };
328
- /** error 子工具类型 */
321
+ /**
322
+ * error 子工具类型
323
+ * @example 模块内部上下文
324
+ * ```ts
325
+ * const tools: ErrorFn = error
326
+ * tools.buildHaiErrorsDef('orders', { NOT_FOUND: '001:404' })
327
+ * ```
328
+ */
329
329
  type ErrorFn = typeof error;
330
330
 
331
331
  /**
@@ -336,11 +336,11 @@ type ErrorFn = typeof error;
336
336
  */
337
337
  /**
338
338
  * ID 生成工具对象。
339
- *
340
339
  * @example
341
340
  * ```ts
342
- * const id1 = id.generate()
343
- * const id2 = id.short()
341
+ * import { core } from '@h-ai/core'
342
+ * const tools = core.id
343
+ * tools.withPrefix('order_')
344
344
  * ```
345
345
  */
346
346
  declare const id: {
@@ -426,7 +426,14 @@ declare const id: {
426
426
  */
427
427
  isValidNanoId(str: string, length?: number): boolean;
428
428
  };
429
- /** id 子工具类型 */
429
+ /**
430
+ * id 子工具类型
431
+ * @example 模块内部上下文
432
+ * ```ts
433
+ * const tools: IdFn = id
434
+ * tools.withPrefix('order_')
435
+ * ```
436
+ */
430
437
  type IdFn = typeof id;
431
438
 
432
439
  /**
@@ -438,10 +445,28 @@ type IdFn = typeof id;
438
445
 
439
446
  declare function getGlobalLocale(): Locale;
440
447
  declare function setGlobalLocale(locale: Locale): void;
448
+ /**
449
+ * 在独立的 Node 请求语言上下文中运行操作,异步子任务继承当前语言。
450
+ *
451
+ * 显式 MessageOptions.locale 优先于请求语言,请求结束不会改变进程启动默认值。
452
+ *
453
+ * @param locale - 当前请求的语言
454
+ * @param operation - 请求处理或 SSR 操作;保留原同步值或 Promise 返回类型
455
+ * @returns operation 的原始返回值
456
+ * @throws 浏览器入口没有 Node 请求上下文时抛出错误;浏览器使用 setGlobalLocale。
457
+ * @example
458
+ * ```ts
459
+ * const response = await core.i18n.runWithLocale('en-US', async () => {
460
+ * await loadData()
461
+ * return renderPage()
462
+ * })
463
+ * ```
464
+ */
465
+ declare function runWithLocale<T>(locale: Locale, operation: () => T): T;
441
466
  /**
442
467
  * 创建消息获取函数。
443
468
  *
444
- * 各模块通过此函数创建自己的消息获取器,自动读取全局 locale。
469
+ * 各模块通过此函数创建消息获取器,依次读取显式 locale、Node 请求语言和应用默认语言。
445
470
  * 若指定的 locale 不支持,回退到默认语言;key 不存在时返回 key 本身。
446
471
  *
447
472
  * @param messages - 多语言消息对象
@@ -459,15 +484,34 @@ declare function setGlobalLocale(locale: Locale): void;
459
484
  * ```
460
485
  */
461
486
  declare function createMessageGetter<K extends string>(messages: LocaleMessages<K>): (key: K, options?: MessageOptions) => string;
487
+ /**
488
+ * 语言上下文、字典消息获取与插值工具;Node 请求通过 runWithLocale 隔离语言。
489
+ * @example
490
+ * ```ts
491
+ * import { core } from '@h-ai/core'
492
+ * const tools = core.i18n
493
+ * const message = tools.createMessageGetter({ 'en-US': { hello: 'Hello' }, 'zh-CN': { hello: '你好' } })
494
+ * message('hello', { locale: 'en-US' })
495
+ * ```
496
+ */
462
497
  declare const i18n: {
463
498
  DEFAULT_LOCALES: LocaleInfo[];
464
499
  DEFAULT_LOCALE: string;
465
500
  setGlobalLocale: typeof setGlobalLocale;
466
501
  getGlobalLocale: typeof getGlobalLocale;
502
+ runWithLocale: typeof runWithLocale;
467
503
  createMessageGetter: typeof createMessageGetter;
468
- coreM: (key: "$schema" | "core_errorUnknown" | "core_errorNetwork" | "core_errorTimeout" | "core_errorNotFound" | "core_errorUnauthorized" | "core_errorForbidden" | "core_errorValidation" | "core_errorInternal" | "core_actionConfirm" | "core_actionCancel" | "core_actionSave" | "core_actionDelete" | "core_actionEdit" | "core_actionCreate" | "core_actionUpdate" | "core_actionSearch" | "core_actionReset" | "core_actionSubmit" | "core_actionLoading" | "core_actionRetry" | "core_statusSuccess" | "core_statusFailed" | "core_statusPending" | "core_statusProcessing" | "core_statusCompleted" | "core_statusCancelled" | "core_validationRequired" | "core_validationMinLength" | "core_validationMaxLength" | "core_validationEmail" | "core_validationUrl" | "core_validationNumber" | "core_validationInteger" | "core_validationPositive" | "core_validationPattern" | "core_timeJustNow" | "core_timeSecondsAgo" | "core_timeMinutesAgo" | "core_timeHoursAgo" | "core_timeDaysAgo" | "core_timeWeeksAgo" | "core_timeMonthsAgo" | "core_timeYearsAgo" | "core_browserFeatureUnsupported" | "core_configEnvVarMissing" | "core_configFileNotExist" | "core_configParseFailed" | "core_configValidationFailed" | "core_configNotLoaded" | "core_configUnsupportedInBrowser", options?: MessageOptions) => string;
504
+ coreM: (key: "$schema" | "core_errorUnknown" | "core_errorNetwork" | "core_errorTimeout" | "core_errorNotFound" | "core_errorUnauthorized" | "core_errorForbidden" | "core_errorValidation" | "core_errorInternal" | "core_actionConfirm" | "core_actionCancel" | "core_actionSave" | "core_actionDelete" | "core_actionEdit" | "core_actionCreate" | "core_actionUpdate" | "core_actionSearch" | "core_actionReset" | "core_actionSubmit" | "core_actionLoading" | "core_actionRetry" | "core_statusSuccess" | "core_statusFailed" | "core_statusPending" | "core_statusProcessing" | "core_statusCompleted" | "core_statusCancelled" | "core_validationRequired" | "core_validationMinLength" | "core_validationMaxLength" | "core_validationEmail" | "core_validationUrl" | "core_validationNumber" | "core_validationInteger" | "core_validationPositive" | "core_validationPattern" | "core_timeJustNow" | "core_timeSecondsAgo" | "core_timeMinutesAgo" | "core_timeHoursAgo" | "core_timeDaysAgo" | "core_timeWeeksAgo" | "core_timeMonthsAgo" | "core_timeYearsAgo" | "core_browserFeatureUnsupported" | "core_configEnvVarMissing" | "core_configFileNotExist" | "core_configParseFailed" | "core_configValidationFailed" | "core_configNotLoaded" | "core_configUnsupportedInBrowser" | "core_cryptoRandomUnavailable", options?: MessageOptions) => string;
469
505
  };
470
- /** i18n 子工具类型 */
506
+ /**
507
+ * i18n 子工具类型
508
+ * @example 模块内部上下文
509
+ * ```ts
510
+ * const tools: I18nFn = i18n
511
+ * const message = tools.createMessageGetter({ 'en-US': { hello: 'Hello' }, 'zh-CN': { hello: '你好' } })
512
+ * message('hello', { locale: 'en-US' })
513
+ * ```
514
+ */
471
515
  type I18nFn = typeof i18n;
472
516
 
473
517
  /**
@@ -600,10 +644,11 @@ declare function intersection<T>(arr1: T[], arr2: T[]): T[];
600
644
  declare function difference<T>(arr1: T[], arr2: T[]): T[];
601
645
  /**
602
646
  * 数组操作工具对象。
603
- *
604
647
  * @example
605
648
  * ```ts
606
- * array.unique([1, 1, 2])
649
+ * import { core } from '@h-ai/core'
650
+ * const tools = core.array
651
+ * tools.chunk([1, 2, 3], 2)
607
652
  * ```
608
653
  */
609
654
  declare const array: {
@@ -618,7 +663,14 @@ declare const array: {
618
663
  intersection: typeof intersection;
619
664
  difference: typeof difference;
620
665
  };
621
- /** array 子工具类型 */
666
+ /**
667
+ * array 子工具类型
668
+ * @example 模块内部上下文
669
+ * ```ts
670
+ * const tools: ArrayFn = array
671
+ * tools.chunk([1, 2, 3], 2)
672
+ * ```
673
+ */
622
674
  type ArrayFn = typeof array;
623
675
 
624
676
  /**
@@ -728,10 +780,11 @@ declare function debounce<T extends (...args: unknown[]) => unknown>(fn: T, ms:
728
780
  declare function throttle<T extends (...args: unknown[]) => unknown>(fn: T, ms: number): (...args: Parameters<T>) => void;
729
781
  /**
730
782
  * 异步操作工具对象。
731
- *
732
783
  * @example
733
784
  * ```ts
734
- * await async.delay(100)
785
+ * import { core } from '@h-ai/core'
786
+ * const tools = core.async
787
+ * await tools.retry(async () => 'ready', { maxRetries: 2 })
735
788
  * ```
736
789
  */
737
790
  declare const async: {
@@ -743,7 +796,14 @@ declare const async: {
743
796
  debounce: typeof debounce;
744
797
  throttle: typeof throttle;
745
798
  };
746
- /** async 子工具类型 */
799
+ /**
800
+ * async 子工具类型
801
+ * @example 模块内部上下文
802
+ * ```ts
803
+ * const tools: AsyncFn = async
804
+ * await tools.retry(async () => 'ready', { maxRetries: 2 })
805
+ * ```
806
+ */
747
807
  type AsyncFn = typeof async;
748
808
 
749
809
  /**
@@ -846,10 +906,11 @@ declare function entries<T extends Record<string, unknown>>(obj: T): [keyof T, T
846
906
  declare function fromEntries<K extends string, V>(entries: [K, V][]): Record<K, V>;
847
907
  /**
848
908
  * 对象操作工具对象。
849
- *
850
909
  * @example
851
910
  * ```ts
852
- * object.deepMerge({ a: 1 }, { b: 2 })
911
+ * import { core } from '@h-ai/core'
912
+ * const tools = core.object
913
+ * tools.pick({ id: 'order-1', password: 'example-only' }, ['id'])
853
914
  * ```
854
915
  */
855
916
  declare const object: {
@@ -862,20 +923,66 @@ declare const object: {
862
923
  entries: typeof entries;
863
924
  fromEntries: typeof fromEntries;
864
925
  };
865
- /** object 子工具类型 */
926
+ /**
927
+ * object 子工具类型
928
+ * @example 模块内部上下文
929
+ * ```ts
930
+ * const tools: ObjectFn = object
931
+ * tools.pick({ id: 'order-1', password: 'example-only' }, ['id'])
932
+ * ```
933
+ */
866
934
  type ObjectFn = typeof object;
867
935
 
868
- /** 敏感字段匹配器 */
936
+ /**
937
+ * 敏感字段匹配器
938
+ * @example 模块内部上下文
939
+ * ```ts
940
+ * const matcher: SensitiveKeyMatcher = ['password', 'credential']
941
+ * const safe = sanitizeSensitiveFields({ credential: 'example-only', id: 'order-1' }, { matcher })
942
+ * ```
943
+ */
869
944
  type SensitiveKeyMatcher = RegExp | string[] | ((key: string) => boolean);
870
- /** 敏感字段脱敏选项 */
945
+ /**
946
+ * 敏感字段脱敏选项
947
+ * @example 模块内部上下文
948
+ * ```ts
949
+ * const options: SanitizeSensitiveFieldsOptions = { matcher: ['credential'], replacement: '[HIDDEN]' }
950
+ * const safe = sanitizeSensitiveFields({ credential: 'example-only' }, options)
951
+ * ```
952
+ */
871
953
  interface SanitizeSensitiveFieldsOptions {
872
954
  /** 自定义敏感字段匹配规则 */
873
955
  matcher?: SensitiveKeyMatcher;
874
956
  /** 自定义脱敏替换值 */
875
957
  replacement?: unknown;
876
958
  }
877
- /** 判断键名是否属于敏感字段 */
959
+ /**
960
+ * 判断键名是否属于敏感字段
961
+ * @param key - 原始字段名;会统一 camelCase、kebab-case 与 snake_case。
962
+ * @param matcher - 自定义规则;省略时使用凭证字段默认规则。
963
+ * @returns 当前字段名是否被匹配为敏感字段。
964
+ * @example
965
+ * ```ts
966
+ * import { core } from '@h-ai/core'
967
+ * const safe = core.sanitize.isSensitiveKey('apiKey')
968
+ * ```
969
+ */
878
970
  declare function isSensitiveKey(key: string, matcher?: SensitiveKeyMatcher): boolean;
971
+ /**
972
+ * 遮蔽 URL 的用户名、密码及敏感查询参数;OAuth 风格 fragment 按查询参数处理。
973
+ *
974
+ * 解析失败返回固定占位符,避免畸形地址把凭据原样写入日志。
975
+ *
976
+ * @param url - 待记录的绝对 URL
977
+ * @param options - 与对象脱敏一致的匹配规则和替换值
978
+ * @returns 可安全用于结构化日志的 URL
979
+ * @example
980
+ * ```ts
981
+ * import { core } from '@h-ai/core'
982
+ * const safe = core.sanitize.sanitizeUrl('https://service.example/path?token=example-only')
983
+ * ```
984
+ */
985
+ declare function sanitizeUrl(url: string, options?: SanitizeSensitiveFieldsOptions): string;
879
986
  /**
880
987
  * 递归脱敏单个值。
881
988
  *
@@ -883,25 +990,54 @@ declare function isSensitiveKey(key: string, matcher?: SensitiveKeyMatcher): boo
883
990
  * @param key - 当前字段名;根节点传 null
884
991
  * @param options - 脱敏选项
885
992
  * @param cache - 循环引用 / 重复引用缓存
993
+ * @returns 递归脱敏后的值;普通对象循环保留,Error 规范化为有界诊断树,原值不被修改。
994
+ * @example
995
+ * ```ts
996
+ * import { core } from '@h-ai/core'
997
+ * const safe = core.sanitize.sanitizeSensitiveValue('example-only', 'password')
998
+ * ```
886
999
  */
887
1000
  declare function sanitizeSensitiveValue(value: unknown, key: string | null, options?: SanitizeSensitiveFieldsOptions, cache?: WeakMap<object, unknown>): unknown;
888
1001
  /**
889
1002
  * 对对象中的敏感字段执行递归脱敏,并自动处理 URL/endpoint 字段中的内嵌凭证。
1003
+ * Error 保留 name/message/stack/cause、aggregate errors 与枚举上下文;错误子图循环和过深路径用固定标记,普通对象循环保留。
1004
+ * 诊断文本不会自动解析自由文本中的秘密;记录前仍需调用方清理,或配置明确的 redact 路径。
890
1005
  *
891
1006
  * @param value - 原始对象/数组/值
892
1007
  * @param options - 脱敏选项
893
1008
  * @returns 脱敏后的新值
1009
+ * @example
1010
+ * ```ts
1011
+ * import { core } from '@h-ai/core'
1012
+ * const safe = core.sanitize.sanitizeSensitiveFields({ password: 'example-only', id: 'order-1' })
1013
+ * ```
894
1014
  */
895
1015
  declare function sanitizeSensitiveFields<T>(value: T, options?: SanitizeSensitiveFieldsOptions): T;
896
- /** 脱敏工具对象。 */
1016
+ /**
1017
+ * 脱敏工具对象。
1018
+ * @example
1019
+ * ```ts
1020
+ * import { core } from '@h-ai/core'
1021
+ * const tools = core.sanitize
1022
+ * tools.sanitizeSensitiveFields({ apiKey: 'example-only', id: 'order-1' })
1023
+ * ```
1024
+ */
897
1025
  declare const sanitize: {
898
1026
  defaultSensitiveKeyRegex: RegExp;
899
1027
  defaultSensitiveReplacement: string;
900
1028
  isSensitiveKey: typeof isSensitiveKey;
1029
+ sanitizeUrl: typeof sanitizeUrl;
901
1030
  sanitizeSensitiveValue: typeof sanitizeSensitiveValue;
902
1031
  sanitizeSensitiveFields: typeof sanitizeSensitiveFields;
903
1032
  };
904
- /** sanitize 子工具类型 */
1033
+ /**
1034
+ * sanitize 子工具类型
1035
+ * @example 模块内部上下文
1036
+ * ```ts
1037
+ * const tools: SanitizeFn = sanitize
1038
+ * tools.sanitizeSensitiveFields({ apiKey: 'example-only', id: 'order-1' })
1039
+ * ```
1040
+ */
905
1041
  type SanitizeFn = typeof sanitize;
906
1042
 
907
1043
  /**
@@ -1043,10 +1179,9 @@ declare function padStart(str: string, length: number, char?: string): string;
1043
1179
  */
1044
1180
  declare function padEnd(str: string, length: number, char?: string): string;
1045
1181
  /**
1046
- * 常量时间字符串比较。
1182
+ * 无内容提前返回的字符串比较;Node 入口使用原生 timingSafeEqual 覆盖此实现。
1047
1183
  *
1048
- * 防止时序侧信道攻击:无论输入差异位置如何,执行时间恒定。
1049
- * 兼容 Node.js 与浏览器环境(纯 JS 实现,无平台依赖)。
1184
+ * 浏览器 JavaScript 引擎不提供恒时保证,不能将此实现当作服务端凭证校验的安全边界。
1050
1185
  *
1051
1186
  * @param a - 字符串 a
1052
1187
  * @param b - 字符串 b
@@ -1061,10 +1196,11 @@ declare function padEnd(str: string, length: number, char?: string): string;
1061
1196
  declare function constantTimeEqual(a: string, b: string): boolean;
1062
1197
  /**
1063
1198
  * 字符串操作工具对象。
1064
- *
1065
1199
  * @example
1066
1200
  * ```ts
1067
- * string.capitalize('hello')
1201
+ * import { core } from '@h-ai/core'
1202
+ * const tools = core.string
1203
+ * tools.camelCase('order-created')
1068
1204
  * ```
1069
1205
  */
1070
1206
  declare const string: {
@@ -1081,7 +1217,14 @@ declare const string: {
1081
1217
  padEnd: typeof padEnd;
1082
1218
  constantTimeEqual: typeof constantTimeEqual;
1083
1219
  };
1084
- /** string 子工具类型 */
1220
+ /**
1221
+ * string 子工具类型
1222
+ * @example 模块内部上下文
1223
+ * ```ts
1224
+ * const tools: StringFn = string
1225
+ * tools.camelCase('order-created')
1226
+ * ```
1227
+ */
1085
1228
  type StringFn = typeof string;
1086
1229
 
1087
1230
  /**
@@ -1203,10 +1346,11 @@ declare function startOfDay(date: Date): Date;
1203
1346
  declare function endOfDay(date: Date): Date;
1204
1347
  /**
1205
1348
  * 时间操作工具对象。
1206
- *
1207
1349
  * @example
1208
1350
  * ```ts
1209
- * time.formatDate(new Date())
1351
+ * import { core } from '@h-ai/core'
1352
+ * const tools = core.time
1353
+ * tools.addDays(new Date('2026-01-01T00:00:00Z'), 1)
1210
1354
  * ```
1211
1355
  */
1212
1356
  declare const time: {
@@ -1221,7 +1365,14 @@ declare const time: {
1221
1365
  startOfDay: typeof startOfDay;
1222
1366
  endOfDay: typeof endOfDay;
1223
1367
  };
1224
- /** time 子工具类型 */
1368
+ /**
1369
+ * time 子工具类型
1370
+ * @example 模块内部上下文
1371
+ * ```ts
1372
+ * const tools: TimeFn = time
1373
+ * tools.addDays(new Date('2026-01-01T00:00:00Z'), 1)
1374
+ * ```
1375
+ */
1225
1376
  type TimeFn = typeof time;
1226
1377
 
1227
1378
  /**
@@ -1318,10 +1469,12 @@ declare function isBoolean(value: unknown): value is boolean;
1318
1469
  declare function isArray<T = unknown>(value: unknown): value is T[];
1319
1470
  /**
1320
1471
  * 类型检查工具对象。
1321
- *
1322
1472
  * @example
1323
1473
  * ```ts
1324
- * typeUtils.isDefined('x')
1474
+ * import { core } from '@h-ai/core'
1475
+ * const tools = core.typeUtils
1476
+ * const value: unknown = 'order-1'
1477
+ * if (tools.isString(value)) value.toUpperCase()
1325
1478
  * ```
1326
1479
  */
1327
1480
  declare const typeUtils: {
@@ -1334,19 +1487,72 @@ declare const typeUtils: {
1334
1487
  isBoolean: typeof isBoolean;
1335
1488
  isArray: typeof isArray;
1336
1489
  };
1337
- /** typeUtils 子工具类型 */
1490
+ /**
1491
+ * typeUtils 子工具类型
1492
+ * @example 模块内部上下文
1493
+ * ```ts
1494
+ * const tools: TypeUtilFn = typeUtils
1495
+ * const value: unknown = 'order-1'
1496
+ * if (tools.isString(value)) value.toUpperCase()
1497
+ * ```
1498
+ */
1338
1499
  type TypeUtilFn = typeof typeUtils;
1339
1500
 
1501
+ /**
1502
+ * Zod 校验错误使用的稳定消息键。
1503
+ * @example
1504
+ * ```ts
1505
+ * import type { ZodValidationMessageKey } from '@h-ai/core'
1506
+ * const value: ZodValidationMessageKey = 'validationRequired'
1507
+ * ```
1508
+ */
1340
1509
  type ZodValidationMessageKey = 'validationFailed' | 'validationRequired' | 'validationInvalid' | 'validationInvalidType' | 'validationStringMin' | 'validationStringMax' | 'validationNumberMin' | 'validationNumberMax' | 'validationArrayMin' | 'validationArrayMax' | 'validationTooSmall' | 'validationTooBig' | 'validationEmail' | 'validationUrl' | 'validationUuid' | 'validationEnum';
1510
+ /**
1511
+ * 把校验消息键及插值参数转换为显示文本的函数。
1512
+ * @example
1513
+ * ```ts
1514
+ * import type { ZodMessageGetter } from '@h-ai/core'
1515
+ * const message: ZodMessageGetter = (key, params) => key === 'validationRequired' ? 'Required' : `${key}: ${String(params?.field ?? '')}`
1516
+ * message('validationRequired')
1517
+ * ```
1518
+ */
1341
1519
  type ZodMessageGetter = (key: ZodValidationMessageKey, params?: Record<string, string | number>) => string;
1520
+ /**
1521
+ * 可绑定表单字段路径的本地化错误。
1522
+ * @example
1523
+ * ```ts
1524
+ * import type { ValidationFormError } from '@h-ai/core'
1525
+ * const value: ValidationFormError = { field: 'email', message: 'Enter an email address' }
1526
+ * ```
1527
+ */
1342
1528
  interface ValidationFormError {
1343
1529
  field: string;
1344
1530
  message: string;
1345
1531
  }
1532
+ /**
1533
+ * 共享 Zod 错误映射契约;业务自定义消息保持原文。
1534
+ * @example
1535
+ * ```ts
1536
+ * import { core, type ZodValidationFn } from '@h-ai/core'
1537
+ * import { z } from 'zod'
1538
+ * const validator: ZodValidationFn = core.zodValidation
1539
+ * const input = z.object({ email: z.email() }).safeParse({ email: 'invalid' })
1540
+ * if (!input.success) validator.mapZodErrorToFormErrors(input.error, key => key)
1541
+ * ```
1542
+ */
1346
1543
  interface ZodValidationFn {
1347
1544
  readonly createPrefixedZodMessageGetter: <TMessageKey extends string>(prefix: string, getMessage: (messageKey: TMessageKey, params?: Record<string, string | number>) => string) => ZodMessageGetter;
1348
1545
  readonly mapZodErrorToFormErrors: (error: unknown, getMessage: ZodMessageGetter) => ValidationFormError[];
1349
1546
  }
1547
+ /**
1548
+ * 业务操作的成功数据或标准失败;访问 data/error 前必须按 success 收窄。
1549
+ * @example
1550
+ * ```ts
1551
+ * import { ok, type HaiResult } from '@h-ai/core'
1552
+ * const result: HaiResult<{ id: string }> = ok({ id: 'order-1' })
1553
+ * const label = result.success ? result.data.id : result.error.message
1554
+ * ```
1555
+ */
1350
1556
  type HaiResult<T> = {
1351
1557
  success: true;
1352
1558
  data: T;
@@ -1354,7 +1560,32 @@ type HaiResult<T> = {
1354
1560
  success: false;
1355
1561
  error: HaiError;
1356
1562
  };
1563
+ /**
1564
+ * 创建成功结果;不会自动捕获后续操作异常。
1565
+ * @param data - 成功分支的数据;保留原类型和对象引用。
1566
+ * @returns success 为 true、data 为输入值的结果。
1567
+ * @example
1568
+ * ```ts
1569
+ * import { ok } from '@h-ai/core'
1570
+ * const result = ok({ id: 'order-1' })
1571
+ * if (result.success) result.data.id.toUpperCase()
1572
+ * ```
1573
+ */
1357
1574
  declare function ok<T>(data: T): HaiResult<T>;
1575
+ /**
1576
+ * 创建失败结果;支持标准错误定义、已有 HaiError 与原生 Error。
1577
+ * @param errorOrDef - 已定义的错误、已有业务错误或原生异常。
1578
+ * @param message - 从错误定义创建实例时使用的消息。
1579
+ * @param cause - 原始原因;对外展示前应按边界脱敏。
1580
+ * @param suggestion - 可选的处理建议。
1581
+ * @returns success 为 false、error 为标准业务错误的结果。
1582
+ * @example
1583
+ * ```ts
1584
+ * import { err, HaiCommonError } from '@h-ai/core'
1585
+ * const result = err(HaiCommonError.NOT_FOUND, 'Order not found')
1586
+ * if (!result.success) result.error.httpStatus
1587
+ * ```
1588
+ */
1358
1589
  declare function err(errorOrDef: HaiErrorDef | HaiError | Error, message?: string, cause?: unknown, suggestion?: string): HaiResult<never>;
1359
1590
  /**
1360
1591
  * HaiResult 模式匹配处理器。
@@ -1364,13 +1595,12 @@ declare function err(errorOrDef: HaiErrorDef | HaiError | Error, message?: strin
1364
1595
  * @template T - 成功数据类型
1365
1596
  * @template R1 - ok 分支返回类型
1366
1597
  * @template R2 - err 分支返回类型
1367
- *
1368
1598
  * @example
1369
1599
  * ```ts
1370
- * const handlers: MatchHandlers<number, number, number> = {
1371
- * ok: n => n + 1,
1372
- * err: () => 0,
1373
- * }
1600
+ * import { type MatchHandlers, ok } from '@h-ai/core'
1601
+ * const handlers: MatchHandlers<number, string, string> = { ok: n => String(n + 1), err: error => error.message }
1602
+ * const result = ok(2)
1603
+ * const label = result.success ? handlers.ok(result.data) : handlers.err(result.error)
1374
1604
  * ```
1375
1605
  */
1376
1606
  interface MatchHandlers<T, R1, R2> {
@@ -1379,16 +1609,46 @@ interface MatchHandlers<T, R1, R2> {
1379
1609
  /** 失败分支处理器 */
1380
1610
  err: (error: HaiError) => R2;
1381
1611
  }
1382
- /** 错误信息值格式:`错误码数字段:HTTP状态码`,例如 `001:500`。 */
1612
+ /**
1613
+ * 错误信息值格式:`错误码数字段:HTTP状态码`,例如 `001:500`。
1614
+ * @example
1615
+ * ```ts
1616
+ * import type { ErrorInfoValue } from '@h-ai/core'
1617
+ * const value: ErrorInfoValue = '001:500'
1618
+ * ```
1619
+ */
1383
1620
  type ErrorInfoValue = `${string}:${string}`;
1384
- /** 模块错误信息映射。 */
1621
+ /**
1622
+ * 模块错误信息映射。
1623
+ * @example
1624
+ * ```ts
1625
+ * import type { ErrorInfo } from '@h-ai/core'
1626
+ * const value: ErrorInfo = { NOT_READY: '001:503' }
1627
+ * ```
1628
+ */
1385
1629
  type ErrorInfo = Record<string, ErrorInfoValue>;
1630
+ /**
1631
+ * 稳定的错误码与 HTTP 映射;消息在创建错误实例时填入。
1632
+ * @example
1633
+ * ```ts
1634
+ * import type { HaiErrorDef } from '@h-ai/core'
1635
+ * const value: HaiErrorDef = { code: 'app:orders:001', httpStatus: 409, system: 'app', module: 'orders' }
1636
+ * ```
1637
+ */
1386
1638
  interface HaiErrorDef {
1387
1639
  code: string | number;
1388
1640
  httpStatus: number;
1389
1641
  system: string;
1390
1642
  module: string;
1391
1643
  }
1644
+ /**
1645
+ * 可跨业务边界传递的错误;cause/ext 对外展示前仍需脱敏。
1646
+ * @example
1647
+ * ```ts
1648
+ * import type { HaiError } from '@h-ai/core'
1649
+ * const value: HaiError = { code: 'app:orders:001', message: 'Order already exists', httpStatus: 409 }
1650
+ * ```
1651
+ */
1392
1652
  interface HaiError {
1393
1653
  code: string | number;
1394
1654
  message: string;
@@ -1399,6 +1659,15 @@ interface HaiError {
1399
1659
  suggestion?: string;
1400
1660
  ext?: Record<string, unknown>;
1401
1661
  }
1662
+ /**
1663
+ * 跨模块通用错误定义及 HTTP 状态映射。
1664
+ * @example
1665
+ * ```ts
1666
+ * import { err, HaiCommonError } from '@h-ai/core'
1667
+ * const result = err(HaiCommonError.UNAUTHORIZED, 'Authentication required')
1668
+ * if (!result.success) result.error.code
1669
+ * ```
1670
+ */
1402
1671
  declare const HaiCommonError: {
1403
1672
  readonly NOT_INITIALIZED: HaiErrorDef;
1404
1673
  readonly INIT_FAILED: HaiErrorDef;
@@ -1421,6 +1690,15 @@ declare const HaiCommonError: {
1421
1690
  readonly DATABASE_ERROR: HaiErrorDef;
1422
1691
  readonly UNKNOWN_ERROR: HaiErrorDef;
1423
1692
  };
1693
+ /**
1694
+ * 文件配置加载、校验、环境缺失及缓存读取的错误定义。
1695
+ * @example
1696
+ * ```ts
1697
+ * import { err, HaiConfigError } from '@h-ai/core'
1698
+ * const result = err(HaiConfigError.CONFIG_NOT_LOADED, 'App configuration is unavailable')
1699
+ * if (!result.success) result.error.message
1700
+ * ```
1701
+ */
1424
1702
  declare const HaiConfigError: {
1425
1703
  readonly CONFIG_FILE_NOT_FOUND: HaiErrorDef;
1426
1704
  readonly CONFIG_PARSE_ERROR: HaiErrorDef;
@@ -1430,10 +1708,10 @@ declare const HaiConfigError: {
1430
1708
  };
1431
1709
  /**
1432
1710
  * 分页参数输入(可选字段,未提供时使用默认值)。
1433
- *
1434
1711
  * @example
1435
1712
  * ```ts
1436
- * const input: PaginationOptionsInput = { page: 2, pageSize: 20 }
1713
+ * import type { PaginationOptionsInput } from '@h-ai/core'
1714
+ * const value: PaginationOptionsInput = { page: 2, pageSize: 20 }
1437
1715
  * ```
1438
1716
  */
1439
1717
  interface PaginationOptionsInput {
@@ -1444,10 +1722,10 @@ interface PaginationOptionsInput {
1444
1722
  }
1445
1723
  /**
1446
1724
  * 分页参数(必填,已确定具体值)。
1447
- *
1448
1725
  * @example
1449
1726
  * ```ts
1450
- * const options: PaginationOptions = { page: 1, pageSize: 20 }
1727
+ * import type { PaginationOptions } from '@h-ai/core'
1728
+ * const value: PaginationOptions = { page: 1, pageSize: 20 }
1451
1729
  * ```
1452
1730
  */
1453
1731
  interface PaginationOptions {
@@ -1460,15 +1738,11 @@ interface PaginationOptions {
1460
1738
  * 分页结果。
1461
1739
  *
1462
1740
  * @template T - 数据项类型
1463
- *
1464
1741
  * @example
1465
1742
  * ```ts
1466
- * const result: PaginatedResult<User> = {
1467
- * items: [{ id: 1, name: 'Alice' }],
1468
- * total: 100,
1469
- * page: 1,
1470
- * pageSize: 20,
1471
- * }
1743
+ * import type { PaginatedResult } from '@h-ai/core'
1744
+ * const page: PaginatedResult<{ id: string }> = { items: [{ id: 'order-1' }], total: 1, page: 1, pageSize: 20 }
1745
+ * const ids = page.items.map(item => item.id)
1472
1746
  * ```
1473
1747
  */
1474
1748
  interface PaginatedResult<T> {
@@ -1483,10 +1757,10 @@ interface PaginatedResult<T> {
1483
1757
  }
1484
1758
  /**
1485
1759
  * 日志上下文。
1486
- *
1487
1760
  * @example
1488
1761
  * ```ts
1489
- * const context: LogContext = { requestId: 'req-1' }
1762
+ * import type { LogContext } from '@h-ai/core'
1763
+ * const value: LogContext = { requestId: 'request-1', level: 'info' }
1490
1764
  * ```
1491
1765
  */
1492
1766
  interface LogContext {
@@ -1497,10 +1771,10 @@ interface LogContext {
1497
1771
  }
1498
1772
  /**
1499
1773
  * 日志选项。
1500
- *
1501
1774
  * @example
1502
1775
  * ```ts
1503
- * const options: LoggerOptions = { name: 'api', level: 'debug' }
1776
+ * import type { LoggerOptions } from '@h-ai/core'
1777
+ * const value: LoggerOptions = { name: 'orders', level: 'debug', context: { service: 'api' } }
1504
1778
  * ```
1505
1779
  */
1506
1780
  interface LoggerOptions {
@@ -1515,10 +1789,11 @@ interface LoggerOptions {
1515
1789
  /**
1516
1790
  * Logger 接口。
1517
1791
  * 统一的日志记录接口,具体实现由 Provider 提供。
1518
- *
1519
1792
  * @example
1520
1793
  * ```ts
1521
- * core.logger.info('ready', { requestId: 'req-1' })
1794
+ * import { core, type Logger } from '@h-ai/core'
1795
+ * const logger: Logger = core.logger.child({ service: 'orders' })
1796
+ * logger.info('Order created', { orderId: 'order-1' })
1522
1797
  * ```
1523
1798
  */
1524
1799
  interface Logger {
@@ -1532,14 +1807,12 @@ interface Logger {
1532
1807
  }
1533
1808
  /**
1534
1809
  * Core 公共 Logger — Logger 实例 + 管理方法。
1535
- *
1536
1810
  * @example
1537
1811
  * ```ts
1538
- * core.logger.info('ready')
1539
- * core.logger.configure({ level: 'debug' })
1540
- * core.logger.setLevel('warn')
1541
- * const level = core.logger.getLevel()
1542
- * const db = core.logger.create({ name: 'db' })
1812
+ * import { core, type CoreLogger } from '@h-ai/core'
1813
+ * const logger: CoreLogger = core.logger
1814
+ * logger.configure({ level: 'warn', redact: ['password'] })
1815
+ * logger.child({ component: 'worker' }).warn('Retry scheduled')
1543
1816
  * ```
1544
1817
  */
1545
1818
  interface CoreLogger extends Logger {
@@ -1556,16 +1829,11 @@ interface CoreLogger extends Logger {
1556
1829
  * Logger 函数组合(平台实现依赖)。
1557
1830
  *
1558
1831
  * 由各平台(Node.js / Browser)提供具体实现,通过 `createCore()` 注入。
1559
- *
1560
1832
  * @example
1561
1833
  * ```ts
1562
- * const fns: LoggerFunctions = {
1563
- * createLogger,
1564
- * getLogger,
1565
- * configureLogger,
1566
- * setLogLevel,
1567
- * getLogLevel,
1568
- * }
1834
+ * import { core, type LoggerFunctions } from '@h-ai/core'
1835
+ * const platform: LoggerFunctions = { createLogger: options => core.logger.create(options), getLogger: name => core.logger.create({ name }), configureLogger: config => core.logger.configure(config), setLogLevel: level => core.logger.setLevel(level), getLogLevel: () => core.logger.getLevel() }
1836
+ * platform.createLogger({ name: 'worker' }).info('Worker ready')
1569
1837
  * ```
1570
1838
  */
1571
1839
  interface LoggerFunctions {
@@ -1582,10 +1850,10 @@ interface LoggerFunctions {
1582
1850
  }
1583
1851
  /**
1584
1852
  * Core 配置选项。
1585
- *
1586
1853
  * @example
1587
1854
  * ```ts
1588
- * const options: CoreOptions = { configDir: './config', watchConfig: true }
1855
+ * import type { CoreOptions } from '@h-ai/core'
1856
+ * const value: CoreOptions = { configDir: './config', watchConfig: false }
1589
1857
  * ```
1590
1858
  */
1591
1859
  interface CoreOptions {
@@ -1598,6 +1866,10 @@ interface CoreOptions {
1598
1866
  * - `_core.yml` → 自动使用 CoreConfigSchema 校验
1599
1867
  * - `_xx.yml` → 加载为 'xx'(各模块自行调用 `config.validate` 校验)
1600
1868
  * - `app.yml` → 加载为 'app'(需使用方自行校验)
1869
+ * - `_deploy.yml` / `_deploy.yaml` → 只由部署 CLI 解析,自动加载和监听均跳过;业务 `deploy.yml` 仍加载
1870
+ *
1871
+ * 单项加载返回失败时记日志并继续;必需配置须检查 `config.validate` 的 success。
1872
+ * 目录扫描等文件系统异常仍可能向调用方传播。
1601
1873
  *
1602
1874
  * @example
1603
1875
  * ```ts
@@ -1610,16 +1882,19 @@ interface CoreOptions {
1610
1882
  }
1611
1883
  /**
1612
1884
  * 语言代码(ISO 639-1 + 地区代码)。
1613
- *
1614
- * @example 'zh-CN', 'en-US', 'ja-JP'
1885
+ * @example
1886
+ * ```ts
1887
+ * import type { Locale } from '@h-ai/core'
1888
+ * const value: Locale = 'en-US'
1889
+ * ```
1615
1890
  */
1616
1891
  type Locale = string;
1617
1892
  /**
1618
1893
  * 语言信息。
1619
- *
1620
1894
  * @example
1621
1895
  * ```ts
1622
- * const locale: LocaleInfo = { code: 'zh-CN', label: '简体中文' }
1896
+ * import type { LocaleInfo } from '@h-ai/core'
1897
+ * const value: LocaleInfo = { code: 'en-US', label: 'English' }
1623
1898
  * ```
1624
1899
  */
1625
1900
  interface LocaleInfo {
@@ -1634,20 +1909,19 @@ interface LocaleInfo {
1634
1909
  * 插值参数类型。
1635
1910
  *
1636
1911
  * 用于 i18n 消息模板中的 `{key}` 占位符替换。
1637
- *
1638
1912
  * @example
1639
1913
  * ```ts
1640
- * const params: InterpolationParams = { name: 'Alice', count: 3 }
1641
- * // 模板 'Hello, {name}! You have {count} items.'
1914
+ * import type { InterpolationParams } from '@h-ai/core'
1915
+ * const value: InterpolationParams = { name: 'Alice', count: 2 }
1642
1916
  * ```
1643
1917
  */
1644
1918
  type InterpolationParams = Record<string, string | number | boolean>;
1645
1919
  /**
1646
1920
  * 消息字典类型(单语言的 key-value 映射)。
1647
- *
1648
1921
  * @example
1649
1922
  * ```ts
1650
- * const dict: MessageDictionary = { hello: '你好', bye: '再见' }
1923
+ * import type { MessageDictionary } from '@h-ai/core'
1924
+ * const value: MessageDictionary = { greeting: 'Hello, {name}!' }
1651
1925
  * ```
1652
1926
  */
1653
1927
  type MessageDictionary = Record<string, string>;
@@ -1657,31 +1931,38 @@ type MessageDictionary = Record<string, string>;
1657
1931
  * 以 locale 为键,每个 locale 下包含该语言的所有消息 key-value。
1658
1932
  *
1659
1933
  * @template K - 消息 key 的联合类型
1660
- *
1661
1934
  * @example
1662
1935
  * ```ts
1663
- * const messages: LocaleMessages<'hello' | 'bye'> = {
1664
- * 'zh-CN': { hello: '你好', bye: '再见' },
1665
- * 'en-US': { hello: 'Hello', bye: 'Bye' },
1666
- * }
1936
+ * import { core, type LocaleMessages } from '@h-ai/core'
1937
+ * const messages: LocaleMessages<'hello'> = { 'en-US': { hello: 'Hello, {name}!' }, 'zh-CN': { hello: '你好,{name}!' } }
1938
+ * const message = core.i18n.createMessageGetter(messages)
1939
+ * message('hello', { locale: 'en-US', params: { name: 'Alice' } })
1667
1940
  * ```
1668
1941
  */
1669
1942
  type LocaleMessages<K extends string = string> = Record<Locale, Record<K, string>>;
1670
1943
  /**
1671
1944
  * 消息获取选项。
1672
- *
1673
1945
  * @example
1674
1946
  * ```ts
1675
- * getMessage('hello', { locale: 'en-US', params: { name: 'World' } })
1947
+ * import type { MessageOptions } from '@h-ai/core'
1948
+ * const value: MessageOptions = { locale: 'en-US', params: { name: 'Alice' } }
1676
1949
  * ```
1677
1950
  */
1678
1951
  interface MessageOptions {
1679
- /** 指定 locale(不传则使用全局 locale) */
1952
+ /** 指定 locale(不传时依次读取 Node 请求上下文、应用默认语言) */
1680
1953
  locale?: Locale;
1681
1954
  /** 插值参数 */
1682
1955
  params?: InterpolationParams;
1683
1956
  }
1684
- /** Core 服务聚合接口(createCore 返回类型) */
1957
+ /**
1958
+ * Core 服务聚合接口(createCore 返回类型)
1959
+ * @example
1960
+ * ```ts
1961
+ * import { core, type CoreFunctions } from '@h-ai/core'
1962
+ * function createRequestId(tools: CoreFunctions): string { return tools.id.request() }
1963
+ * const requestId = createRequestId(core)
1964
+ * ```
1965
+ */
1685
1966
  interface CoreFunctions {
1686
1967
  /** 默认 Logger(懒加载单例),同时提供日志管理方法 */
1687
1968
  readonly logger: CoreLogger;
@@ -1725,6 +2006,12 @@ interface CoreFunctions {
1725
2006
  * 用于模块未初始化时的安全回退。
1726
2007
  *
1727
2008
  * @template E - 模块错误类型(必须继承 HaiError)
2009
+ * @example 模块内部上下文
2010
+ * ```ts
2011
+ * const state: NotInitializedKit<HaiError> = createNotInitializedKit({ code: 'app:orders:001', httpStatus: 503, system: 'app', module: 'orders' }, () => 'Orders unavailable')
2012
+ * const result = state.result<string>()
2013
+ * if (!result.success) result.error.message
2014
+ * ```
1728
2015
  */
1729
2016
  interface NotInitializedKit<E extends HaiError> {
1730
2017
  /** 创建未初始化错误对象 */
@@ -1739,13 +2026,53 @@ interface NotInitializedKit<E extends HaiError> {
1739
2026
  proxy: <T>(mode?: 'async' | 'sync') => T;
1740
2027
  }
1741
2028
  /** module 子工具类型 */
1742
- /** overloaded function type for createNotInitializedKit */
2029
+ /**
2030
+ * 未初始化代理的两个重载:错误定义或具体错误码。
2031
+ * @example 模块内部上下文
2032
+ * ```ts
2033
+ * const create: CreateNotInitializedKitFn = createNotInitializedKit
2034
+ * const state = create({ code: 'app:orders:001', httpStatus: 503, system: 'app', module: 'orders' }, () => 'Orders unavailable')
2035
+ * const result = state.result<string>()
2036
+ * if (!result.success) result.error.code
2037
+ * ```
2038
+ */
1743
2039
  interface CreateNotInitializedKitFn {
1744
2040
  (codeOrDef: HaiErrorDef, messageFn: () => string): NotInitializedKit<HaiError>;
1745
2041
  <E extends HaiError>(codeOrDef: E['code'], messageFn: () => string): NotInitializedKit<E>;
1746
2042
  }
2043
+ /**
2044
+ * 生产进程默认要求跨主机共享状态;显式E2E测试可使用测试替身。
2045
+ * @param environment - 服务端实际进程环境,不接受请求参数
2046
+ * @param environment.NODE_ENV - 实际运行环境
2047
+ * @param environment.HAI_CORE_ENV - 框架环境文件声明的运行环境
2048
+ * @param environment.HAI_E2E - 显式真实端到端测试标记
2049
+ * @param environment.HAI_E2E_MOCK - 显式模拟端到端测试标记
2050
+ * @returns 是否拒绝仅本机/进程有效的状态后端
2051
+ * @example
2052
+ * ```ts
2053
+ * import { core } from '@h-ai/core'
2054
+ * const production = core.module.requiresSharedState({ HAI_CORE_ENV: 'production' }) // true
2055
+ * const test = core.module.requiresSharedState({ NODE_ENV: 'production', HAI_E2E: '1' }) // false
2056
+ * ```
2057
+ */
2058
+ declare function requiresSharedState(environment: {
2059
+ NODE_ENV?: string;
2060
+ HAI_CORE_ENV?: string;
2061
+ HAI_E2E?: string;
2062
+ HAI_E2E_MOCK?: string;
2063
+ }): boolean;
2064
+ /**
2065
+ * 模块初始化占位与生产共享状态要求的工具契约。
2066
+ * @example 模块内部上下文
2067
+ * ```ts
2068
+ * const tools: ModuleFn = { createNotInitializedKit, requiresSharedState }
2069
+ * const shared = tools.requiresSharedState({ NODE_ENV: 'production' })
2070
+ * ```
2071
+ */
1747
2072
  interface ModuleFn {
1748
2073
  createNotInitializedKit: CreateNotInitializedKitFn;
2074
+ /** 生产共享状态要求;浏览器工具为纯函数,不隐式读取进程环境。 */
2075
+ requiresSharedState: typeof requiresSharedState;
1749
2076
  }
1750
2077
 
1751
2078
  /**
@@ -1759,25 +2086,22 @@ interface ModuleFn {
1759
2086
  * 监听回调类型。
1760
2087
  *
1761
2088
  * @template T - 配置数据类型
1762
- *
1763
- * @example
2089
+ * @example 模块内部上下文
1764
2090
  * ```ts
1765
- * const callback: WatchCallback<AppConfig> = (cfg, error) => {
1766
- * if (error) { core.logger.error('Config reload failed', { error }); return }
1767
- * // 使用更新后的 cfg
2091
+ * const callback: WatchCallback<{ enabled: boolean }> = (config, failure) => {
2092
+ * if (failure) { messages.push(failure.message); return }
2093
+ * if (config) messages.push(String(config.enabled))
1768
2094
  * }
2095
+ * const messages: string[] = []
1769
2096
  * ```
1770
2097
  */
1771
2098
  type WatchCallback<T = unknown> = (config: T | null, error?: HaiError) => void;
1772
2099
  /**
1773
2100
  * 配置管理对象。
1774
- *
1775
- * @example
2101
+ * @example 模块内部上下文
1776
2102
  * ```ts
1777
- * const result = config.load('app', './config/app.yml')
1778
- * if (result.success) {
1779
- * const cfg = config.get('app')
1780
- * }
2103
+ * const result = config.load('app', '/srv/app/config/app.yml')
2104
+ * if (!result.success) result.error.message
1781
2105
  * ```
1782
2106
  */
1783
2107
  declare const config: {
@@ -1971,4 +2295,4 @@ declare const config: {
1971
2295
  isWatching(name: string): boolean;
1972
2296
  };
1973
2297
 
1974
- export { err as $, type ArrayFn as A, LogLevelSchema as B, type CoreOptions as C, type Logger as D, type ErrorFn as E, type LoggerFunctions as F, type LoggerOptions as G, type HaiResult as H, type I18nFn as I, type LoggingConfig as J, LoggingConfigSchema as K, type Locale as L, type ModuleFn as M, type MatchHandlers as N, type ObjectFn as O, type MessageDictionary as P, type MessageOptions as Q, type PaginatedResult as R, type SanitizeFn as S, type TypeUtilFn as T, type PaginationOptions as U, type PaginationOptionsInput as V, type WatchCallback as W, type ValidationFormError as X, type ZodValidationFn as Y, type ZodMessageGetter as Z, type ZodValidationMessageKey as _, type CoreLogger as a, ok as a0, config as a1, type IdFn as b, type StringFn as c, type AsyncFn as d, type TimeFn as e, type CoreConfig as f, CoreConfigSchema as g, type CoreFunctions as h, type Env as i, EnvSchema as j, type ErrorInfo as k, type ErrorInfoValue as l, HaiCommonError as m, HaiConfigError as n, type HaiError as o, type HaiErrorDef as p, type IdConfig as q, IdConfigSchema as r, type InterpolationParams as s, type LocaleInfo as t, type LocaleMessages as u, type LogContext as v, type LogFormat as w, LogFormatSchema as x, type LogLevel as y, zodValidation as z };
2298
+ export { config as $, type ArrayFn as A, type LoggerFunctions as B, type CoreOptions as C, type LoggerOptions as D, type ErrorFn as E, type LoggingConfig as F, LoggingConfigSchema as G, type HaiResult as H, type I18nFn as I, type MatchHandlers as J, type MessageDictionary as K, type Locale as L, type ModuleFn as M, type MessageOptions as N, type ObjectFn as O, type PaginatedResult as P, type PaginationOptions as Q, type PaginationOptionsInput as R, type SanitizeFn as S, type TypeUtilFn as T, type ZodValidationFn as U, type ValidationFormError as V, type WatchCallback as W, type ZodValidationMessageKey as X, err as Y, type ZodMessageGetter as Z, ok as _, type CoreLogger as a, type IdFn as b, type StringFn as c, type AsyncFn as d, type TimeFn as e, type CoreConfig as f, CoreConfigSchema as g, type CoreFunctions as h, type Env as i, EnvSchema as j, type ErrorInfo as k, type ErrorInfoValue as l, HaiCommonError as m, HaiConfigError as n, type HaiError as o, type HaiErrorDef as p, type InterpolationParams as q, type LocaleInfo as r, type LocaleMessages as s, type LogContext as t, type LogFormat as u, LogFormatSchema as v, type LogLevel as w, LogLevelSchema as x, type Logger as y, zodValidation as z };