@eidentic/rag 0.1.0
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 +201 -0
- package/README.md +50 -0
- package/dist/index.cjs +417 -0
- package/dist/index.d.cts +225 -0
- package/dist/index.d.ts +225 -0
- package/dist/index.js +392 -0
- package/package.json +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work, excluding
|
|
103
|
+
those notices that do not pertain to any part of the Derivative
|
|
104
|
+
Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and do
|
|
117
|
+
not modify the License. You may add Your own attribution notices
|
|
118
|
+
within Derivative Works that You distribute, alongside or as an
|
|
119
|
+
addendum to the NOTICE text from the Work, provided that such
|
|
120
|
+
additional attribution notices cannot be construed as modifying
|
|
121
|
+
the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Baran Özdemir
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# @eidentic/rag
|
|
2
|
+
|
|
3
|
+
RAG pipeline utilities for Eidentic — chunk text into overlapping windows, ingest
|
|
4
|
+
documents from URLs or typed content sources, and load Markdown, HTML, and PDF files
|
|
5
|
+
into a format ready for agent memory. Works with any `Memory` instance.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @eidentic/rag
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
For PDF loading, also install `pdf-parse`:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pnpm add pdf-parse
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { ingestDocument, loadMarkdown, chunkText } from "@eidentic/rag";
|
|
23
|
+
import { Memory } from "@eidentic/memory";
|
|
24
|
+
|
|
25
|
+
// Ingest a URL directly into agent memory
|
|
26
|
+
await ingestDocument({
|
|
27
|
+
source: { type: "url", url: "https://docs.example.com/guide" },
|
|
28
|
+
memory,
|
|
29
|
+
scope: { userId: "u-1" },
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Or load and chunk manually
|
|
33
|
+
const doc = await loadMarkdown({ path: "./docs/guide.md" });
|
|
34
|
+
const chunks = chunkText(doc.text, { chunkSize: 512, overlap: 64 });
|
|
35
|
+
|
|
36
|
+
// Or ingest typed content
|
|
37
|
+
await ingestDocument({
|
|
38
|
+
source: { type: "text", text: "...", mimeType: "text/plain", title: "My Doc" },
|
|
39
|
+
memory,
|
|
40
|
+
scope: { userId: "u-1" },
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Links
|
|
45
|
+
|
|
46
|
+
- [GitHub](https://github.com/eidentic/eidentic)
|
|
47
|
+
- [Issue tracker](https://github.com/eidentic/eidentic/issues)
|
|
48
|
+
- [Root README](https://github.com/eidentic/eidentic#readme)
|
|
49
|
+
|
|
50
|
+
Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
chunkText: () => chunkText,
|
|
24
|
+
ingestDocument: () => ingestDocument,
|
|
25
|
+
loadHtml: () => loadHtml,
|
|
26
|
+
loadMarkdown: () => loadMarkdown,
|
|
27
|
+
loadPdf: () => loadPdf
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(index_exports);
|
|
30
|
+
|
|
31
|
+
// src/chunk.ts
|
|
32
|
+
function splitByWordBoundary(text, size) {
|
|
33
|
+
if (text.length <= size) return text ? [text] : [];
|
|
34
|
+
const segments = [];
|
|
35
|
+
let pos = 0;
|
|
36
|
+
while (pos < text.length) {
|
|
37
|
+
if (pos + size >= text.length) {
|
|
38
|
+
segments.push(text.slice(pos));
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
let cut = pos + size;
|
|
42
|
+
while (cut > pos && !/\s/.test(text[cut])) cut--;
|
|
43
|
+
if (cut === pos) {
|
|
44
|
+
cut = pos + size;
|
|
45
|
+
} else {
|
|
46
|
+
while (cut < text.length && /\s/.test(text[cut])) cut++;
|
|
47
|
+
}
|
|
48
|
+
segments.push(text.slice(pos, cut).trimEnd());
|
|
49
|
+
pos = cut;
|
|
50
|
+
}
|
|
51
|
+
return segments.filter((s) => s.length > 0);
|
|
52
|
+
}
|
|
53
|
+
function splitIntoParagraphs(text) {
|
|
54
|
+
return text.split(/\n\s*\n/).map((p) => p.trim()).filter((p) => p.length > 0);
|
|
55
|
+
}
|
|
56
|
+
function splitIntoSentences(text) {
|
|
57
|
+
const parts = text.split(/(?<=[.!?])\s+/);
|
|
58
|
+
return parts.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
59
|
+
}
|
|
60
|
+
function packSegments(segments, source, size, overlap, separator = "\n\n") {
|
|
61
|
+
const segmentOffsets = [];
|
|
62
|
+
let searchFrom = 0;
|
|
63
|
+
for (const seg of segments) {
|
|
64
|
+
const idx = source.indexOf(seg, searchFrom);
|
|
65
|
+
if (idx === -1) {
|
|
66
|
+
const prev = segmentOffsets[segmentOffsets.length - 1];
|
|
67
|
+
const fallbackStart = prev ? prev.end : 0;
|
|
68
|
+
segmentOffsets.push({ start: fallbackStart, end: fallbackStart + seg.length, text: seg });
|
|
69
|
+
searchFrom = fallbackStart + seg.length;
|
|
70
|
+
} else {
|
|
71
|
+
segmentOffsets.push({ start: idx, end: idx + seg.length, text: seg });
|
|
72
|
+
searchFrom = idx + seg.length;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const chunks = [];
|
|
76
|
+
let current = [];
|
|
77
|
+
let currentLen = 0;
|
|
78
|
+
const flush = () => {
|
|
79
|
+
if (current.length === 0) return;
|
|
80
|
+
const start = current[0].start;
|
|
81
|
+
const end = current[current.length - 1].end;
|
|
82
|
+
const text = current.map((s) => s.text).join(separator);
|
|
83
|
+
chunks.push({ text, start, end });
|
|
84
|
+
current = [];
|
|
85
|
+
currentLen = 0;
|
|
86
|
+
};
|
|
87
|
+
for (const seg of segmentOffsets) {
|
|
88
|
+
if (currentLen > 0 && currentLen + separator.length + seg.text.length > size) {
|
|
89
|
+
flush();
|
|
90
|
+
}
|
|
91
|
+
if (seg.text.length > size) {
|
|
92
|
+
flush();
|
|
93
|
+
const subSegs = splitByWordBoundary(seg.text, size);
|
|
94
|
+
let subOffset = seg.start;
|
|
95
|
+
for (const sub of subSegs) {
|
|
96
|
+
const subStart = source.indexOf(sub, subOffset);
|
|
97
|
+
const actualStart = subStart === -1 ? subOffset : subStart;
|
|
98
|
+
chunks.push({ text: sub, start: actualStart, end: actualStart + sub.length });
|
|
99
|
+
subOffset = actualStart + sub.length;
|
|
100
|
+
}
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
current.push(seg);
|
|
104
|
+
currentLen += (currentLen > 0 ? separator.length : 0) + seg.text.length;
|
|
105
|
+
}
|
|
106
|
+
flush();
|
|
107
|
+
return chunks.map((chunk, i) => {
|
|
108
|
+
if (i === 0 || overlap === 0) return chunk;
|
|
109
|
+
const prev = chunks[i - 1];
|
|
110
|
+
const prefix = prev.text.slice(-overlap);
|
|
111
|
+
return { text: prefix + chunk.text, start: chunk.start, end: chunk.end };
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function chunkText(text, opts) {
|
|
115
|
+
const size = opts?.size ?? 1e3;
|
|
116
|
+
const overlap = Math.min(opts?.overlap ?? 150, size - 1);
|
|
117
|
+
const strategy = opts?.strategy ?? "fixed";
|
|
118
|
+
const normalized = text.trim();
|
|
119
|
+
if (normalized.length === 0) return [];
|
|
120
|
+
if (strategy === "paragraph" || strategy === "sentence") {
|
|
121
|
+
const naturalSegments = strategy === "paragraph" ? splitIntoParagraphs(normalized) : splitIntoSentences(normalized);
|
|
122
|
+
const separator = strategy === "sentence" ? " " : "\n\n";
|
|
123
|
+
const packed = packSegments(naturalSegments, normalized, size, overlap, separator);
|
|
124
|
+
return packed.map((c, i) => ({ text: c.text, index: i, start: c.start, end: c.end }));
|
|
125
|
+
}
|
|
126
|
+
const chunks = [];
|
|
127
|
+
let pos = 0;
|
|
128
|
+
let index = 0;
|
|
129
|
+
while (pos < normalized.length) {
|
|
130
|
+
let end = pos + size;
|
|
131
|
+
if (end >= normalized.length) {
|
|
132
|
+
end = normalized.length;
|
|
133
|
+
} else {
|
|
134
|
+
let cut = end;
|
|
135
|
+
while (cut > pos && !/\s/.test(normalized[cut])) cut--;
|
|
136
|
+
if (cut === pos) {
|
|
137
|
+
cut = end;
|
|
138
|
+
}
|
|
139
|
+
end = cut;
|
|
140
|
+
}
|
|
141
|
+
const chunkText2 = normalized.slice(pos, end).trim();
|
|
142
|
+
if (chunkText2.length > 0) {
|
|
143
|
+
let fullText = chunkText2;
|
|
144
|
+
if (index > 0 && overlap > 0) {
|
|
145
|
+
const prev = chunks[chunks.length - 1];
|
|
146
|
+
const prefix = prev.text.slice(-overlap);
|
|
147
|
+
fullText = prefix + chunkText2;
|
|
148
|
+
}
|
|
149
|
+
chunks.push({ text: fullText, index, start: pos, end });
|
|
150
|
+
index++;
|
|
151
|
+
}
|
|
152
|
+
let next = end;
|
|
153
|
+
while (next < normalized.length && /\s/.test(normalized[next])) next++;
|
|
154
|
+
if (next === pos) {
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
pos = next;
|
|
158
|
+
}
|
|
159
|
+
return chunks;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/ingest.ts
|
|
163
|
+
var import_tools = require("@eidentic/tools");
|
|
164
|
+
|
|
165
|
+
// src/loaders.ts
|
|
166
|
+
var import_node_module = require("node:module");
|
|
167
|
+
var import_node_html_parser = require("node-html-parser");
|
|
168
|
+
var import_meta = {};
|
|
169
|
+
function loadMarkdown(content, opts) {
|
|
170
|
+
const source = opts?.source ?? "markdown";
|
|
171
|
+
let text = content;
|
|
172
|
+
text = text.replace(/```[\s\S]*?```/g, "");
|
|
173
|
+
text = text.replace(/^(?: |\t).+$/gm, "");
|
|
174
|
+
text = text.replace(/<[^>]+>/g, "");
|
|
175
|
+
text = text.replace(/^#{1,6}\s+(.+)$/gm, "$1");
|
|
176
|
+
text = text.replace(/^[=-]{2,}\s*$/gm, "");
|
|
177
|
+
text = text.replace(/^(?:[*_-][\s]*){3,}$/gm, "");
|
|
178
|
+
text = text.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
|
|
179
|
+
text = text.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1");
|
|
180
|
+
text = text.replace(/\[([^\]]+)\]\[[^\]]*\]/g, "$1");
|
|
181
|
+
text = text.replace(/^\[[^\]]+\]:\s+\S+(?:\s+"[^"]*")?$/gm, "");
|
|
182
|
+
text = text.replace(/\*{1,2}([^*\n]+)\*{1,2}/g, "$1");
|
|
183
|
+
text = text.replace(/_{1,2}([^_\n]+)_{1,2}/g, "$1");
|
|
184
|
+
text = text.replace(/`([^`]+)`/g, "$1");
|
|
185
|
+
text = text.replace(/~~([^~]+)~~/g, "$1");
|
|
186
|
+
text = text.replace(/^>\s?/gm, "");
|
|
187
|
+
text = text.replace(/^[\s]*[-*+]\s+/gm, "");
|
|
188
|
+
text = text.replace(/^[\s]*\d+\.\s+/gm, "");
|
|
189
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
190
|
+
text = text.trim();
|
|
191
|
+
return { text, metadata: { source } };
|
|
192
|
+
}
|
|
193
|
+
var BLOCK_TAGS = /* @__PURE__ */ new Set([
|
|
194
|
+
"p",
|
|
195
|
+
"div",
|
|
196
|
+
"section",
|
|
197
|
+
"article",
|
|
198
|
+
"aside",
|
|
199
|
+
"main",
|
|
200
|
+
"header",
|
|
201
|
+
"footer",
|
|
202
|
+
"nav",
|
|
203
|
+
"h1",
|
|
204
|
+
"h2",
|
|
205
|
+
"h3",
|
|
206
|
+
"h4",
|
|
207
|
+
"h5",
|
|
208
|
+
"h6",
|
|
209
|
+
"li",
|
|
210
|
+
"dt",
|
|
211
|
+
"dd",
|
|
212
|
+
"ul",
|
|
213
|
+
"ol",
|
|
214
|
+
"blockquote",
|
|
215
|
+
"pre",
|
|
216
|
+
"figure",
|
|
217
|
+
"figcaption",
|
|
218
|
+
"br",
|
|
219
|
+
"hr",
|
|
220
|
+
"tr",
|
|
221
|
+
"th",
|
|
222
|
+
"td",
|
|
223
|
+
"table"
|
|
224
|
+
]);
|
|
225
|
+
function loadHtml(html, opts) {
|
|
226
|
+
const source = opts?.source ?? "html";
|
|
227
|
+
const root = (0, import_node_html_parser.parse)(html, {
|
|
228
|
+
lowerCaseTagName: true,
|
|
229
|
+
comment: false,
|
|
230
|
+
blockTextElements: {
|
|
231
|
+
script: false,
|
|
232
|
+
style: false,
|
|
233
|
+
noscript: false,
|
|
234
|
+
pre: true
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
for (const tag of ["script", "style", "noscript", "head"]) {
|
|
238
|
+
for (const el of root.querySelectorAll(tag)) {
|
|
239
|
+
el.remove();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function extractText(node) {
|
|
243
|
+
if (node.nodeType === 3) {
|
|
244
|
+
return node.rawText ?? node.text ?? "";
|
|
245
|
+
}
|
|
246
|
+
const tag = node.tagName?.toLowerCase() ?? "";
|
|
247
|
+
const isBlock = BLOCK_TAGS.has(tag);
|
|
248
|
+
const childText = node.childNodes.map((c) => extractText(c)).join("");
|
|
249
|
+
return isBlock ? `
|
|
250
|
+
${childText}
|
|
251
|
+
` : childText;
|
|
252
|
+
}
|
|
253
|
+
let text = extractText(root);
|
|
254
|
+
text = text.replace(/[^\S\n]+/g, " ");
|
|
255
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
256
|
+
text = text.trim();
|
|
257
|
+
return { text, metadata: { source } };
|
|
258
|
+
}
|
|
259
|
+
function loadPdfParseModule() {
|
|
260
|
+
const req = typeof require === "function" ? require : (0, import_node_module.createRequire)(import_meta.url);
|
|
261
|
+
try {
|
|
262
|
+
const mod = req("pdf-parse");
|
|
263
|
+
const fn = typeof mod === "function" ? mod : mod.default;
|
|
264
|
+
if (typeof fn !== "function") {
|
|
265
|
+
throw new Error("unexpected module shape");
|
|
266
|
+
}
|
|
267
|
+
return fn;
|
|
268
|
+
} catch (err) {
|
|
269
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
270
|
+
if (msg.includes("Cannot find module") || msg.includes("unexpected module shape")) {
|
|
271
|
+
throw new Error(
|
|
272
|
+
"[eidentic/rag] loadPdf requires the `pdf-parse` package.\nInstall it in your project:\n npm install pdf-parse\n # or\n pnpm add pdf-parse"
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
throw err;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async function loadPdf(buf, opts) {
|
|
279
|
+
const source = opts?.source ?? "pdf";
|
|
280
|
+
const parse = opts?._parser ?? loadPdfParseModule();
|
|
281
|
+
const result = await parse(buf);
|
|
282
|
+
let text = result.text;
|
|
283
|
+
text = text.replace(/[^\S\n]+/g, " ");
|
|
284
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
285
|
+
text = text.trim();
|
|
286
|
+
return {
|
|
287
|
+
text,
|
|
288
|
+
metadata: { source, pages: result.numpages }
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// src/ingest.ts
|
|
293
|
+
function slugFromUrl(url) {
|
|
294
|
+
try {
|
|
295
|
+
const u = new URL(url);
|
|
296
|
+
const parts = (u.hostname + u.pathname).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
|
|
297
|
+
return parts.slice(0, 64) || "doc";
|
|
298
|
+
} catch {
|
|
299
|
+
return "doc";
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function hashSlug(text) {
|
|
303
|
+
let h = 5381;
|
|
304
|
+
for (let i = 0; i < Math.min(text.length, 2048); i++) {
|
|
305
|
+
h = (h << 5) + h + text.charCodeAt(i) >>> 0;
|
|
306
|
+
}
|
|
307
|
+
return `doc-${h.toString(16)}`;
|
|
308
|
+
}
|
|
309
|
+
var MAX_REDIRECT_HOPS = 5;
|
|
310
|
+
function normalizeUrl(url) {
|
|
311
|
+
try {
|
|
312
|
+
const u = new URL(url);
|
|
313
|
+
return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, "")}${u.search}`;
|
|
314
|
+
} catch {
|
|
315
|
+
return url;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async function ingestDocument(source, opts) {
|
|
319
|
+
let rawText;
|
|
320
|
+
let docId;
|
|
321
|
+
let extraMeta = {};
|
|
322
|
+
if (typeof source === "string") {
|
|
323
|
+
if (source.startsWith("http://") || source.startsWith("https://")) {
|
|
324
|
+
console.warn(
|
|
325
|
+
`[ingestDocument] source looks like a URL but was passed as a plain string \u2014 it will be ingested as raw text, NOT fetched. If you meant to fetch this URL, use { url: "${source}" } instead.`
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
rawText = source;
|
|
329
|
+
docId = opts.docId ?? hashSlug(rawText);
|
|
330
|
+
} else if ("type" in source) {
|
|
331
|
+
const typedSource = source;
|
|
332
|
+
let loaded;
|
|
333
|
+
if (typedSource.type === "markdown") {
|
|
334
|
+
loaded = loadMarkdown(typedSource.data, { source: typedSource.source });
|
|
335
|
+
} else if (typedSource.type === "html") {
|
|
336
|
+
loaded = loadHtml(typedSource.data, { source: typedSource.source });
|
|
337
|
+
} else {
|
|
338
|
+
loaded = await loadPdf(typedSource.data, {
|
|
339
|
+
source: typedSource.source,
|
|
340
|
+
_parser: typedSource._parser
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
rawText = loaded.text;
|
|
344
|
+
extraMeta = loaded.metadata;
|
|
345
|
+
docId = opts.docId ?? hashSlug(rawText);
|
|
346
|
+
} else {
|
|
347
|
+
(0, import_tools.assertFetchableUrl)(source.url, { allowlist: opts.allowlist });
|
|
348
|
+
const doFetch = opts.fetchImpl ?? globalThis.fetch;
|
|
349
|
+
let currentUrl = source.url;
|
|
350
|
+
let hops = 0;
|
|
351
|
+
let finalRes;
|
|
352
|
+
while (true) {
|
|
353
|
+
const res = await (0, import_tools.resilientFetch)(currentUrl, { redirect: "manual" }, { fetchImpl: doFetch });
|
|
354
|
+
const autoFollowed = res.redirected === true || res.status < 300 && typeof res.url === "string" && res.url !== "" && normalizeUrl(res.url) !== normalizeUrl(currentUrl);
|
|
355
|
+
if (autoFollowed) {
|
|
356
|
+
throw new Error(
|
|
357
|
+
'ingestDocument: the supplied fetchImpl auto-followed a redirect instead of honouring redirect:"manual". Replace it with a fetch implementation that returns 3xx responses rather than following them, so every redirect hop can be re-validated by the SSRF guard.'
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
if (res.status >= 300 && res.status < 400) {
|
|
361
|
+
hops++;
|
|
362
|
+
if (hops > MAX_REDIRECT_HOPS) {
|
|
363
|
+
throw new Error(
|
|
364
|
+
`ingestDocument: too many redirects (> ${MAX_REDIRECT_HOPS} hops) starting from ${source.url}`
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
const location = res.headers.get("location");
|
|
368
|
+
if (location === null) {
|
|
369
|
+
throw new Error(`ingestDocument: redirect has no Location header (hop ${hops})`);
|
|
370
|
+
}
|
|
371
|
+
let nextUrl;
|
|
372
|
+
try {
|
|
373
|
+
nextUrl = new URL(location, currentUrl);
|
|
374
|
+
} catch {
|
|
375
|
+
throw new Error(`ingestDocument: invalid redirect target at hop ${hops} (URL omitted for security)`);
|
|
376
|
+
}
|
|
377
|
+
(0, import_tools.assertFetchableUrl)(nextUrl.toString(), { allowlist: opts.allowlist });
|
|
378
|
+
currentUrl = nextUrl.toString();
|
|
379
|
+
} else {
|
|
380
|
+
finalRes = res;
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (!finalRes.ok) {
|
|
385
|
+
throw new Error(`ingestDocument: failed to fetch ${source.url} \u2014 HTTP ${finalRes.status}`);
|
|
386
|
+
}
|
|
387
|
+
rawText = await finalRes.text();
|
|
388
|
+
docId = opts.docId ?? slugFromUrl(source.url);
|
|
389
|
+
}
|
|
390
|
+
const chunks = chunkText(rawText, opts.chunk);
|
|
391
|
+
if (chunks.length === 0) return { chunks: 0 };
|
|
392
|
+
let citationSource;
|
|
393
|
+
if (typeof source === "string") {
|
|
394
|
+
citationSource = docId;
|
|
395
|
+
} else if ("type" in source) {
|
|
396
|
+
citationSource = extraMeta.source ?? docId;
|
|
397
|
+
} else {
|
|
398
|
+
citationSource = source.url;
|
|
399
|
+
}
|
|
400
|
+
const events = chunks.map((chunk, i) => ({
|
|
401
|
+
id: `${docId}:chunk:${i}`,
|
|
402
|
+
scope: opts.scope,
|
|
403
|
+
text: chunk.text,
|
|
404
|
+
// Merge loader-provided metadata (source, pages, etc.) into chunk metadata.
|
|
405
|
+
metadata: { ...extraMeta, source: citationSource }
|
|
406
|
+
}));
|
|
407
|
+
await opts.memory.ingest(events);
|
|
408
|
+
return { chunks: chunks.length };
|
|
409
|
+
}
|
|
410
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
411
|
+
0 && (module.exports = {
|
|
412
|
+
chunkText,
|
|
413
|
+
ingestDocument,
|
|
414
|
+
loadHtml,
|
|
415
|
+
loadMarkdown,
|
|
416
|
+
loadPdf
|
|
417
|
+
});
|