@h-ai/datapipe 0.1.0-alpha5

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [2026] [idealworld.group]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @h-ai/datapipe
2
+
3
+ 数据处理管线模块,提供文本清洗(clean)、分块(chunk)和可组合管线(pipeline)功能。纯函数模块,无需初始化。
4
+
5
+ ## 支持的功能
6
+
7
+ | 功能 | 说明 |
8
+ | -------- | ----------------------------------------------------------- |
9
+ | 文本清洗 | 移除 HTML 标签、URL、Email,标准化空白,自定义正则替换 |
10
+ | 文本分块 | 句子、段落、Markdown 标题、分页符、字数、字符、自定义分隔符 |
11
+ | 管线组合 | 链式组合清洗 → 转换 → 分块 → 分块后处理,一次执行 |
12
+
13
+ ## 快速开始
14
+
15
+ ```ts
16
+ import { datapipe, HaiDatapipeError } from '@h-ai/datapipe'
17
+
18
+ // 直接清洗
19
+ const cleaned = datapipe.clean('<p>Hello</p>', { removeHtml: true })
20
+
21
+ // 按 Markdown 标题分块
22
+ const chunks = datapipe.chunk(text, { mode: 'markdown', maxSize: 2000 })
23
+
24
+ // 管线模式(链式组合多步操作)
25
+ const result = await datapipe.pipeline()
26
+ .clean({ removeHtml: true, removeUrls: true })
27
+ .transform(text => text.toLowerCase())
28
+ .chunk({ mode: 'paragraph', maxSize: 1000, overlap: 100 })
29
+ .chunkTransform(chunks => chunks.filter(c => c.content.length > 50))
30
+ .run(rawText)
31
+ ```
32
+
33
+ ## 分块模式
34
+
35
+ | 模式 | 说明 |
36
+ | --------- | -------------------------------- |
37
+ | sentence | 按句子分块 |
38
+ | paragraph | 按段落分块 |
39
+ | markdown | 按 Markdown 标题分块 |
40
+ | page | 按分页符分块 |
41
+ | word | 按字数分块 |
42
+ | character | 按字符数分块 |
43
+ | custom | 自定义分隔符(需提供 separator) |
44
+
45
+ ## 错误处理
46
+
47
+ 所有操作返回 `HaiResult<T>`,通过 `result.success` 判断成功或失败。错误码为字符串格式 `hai:datapipe:NNN`。
48
+
49
+ ```ts
50
+ const result = datapipe.chunk(text, { mode: 'custom' })
51
+ if (!result.success) {
52
+ switch (result.error.code) {
53
+ case HaiDatapipeError.MISSING_SEPARATOR.code:
54
+ // mode='custom' 时需要提供 separator
55
+ break
56
+ case HaiDatapipeError.CONFIG_ERROR.code:
57
+ // 配置参数校验失败
58
+ break
59
+ }
60
+ }
61
+ ```
62
+
63
+ ## 测试
64
+
65
+ ```bash
66
+ pnpm --filter @h-ai/datapipe test
67
+ ```
68
+
69
+ ## License
70
+
71
+ Apache-2.0
@@ -0,0 +1,296 @@
1
+ import { z } from 'zod';
2
+ import * as _h_ai_core from '@h-ai/core';
3
+ import { HaiResult } from '@h-ai/core';
4
+
5
+ /**
6
+ * @h-ai/datapipe — 数据处理管线配置 Schema
7
+ *
8
+ * 本文件定义数据处理模块的错误码常量、Zod Schema 和配置类型。
9
+ * 支持清洗(clean)、分块(chunk)、转换(transform)和管线(pipeline)。
10
+ * @module datapipe-config
11
+ */
12
+
13
+ /**
14
+ * 清洗选项 Schema
15
+ *
16
+ * 数据清洗规则配置,支持移除 HTML、URL、Email、标准化空白等。
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const cleanOptions = {
21
+ * removeHtml: true,
22
+ * removeUrls: true,
23
+ * normalizeWhitespace: true,
24
+ * }
25
+ * ```
26
+ */
27
+ declare const CleanOptionsSchema: z.ZodObject<{
28
+ removeHtml: z.ZodDefault<z.ZodBoolean>;
29
+ removeUrls: z.ZodDefault<z.ZodBoolean>;
30
+ removeEmails: z.ZodDefault<z.ZodBoolean>;
31
+ normalizeWhitespace: z.ZodDefault<z.ZodBoolean>;
32
+ trim: z.ZodDefault<z.ZodBoolean>;
33
+ customReplacements: z.ZodOptional<z.ZodArray<z.ZodObject<{
34
+ pattern: z.ZodString;
35
+ replacement: z.ZodString;
36
+ }, z.core.$strip>>>;
37
+ }, z.core.$strip>;
38
+ /** 清洗选项类型 */
39
+ type CleanOptions = z.infer<typeof CleanOptionsSchema>;
40
+ /** 清洗选项输入类型 */
41
+ type CleanOptionsInput = z.input<typeof CleanOptionsSchema>;
42
+ /**
43
+ * 分块模式枚举
44
+ *
45
+ * - `sentence` — 按句子分块
46
+ * - `paragraph` — 按段落分块
47
+ * - `markdown` — 按 Markdown 标题分块(## / ### 等)
48
+ * - `page` — 按分页符分块
49
+ * - `word` — 按字数分块
50
+ * - `character` — 按字符数分块
51
+ * - `custom` — 自定义分隔符分块
52
+ */
53
+ declare const ChunkModeSchema: z.ZodEnum<{
54
+ custom: "custom";
55
+ sentence: "sentence";
56
+ paragraph: "paragraph";
57
+ markdown: "markdown";
58
+ page: "page";
59
+ word: "word";
60
+ character: "character";
61
+ }>;
62
+ /** 分块模式类型 */
63
+ type ChunkMode = z.infer<typeof ChunkModeSchema>;
64
+ /**
65
+ * 分块选项 Schema
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * // 按 Markdown 标题分块
70
+ * const chunkOptions = {
71
+ * mode: 'markdown',
72
+ * maxSize: 2000,
73
+ * overlap: 200,
74
+ * }
75
+ *
76
+ * // 按字符分块
77
+ * const chunkOptions = {
78
+ * mode: 'character',
79
+ * maxSize: 1000,
80
+ * overlap: 100,
81
+ * }
82
+ * ```
83
+ */
84
+ declare const ChunkOptionsSchema: z.ZodObject<{
85
+ mode: z.ZodEnum<{
86
+ custom: "custom";
87
+ sentence: "sentence";
88
+ paragraph: "paragraph";
89
+ markdown: "markdown";
90
+ page: "page";
91
+ word: "word";
92
+ character: "character";
93
+ }>;
94
+ maxSize: z.ZodDefault<z.ZodNumber>;
95
+ overlap: z.ZodDefault<z.ZodNumber>;
96
+ separator: z.ZodOptional<z.ZodString>;
97
+ markdownMinLevel: z.ZodDefault<z.ZodNumber>;
98
+ markdownKeepTitle: z.ZodDefault<z.ZodBoolean>;
99
+ }, z.core.$strip>;
100
+ /** 分块选项类型 */
101
+ type ChunkOptions = z.infer<typeof ChunkOptionsSchema>;
102
+ /** 分块选项输入类型 */
103
+ type ChunkOptionsInput = z.input<typeof ChunkOptionsSchema>;
104
+
105
+ /**
106
+ * Datapipe 模块标准错误定义对象。
107
+ */
108
+ declare const HaiDatapipeError: {
109
+ readonly CLEAN_FAILED: _h_ai_core.HaiErrorDef;
110
+ readonly CHUNK_FAILED: _h_ai_core.HaiErrorDef;
111
+ readonly TRANSFORM_FAILED: _h_ai_core.HaiErrorDef;
112
+ readonly PIPELINE_FAILED: _h_ai_core.HaiErrorDef;
113
+ readonly CONFIG_ERROR: _h_ai_core.HaiErrorDef;
114
+ readonly MISSING_SEPARATOR: _h_ai_core.HaiErrorDef;
115
+ };
116
+ /**
117
+ * 数据块接口
118
+ *
119
+ * 表示经过分块处理后的单个文本片段。
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * const chunk: DataChunk = {
124
+ * index: 0,
125
+ * content: '## 简介\n这是文档的第一部分。',
126
+ * metadata: { title: '简介', level: 2 },
127
+ * }
128
+ * ```
129
+ */
130
+ interface DataChunk {
131
+ /** 分块索引(从 0 开始) */
132
+ index: number;
133
+ /** 分块内容 */
134
+ content: string;
135
+ /** 分块元数据(可选) */
136
+ metadata?: Record<string, unknown>;
137
+ }
138
+ /**
139
+ * 转换函数类型
140
+ *
141
+ * 自定义文本后处理函数,可以是同步或异步。
142
+ */
143
+ type TransformFn = (text: string) => string | Promise<string>;
144
+ /**
145
+ * 分块转换函数类型
146
+ *
147
+ * 对分块列表进行后处理(如过滤、合并等)。
148
+ */
149
+ type ChunkTransformFn = (chunks: DataChunk[]) => DataChunk[] | Promise<DataChunk[]>;
150
+ /**
151
+ * 管线步骤类型
152
+ *
153
+ * 管线由一系列步骤组成,支持清洗、分块和自定义转换。
154
+ */
155
+ type PipelineStep = {
156
+ type: 'clean';
157
+ options?: CleanOptionsInput;
158
+ } | {
159
+ type: 'chunk';
160
+ options: ChunkOptionsInput;
161
+ } | {
162
+ type: 'transform';
163
+ fn: TransformFn;
164
+ } | {
165
+ type: 'chunkTransform';
166
+ fn: ChunkTransformFn;
167
+ };
168
+ /**
169
+ * 管线执行结果
170
+ */
171
+ interface PipelineResult {
172
+ /** 处理后的文本(分块前的最终文本) */
173
+ text: string;
174
+ /** 分块列表(如果管线包含 chunk 步骤) */
175
+ chunks: DataChunk[];
176
+ }
177
+ /**
178
+ * 清洗操作接口
179
+ *
180
+ * 通过 `datapipe.clean()` 调用。
181
+ */
182
+ interface CleanOperations {
183
+ /**
184
+ * 清洗文本
185
+ *
186
+ * @param text - 原始文本
187
+ * @param options - 清洗选项(可选,使用默认值)
188
+ * @returns 清洗后的文本
189
+ */
190
+ (text: string, options?: CleanOptionsInput): HaiResult<string>;
191
+ }
192
+ /**
193
+ * 分块操作接口
194
+ *
195
+ * 通过 `datapipe.chunk()` 调用。
196
+ */
197
+ interface ChunkOperations {
198
+ /**
199
+ * 对文本进行分块
200
+ *
201
+ * @param text - 输入文本
202
+ * @param options - 分块选项
203
+ * @returns 分块列表
204
+ */
205
+ (text: string, options: ChunkOptionsInput): HaiResult<DataChunk[]>;
206
+ }
207
+ /**
208
+ * 管线构建器接口
209
+ *
210
+ * 通过 `datapipe.pipeline()` 创建,链式添加步骤后执行。
211
+ *
212
+ * @example
213
+ * ```ts
214
+ * const result = await datapipe.pipeline()
215
+ * .clean({ removeHtml: true })
216
+ * .transform(text => text.toLowerCase())
217
+ * .chunk({ mode: 'markdown', maxSize: 2000 })
218
+ * .run('原始文本')
219
+ * ```
220
+ */
221
+ interface PipelineBuilder {
222
+ /** 添加清洗步骤 */
223
+ clean: (options?: CleanOptionsInput) => PipelineBuilder;
224
+ /** 添加分块步骤 */
225
+ chunk: (options: ChunkOptionsInput) => PipelineBuilder;
226
+ /** 添加文本转换步骤 */
227
+ transform: (fn: TransformFn) => PipelineBuilder;
228
+ /** 添加分块后处理步骤 */
229
+ chunkTransform: (fn: ChunkTransformFn) => PipelineBuilder;
230
+ /** 执行管线 */
231
+ run: (text: string) => Promise<HaiResult<PipelineResult>>;
232
+ }
233
+ /**
234
+ * 数据处理管线服务接口
235
+ *
236
+ * @example
237
+ * ```ts
238
+ * import { datapipe } from '@h-ai/datapipe'
239
+ *
240
+ * // 直接清洗
241
+ * const cleaned = datapipe.clean('<p>Hello</p>', { removeHtml: true })
242
+ *
243
+ * // 直接分块
244
+ * const chunks = datapipe.chunk(text, { mode: 'markdown', maxSize: 2000 })
245
+ *
246
+ * // 管线模式
247
+ * const result = await datapipe.pipeline()
248
+ * .clean()
249
+ * .chunk({ mode: 'paragraph' })
250
+ * .run(text)
251
+ * ```
252
+ */
253
+ interface DatapipeFunctions {
254
+ /** 清洗文本 */
255
+ clean: CleanOperations;
256
+ /** 分块文本 */
257
+ chunk: ChunkOperations;
258
+ /** 创建管线构建器 */
259
+ pipeline: () => PipelineBuilder;
260
+ }
261
+
262
+ /**
263
+ * @h-ai/datapipe — 数据处理管线主入口
264
+ *
265
+ * 提供统一的 `datapipe` 对象,聚合清洗、分块和管线功能。
266
+ * datapipe 为纯函数模块,无需初始化即可使用。
267
+ * @module datapipe-main
268
+ */
269
+
270
+ /**
271
+ * 数据处理管线服务对象
272
+ *
273
+ * 纯函数模块,无需初始化即可使用。
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * import { datapipe } from '@h-ai/datapipe'
278
+ *
279
+ * // 直接清洗
280
+ * const cleaned = datapipe.clean('<p>Hello</p>')
281
+ *
282
+ * // 按 Markdown 标题分块
283
+ * const chunks = datapipe.chunk(text, { mode: 'markdown', maxSize: 2000 })
284
+ *
285
+ * // 管线模式
286
+ * const result = await datapipe.pipeline()
287
+ * .clean({ removeHtml: true, removeUrls: true })
288
+ * .transform(text => text.toLowerCase())
289
+ * .chunk({ mode: 'paragraph', maxSize: 1000, overlap: 100 })
290
+ * .chunkTransform(chunks => chunks.filter(c => c.content.length > 50))
291
+ * .run(rawHtml)
292
+ * ```
293
+ */
294
+ declare const datapipe: DatapipeFunctions;
295
+
296
+ export { type ChunkMode, ChunkModeSchema, type ChunkOperations, type ChunkOptions, type ChunkOptionsInput, ChunkOptionsSchema, type ChunkTransformFn, type CleanOperations, type CleanOptions, type CleanOptionsInput, CleanOptionsSchema, type DataChunk, type DatapipeFunctions, HaiDatapipeError, type PipelineBuilder, type PipelineResult, type PipelineStep, type TransformFn, datapipe };
package/dist/index.js ADDED
@@ -0,0 +1,411 @@
1
+ import { z } from 'zod';
2
+ import { core, err, ok } from '@h-ai/core';
3
+
4
+ // src/datapipe-config.ts
5
+ var CleanOptionsSchema = z.object({
6
+ /** 移除 HTML 标签(默认 true) */
7
+ removeHtml: z.boolean().default(true),
8
+ /** 移除 URL(默认 false) */
9
+ removeUrls: z.boolean().default(false),
10
+ /** 移除 Email 地址(默认 false) */
11
+ removeEmails: z.boolean().default(false),
12
+ /** 标准化空白字符(多空格→单空格、去掉多余空行,默认 true) */
13
+ normalizeWhitespace: z.boolean().default(true),
14
+ /** 去除首尾空白(默认 true) */
15
+ trim: z.boolean().default(true),
16
+ /**
17
+ * 自定义替换规则(正则→替换字符串)
18
+ *
19
+ * ❗ 安全提示:pattern 会通过 `new RegExp()` 构造,如果其值来源于用户输入,请在调用方先行校验以防止 ReDoS 攻击。
20
+ */
21
+ customReplacements: z.array(z.object({
22
+ /** 正则表达式字符串 */
23
+ pattern: z.string(),
24
+ /** 替换文本 */
25
+ replacement: z.string()
26
+ })).optional()
27
+ });
28
+ var ChunkModeSchema = z.enum([
29
+ "sentence",
30
+ "paragraph",
31
+ "markdown",
32
+ "page",
33
+ "word",
34
+ "character",
35
+ "custom"
36
+ ]);
37
+ var ChunkOptionsSchema = z.object({
38
+ /** 分块模式 */
39
+ mode: ChunkModeSchema,
40
+ /** 每个分块的最大大小(字符数 / 字数,取决于 mode,默认 1000) */
41
+ maxSize: z.number().int().positive().default(1500),
42
+ /** 重叠大小(字符数 / 字数,用于上下文衔接,默认 200) */
43
+ overlap: z.number().int().min(0).default(200),
44
+ /**
45
+ * 自定义分隔符正则(仅 mode='custom' 时使用)
46
+ *
47
+ * ❗ 安全提示:separator 会通过 `new RegExp()` 构造,如果其值来源于用户输入,请在调用方先行校验以防止 ReDoS 攻击。
48
+ */
49
+ separator: z.string().optional(),
50
+ /** Markdown 标题分割深度(1-6,默认 2,即 # 和 ## 作为分块边界;设为 3 则 ### 也作为分块边界) */
51
+ markdownMinLevel: z.number().int().min(1).max(6).default(2),
52
+ /** 是否保留 Markdown 标题在分块内容中(默认 true) */
53
+ markdownKeepTitle: z.boolean().default(true)
54
+ });
55
+
56
+ // messages/en-US.json
57
+ var en_US_default = {
58
+ $schema: "https://inlang.com/schema/inlang-message-format",
59
+ datapipe_cleanFailed: "Failed to clean text: {error}",
60
+ datapipe_chunkFailed: "Failed to chunk text: {error}",
61
+ datapipe_transformFailed: "Failed to transform text: {error}",
62
+ datapipe_pipelineFailed: "Pipeline execution failed: {error}",
63
+ datapipe_configError: "Datapipe config validation failed: {error}",
64
+ datapipe_missingSeparator: "Custom chunk mode requires a separator parameter"
65
+ };
66
+
67
+ // messages/zh-CN.json
68
+ var zh_CN_default = {
69
+ $schema: "https://inlang.com/schema/inlang-message-format",
70
+ datapipe_cleanFailed: "\u6E05\u6D17\u6587\u672C\u5931\u8D25: {error}",
71
+ datapipe_chunkFailed: "\u5206\u5757\u6587\u672C\u5931\u8D25: {error}",
72
+ datapipe_transformFailed: "\u8F6C\u6362\u6587\u672C\u5931\u8D25: {error}",
73
+ datapipe_pipelineFailed: "\u7BA1\u7EBF\u6267\u884C\u5931\u8D25: {error}",
74
+ datapipe_configError: "\u6570\u636E\u5904\u7406\u914D\u7F6E\u6821\u9A8C\u5931\u8D25\uFF1A{error}",
75
+ datapipe_missingSeparator: "\u81EA\u5B9A\u4E49\u5206\u5757\u6A21\u5F0F\u9700\u8981\u63D0\u4F9B separator \u53C2\u6570"
76
+ };
77
+
78
+ // src/datapipe-i18n.ts
79
+ var datapipeM = core.i18n.createMessageGetter({
80
+ "zh-CN": zh_CN_default,
81
+ "en-US": en_US_default
82
+ });
83
+ var DatapipeErrorInfo = {
84
+ CLEAN_FAILED: "001:500",
85
+ CHUNK_FAILED: "002:500",
86
+ TRANSFORM_FAILED: "003:500",
87
+ PIPELINE_FAILED: "004:500",
88
+ CONFIG_ERROR: "005:400",
89
+ MISSING_SEPARATOR: "006:400"
90
+ };
91
+ var HaiDatapipeError = core.error.buildHaiErrorsDef("datapipe", DatapipeErrorInfo);
92
+
93
+ // src/datapipe-chunk.ts
94
+ function splitBySentence(text) {
95
+ const segments = text.split(/(?<=[。!?.!?])\s*/);
96
+ return segments.filter((s) => s.trim().length > 0);
97
+ }
98
+ function splitByParagraph(text) {
99
+ const segments = text.split(/\n\s*\n/);
100
+ return segments.filter((s) => s.trim().length > 0);
101
+ }
102
+ function splitByMarkdown(text, minLevel, keepTitle) {
103
+ const headerPattern = new RegExp(`^(#{1,${minLevel}})\\s+(.+)$`, "gm");
104
+ const sections = [];
105
+ let lastIndex = 0;
106
+ let lastTitle = "";
107
+ let lastLevel = 0;
108
+ let match = null;
109
+ match = headerPattern.exec(text);
110
+ if (match && match.index > 0) {
111
+ const preContent = text.slice(0, match.index).trim();
112
+ if (preContent.length > 0) {
113
+ sections.push({ content: preContent, title: "", level: 0 });
114
+ }
115
+ }
116
+ headerPattern.lastIndex = 0;
117
+ while ((match = headerPattern.exec(text)) !== null) {
118
+ if (lastIndex > 0 || lastTitle) {
119
+ const content = text.slice(lastIndex, match.index).trim();
120
+ if (content.length > 0 || lastTitle) {
121
+ const finalContent = keepTitle && lastTitle ? `${"#".repeat(lastLevel)} ${lastTitle}
122
+ ${content}` : content;
123
+ sections.push({
124
+ content: finalContent.trim(),
125
+ title: lastTitle,
126
+ level: lastLevel
127
+ });
128
+ }
129
+ }
130
+ lastTitle = match[2].trim();
131
+ lastLevel = match[1].length;
132
+ lastIndex = match.index + match[0].length;
133
+ }
134
+ if (lastTitle || lastIndex > 0) {
135
+ const content = text.slice(lastIndex).trim();
136
+ const finalContent = keepTitle && lastTitle ? `${"#".repeat(lastLevel)} ${lastTitle}
137
+ ${content}` : content;
138
+ sections.push({
139
+ content: finalContent.trim(),
140
+ title: lastTitle,
141
+ level: lastLevel
142
+ });
143
+ }
144
+ if (sections.length === 0) {
145
+ sections.push({ content: text.trim(), title: "", level: 0 });
146
+ }
147
+ return sections.filter((s) => s.content.length > 0);
148
+ }
149
+ function splitByPage(text) {
150
+ const segments = text.split(/\f/);
151
+ return segments.filter((s) => s.trim().length > 0);
152
+ }
153
+ function splitByWord(text, maxSize) {
154
+ const words = text.split(/\s+/);
155
+ const chunks = [];
156
+ let current = [];
157
+ let currentSize = 0;
158
+ for (const word of words) {
159
+ if (currentSize + 1 > maxSize && current.length > 0) {
160
+ chunks.push(current.join(" "));
161
+ current = [];
162
+ currentSize = 0;
163
+ }
164
+ current.push(word);
165
+ currentSize++;
166
+ }
167
+ if (current.length > 0) {
168
+ chunks.push(current.join(" "));
169
+ }
170
+ return chunks;
171
+ }
172
+ function splitByCharacter(text, maxSize) {
173
+ const chunks = [];
174
+ for (let i = 0; i < text.length; i += maxSize) {
175
+ chunks.push(text.slice(i, i + maxSize));
176
+ }
177
+ return chunks;
178
+ }
179
+ function splitByCustom(text, separator) {
180
+ const regex = new RegExp(separator);
181
+ const segments = text.split(regex);
182
+ return segments.filter((s) => s.trim().length > 0);
183
+ }
184
+ function splitTextByMode(text, mode, maxSize, separator) {
185
+ switch (mode) {
186
+ case "sentence":
187
+ return splitBySentence(text);
188
+ case "paragraph":
189
+ return splitByParagraph(text);
190
+ case "page":
191
+ return splitByPage(text);
192
+ case "word":
193
+ return splitByWord(text, maxSize);
194
+ case "character":
195
+ return splitByCharacter(text, maxSize);
196
+ case "custom":
197
+ return splitByCustom(text, separator ?? "\n");
198
+ default:
199
+ return [text];
200
+ }
201
+ }
202
+ function buildChunks(segments, maxSize, overlap) {
203
+ const chunks = [];
204
+ let currentContent = "";
205
+ let chunkIndex = 0;
206
+ for (const segment of segments) {
207
+ if (currentContent.length > 0 && currentContent.length + segment.length + 1 > maxSize) {
208
+ chunks.push({
209
+ index: chunkIndex++,
210
+ content: currentContent.trim()
211
+ });
212
+ if (overlap > 0 && currentContent.length > overlap) {
213
+ currentContent = currentContent.slice(-overlap);
214
+ } else {
215
+ currentContent = "";
216
+ }
217
+ }
218
+ if (segment.length > maxSize) {
219
+ if (currentContent.length > 0) {
220
+ chunks.push({
221
+ index: chunkIndex++,
222
+ content: currentContent.trim()
223
+ });
224
+ currentContent = "";
225
+ }
226
+ for (let i = 0; i < segment.length; i += maxSize) {
227
+ const part = segment.slice(i, i + maxSize);
228
+ chunks.push({
229
+ index: chunkIndex++,
230
+ content: part.trim()
231
+ });
232
+ }
233
+ continue;
234
+ }
235
+ currentContent += (currentContent.length > 0 ? "\n" : "") + segment;
236
+ }
237
+ if (currentContent.trim().length > 0) {
238
+ chunks.push({
239
+ index: chunkIndex,
240
+ content: currentContent.trim()
241
+ });
242
+ }
243
+ return chunks;
244
+ }
245
+ function buildMarkdownChunks(text, maxSize, overlap, markdownMinLevel, markdownKeepTitle) {
246
+ const mdSegments = splitByMarkdown(text, markdownMinLevel, markdownKeepTitle);
247
+ const chunks = [];
248
+ for (const segment of mdSegments) {
249
+ if (segment.content.length > maxSize) {
250
+ const subChunks = buildChunks([segment.content], maxSize, overlap);
251
+ for (const sub of subChunks) {
252
+ chunks.push({
253
+ index: chunks.length,
254
+ content: sub.content,
255
+ metadata: { title: segment.title, level: segment.level, subChunk: true }
256
+ });
257
+ }
258
+ } else {
259
+ chunks.push({
260
+ index: chunks.length,
261
+ content: segment.content,
262
+ metadata: { title: segment.title, level: segment.level }
263
+ });
264
+ }
265
+ }
266
+ return chunks;
267
+ }
268
+ function chunkText(text, options) {
269
+ const parseResult = ChunkOptionsSchema.safeParse(options);
270
+ if (!parseResult.success) {
271
+ return err(HaiDatapipeError.CONFIG_ERROR, datapipeM("datapipe_configError", { params: { error: parseResult.error.message } }), parseResult.error);
272
+ }
273
+ const opts = parseResult.data;
274
+ if (opts.mode === "custom" && !opts.separator) {
275
+ return err(HaiDatapipeError.MISSING_SEPARATOR, datapipeM("datapipe_missingSeparator"));
276
+ }
277
+ if (!text || text.trim().length === 0) {
278
+ return ok([]);
279
+ }
280
+ try {
281
+ if (opts.mode === "markdown") {
282
+ const chunks2 = buildMarkdownChunks(text, opts.maxSize, opts.overlap, opts.markdownMinLevel, opts.markdownKeepTitle);
283
+ return ok(chunks2);
284
+ }
285
+ const segments = splitTextByMode(text, opts.mode, opts.maxSize, opts.separator);
286
+ const chunks = buildChunks(segments, opts.maxSize, opts.overlap);
287
+ return ok(chunks);
288
+ } catch (error) {
289
+ return err(HaiDatapipeError.CHUNK_FAILED, datapipeM("datapipe_chunkFailed", { params: { error: String(error) } }), error);
290
+ }
291
+ }
292
+ var HTML_TAG_REGEX = /<[^>]*>/g;
293
+ var URL_REGEX = /https?:\/\/[^\s<>"{}|\\^`[\]]+/g;
294
+ var EMAIL_REGEX = /[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi;
295
+ var MULTI_NEWLINE_REGEX = /\n{3,}/g;
296
+ var MULTI_SPACE_REGEX = /[ \t]{2,}/g;
297
+ function cleanText(text, options) {
298
+ const parseResult = CleanOptionsSchema.safeParse(options ?? {});
299
+ if (!parseResult.success) {
300
+ return err(HaiDatapipeError.CONFIG_ERROR, datapipeM("datapipe_configError", { params: { error: parseResult.error.message } }), parseResult.error);
301
+ }
302
+ const opts = parseResult.data;
303
+ let result = text;
304
+ try {
305
+ if (opts.removeHtml) {
306
+ result = result.replace(HTML_TAG_REGEX, "");
307
+ }
308
+ if (opts.removeUrls) {
309
+ result = result.replace(URL_REGEX, "");
310
+ }
311
+ if (opts.removeEmails) {
312
+ result = result.replace(EMAIL_REGEX, "");
313
+ }
314
+ if (opts.customReplacements) {
315
+ for (const { pattern, replacement } of opts.customReplacements) {
316
+ let regex;
317
+ try {
318
+ regex = new RegExp(pattern, "g");
319
+ } catch (regexError) {
320
+ return err(HaiDatapipeError.CONFIG_ERROR, datapipeM("datapipe_configError", { params: { error: String(regexError) } }), regexError);
321
+ }
322
+ result = result.replace(regex, replacement);
323
+ }
324
+ }
325
+ if (opts.normalizeWhitespace) {
326
+ result = result.replace(MULTI_SPACE_REGEX, " ");
327
+ result = result.replace(MULTI_NEWLINE_REGEX, "\n\n");
328
+ }
329
+ if (opts.trim) {
330
+ result = result.trim();
331
+ }
332
+ return ok(result);
333
+ } catch (error) {
334
+ return err(HaiDatapipeError.CLEAN_FAILED, datapipeM("datapipe_cleanFailed", { params: { error: String(error) } }), error);
335
+ }
336
+ }
337
+ function createPipelineBuilder() {
338
+ const steps = [];
339
+ const builder = {
340
+ clean(options) {
341
+ steps.push({ type: "clean", options });
342
+ return builder;
343
+ },
344
+ chunk(options) {
345
+ steps.push({ type: "chunk", options });
346
+ return builder;
347
+ },
348
+ transform(fn) {
349
+ steps.push({ type: "transform", fn });
350
+ return builder;
351
+ },
352
+ chunkTransform(fn) {
353
+ steps.push({ type: "chunkTransform", fn });
354
+ return builder;
355
+ },
356
+ run: (text) => runPipeline(steps, text)
357
+ };
358
+ return builder;
359
+ }
360
+ async function runPipeline(steps, text) {
361
+ let currentText = text;
362
+ let chunks = [];
363
+ for (const step of steps) {
364
+ switch (step.type) {
365
+ case "clean": {
366
+ const result = cleanText(currentText, step.options);
367
+ if (!result.success)
368
+ return result;
369
+ currentText = result.data;
370
+ break;
371
+ }
372
+ case "chunk": {
373
+ const result = chunkText(currentText, step.options);
374
+ if (!result.success)
375
+ return result;
376
+ chunks = result.data;
377
+ break;
378
+ }
379
+ case "transform": {
380
+ try {
381
+ currentText = await step.fn(currentText);
382
+ } catch (error) {
383
+ return err(HaiDatapipeError.TRANSFORM_FAILED, datapipeM("datapipe_transformFailed", { params: { error: String(error) } }), error);
384
+ }
385
+ break;
386
+ }
387
+ case "chunkTransform": {
388
+ if (chunks.length > 0) {
389
+ try {
390
+ chunks = await step.fn(chunks);
391
+ } catch (error) {
392
+ return err(HaiDatapipeError.PIPELINE_FAILED, datapipeM("datapipe_pipelineFailed", { params: { error: String(error) } }), error);
393
+ }
394
+ }
395
+ break;
396
+ }
397
+ }
398
+ }
399
+ return ok({ text: currentText, chunks });
400
+ }
401
+
402
+ // src/datapipe-main.ts
403
+ var datapipe = {
404
+ clean: cleanText,
405
+ chunk: chunkText,
406
+ pipeline: createPipelineBuilder
407
+ };
408
+
409
+ export { ChunkModeSchema, ChunkOptionsSchema, CleanOptionsSchema, HaiDatapipeError, datapipe };
410
+ //# sourceMappingURL=index.js.map
411
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/datapipe-config.ts","../messages/en-US.json","../messages/zh-CN.json","../src/datapipe-i18n.ts","../src/datapipe-types.ts","../src/datapipe-chunk.ts","../src/datapipe-clean.ts","../src/datapipe-pipeline.ts","../src/datapipe-main.ts"],"names":["core","chunks","err","ok"],"mappings":";;;;AA0BO,IAAM,kBAAA,GAAqB,EAAE,MAAA,CAAO;AAAA;AAAA,EAEzC,UAAA,EAAY,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,IAAI,CAAA;AAAA;AAAA,EAEpC,UAAA,EAAY,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA;AAAA;AAAA,EAErC,YAAA,EAAc,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA;AAAA;AAAA,EAEvC,mBAAA,EAAqB,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,IAAI,CAAA;AAAA;AAAA,EAE7C,IAAA,EAAM,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,IAAI,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,kBAAA,EAAoB,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,CAAO;AAAA;AAAA,IAEnC,OAAA,EAAS,EAAE,MAAA,EAAO;AAAA;AAAA,IAElB,WAAA,EAAa,EAAE,MAAA;AA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EAAO;AACZ,YAAA,OAAOA,GAAAA,CAAI,gBAAA,CAAiB,eAAA,EAAiB,SAAA,CAAU,2BAA2B,EAAE,MAAA,EAAQ,EAAE,KAAA,EAAO,OAAO,KAAK,CAAA,EAAE,EAAG,GAAG,KAAK,CAAA;AAAA,UAChI;AAAA,QACF;AACA,QAAA;AAAA,MACF;AAAA;AACF,EACF;AAEA,EAAA,OAAOC,EAAAA,CAAG,EAAE,IAAA,EAAM,WAAA,EAAa,QAAQ,CAAA;AACzC;;;ACxFO,IAAM,QAAA,GAA8B;AAAA,EACzC,KAAA,EAAO,SAAA;AAAA,EACP,KAAA,EAAO,SAAA;AAAA,EACP,QAAA,EAAU;AACZ","file":"index.js","sourcesContent":["/**\n * @h-ai/datapipe — 数据处理管线配置 Schema\n *\n * 本文件定义数据处理模块的错误码常量、Zod Schema 和配置类型。\n * 支持清洗(clean)、分块(chunk)、转换(transform)和管线(pipeline)。\n * @module datapipe-config\n */\n\nimport { z } from 'zod'\n\n// ─── 清洗配置 ───\n\n/**\n * 清洗选项 Schema\n *\n * 数据清洗规则配置,支持移除 HTML、URL、Email、标准化空白等。\n *\n * @example\n * ```ts\n * const cleanOptions = {\n * removeHtml: true,\n * removeUrls: true,\n * normalizeWhitespace: true,\n * }\n * ```\n */\nexport const CleanOptionsSchema = z.object({\n /** 移除 HTML 标签(默认 true) */\n removeHtml: z.boolean().default(true),\n /** 移除 URL(默认 false) */\n removeUrls: z.boolean().default(false),\n /** 移除 Email 地址(默认 false) */\n removeEmails: z.boolean().default(false),\n /** 标准化空白字符(多空格→单空格、去掉多余空行,默认 true) */\n normalizeWhitespace: z.boolean().default(true),\n /** 去除首尾空白(默认 true) */\n trim: z.boolean().default(true),\n /**\n * 自定义替换规则(正则→替换字符串)\n *\n * ❗ 安全提示:pattern 会通过 `new RegExp()` 构造,如果其值来源于用户输入,请在调用方先行校验以防止 ReDoS 攻击。\n */\n customReplacements: z.array(z.object({\n /** 正则表达式字符串 */\n pattern: z.string(),\n /** 替换文本 */\n replacement: z.string(),\n })).optional(),\n})\n\n/** 清洗选项类型 */\nexport type CleanOptions = z.infer<typeof CleanOptionsSchema>\n\n/** 清洗选项输入类型 */\nexport type CleanOptionsInput = z.input<typeof CleanOptionsSchema>\n\n// ─── 分块配置 ───\n\n/**\n * 分块模式枚举\n *\n * - `sentence` — 按句子分块\n * - `paragraph` — 按段落分块\n * - `markdown` — 按 Markdown 标题分块(## / ### 等)\n * - `page` — 按分页符分块\n * - `word` — 按字数分块\n * - `character` — 按字符数分块\n * - `custom` — 自定义分隔符分块\n */\nexport const ChunkModeSchema = z.enum([\n 'sentence',\n 'paragraph',\n 'markdown',\n 'page',\n 'word',\n 'character',\n 'custom',\n])\n\n/** 分块模式类型 */\nexport type ChunkMode = z.infer<typeof ChunkModeSchema>\n\n/**\n * 分块选项 Schema\n *\n * @example\n * ```ts\n * // 按 Markdown 标题分块\n * const chunkOptions = {\n * mode: 'markdown',\n * maxSize: 2000,\n * overlap: 200,\n * }\n *\n * // 按字符分块\n * const chunkOptions = {\n * mode: 'character',\n * maxSize: 1000,\n * overlap: 100,\n * }\n * ```\n */\nexport const ChunkOptionsSchema = z.object({\n /** 分块模式 */\n mode: ChunkModeSchema,\n /** 每个分块的最大大小(字符数 / 字数,取决于 mode,默认 1000) */\n maxSize: z.number().int().positive().default(1500),\n /** 重叠大小(字符数 / 字数,用于上下文衔接,默认 200) */\n overlap: z.number().int().min(0).default(200),\n /**\n * 自定义分隔符正则(仅 mode='custom' 时使用)\n *\n * ❗ 安全提示:separator 会通过 `new RegExp()` 构造,如果其值来源于用户输入,请在调用方先行校验以防止 ReDoS 攻击。\n */\n separator: z.string().optional(),\n /** Markdown 标题分割深度(1-6,默认 2,即 # 和 ## 作为分块边界;设为 3 则 ### 也作为分块边界) */\n markdownMinLevel: z.number().int().min(1).max(6).default(2),\n /** 是否保留 Markdown 标题在分块内容中(默认 true) */\n markdownKeepTitle: z.boolean().default(true),\n})\n\n/** 分块选项类型 */\nexport type ChunkOptions = z.infer<typeof ChunkOptionsSchema>\n\n/** 分块选项输入类型 */\nexport type ChunkOptionsInput = z.input<typeof ChunkOptionsSchema>\n","{\n \"$schema\": \"https://inlang.com/schema/inlang-message-format\",\n \"datapipe_cleanFailed\": \"Failed to clean text: {error}\",\n \"datapipe_chunkFailed\": \"Failed to chunk text: {error}\",\n \"datapipe_transformFailed\": \"Failed to transform text: {error}\",\n \"datapipe_pipelineFailed\": \"Pipeline execution failed: {error}\",\n \"datapipe_configError\": \"Datapipe config validation failed: {error}\",\n \"datapipe_missingSeparator\": \"Custom chunk mode requires a separator parameter\"\n}\n","{\n \"$schema\": \"https://inlang.com/schema/inlang-message-format\",\n \"datapipe_cleanFailed\": \"清洗文本失败: {error}\",\n \"datapipe_chunkFailed\": \"分块文本失败: {error}\",\n \"datapipe_transformFailed\": \"转换文本失败: {error}\",\n \"datapipe_pipelineFailed\": \"管线执行失败: {error}\",\n \"datapipe_configError\": \"数据处理配置校验失败:{error}\",\n \"datapipe_missingSeparator\": \"自定义分块模式需要提供 separator 参数\"\n}\n","/**\n * @h-ai/datapipe — i18n\n *\n * 本文件提供数据处理模块的 i18n 文案访问入口。\n * @module datapipe-i18n\n */\n\nimport { core } from '@h-ai/core'\nimport messagesEnUS from '../messages/en-US.json'\nimport messagesZhCN from '../messages/zh-CN.json'\n\n// ─── i18n ───\n\n/**\n * 数据处理模块文案 Key 类型\n */\ntype DatapipeMessageKey = keyof typeof messagesZhCN\n\n/**\n * 获取数据处理模块文案。\n * @param key - 文案 Key\n * @param options - 插值参数与格式化选项\n * @returns 本地化后的文案字符串\n */\nexport const datapipeM = core.i18n.createMessageGetter<DatapipeMessageKey>({\n 'zh-CN': messagesZhCN,\n 'en-US': messagesEnUS,\n})\n","/**\n * @h-ai/datapipe — 类型定义\n *\n * 本文件定义数据处理模块的核心接口和类型。\n * @module datapipe-types\n */\n\nimport type { ErrorInfo, HaiResult } from '@h-ai/core'\nimport type { ChunkOptionsInput, CleanOptionsInput } from './datapipe-config.js'\nimport { core } from '@h-ai/core'\n\n// ─── 错误定义(照 @h-ai/core 范式) ───\n\n/**\n * 数据处理错误信息映射(错误码:HTTP状态码)。\n *\n * 完整错误码将自动生成为:`hai:datapipe:NNN`\n */\nconst DatapipeErrorInfo = {\n CLEAN_FAILED: '001:500',\n CHUNK_FAILED: '002:500',\n TRANSFORM_FAILED: '003:500',\n PIPELINE_FAILED: '004:500',\n CONFIG_ERROR: '005:400',\n MISSING_SEPARATOR: '006:400',\n} as const satisfies ErrorInfo\n\n/**\n * Datapipe 模块标准错误定义对象。\n */\nexport const HaiDatapipeError = core.error.buildHaiErrorsDef('datapipe', DatapipeErrorInfo)\n\n// ─── 数据块 ───\n\n/**\n * 数据块接口\n *\n * 表示经过分块处理后的单个文本片段。\n *\n * @example\n * ```ts\n * const chunk: DataChunk = {\n * index: 0,\n * content: '## 简介\\n这是文档的第一部分。',\n * metadata: { title: '简介', level: 2 },\n * }\n * ```\n */\nexport interface DataChunk {\n /** 分块索引(从 0 开始) */\n index: number\n /** 分块内容 */\n content: string\n /** 分块元数据(可选) */\n metadata?: Record<string, unknown>\n}\n\n// ─── 转换函数 ───\n\n/**\n * 转换函数类型\n *\n * 自定义文本后处理函数,可以是同步或异步。\n */\nexport type TransformFn = (text: string) => string | Promise<string>\n\n/**\n * 分块转换函数类型\n *\n * 对分块列表进行后处理(如过滤、合并等)。\n */\nexport type ChunkTransformFn = (chunks: DataChunk[]) => DataChunk[] | Promise<DataChunk[]>\n\n// ─── 管线步骤 ───\n\n/**\n * 管线步骤类型\n *\n * 管线由一系列步骤组成,支持清洗、分块和自定义转换。\n */\nexport type PipelineStep\n = | { type: 'clean', options?: CleanOptionsInput }\n | { type: 'chunk', options: ChunkOptionsInput }\n | { type: 'transform', fn: TransformFn }\n | { type: 'chunkTransform', fn: ChunkTransformFn }\n\n// ─── 管线结果 ───\n\n/**\n * 管线执行结果\n */\nexport interface PipelineResult {\n /** 处理后的文本(分块前的最终文本) */\n text: string\n /** 分块列表(如果管线包含 chunk 步骤) */\n chunks: DataChunk[]\n}\n\n// ─── 操作接口 ───\n\n/**\n * 清洗操作接口\n *\n * 通过 `datapipe.clean()` 调用。\n */\nexport interface CleanOperations {\n /**\n * 清洗文本\n *\n * @param text - 原始文本\n * @param options - 清洗选项(可选,使用默认值)\n * @returns 清洗后的文本\n */\n (text: string, options?: CleanOptionsInput): HaiResult<string>\n}\n\n/**\n * 分块操作接口\n *\n * 通过 `datapipe.chunk()` 调用。\n */\nexport interface ChunkOperations {\n /**\n * 对文本进行分块\n *\n * @param text - 输入文本\n * @param options - 分块选项\n * @returns 分块列表\n */\n (text: string, options: ChunkOptionsInput): HaiResult<DataChunk[]>\n}\n\n/**\n * 管线构建器接口\n *\n * 通过 `datapipe.pipeline()` 创建,链式添加步骤后执行。\n *\n * @example\n * ```ts\n * const result = await datapipe.pipeline()\n * .clean({ removeHtml: true })\n * .transform(text => text.toLowerCase())\n * .chunk({ mode: 'markdown', maxSize: 2000 })\n * .run('原始文本')\n * ```\n */\nexport interface PipelineBuilder {\n /** 添加清洗步骤 */\n clean: (options?: CleanOptionsInput) => PipelineBuilder\n /** 添加分块步骤 */\n chunk: (options: ChunkOptionsInput) => PipelineBuilder\n /** 添加文本转换步骤 */\n transform: (fn: TransformFn) => PipelineBuilder\n /** 添加分块后处理步骤 */\n chunkTransform: (fn: ChunkTransformFn) => PipelineBuilder\n /** 执行管线 */\n run: (text: string) => Promise<HaiResult<PipelineResult>>\n}\n\n/**\n * 数据处理管线服务接口\n *\n * @example\n * ```ts\n * import { datapipe } from '@h-ai/datapipe'\n *\n * // 直接清洗\n * const cleaned = datapipe.clean('<p>Hello</p>', { removeHtml: true })\n *\n * // 直接分块\n * const chunks = datapipe.chunk(text, { mode: 'markdown', maxSize: 2000 })\n *\n * // 管线模式\n * const result = await datapipe.pipeline()\n * .clean()\n * .chunk({ mode: 'paragraph' })\n * .run(text)\n * ```\n */\nexport interface DatapipeFunctions {\n /** 清洗文本 */\n clean: CleanOperations\n /** 分块文本 */\n chunk: ChunkOperations\n /** 创建管线构建器 */\n pipeline: () => PipelineBuilder\n}\n","/**\n * @h-ai/datapipe — 文本分块功能\n *\n * 提供多种分块模式:句子、段落、Markdown 标题、分页、字数、字符、自定义分隔符。\n * 支持重叠分块以保持上下文衔接。\n * @module datapipe-chunk\n */\n\nimport type { HaiResult } from '@h-ai/core'\nimport type { ChunkMode, ChunkOptionsInput } from './datapipe-config.js'\nimport type { DataChunk } from './datapipe-types.js'\n\nimport { err, ok } from '@h-ai/core'\n\nimport { ChunkOptionsSchema } from './datapipe-config.js'\nimport { datapipeM } from './datapipe-i18n.js'\nimport { HaiDatapipeError } from './datapipe-types.js'\n\n// ─── 分割函数 ───\n\n/**\n * 按句子分割文本\n *\n * 支持中英文句号、问号、感叹号作为分隔符。\n */\nfunction splitBySentence(text: string): string[] {\n // 匹配中文和英文的句末标点\n const segments = text.split(/(?<=[。!?.!?])\\s*/)\n return segments.filter(s => s.trim().length > 0)\n}\n\n/**\n * 按段落分割文本\n *\n * 以双换行符作为段落分隔符。\n */\nfunction splitByParagraph(text: string): string[] {\n const segments = text.split(/\\n\\s*\\n/)\n return segments.filter(s => s.trim().length > 0)\n}\n\n/**\n * 按 Markdown 标题分割文本\n *\n * 根据最低标题级别(默认 ##),按标题分割为独立的内容块。\n * 每个分块包含标题和其下属内容。\n *\n * @param text - Markdown 文本\n * @param minLevel - 最低标题级别(1-6)\n * @param keepTitle - 是否在分块中保留标题\n * @returns 分块列表(包含元数据:title, level)\n */\nfunction splitByMarkdown(text: string, minLevel: number, keepTitle: boolean): { content: string, title: string, level: number }[] {\n // 构造匹配 minLevel 及以上级别标题的正则\n const headerPattern = new RegExp(`^(#{1,${minLevel}})\\\\s+(.+)$`, 'gm')\n\n const sections: { content: string, title: string, level: number }[] = []\n let lastIndex = 0\n let lastTitle = ''\n let lastLevel = 0\n let match: RegExpExecArray | null = null\n\n // 处理标题前的前置内容\n match = headerPattern.exec(text)\n if (match && match.index > 0) {\n const preContent = text.slice(0, match.index).trim()\n if (preContent.length > 0) {\n sections.push({ content: preContent, title: '', level: 0 })\n }\n }\n\n // 重置正则\n headerPattern.lastIndex = 0\n\n // eslint-disable-next-line no-cond-assign\n while ((match = headerPattern.exec(text)) !== null) {\n // 保存上一个分块\n if (lastIndex > 0 || lastTitle) {\n const content = text.slice(lastIndex, match.index).trim()\n if (content.length > 0 || lastTitle) {\n const finalContent = keepTitle && lastTitle\n ? `${'#'.repeat(lastLevel)} ${lastTitle}\\n${content}`\n : content\n sections.push({\n content: finalContent.trim(),\n title: lastTitle,\n level: lastLevel,\n })\n }\n }\n\n lastTitle = match[2].trim()\n lastLevel = match[1].length\n lastIndex = match.index + match[0].length\n }\n\n // 处理最后一个分块\n if (lastTitle || lastIndex > 0) {\n const content = text.slice(lastIndex).trim()\n const finalContent = keepTitle && lastTitle\n ? `${'#'.repeat(lastLevel)} ${lastTitle}\\n${content}`\n : content\n sections.push({\n content: finalContent.trim(),\n title: lastTitle,\n level: lastLevel,\n })\n }\n\n // 如果没有匹配到任何标题,返回整个文本\n if (sections.length === 0) {\n sections.push({ content: text.trim(), title: '', level: 0 })\n }\n\n return sections.filter(s => s.content.length > 0)\n}\n\n/**\n * 按分页符分割文本\n */\nfunction splitByPage(text: string): string[] {\n const segments = text.split(/\\f/)\n return segments.filter(s => s.trim().length > 0)\n}\n\n/**\n * 按空格分词分割文本\n *\n * 以空白字符为分隔符进行分词,每个分块包含不超过 maxSize 个词。\n * 注意:中文等无空格语言的连续文本会被视为单个词。\n */\nfunction splitByWord(text: string, maxSize: number): string[] {\n const words = text.split(/\\s+/)\n const chunks: string[] = []\n let current: string[] = []\n let currentSize = 0\n\n for (const word of words) {\n if (currentSize + 1 > maxSize && current.length > 0) {\n chunks.push(current.join(' '))\n current = []\n currentSize = 0\n }\n current.push(word)\n currentSize++\n }\n\n if (current.length > 0) {\n chunks.push(current.join(' '))\n }\n\n return chunks\n}\n\n/**\n * 按字符数分割文本\n */\nfunction splitByCharacter(text: string, maxSize: number): string[] {\n const chunks: string[] = []\n for (let i = 0; i < text.length; i += maxSize) {\n chunks.push(text.slice(i, i + maxSize))\n }\n return chunks\n}\n\n/**\n * 按自定义分隔符分割文本\n *\n * @throws 当 separator 不是合法正则表达式时抛出异常,由外层 catch 转为 HaiResult\n */\nfunction splitByCustom(text: string, separator: string): string[] {\n const regex = new RegExp(separator)\n const segments = text.split(regex)\n return segments.filter(s => s.trim().length > 0)\n}\n\n// ─── 分割模式分发 ───\n\n/**\n * 按指定模式分割文本为字符串片段(非 Markdown 模式)\n */\nfunction splitTextByMode(\n text: string,\n mode: ChunkMode,\n maxSize: number,\n separator?: string,\n): string[] {\n switch (mode) {\n case 'sentence':\n return splitBySentence(text)\n case 'paragraph':\n return splitByParagraph(text)\n case 'page':\n return splitByPage(text)\n case 'word':\n return splitByWord(text, maxSize)\n case 'character':\n return splitByCharacter(text, maxSize)\n case 'custom':\n return splitByCustom(text, separator ?? '\\n')\n default:\n return [text]\n }\n}\n\n// ─── 合并分段至分块 ───\n\n/**\n * 将分段合并为不超过 maxSize 的分块,支持重叠\n */\nfunction buildChunks(\n segments: string[],\n maxSize: number,\n overlap: number,\n): DataChunk[] {\n const chunks: DataChunk[] = []\n let currentContent = ''\n let chunkIndex = 0\n\n for (const segment of segments) {\n // 如果当前内容加上新分段超过限制,先保存当前分块\n if (currentContent.length > 0 && currentContent.length + segment.length + 1 > maxSize) {\n chunks.push({\n index: chunkIndex++,\n content: currentContent.trim(),\n })\n\n // 处理重叠:保留尾部内容\n if (overlap > 0 && currentContent.length > overlap) {\n currentContent = currentContent.slice(-overlap)\n }\n else {\n currentContent = ''\n }\n }\n\n // 如果单个分段已超过 maxSize,按字符截断\n if (segment.length > maxSize) {\n if (currentContent.length > 0) {\n chunks.push({\n index: chunkIndex++,\n content: currentContent.trim(),\n })\n currentContent = ''\n }\n\n for (let i = 0; i < segment.length; i += maxSize) {\n const part = segment.slice(i, i + maxSize)\n chunks.push({\n index: chunkIndex++,\n content: part.trim(),\n })\n }\n continue\n }\n\n currentContent += (currentContent.length > 0 ? '\\n' : '') + segment\n }\n\n // 保存最后一个分块\n if (currentContent.trim().length > 0) {\n chunks.push({\n index: chunkIndex,\n content: currentContent.trim(),\n })\n }\n\n return chunks\n}\n\n// ─── Markdown 分块构建 ───\n\n/**\n * 将 Markdown 分割结果构建为带元数据的分块列表\n *\n * Markdown 模式下 overlap 仅用于单 section 超限时的子分块,section 间不做 overlap。\n */\nfunction buildMarkdownChunks(\n text: string,\n maxSize: number,\n overlap: number,\n markdownMinLevel: number,\n markdownKeepTitle: boolean,\n): DataChunk[] {\n const mdSegments = splitByMarkdown(text, markdownMinLevel, markdownKeepTitle)\n const chunks: DataChunk[] = []\n\n for (const segment of mdSegments) {\n if (segment.content.length > maxSize) {\n const subChunks = buildChunks([segment.content], maxSize, overlap)\n for (const sub of subChunks) {\n chunks.push({\n index: chunks.length,\n content: sub.content,\n metadata: { title: segment.title, level: segment.level, subChunk: true },\n })\n }\n }\n else {\n chunks.push({\n index: chunks.length,\n content: segment.content,\n metadata: { title: segment.title, level: segment.level },\n })\n }\n }\n\n return chunks\n}\n\n// ─── 公共 API ───\n\n/**\n * 对文本进行分块\n *\n * @param text - 输入文本\n * @param options - 分块选项\n * @returns 分块列表\n *\n * @example\n * ```ts\n * // 按 Markdown 标题分块\n * const result = chunkText(markdownText, { mode: 'markdown', maxSize: 2000 })\n *\n * // 按句子分块\n * const result = chunkText(text, { mode: 'sentence', maxSize: 500, overlap: 50 })\n * ```\n */\nexport function chunkText(text: string, options: ChunkOptionsInput): HaiResult<DataChunk[]> {\n const parseResult = ChunkOptionsSchema.safeParse(options)\n if (!parseResult.success) {\n return err(HaiDatapipeError.CONFIG_ERROR, datapipeM('datapipe_configError', { params: { error: parseResult.error.message } }), parseResult.error)\n }\n\n const opts = parseResult.data\n\n // 校验 custom 模式需要 separator\n if (opts.mode === 'custom' && !opts.separator) {\n return err(HaiDatapipeError.MISSING_SEPARATOR, datapipeM('datapipe_missingSeparator'))\n }\n\n if (!text || text.trim().length === 0) {\n return ok([])\n }\n\n try {\n // Markdown 模式:独立处理,带有 title 和 level 元数据\n if (opts.mode === 'markdown') {\n const chunks = buildMarkdownChunks(text, opts.maxSize, opts.overlap, opts.markdownMinLevel, opts.markdownKeepTitle)\n return ok(chunks)\n }\n\n // 其他模式:字符串形式的分段\n const segments = splitTextByMode(text, opts.mode, opts.maxSize, opts.separator)\n const chunks = buildChunks(segments, opts.maxSize, opts.overlap)\n\n return ok(chunks)\n }\n catch (error) {\n return err(HaiDatapipeError.CHUNK_FAILED, datapipeM('datapipe_chunkFailed', { params: { error: String(error) } }), error)\n }\n}\n","/**\n * @h-ai/datapipe — 文本清洗功能\n *\n * 提供文本清洗工具,支持移除 HTML、URL、Email、标准化空白等。\n * @module datapipe-clean\n */\n\nimport type { HaiResult } from '@h-ai/core'\nimport type { CleanOptionsInput } from './datapipe-config.js'\n\nimport { err, ok } from '@h-ai/core'\n\nimport { CleanOptionsSchema } from './datapipe-config.js'\nimport { datapipeM } from './datapipe-i18n.js'\nimport { HaiDatapipeError } from './datapipe-types.js'\n\n/**\n * HTML 标签正则\n */\nconst HTML_TAG_REGEX = /<[^>]*>/g\n\n/**\n * URL 正则(HTTP/HTTPS)\n */\nconst URL_REGEX = /https?:\\/\\/[^\\s<>\"{}|\\\\^`[\\]]+/g\n\n/**\n * Email 正则\n */\nconst EMAIL_REGEX = /[\\w.%+-]+@[a-z0-9.-]+\\.[a-z]{2,}/gi\n\n/**\n * 多空行正则(3行及以上空行 → 2行)\n */\nconst MULTI_NEWLINE_REGEX = /\\n{3,}/g\n\n/**\n * 多空格正则\n */\nconst MULTI_SPACE_REGEX = /[ \\t]{2,}/g\n\n/**\n * 清洗文本\n *\n * 根据配置选项对文本进行清洗处理。\n *\n * @param text - 原始文本\n * @param options - 清洗选项(可选)\n * @returns 清洗后的文本\n *\n * @example\n * ```ts\n * const result = cleanText('<p>Hello World</p>', { removeHtml: true })\n * // result.data === 'Hello World'\n * ```\n */\nexport function cleanText(text: string, options?: CleanOptionsInput): HaiResult<string> {\n const parseResult = CleanOptionsSchema.safeParse(options ?? {})\n if (!parseResult.success) {\n return err(HaiDatapipeError.CONFIG_ERROR, datapipeM('datapipe_configError', { params: { error: parseResult.error.message } }), parseResult.error)\n }\n\n const opts = parseResult.data\n let result = text\n\n try {\n // 移除 HTML 标签\n if (opts.removeHtml) {\n result = result.replace(HTML_TAG_REGEX, '')\n }\n\n // 移除 URL\n if (opts.removeUrls) {\n result = result.replace(URL_REGEX, '')\n }\n\n // 移除 Email\n if (opts.removeEmails) {\n result = result.replace(EMAIL_REGEX, '')\n }\n\n // 自定义替换\n if (opts.customReplacements) {\n for (const { pattern, replacement } of opts.customReplacements) {\n let regex: RegExp\n try {\n regex = new RegExp(pattern, 'g')\n }\n catch (regexError) {\n return err(HaiDatapipeError.CONFIG_ERROR, datapipeM('datapipe_configError', { params: { error: String(regexError) } }), regexError)\n }\n result = result.replace(regex, replacement)\n }\n }\n\n // 标准化空白\n if (opts.normalizeWhitespace) {\n result = result.replace(MULTI_SPACE_REGEX, ' ')\n result = result.replace(MULTI_NEWLINE_REGEX, '\\n\\n')\n }\n\n // 去除首尾空白\n if (opts.trim) {\n result = result.trim()\n }\n\n return ok(result)\n }\n catch (error) {\n return err(HaiDatapipeError.CLEAN_FAILED, datapipeM('datapipe_cleanFailed', { params: { error: String(error) } }), error)\n }\n}\n","/**\n * @h-ai/datapipe — 管线构建器\n *\n * 提供可组合的管线构建器,支持链式添加清洗、分块、转换步骤后执行。\n * @module datapipe-pipeline\n */\n\nimport type { HaiResult } from '@h-ai/core'\nimport type { ChunkOptionsInput, CleanOptionsInput } from './datapipe-config.js'\nimport type {\n ChunkTransformFn,\n DataChunk,\n PipelineBuilder,\n PipelineResult,\n PipelineStep,\n TransformFn,\n} from './datapipe-types.js'\n\nimport { err, ok } from '@h-ai/core'\n\nimport { chunkText } from './datapipe-chunk.js'\nimport { cleanText } from './datapipe-clean.js'\nimport { datapipeM } from './datapipe-i18n.js'\nimport { HaiDatapipeError } from './datapipe-types.js'\n\n/**\n * 创建管线构建器\n *\n * @returns PipelineBuilder 实例,支持链式添加步骤后执行\n *\n * @example\n * ```ts\n * const result = await datapipe.pipeline()\n * .clean({ removeHtml: true })\n * .transform(text => text.toLowerCase())\n * .chunk({ mode: 'markdown', maxSize: 2000 })\n * .run('原始文本')\n *\n * if (result.success) {\n * // result.data => { text, chunks }\n * }\n * ```\n */\nexport function createPipelineBuilder(): PipelineBuilder {\n const steps: PipelineStep[] = []\n\n const builder: PipelineBuilder = {\n clean(options?: CleanOptionsInput): PipelineBuilder {\n steps.push({ type: 'clean', options })\n return builder\n },\n\n chunk(options: ChunkOptionsInput): PipelineBuilder {\n steps.push({ type: 'chunk', options })\n return builder\n },\n\n transform(fn: TransformFn): PipelineBuilder {\n steps.push({ type: 'transform', fn })\n return builder\n },\n\n chunkTransform(fn: ChunkTransformFn): PipelineBuilder {\n steps.push({ type: 'chunkTransform', fn })\n return builder\n },\n\n run: (text: string) => runPipeline(steps, text),\n }\n\n return builder\n}\n\n// ─── 管线执行 ───\n\n/**\n * 执行管线步骤\n */\nasync function runPipeline(\n steps: PipelineStep[],\n text: string,\n): Promise<HaiResult<PipelineResult>> {\n let currentText = text\n let chunks: DataChunk[] = []\n\n for (const step of steps) {\n switch (step.type) {\n case 'clean': {\n const result = cleanText(currentText, step.options)\n if (!result.success)\n return result\n currentText = result.data\n break\n }\n\n case 'chunk': {\n const result = chunkText(currentText, step.options)\n if (!result.success)\n return result\n chunks = result.data\n break\n }\n\n case 'transform': {\n try {\n currentText = await step.fn(currentText)\n }\n catch (error) {\n return err(HaiDatapipeError.TRANSFORM_FAILED, datapipeM('datapipe_transformFailed', { params: { error: String(error) } }), error)\n }\n break\n }\n\n case 'chunkTransform': {\n if (chunks.length > 0) {\n try {\n chunks = await step.fn(chunks)\n }\n catch (error) {\n return err(HaiDatapipeError.PIPELINE_FAILED, datapipeM('datapipe_pipelineFailed', { params: { error: String(error) } }), error)\n }\n }\n break\n }\n }\n }\n\n return ok({ text: currentText, chunks })\n}\n","/**\n * @h-ai/datapipe — 数据处理管线主入口\n *\n * 提供统一的 `datapipe` 对象,聚合清洗、分块和管线功能。\n * datapipe 为纯函数模块,无需初始化即可使用。\n * @module datapipe-main\n */\n\nimport type { DatapipeFunctions } from './datapipe-types.js'\n\nimport { chunkText } from './datapipe-chunk.js'\nimport { cleanText } from './datapipe-clean.js'\nimport { createPipelineBuilder } from './datapipe-pipeline.js'\n\n// ─── 统一服务对象 ───\n\n/**\n * 数据处理管线服务对象\n *\n * 纯函数模块,无需初始化即可使用。\n *\n * @example\n * ```ts\n * import { datapipe } from '@h-ai/datapipe'\n *\n * // 直接清洗\n * const cleaned = datapipe.clean('<p>Hello</p>')\n *\n * // 按 Markdown 标题分块\n * const chunks = datapipe.chunk(text, { mode: 'markdown', maxSize: 2000 })\n *\n * // 管线模式\n * const result = await datapipe.pipeline()\n * .clean({ removeHtml: true, removeUrls: true })\n * .transform(text => text.toLowerCase())\n * .chunk({ mode: 'paragraph', maxSize: 1000, overlap: 100 })\n * .chunkTransform(chunks => chunks.filter(c => c.content.length > 50))\n * .run(rawHtml)\n * ```\n */\nexport const datapipe: DatapipeFunctions = {\n clean: cleanText,\n chunk: chunkText,\n pipeline: createPipelineBuilder,\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@h-ai/datapipe",
3
+ "type": "module",
4
+ "version": "0.1.0-alpha5",
5
+ "description": "Data processing pipeline module for hai-framework: clean, chunk, transform",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js"
10
+ }
11
+ },
12
+ "main": "dist/index.js",
13
+ "types": "dist/index.d.ts",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "dependencies": {
21
+ "zod": "^4.3.6",
22
+ "@h-ai/core": "0.1.0-alpha5"
23
+ },
24
+ "devDependencies": {
25
+ "tsup": "^8.3.5",
26
+ "typescript": "^5.7.2"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "dev": "tsup --watch",
31
+ "typecheck": "tsc --noEmit",
32
+ "lint": "eslint src/",
33
+ "lint:fix": "eslint src/ --fix",
34
+ "test": "vitest run",
35
+ "test:watch": "vitest",
36
+ "test:coverage": "vitest run --coverage"
37
+ }
38
+ }