langchain-stripe-loader 0.1.0 → 0.3.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 +21 -0
- package/README.md +83 -9
- package/dist/index.cjs +602 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +185 -0
- package/dist/index.d.ts +185 -3
- package/dist/index.js +580 -0
- package/dist/index.js.map +1 -0
- package/package.json +28 -19
- package/dist/StripeComLoader.d.ts +0 -44
- package/dist/StripeComLoader.d.ts.map +0 -1
- package/dist/StripeDocsLoader.d.ts +0 -34
- package/dist/StripeDocsLoader.d.ts.map +0 -1
- package/dist/StripeDocsLoader.spec.d.ts +0 -2
- package/dist/StripeDocsLoader.spec.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.spec.d.ts +0 -2
- package/dist/index.spec.d.ts.map +0 -1
- package/dist/langchain-stripe-loader.cjs +0 -30
- package/dist/langchain-stripe-loader.cjs.map +0 -1
- package/dist/langchain-stripe-loader.js +0 -6922
- package/dist/langchain-stripe-loader.js.map +0 -1
- package/dist/utils/index.d.ts +0 -3
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/url-filter.d.ts +0 -26
- package/dist/utils/url-filter.d.ts.map +0 -1
- package/dist/utils/url-filter.spec.d.ts +0 -2
- package/dist/utils/url-filter.spec.d.ts.map +0 -1
- package/dist/utils.d.ts +0 -13
- package/dist/utils.d.ts.map +0 -1
- package/dist/utils.spec.d.ts +0 -2
- package/dist/utils.spec.d.ts.map +0 -1
package/dist/index.js
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
// src/StripeDocsLoader.ts
|
|
2
|
+
import { SitemapProcessor, fetchWithRetry, RequestPacer } from "stripe-loaders-core";
|
|
3
|
+
import { BaseDocumentLoader } from "@langchain/core/document_loaders/base";
|
|
4
|
+
import { Document } from "@langchain/core/documents";
|
|
5
|
+
import { NodeHtmlMarkdown } from "node-html-markdown";
|
|
6
|
+
|
|
7
|
+
// src/utils.ts
|
|
8
|
+
import { ConsoleLogger } from "stripe-loaders-core";
|
|
9
|
+
var defaultLogger = new ConsoleLogger(false);
|
|
10
|
+
function extractBodyFromHTML(htmlString, logger = defaultLogger) {
|
|
11
|
+
try {
|
|
12
|
+
if (!htmlString) {
|
|
13
|
+
logger.log("Input HTML is null or undefined");
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
const bodyRegex = /<body[^>]*>([\s\S]*?)<\/body>/gi;
|
|
17
|
+
const matches = [];
|
|
18
|
+
let match;
|
|
19
|
+
while ((match = bodyRegex.exec(htmlString)) !== null) {
|
|
20
|
+
if (match[1]) {
|
|
21
|
+
matches.push(match[1].trim());
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (matches.length === 0) {
|
|
25
|
+
logger.log("No body tags found");
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
return matches;
|
|
29
|
+
} catch (error) {
|
|
30
|
+
logger.error(`An error occurred: ${error}`);
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function extractArticleFromHTML(htmlString, logger = defaultLogger) {
|
|
35
|
+
try {
|
|
36
|
+
if (!htmlString) {
|
|
37
|
+
logger.log("Input HTML is null or undefined");
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
const articles = [];
|
|
41
|
+
const processArticleTags = () => {
|
|
42
|
+
const articleRegex = /<article(?:\s+[^>]*)?>(.*?)<\/article>/gis;
|
|
43
|
+
let articleMatch;
|
|
44
|
+
let foundArticles = false;
|
|
45
|
+
while ((articleMatch = articleRegex.exec(htmlString)) !== null) {
|
|
46
|
+
if (articleMatch[1]) {
|
|
47
|
+
articles.push(articleMatch[1].trim());
|
|
48
|
+
foundArticles = true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return foundArticles;
|
|
52
|
+
};
|
|
53
|
+
const processMainContent = () => {
|
|
54
|
+
const mainContentRegex = /<(div|section|main|article)(?:\s+[^>]*?)id=["']main-content["'](?:[^>]*?)>(.*?)<\/\1>/is;
|
|
55
|
+
const mainContentMatch = mainContentRegex.exec(htmlString);
|
|
56
|
+
if (mainContentMatch && mainContentMatch[2]) {
|
|
57
|
+
logger.log("Found element with main-content ID");
|
|
58
|
+
const contentArticleRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Content-article[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
|
|
59
|
+
const contentArticleMatch = contentArticleRegex.exec(mainContentMatch[2]);
|
|
60
|
+
if (contentArticleMatch && contentArticleMatch[1]) {
|
|
61
|
+
logger.log("Found content with Content-article class");
|
|
62
|
+
articles.push(contentArticleMatch[1].trim());
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
const documentRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Document[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
|
|
66
|
+
const documentMatch = documentRegex.exec(mainContentMatch[2]);
|
|
67
|
+
if (documentMatch && documentMatch[1]) {
|
|
68
|
+
logger.log("Found content with Document class");
|
|
69
|
+
articles.push(documentMatch[1].trim());
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
logger.log("Using all content within main-content");
|
|
73
|
+
articles.push(mainContentMatch[2].trim());
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
};
|
|
78
|
+
const processBody = () => {
|
|
79
|
+
const bodyRegex = /<body(?:\s+[^>]*?)>(.*?)<\/body>/is;
|
|
80
|
+
const bodyMatch = bodyRegex.exec(htmlString);
|
|
81
|
+
if (bodyMatch && bodyMatch[1]) {
|
|
82
|
+
const contentArticleRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Content-article[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
|
|
83
|
+
const contentArticleMatch = contentArticleRegex.exec(bodyMatch[1]);
|
|
84
|
+
if (contentArticleMatch && contentArticleMatch[1]) {
|
|
85
|
+
logger.log("Found content with Content-article class in body");
|
|
86
|
+
articles.push(contentArticleMatch[1].trim());
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
const documentRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Document[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
|
|
90
|
+
const documentMatch = documentRegex.exec(bodyMatch[1]);
|
|
91
|
+
if (documentMatch && documentMatch[1]) {
|
|
92
|
+
logger.log("Found content with Document class in body");
|
|
93
|
+
articles.push(documentMatch[1].trim());
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
logger.log("No specific content container found");
|
|
98
|
+
return false;
|
|
99
|
+
};
|
|
100
|
+
if (!processArticleTags()) {
|
|
101
|
+
logger.log("No article tags found, trying to find main-content");
|
|
102
|
+
if (!processMainContent()) {
|
|
103
|
+
logger.log("No main-content found, trying to find body content");
|
|
104
|
+
processBody();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return articles;
|
|
108
|
+
} catch (error) {
|
|
109
|
+
logger.error(`Error extracting article from HTML: ${error}`);
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function toMarkdownUrl(pageUrl, locale) {
|
|
114
|
+
const url = new URL(pageUrl);
|
|
115
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
116
|
+
url.pathname = path.endsWith(".md") ? path : `${path || ""}.md`;
|
|
117
|
+
url.hash = "";
|
|
118
|
+
url.searchParams.set("locale", locale);
|
|
119
|
+
return url.toString();
|
|
120
|
+
}
|
|
121
|
+
function parseMarkdownDocument(markdown) {
|
|
122
|
+
const lines = (markdown ?? "").replace(/\r\n?/g, "\n").split("\n");
|
|
123
|
+
let title = "Unknown";
|
|
124
|
+
let description = "No description";
|
|
125
|
+
let index = lines.findIndex((line) => /^#\s+\S/.test(line));
|
|
126
|
+
if (index === -1) {
|
|
127
|
+
return { title, description };
|
|
128
|
+
}
|
|
129
|
+
title = lines[index].replace(/^#\s+/, "").trim();
|
|
130
|
+
const paragraph = [];
|
|
131
|
+
for (index += 1; index < lines.length; index++) {
|
|
132
|
+
const line = lines[index].trim();
|
|
133
|
+
if (line === "") {
|
|
134
|
+
if (paragraph.length > 0) break;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (/^(#|```|[-*+]\s|\d+\.\s|>|\||<)/.test(line)) {
|
|
138
|
+
if (paragraph.length > 0) break;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
paragraph.push(line);
|
|
142
|
+
}
|
|
143
|
+
if (paragraph.length > 0) {
|
|
144
|
+
description = paragraph.join(" ");
|
|
145
|
+
}
|
|
146
|
+
return { title, description };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/utils/url-filter.ts
|
|
150
|
+
function matchesResource(url, resource) {
|
|
151
|
+
const urlPath = new URL(url).pathname;
|
|
152
|
+
const pathSegments = urlPath.split("/").filter(Boolean);
|
|
153
|
+
if (resource.includes("/")) {
|
|
154
|
+
const resourceSegments = resource.split("/").filter(Boolean);
|
|
155
|
+
return resourceSegments.every((segment, index) => pathSegments[index] === segment);
|
|
156
|
+
} else {
|
|
157
|
+
return pathSegments[0] === resource;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function matchesExcludeResources(url, excludeResources) {
|
|
161
|
+
if (!excludeResources || excludeResources.length === 0) {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
const urlPath = new URL(url).pathname;
|
|
165
|
+
const pathSegments = urlPath.split("/").filter(Boolean);
|
|
166
|
+
for (const excludeResource of excludeResources) {
|
|
167
|
+
if (excludeResource.includes("/")) {
|
|
168
|
+
const excludeSegments = excludeResource.split("/").filter(Boolean);
|
|
169
|
+
const matchesExclude = excludeSegments.every(
|
|
170
|
+
(segment, index) => pathSegments[index] === segment
|
|
171
|
+
);
|
|
172
|
+
if (matchesExclude) {
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
} else {
|
|
176
|
+
if (pathSegments[0] === excludeResource) {
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
function filterUrls(urls, resource, excludeResources) {
|
|
184
|
+
if (!resource && (!excludeResources || excludeResources.length === 0)) {
|
|
185
|
+
return urls;
|
|
186
|
+
}
|
|
187
|
+
return urls.filter((url) => {
|
|
188
|
+
if (resource && !matchesResource(url, resource)) {
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
if (excludeResources && matchesExcludeResources(url, excludeResources)) {
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
return true;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// src/options.ts
|
|
199
|
+
import {
|
|
200
|
+
ConsoleLogger as ConsoleLogger2,
|
|
201
|
+
resolveRateLimit
|
|
202
|
+
} from "stripe-loaders-core";
|
|
203
|
+
function resolveLoaderOptions(options) {
|
|
204
|
+
const opts = typeof options === "boolean" ? { debug: options } : options ?? {};
|
|
205
|
+
const debug = opts.debug ?? false;
|
|
206
|
+
return {
|
|
207
|
+
debug,
|
|
208
|
+
logger: opts.logger ?? new ConsoleLogger2(debug),
|
|
209
|
+
rateLimit: resolveRateLimit(opts.rateLimit),
|
|
210
|
+
fetch: opts.fetch,
|
|
211
|
+
sleep: opts.sleep
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/StripeDocsLoader.ts
|
|
216
|
+
var StripeDocsDocumentLoader = class extends BaseDocumentLoader {
|
|
217
|
+
/**
|
|
218
|
+
* @param options Loader options, or a boolean to enable debug logging (legacy signature)
|
|
219
|
+
*/
|
|
220
|
+
constructor(options) {
|
|
221
|
+
super();
|
|
222
|
+
this.options = resolveLoaderOptions(options);
|
|
223
|
+
this.format = typeof options === "object" && options.format || "html";
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Fetches URLs from the Stripe Docs sitemap
|
|
227
|
+
* @returns {Promise<string[]>} Array of URLs from the sitemap
|
|
228
|
+
*/
|
|
229
|
+
async fetchURLsFromSitemap() {
|
|
230
|
+
const documentUrls = await new SitemapProcessor({
|
|
231
|
+
debug: this.options.debug,
|
|
232
|
+
logger: this.options.logger,
|
|
233
|
+
rateLimit: this.options.rateLimit,
|
|
234
|
+
fetch: this.options.fetch,
|
|
235
|
+
sleep: this.options.sleep
|
|
236
|
+
}).fetchAndProcessSitemap("https://docs.stripe.com/sitemap.xml");
|
|
237
|
+
return documentUrls;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Fetches articles from the sitemap
|
|
241
|
+
*/
|
|
242
|
+
async fetchArticlesFromSitemap({
|
|
243
|
+
locale,
|
|
244
|
+
resource,
|
|
245
|
+
excludeResources,
|
|
246
|
+
format
|
|
247
|
+
}) {
|
|
248
|
+
const documentUrls = await this.fetchURLsFromSitemap();
|
|
249
|
+
const filteredDocumentUrls = filterUrls(documentUrls, resource, excludeResources);
|
|
250
|
+
return this.fetchArticlesFromURLs(filteredDocumentUrls, locale, format);
|
|
251
|
+
}
|
|
252
|
+
async fetchArticlesFromURLs(documentUrls, locale, format = this.format) {
|
|
253
|
+
const { logger } = this.options;
|
|
254
|
+
const pacer = new RequestPacer(this.options.rateLimit, this.options.sleep);
|
|
255
|
+
const articles = [];
|
|
256
|
+
for (const docsUrl of documentUrls) {
|
|
257
|
+
const requestUrl = format === "markdown" ? toMarkdownUrl(docsUrl, locale) : `${docsUrl}?locale=${locale}`;
|
|
258
|
+
try {
|
|
259
|
+
await pacer.wait();
|
|
260
|
+
logger.log(`Fetching ${requestUrl}`);
|
|
261
|
+
const response = await fetchWithRetry(requestUrl, void 0, {
|
|
262
|
+
rateLimit: this.options.rateLimit,
|
|
263
|
+
fetch: this.options.fetch,
|
|
264
|
+
sleep: this.options.sleep,
|
|
265
|
+
onRetry: ({ attempt, waitMs, reason }) => logger.warn(`Retrying ${requestUrl} (attempt ${attempt}, ${reason}) in ${waitMs}ms`)
|
|
266
|
+
});
|
|
267
|
+
if (response.status >= 400) {
|
|
268
|
+
logger.warn(`Skipping ${docsUrl} - HTTP status: ${response.status}`);
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const body = await response.text();
|
|
272
|
+
if (format === "markdown") {
|
|
273
|
+
const { title: title2, description: description2 } = parseMarkdownDocument(body);
|
|
274
|
+
articles.push({ url: docsUrl, content: body.trim(), title: title2, description: description2, format });
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const extracted = extractArticleFromHTML(body, logger);
|
|
278
|
+
const titleMatch = body.match(/<title[^>]*>([^<]+)<\/title>/);
|
|
279
|
+
const descMatch = body.match(/<meta[^>]*name="description"[^>]*content="([^"]+)"[^>]*>/);
|
|
280
|
+
const title = titleMatch ? titleMatch[1].trim() : "Unknown";
|
|
281
|
+
const description = descMatch ? descMatch[1].trim() : "No description";
|
|
282
|
+
articles.push(
|
|
283
|
+
...extracted.map((content) => ({ url: docsUrl, content, title, description, format }))
|
|
284
|
+
);
|
|
285
|
+
} catch (error) {
|
|
286
|
+
logger.error(`Error fetching ${docsUrl}: ${error}`);
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return articles;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* @deprecated Use `this.load()` and `splitter.splitDocuments()` individually.
|
|
294
|
+
* Loads the documents and splits them using the given document transformer.
|
|
295
|
+
* Kept for compatibility with LangChain's `index()` API, which only treats a
|
|
296
|
+
* source as a document loader when it has both `load()` and `loadAndSplit()`.
|
|
297
|
+
* `@langchain/core` 1.x no longer provides this method on BaseDocumentLoader.
|
|
298
|
+
* @param splitter The document transformer (e.g. a text splitter) to apply
|
|
299
|
+
* @returns {Promise<Document[]>} The loaded and split documents
|
|
300
|
+
*/
|
|
301
|
+
async loadAndSplit(splitter) {
|
|
302
|
+
if (splitter === void 0) {
|
|
303
|
+
throw new Error("You must pass a text splitter to use this method.");
|
|
304
|
+
}
|
|
305
|
+
const docs = await this.load();
|
|
306
|
+
return splitter.invoke(docs);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Loads documents from Stripe Docs
|
|
310
|
+
* @returns {Promise<Document[]>} Array of LangChain documents
|
|
311
|
+
*/
|
|
312
|
+
async load(options) {
|
|
313
|
+
const { urls, resource, excludeResources } = options ?? {};
|
|
314
|
+
const locale = options?.locale ?? "en-US";
|
|
315
|
+
const format = options?.format ?? this.format;
|
|
316
|
+
const articles = urls ? await this.fetchArticlesFromURLs(urls, locale, format) : await this.fetchArticlesFromSitemap({ locale, resource, excludeResources, format });
|
|
317
|
+
const nhm = new NodeHtmlMarkdown();
|
|
318
|
+
return articles.map(
|
|
319
|
+
(article) => new Document({
|
|
320
|
+
pageContent: article.format === "markdown" ? article.content : nhm.translate(article.content),
|
|
321
|
+
metadata: {
|
|
322
|
+
source: article.url,
|
|
323
|
+
title: article.title,
|
|
324
|
+
description: article.description
|
|
325
|
+
}
|
|
326
|
+
})
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
// src/StripeComLoader.ts
|
|
332
|
+
import { SitemapProcessor as SitemapProcessor2, fetchWithRetry as fetchWithRetry2, RequestPacer as RequestPacer2 } from "stripe-loaders-core";
|
|
333
|
+
import { BaseDocumentLoader as BaseDocumentLoader2 } from "@langchain/core/document_loaders/base";
|
|
334
|
+
import { Document as Document2 } from "@langchain/core/documents";
|
|
335
|
+
import { NodeHtmlMarkdown as NodeHtmlMarkdown2 } from "node-html-markdown";
|
|
336
|
+
var StripeComDocumentLoader = class extends BaseDocumentLoader2 {
|
|
337
|
+
/**
|
|
338
|
+
* @param options Loader options, or a boolean to enable debug logging (legacy signature)
|
|
339
|
+
*/
|
|
340
|
+
constructor(options) {
|
|
341
|
+
super();
|
|
342
|
+
this.options = resolveLoaderOptions(options);
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Fetches URLs from the Stripe.com sitemap
|
|
346
|
+
* @param {string} resource Optional resource path to filter URLs
|
|
347
|
+
* @returns {Promise<string[]>} Array of URLs from the sitemap
|
|
348
|
+
*/
|
|
349
|
+
async fetchURLsFromSitemap(resource) {
|
|
350
|
+
return new SitemapProcessor2({
|
|
351
|
+
debug: this.options.debug,
|
|
352
|
+
logger: this.options.logger,
|
|
353
|
+
rateLimit: this.options.rateLimit,
|
|
354
|
+
fetch: this.options.fetch,
|
|
355
|
+
sleep: this.options.sleep
|
|
356
|
+
}).fetchAndProcessSitemapIndex(
|
|
357
|
+
"https://stripe.com/sitemap/sitemap.xml",
|
|
358
|
+
["https://stripe.com/", resource].filter(Boolean).join("")
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Fetches article content from a list of URLs
|
|
363
|
+
* @param {string[]} urls Array of URLs to fetch content from
|
|
364
|
+
* @param {string} locale Locale for the content
|
|
365
|
+
* @returns {Promise<StripeDocsArticle[]>} Array of article objects
|
|
366
|
+
*/
|
|
367
|
+
async fetchArticlesFromURLs(urls, locale) {
|
|
368
|
+
const { logger } = this.options;
|
|
369
|
+
const pacer = new RequestPacer2(this.options.rateLimit, this.options.sleep);
|
|
370
|
+
const articles = [];
|
|
371
|
+
for (const pageUrl of urls) {
|
|
372
|
+
const requestUrl = `${pageUrl}?locale=${locale}`;
|
|
373
|
+
try {
|
|
374
|
+
await pacer.wait();
|
|
375
|
+
logger.log(`Fetching ${requestUrl}`);
|
|
376
|
+
const response = await fetchWithRetry2(requestUrl, void 0, {
|
|
377
|
+
rateLimit: this.options.rateLimit,
|
|
378
|
+
fetch: this.options.fetch,
|
|
379
|
+
sleep: this.options.sleep,
|
|
380
|
+
onRetry: ({ attempt, waitMs, reason }) => logger.warn(`Retrying ${requestUrl} (attempt ${attempt}, ${reason}) in ${waitMs}ms`)
|
|
381
|
+
});
|
|
382
|
+
if (response.status >= 400) {
|
|
383
|
+
logger.warn(`Skipping ${pageUrl} - HTTP status: ${response.status}`);
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
const html = await response.text();
|
|
387
|
+
const rawArticles = extractBodyFromHTML(html, logger);
|
|
388
|
+
const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/);
|
|
389
|
+
const descMatch = html.match(/<meta[^>]*name="description"[^>]*content="([^"]+)"[^>]*>/);
|
|
390
|
+
const title = titleMatch ? titleMatch[1].trim() : "Unknown";
|
|
391
|
+
const description = descMatch ? descMatch[1].trim() : "No description";
|
|
392
|
+
articles.push(
|
|
393
|
+
...rawArticles.map((content) => ({ url: pageUrl, content, title, description }))
|
|
394
|
+
);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
logger.error(`Error fetching ${pageUrl}: ${error}`);
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return articles;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Fetches articles from the sitemap
|
|
404
|
+
* @param {string} resource Optional resource path to filter URLs
|
|
405
|
+
* @param {string} locale Locale for the content
|
|
406
|
+
* @returns {Promise<StripeDocsArticle[]>} Array of article objects
|
|
407
|
+
*/
|
|
408
|
+
async fetchArticlesFromSitemap(resource, locale) {
|
|
409
|
+
const documentUrls = await this.fetchURLsFromSitemap(resource);
|
|
410
|
+
return this.fetchArticlesFromURLs(documentUrls, locale);
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* @deprecated Use `this.load()` and `splitter.splitDocuments()` individually.
|
|
414
|
+
* Loads the documents and splits them using the given document transformer.
|
|
415
|
+
* Kept for compatibility with LangChain's `index()` API, which only treats a
|
|
416
|
+
* source as a document loader when it has both `load()` and `loadAndSplit()`.
|
|
417
|
+
* `@langchain/core` 1.x no longer provides this method on BaseDocumentLoader.
|
|
418
|
+
* @param splitter The document transformer (e.g. a text splitter) to apply
|
|
419
|
+
* @returns {Promise<Document[]>} The loaded and split documents
|
|
420
|
+
*/
|
|
421
|
+
async loadAndSplit(splitter) {
|
|
422
|
+
if (splitter === void 0) {
|
|
423
|
+
throw new Error("You must pass a text splitter to use this method.");
|
|
424
|
+
}
|
|
425
|
+
const docs = await this.load();
|
|
426
|
+
return splitter.invoke(docs);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Loads documents from Stripe.com
|
|
430
|
+
* @param {Object} options Loading options
|
|
431
|
+
* @param {string} options.resource Optional resource path to filter URLs
|
|
432
|
+
* @param {string} options.locale Optional locale for the content (defaults to 'en-US')
|
|
433
|
+
* @param {string[]} options.urls Optional list of specific URLs to load
|
|
434
|
+
* @returns {Promise<Document[]>} Array of LangChain documents
|
|
435
|
+
*/
|
|
436
|
+
async load(options) {
|
|
437
|
+
const { resource, urls } = options ?? {};
|
|
438
|
+
const locale = options?.locale ?? "en-US";
|
|
439
|
+
const articles = urls ? await this.fetchArticlesFromURLs(urls, locale) : await this.fetchArticlesFromSitemap(resource, locale);
|
|
440
|
+
const nhm = new NodeHtmlMarkdown2();
|
|
441
|
+
return articles.map(
|
|
442
|
+
(article) => new Document2({
|
|
443
|
+
pageContent: nhm.translate(article.content),
|
|
444
|
+
metadata: {
|
|
445
|
+
source: article.url,
|
|
446
|
+
title: article.title,
|
|
447
|
+
description: article.description
|
|
448
|
+
}
|
|
449
|
+
})
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// src/StripeChangelogLoader.ts
|
|
455
|
+
import {
|
|
456
|
+
delayWithJitter,
|
|
457
|
+
fetchStripeChangelog,
|
|
458
|
+
fetchWithRetry as fetchWithRetry3
|
|
459
|
+
} from "stripe-loaders-core";
|
|
460
|
+
import { BaseDocumentLoader as BaseDocumentLoader3 } from "@langchain/core/document_loaders/base";
|
|
461
|
+
import { Document as Document3 } from "@langchain/core/documents";
|
|
462
|
+
function entryMetadata(entry) {
|
|
463
|
+
return {
|
|
464
|
+
source: entry.link || "https://docs.stripe.com/changelog",
|
|
465
|
+
title: entry.title,
|
|
466
|
+
version: entry.version,
|
|
467
|
+
date: entry.date,
|
|
468
|
+
release: entry.release,
|
|
469
|
+
category: entry.category,
|
|
470
|
+
affectedProducts: entry.affectedProducts,
|
|
471
|
+
breaking: entry.isBreakingChange,
|
|
472
|
+
changeType: entry.changeType
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
function entrySummary(entry) {
|
|
476
|
+
return [
|
|
477
|
+
`# ${entry.title}`,
|
|
478
|
+
"",
|
|
479
|
+
`- Version: ${entry.version}`,
|
|
480
|
+
...entry.release ? [`- Release: ${entry.release}`] : [],
|
|
481
|
+
...entry.category ? [`- Category: ${entry.category}`] : [],
|
|
482
|
+
`- Affected products: ${entry.affectedProducts.join(", ") || "None"}`,
|
|
483
|
+
`- Breaking change: ${entry.isBreakingChange ? "Yes" : "No"}`,
|
|
484
|
+
...entry.link ? [`- Details: ${entry.link}`] : []
|
|
485
|
+
].join("\n");
|
|
486
|
+
}
|
|
487
|
+
var StripeChangelogDocumentLoader = class extends BaseDocumentLoader3 {
|
|
488
|
+
/**
|
|
489
|
+
* @param options Loader options, or a boolean to enable debug logging
|
|
490
|
+
*/
|
|
491
|
+
constructor(options) {
|
|
492
|
+
super();
|
|
493
|
+
this.options = resolveLoaderOptions(options);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Fetches the changelog and returns the entries that match the filters (newest first).
|
|
497
|
+
*/
|
|
498
|
+
async fetchEntries(options = {}) {
|
|
499
|
+
const locale = options.locale ?? "en-US";
|
|
500
|
+
this.options.logger.log(`Fetching Stripe changelog (${locale})`);
|
|
501
|
+
const versions = await fetchStripeChangelog({
|
|
502
|
+
locale,
|
|
503
|
+
rateLimit: this.options.rateLimit,
|
|
504
|
+
fetch: this.options.fetch,
|
|
505
|
+
sleep: this.options.sleep
|
|
506
|
+
});
|
|
507
|
+
const releases = options.releases?.map((release) => release.toLowerCase());
|
|
508
|
+
return versions.flatMap((version) => version.entries).filter(
|
|
509
|
+
(entry) => (!options.since || entry.date >= options.since) && (!releases || entry.release !== void 0 && releases.includes(entry.release.toLowerCase())) && (!options.breakingOnly || entry.isBreakingChange)
|
|
510
|
+
).slice(0, Math.max(0, options.limit ?? Infinity));
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* @deprecated Use `this.load()` and `splitter.splitDocuments()` individually.
|
|
514
|
+
* Kept for compatibility with LangChain's `index()` API, which only treats a
|
|
515
|
+
* source as a document loader when it has both `load()` and `loadAndSplit()`.
|
|
516
|
+
*/
|
|
517
|
+
async loadAndSplit(splitter) {
|
|
518
|
+
if (splitter === void 0) {
|
|
519
|
+
throw new Error("You must pass a text splitter to use this method.");
|
|
520
|
+
}
|
|
521
|
+
return splitter.invoke(await this.load());
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Loads changelog entries as LangChain documents.
|
|
525
|
+
* When `includeDetails` is true and a detail page cannot be fetched, the entry falls back
|
|
526
|
+
* to the changelog row summary (and `metadata.detailsFetched` is false).
|
|
527
|
+
*/
|
|
528
|
+
async load(options = {}) {
|
|
529
|
+
const locale = options.locale ?? "en-US";
|
|
530
|
+
const entries = await this.fetchEntries(options);
|
|
531
|
+
if (!options.includeDetails) {
|
|
532
|
+
return entries.map(
|
|
533
|
+
(entry) => new Document3({ pageContent: entrySummary(entry), metadata: entryMetadata(entry) })
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
const documents = [];
|
|
537
|
+
const { requestDelayMs, requestJitterMs } = this.options.rateLimit;
|
|
538
|
+
for (const entry of entries) {
|
|
539
|
+
let detail = null;
|
|
540
|
+
if (entry.link) {
|
|
541
|
+
await delayWithJitter(requestDelayMs, requestJitterMs, this.options.sleep);
|
|
542
|
+
let url = entry.link;
|
|
543
|
+
try {
|
|
544
|
+
url = toMarkdownUrl(entry.link, locale);
|
|
545
|
+
this.options.logger.log(`Fetching ${url}`);
|
|
546
|
+
const response = await fetchWithRetry3(url, void 0, {
|
|
547
|
+
rateLimit: this.options.rateLimit,
|
|
548
|
+
fetch: this.options.fetch,
|
|
549
|
+
sleep: this.options.sleep,
|
|
550
|
+
onRetry: ({ attempt, waitMs, reason }) => this.options.logger.warn(
|
|
551
|
+
`Retrying ${url} (attempt ${attempt}, ${reason}) in ${waitMs}ms`
|
|
552
|
+
)
|
|
553
|
+
});
|
|
554
|
+
if (response.status >= 400) {
|
|
555
|
+
this.options.logger.warn(
|
|
556
|
+
`Skipping details of ${entry.link} - HTTP status: ${response.status}`
|
|
557
|
+
);
|
|
558
|
+
} else {
|
|
559
|
+
detail = (await response.text()).trim() || null;
|
|
560
|
+
}
|
|
561
|
+
} catch (error) {
|
|
562
|
+
this.options.logger.error(`Error fetching ${url}: ${error}`);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
documents.push(
|
|
566
|
+
new Document3({
|
|
567
|
+
pageContent: detail ?? entrySummary(entry),
|
|
568
|
+
metadata: { ...entryMetadata(entry), detailsFetched: detail !== null }
|
|
569
|
+
})
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
return documents;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
export {
|
|
576
|
+
StripeChangelogDocumentLoader,
|
|
577
|
+
StripeComDocumentLoader,
|
|
578
|
+
StripeDocsDocumentLoader
|
|
579
|
+
};
|
|
580
|
+
//# sourceMappingURL=index.js.map
|