langchain-stripe-loader 0.1.0 → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 wpkyoto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -40,10 +40,41 @@ const customDocuments = await loader.load({
40
40
  excludeResources: ['connect/account-balances'],
41
41
  });
42
42
 
43
+ // Fetch the Markdown version that docs.stripe.com serves at `<page>.md`
44
+ // (no HTML extraction; titles come without the " | Stripe Documentation" suffix)
45
+ const markdownDocuments = await loader.load({
46
+ locale: 'ja-JP',
47
+ resource: 'payments',
48
+ format: 'markdown',
49
+ });
50
+
43
51
  // Use the documents with your LangChain application
44
52
  console.log(`Loaded ${documents.length} documents`);
45
53
  ```
46
54
 
55
+ ### Options: rate limiting, logging, and format
56
+
57
+ Requests are sent one at a time with a delay between them, and HTTP 429 / 5xx responses are
58
+ retried with exponential backoff (honouring `Retry-After`). A full sitemap contains thousands of
59
+ pages, so narrow it down with `resource` or `urls` where you can.
60
+
61
+ ```typescript
62
+ const loader = new StripeDocsDocumentLoader({
63
+ format: 'markdown', // default format for load(); 'html' when omitted
64
+ debug: true, // print log / warn messages with the default console logger
65
+ logger: myLogger, // any object with log / warn / error; defaults to console
66
+ rateLimit: {
67
+ requestDelayMs: 1000, // delay between requests (default 1000)
68
+ requestJitterMs: 500, // random variation, ±half of this value (default 500)
69
+ maxRetries: 3, // retries for 429 / 5xx and network errors (default 3)
70
+ backoffBaseMs: 1000, // exponential backoff base (default 1000)
71
+ backoffMaxMs: 30000, // upper bound for a single wait (default 30000)
72
+ },
73
+ });
74
+ ```
75
+
76
+ `new StripeDocsDocumentLoader(true)` (debug only) is still supported.
77
+
47
78
  ### Loading Content from Stripe.com Website
48
79
 
49
80
  ```typescript
@@ -76,14 +107,16 @@ Document loader for Stripe's official documentation (docs.stripe.com).
76
107
  **Constructor**
77
108
 
78
109
  ```typescript
79
- constructor(debug: boolean = false)
110
+ constructor(options?: boolean | StripeDocsLoaderOptions)
80
111
  ```
81
112
 
82
- - `debug`: Enable debug logging
113
+ - `options.format`: `'html'` (default) or `'markdown'`
114
+ - `options.debug`, `options.logger`, `options.rateLimit`, `options.fetch`, `options.sleep`: see "Options" above
115
+ - Passing a boolean sets `debug` (legacy signature)
83
116
 
84
117
  **Methods**
85
118
 
86
- - `load(locale: string = 'en-US'): Promise<Document[]>` - Load documents from Stripe Docs with the specified locale
119
+ - `load(options?: { locale?: string; urls?: string[]; resource?: string; excludeResources?: string[]; format?: 'html' | 'markdown' }): Promise<Document[]>` - Load documents from Stripe Docs. `locale` defaults to `en-US`
87
120
 
88
121
  ### StripeComDocumentLoader
89
122
 
@@ -92,21 +125,22 @@ Document loader for Stripe's main website (stripe.com).
92
125
  **Constructor**
93
126
 
94
127
  ```typescript
95
- constructor(debug: boolean = false)
128
+ constructor(options?: boolean | StripeLoaderOptions)
96
129
  ```
97
130
 
98
- - `debug`: Enable debug logging
131
+ - `options.debug`, `options.logger`, `options.rateLimit`, `options.fetch`, `options.sleep`: see "Options" above
132
+ - Passing a boolean sets `debug` (legacy signature)
99
133
 
100
134
  **Methods**
101
135
 
102
- - `load(options?: { resource?: string; locale?: string; urls?: string[] }): Promise<Document[]>` - Load documents from Stripe.com with optional filtering
136
+ - `load(options?: { resource?: string; locale?: string; urls?: string[] }): Promise<Document[]>` - Load documents from Stripe.com with optional filtering. Pages that return HTTP 400 or higher are skipped
103
137
 
104
138
  ## How It Works
105
139
 
106
140
  1. The loaders fetch URLs from Stripe's sitemaps
107
- 2. HTML content is downloaded from each URL
108
- 3. Relevant content is extracted using regex patterns
109
- 4. HTML is converted to Markdown using Turndown
141
+ 2. Each page is downloaded one at a time, with a delay between requests and retries on 429 / 5xx
142
+ 3. With `format: 'html'`, relevant content is extracted using regex patterns and converted to Markdown using node-html-markdown
143
+ 4. With `format: 'markdown'` (docs.stripe.com only), the `<page>.md` Markdown is used as-is
110
144
  5. Content is wrapped in LangChain Document objects with metadata
111
145
 
112
146
  ## Dependencies
package/dist/index.cjs ADDED
@@ -0,0 +1,482 @@
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
+ StripeComDocumentLoader: () => StripeComDocumentLoader,
24
+ StripeDocsDocumentLoader: () => StripeDocsDocumentLoader
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/StripeDocsLoader.ts
29
+ var import_stripe_loaders_core3 = require("stripe-loaders-core");
30
+ var import_base = require("@langchain/core/document_loaders/base");
31
+ var import_documents = require("@langchain/core/documents");
32
+ var import_node_html_markdown = require("node-html-markdown");
33
+
34
+ // src/utils.ts
35
+ var import_stripe_loaders_core = require("stripe-loaders-core");
36
+ var defaultLogger = new import_stripe_loaders_core.ConsoleLogger(false);
37
+ function extractBodyFromHTML(htmlString, logger = defaultLogger) {
38
+ try {
39
+ if (!htmlString) {
40
+ logger.log("Input HTML is null or undefined");
41
+ return [];
42
+ }
43
+ const bodyRegex = /<body[^>]*>([\s\S]*?)<\/body>/gi;
44
+ const matches = [];
45
+ let match;
46
+ while ((match = bodyRegex.exec(htmlString)) !== null) {
47
+ if (match[1]) {
48
+ matches.push(match[1].trim());
49
+ }
50
+ }
51
+ if (matches.length === 0) {
52
+ logger.log("No body tags found");
53
+ return [];
54
+ }
55
+ return matches;
56
+ } catch (error) {
57
+ logger.error(`An error occurred: ${error}`);
58
+ return [];
59
+ }
60
+ }
61
+ function extractArticleFromHTML(htmlString, logger = defaultLogger) {
62
+ try {
63
+ if (!htmlString) {
64
+ logger.log("Input HTML is null or undefined");
65
+ return [];
66
+ }
67
+ const articles = [];
68
+ const processArticleTags = () => {
69
+ const articleRegex = /<article(?:\s+[^>]*)?>(.*?)<\/article>/gis;
70
+ let articleMatch;
71
+ let foundArticles = false;
72
+ while ((articleMatch = articleRegex.exec(htmlString)) !== null) {
73
+ if (articleMatch[1]) {
74
+ articles.push(articleMatch[1].trim());
75
+ foundArticles = true;
76
+ }
77
+ }
78
+ return foundArticles;
79
+ };
80
+ const processMainContent = () => {
81
+ const mainContentRegex = /<(div|section|main|article)(?:\s+[^>]*?)id=["']main-content["'](?:[^>]*?)>(.*?)<\/\1>/is;
82
+ const mainContentMatch = mainContentRegex.exec(htmlString);
83
+ if (mainContentMatch && mainContentMatch[2]) {
84
+ logger.log("Found element with main-content ID");
85
+ const contentArticleRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Content-article[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
86
+ const contentArticleMatch = contentArticleRegex.exec(mainContentMatch[2]);
87
+ if (contentArticleMatch && contentArticleMatch[1]) {
88
+ logger.log("Found content with Content-article class");
89
+ articles.push(contentArticleMatch[1].trim());
90
+ return true;
91
+ }
92
+ const documentRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Document[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
93
+ const documentMatch = documentRegex.exec(mainContentMatch[2]);
94
+ if (documentMatch && documentMatch[1]) {
95
+ logger.log("Found content with Document class");
96
+ articles.push(documentMatch[1].trim());
97
+ return true;
98
+ }
99
+ logger.log("Using all content within main-content");
100
+ articles.push(mainContentMatch[2].trim());
101
+ return true;
102
+ }
103
+ return false;
104
+ };
105
+ const processBody = () => {
106
+ const bodyRegex = /<body(?:\s+[^>]*?)>(.*?)<\/body>/is;
107
+ const bodyMatch = bodyRegex.exec(htmlString);
108
+ if (bodyMatch && bodyMatch[1]) {
109
+ const contentArticleRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Content-article[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
110
+ const contentArticleMatch = contentArticleRegex.exec(bodyMatch[1]);
111
+ if (contentArticleMatch && contentArticleMatch[1]) {
112
+ logger.log("Found content with Content-article class in body");
113
+ articles.push(contentArticleMatch[1].trim());
114
+ return true;
115
+ }
116
+ const documentRegex = /<div(?:\s+[^>]*?)class=["'][^"']*Document[^"']*["'](?:[^>]*?)>(.*?)<\/div>/is;
117
+ const documentMatch = documentRegex.exec(bodyMatch[1]);
118
+ if (documentMatch && documentMatch[1]) {
119
+ logger.log("Found content with Document class in body");
120
+ articles.push(documentMatch[1].trim());
121
+ return true;
122
+ }
123
+ }
124
+ logger.log("No specific content container found");
125
+ return false;
126
+ };
127
+ if (!processArticleTags()) {
128
+ logger.log("No article tags found, trying to find main-content");
129
+ if (!processMainContent()) {
130
+ logger.log("No main-content found, trying to find body content");
131
+ processBody();
132
+ }
133
+ }
134
+ return articles;
135
+ } catch (error) {
136
+ logger.error(`Error extracting article from HTML: ${error}`);
137
+ return [];
138
+ }
139
+ }
140
+ function toMarkdownUrl(pageUrl, locale) {
141
+ const url = new URL(pageUrl);
142
+ const path = url.pathname.replace(/\/+$/, "");
143
+ url.pathname = path.endsWith(".md") ? path : `${path || ""}.md`;
144
+ url.hash = "";
145
+ url.searchParams.set("locale", locale);
146
+ return url.toString();
147
+ }
148
+ function parseMarkdownDocument(markdown) {
149
+ const lines = (markdown ?? "").replace(/\r\n?/g, "\n").split("\n");
150
+ let title = "Unknown";
151
+ let description = "No description";
152
+ let index = lines.findIndex((line) => /^#\s+\S/.test(line));
153
+ if (index === -1) {
154
+ return { title, description };
155
+ }
156
+ title = lines[index].replace(/^#\s+/, "").trim();
157
+ const paragraph = [];
158
+ for (index += 1; index < lines.length; index++) {
159
+ const line = lines[index].trim();
160
+ if (line === "") {
161
+ if (paragraph.length > 0) break;
162
+ continue;
163
+ }
164
+ if (/^(#|```|[-*+]\s|\d+\.\s|>|\||<)/.test(line)) {
165
+ if (paragraph.length > 0) break;
166
+ continue;
167
+ }
168
+ paragraph.push(line);
169
+ }
170
+ if (paragraph.length > 0) {
171
+ description = paragraph.join(" ");
172
+ }
173
+ return { title, description };
174
+ }
175
+
176
+ // src/utils/url-filter.ts
177
+ function matchesResource(url, resource) {
178
+ const urlPath = new URL(url).pathname;
179
+ const pathSegments = urlPath.split("/").filter(Boolean);
180
+ if (resource.includes("/")) {
181
+ const resourceSegments = resource.split("/").filter(Boolean);
182
+ return resourceSegments.every((segment, index) => pathSegments[index] === segment);
183
+ } else {
184
+ return pathSegments[0] === resource;
185
+ }
186
+ }
187
+ function matchesExcludeResources(url, excludeResources) {
188
+ if (!excludeResources || excludeResources.length === 0) {
189
+ return false;
190
+ }
191
+ const urlPath = new URL(url).pathname;
192
+ const pathSegments = urlPath.split("/").filter(Boolean);
193
+ for (const excludeResource of excludeResources) {
194
+ if (excludeResource.includes("/")) {
195
+ const excludeSegments = excludeResource.split("/").filter(Boolean);
196
+ const matchesExclude = excludeSegments.every(
197
+ (segment, index) => pathSegments[index] === segment
198
+ );
199
+ if (matchesExclude) {
200
+ return true;
201
+ }
202
+ } else {
203
+ if (pathSegments[0] === excludeResource) {
204
+ return true;
205
+ }
206
+ }
207
+ }
208
+ return false;
209
+ }
210
+ function filterUrls(urls, resource, excludeResources) {
211
+ if (!resource && (!excludeResources || excludeResources.length === 0)) {
212
+ return urls;
213
+ }
214
+ return urls.filter((url) => {
215
+ if (resource && !matchesResource(url, resource)) {
216
+ return false;
217
+ }
218
+ if (excludeResources && matchesExcludeResources(url, excludeResources)) {
219
+ return false;
220
+ }
221
+ return true;
222
+ });
223
+ }
224
+
225
+ // src/options.ts
226
+ var import_stripe_loaders_core2 = require("stripe-loaders-core");
227
+ function resolveLoaderOptions(options) {
228
+ const opts = typeof options === "boolean" ? { debug: options } : options ?? {};
229
+ const debug = opts.debug ?? false;
230
+ return {
231
+ debug,
232
+ logger: opts.logger ?? new import_stripe_loaders_core2.ConsoleLogger(debug),
233
+ rateLimit: (0, import_stripe_loaders_core2.resolveRateLimit)(opts.rateLimit),
234
+ fetch: opts.fetch,
235
+ sleep: opts.sleep
236
+ };
237
+ }
238
+
239
+ // src/StripeDocsLoader.ts
240
+ var StripeDocsDocumentLoader = class extends import_base.BaseDocumentLoader {
241
+ /**
242
+ * @param options Loader options, or a boolean to enable debug logging (legacy signature)
243
+ */
244
+ constructor(options) {
245
+ super();
246
+ this.options = resolveLoaderOptions(options);
247
+ this.format = typeof options === "object" && options.format || "html";
248
+ }
249
+ /**
250
+ * Fetches URLs from the Stripe Docs sitemap
251
+ * @returns {Promise<string[]>} Array of URLs from the sitemap
252
+ */
253
+ async fetchURLsFromSitemap() {
254
+ const documentUrls = await new import_stripe_loaders_core3.SitemapProcessor({
255
+ debug: this.options.debug,
256
+ logger: this.options.logger,
257
+ rateLimit: this.options.rateLimit,
258
+ fetch: this.options.fetch,
259
+ sleep: this.options.sleep
260
+ }).fetchAndProcessSitemap("https://docs.stripe.com/sitemap.xml");
261
+ return documentUrls;
262
+ }
263
+ /**
264
+ * Fetches articles from the sitemap
265
+ */
266
+ async fetchArticlesFromSitemap({
267
+ locale,
268
+ resource,
269
+ excludeResources,
270
+ format
271
+ }) {
272
+ const documentUrls = await this.fetchURLsFromSitemap();
273
+ const filteredDocumentUrls = filterUrls(documentUrls, resource, excludeResources);
274
+ return this.fetchArticlesFromURLs(filteredDocumentUrls, locale, format);
275
+ }
276
+ async fetchArticlesFromURLs(documentUrls, locale, format = this.format) {
277
+ const { logger } = this.options;
278
+ const pacer = new import_stripe_loaders_core3.RequestPacer(this.options.rateLimit, this.options.sleep);
279
+ const articles = [];
280
+ for (const docsUrl of documentUrls) {
281
+ const requestUrl = format === "markdown" ? toMarkdownUrl(docsUrl, locale) : `${docsUrl}?locale=${locale}`;
282
+ try {
283
+ await pacer.wait();
284
+ logger.log(`Fetching ${requestUrl}`);
285
+ const response = await (0, import_stripe_loaders_core3.fetchWithRetry)(requestUrl, void 0, {
286
+ rateLimit: this.options.rateLimit,
287
+ fetch: this.options.fetch,
288
+ sleep: this.options.sleep,
289
+ onRetry: ({ attempt, waitMs, reason }) => logger.warn(`Retrying ${requestUrl} (attempt ${attempt}, ${reason}) in ${waitMs}ms`)
290
+ });
291
+ if (response.status >= 400) {
292
+ logger.warn(`Skipping ${docsUrl} - HTTP status: ${response.status}`);
293
+ continue;
294
+ }
295
+ const body = await response.text();
296
+ if (format === "markdown") {
297
+ const { title: title2, description: description2 } = parseMarkdownDocument(body);
298
+ articles.push({ url: docsUrl, content: body.trim(), title: title2, description: description2, format });
299
+ continue;
300
+ }
301
+ const extracted = extractArticleFromHTML(body, logger);
302
+ const titleMatch = body.match(/<title[^>]*>([^<]+)<\/title>/);
303
+ const descMatch = body.match(/<meta[^>]*name="description"[^>]*content="([^"]+)"[^>]*>/);
304
+ const title = titleMatch ? titleMatch[1].trim() : "Unknown";
305
+ const description = descMatch ? descMatch[1].trim() : "No description";
306
+ articles.push(
307
+ ...extracted.map((content) => ({ url: docsUrl, content, title, description, format }))
308
+ );
309
+ } catch (error) {
310
+ logger.error(`Error fetching ${docsUrl}: ${error}`);
311
+ continue;
312
+ }
313
+ }
314
+ return articles;
315
+ }
316
+ /**
317
+ * @deprecated Use `this.load()` and `splitter.splitDocuments()` individually.
318
+ * Loads the documents and splits them using the given document transformer.
319
+ * Kept for compatibility with LangChain's `index()` API, which only treats a
320
+ * source as a document loader when it has both `load()` and `loadAndSplit()`.
321
+ * `@langchain/core` 1.x no longer provides this method on BaseDocumentLoader.
322
+ * @param splitter The document transformer (e.g. a text splitter) to apply
323
+ * @returns {Promise<Document[]>} The loaded and split documents
324
+ */
325
+ async loadAndSplit(splitter) {
326
+ if (splitter === void 0) {
327
+ throw new Error("You must pass a text splitter to use this method.");
328
+ }
329
+ const docs = await this.load();
330
+ return splitter.invoke(docs);
331
+ }
332
+ /**
333
+ * Loads documents from Stripe Docs
334
+ * @returns {Promise<Document[]>} Array of LangChain documents
335
+ */
336
+ async load(options) {
337
+ const { urls, resource, excludeResources } = options ?? {};
338
+ const locale = options?.locale ?? "en-US";
339
+ const format = options?.format ?? this.format;
340
+ const articles = urls ? await this.fetchArticlesFromURLs(urls, locale, format) : await this.fetchArticlesFromSitemap({ locale, resource, excludeResources, format });
341
+ const nhm = new import_node_html_markdown.NodeHtmlMarkdown();
342
+ return articles.map(
343
+ (article) => new import_documents.Document({
344
+ pageContent: article.format === "markdown" ? article.content : nhm.translate(article.content),
345
+ metadata: {
346
+ source: article.url,
347
+ title: article.title,
348
+ description: article.description
349
+ }
350
+ })
351
+ );
352
+ }
353
+ };
354
+
355
+ // src/StripeComLoader.ts
356
+ var import_stripe_loaders_core4 = require("stripe-loaders-core");
357
+ var import_base2 = require("@langchain/core/document_loaders/base");
358
+ var import_documents2 = require("@langchain/core/documents");
359
+ var import_node_html_markdown2 = require("node-html-markdown");
360
+ var StripeComDocumentLoader = class extends import_base2.BaseDocumentLoader {
361
+ /**
362
+ * @param options Loader options, or a boolean to enable debug logging (legacy signature)
363
+ */
364
+ constructor(options) {
365
+ super();
366
+ this.options = resolveLoaderOptions(options);
367
+ }
368
+ /**
369
+ * Fetches URLs from the Stripe.com sitemap
370
+ * @param {string} resource Optional resource path to filter URLs
371
+ * @returns {Promise<string[]>} Array of URLs from the sitemap
372
+ */
373
+ async fetchURLsFromSitemap(resource) {
374
+ return new import_stripe_loaders_core4.SitemapProcessor({
375
+ debug: this.options.debug,
376
+ logger: this.options.logger,
377
+ rateLimit: this.options.rateLimit,
378
+ fetch: this.options.fetch,
379
+ sleep: this.options.sleep
380
+ }).fetchAndProcessSitemapIndex(
381
+ "https://stripe.com/sitemap/sitemap.xml",
382
+ ["https://stripe.com/", resource].filter(Boolean).join("")
383
+ );
384
+ }
385
+ /**
386
+ * Fetches article content from a list of URLs
387
+ * @param {string[]} urls Array of URLs to fetch content from
388
+ * @param {string} locale Locale for the content
389
+ * @returns {Promise<StripeDocsArticle[]>} Array of article objects
390
+ */
391
+ async fetchArticlesFromURLs(urls, locale) {
392
+ const { logger } = this.options;
393
+ const pacer = new import_stripe_loaders_core4.RequestPacer(this.options.rateLimit, this.options.sleep);
394
+ const articles = [];
395
+ for (const pageUrl of urls) {
396
+ const requestUrl = `${pageUrl}?locale=${locale}`;
397
+ try {
398
+ await pacer.wait();
399
+ logger.log(`Fetching ${requestUrl}`);
400
+ const response = await (0, import_stripe_loaders_core4.fetchWithRetry)(requestUrl, void 0, {
401
+ rateLimit: this.options.rateLimit,
402
+ fetch: this.options.fetch,
403
+ sleep: this.options.sleep,
404
+ onRetry: ({ attempt, waitMs, reason }) => logger.warn(`Retrying ${requestUrl} (attempt ${attempt}, ${reason}) in ${waitMs}ms`)
405
+ });
406
+ if (response.status >= 400) {
407
+ logger.warn(`Skipping ${pageUrl} - HTTP status: ${response.status}`);
408
+ continue;
409
+ }
410
+ const html = await response.text();
411
+ const rawArticles = extractBodyFromHTML(html, logger);
412
+ const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/);
413
+ const descMatch = html.match(/<meta[^>]*name="description"[^>]*content="([^"]+)"[^>]*>/);
414
+ const title = titleMatch ? titleMatch[1].trim() : "Unknown";
415
+ const description = descMatch ? descMatch[1].trim() : "No description";
416
+ articles.push(
417
+ ...rawArticles.map((content) => ({ url: pageUrl, content, title, description }))
418
+ );
419
+ } catch (error) {
420
+ logger.error(`Error fetching ${pageUrl}: ${error}`);
421
+ continue;
422
+ }
423
+ }
424
+ return articles;
425
+ }
426
+ /**
427
+ * Fetches articles from the sitemap
428
+ * @param {string} resource Optional resource path to filter URLs
429
+ * @param {string} locale Locale for the content
430
+ * @returns {Promise<StripeDocsArticle[]>} Array of article objects
431
+ */
432
+ async fetchArticlesFromSitemap(resource, locale) {
433
+ const documentUrls = await this.fetchURLsFromSitemap(resource);
434
+ return this.fetchArticlesFromURLs(documentUrls, locale);
435
+ }
436
+ /**
437
+ * @deprecated Use `this.load()` and `splitter.splitDocuments()` individually.
438
+ * Loads the documents and splits them using the given document transformer.
439
+ * Kept for compatibility with LangChain's `index()` API, which only treats a
440
+ * source as a document loader when it has both `load()` and `loadAndSplit()`.
441
+ * `@langchain/core` 1.x no longer provides this method on BaseDocumentLoader.
442
+ * @param splitter The document transformer (e.g. a text splitter) to apply
443
+ * @returns {Promise<Document[]>} The loaded and split documents
444
+ */
445
+ async loadAndSplit(splitter) {
446
+ if (splitter === void 0) {
447
+ throw new Error("You must pass a text splitter to use this method.");
448
+ }
449
+ const docs = await this.load();
450
+ return splitter.invoke(docs);
451
+ }
452
+ /**
453
+ * Loads documents from Stripe.com
454
+ * @param {Object} options Loading options
455
+ * @param {string} options.resource Optional resource path to filter URLs
456
+ * @param {string} options.locale Optional locale for the content (defaults to 'en-US')
457
+ * @param {string[]} options.urls Optional list of specific URLs to load
458
+ * @returns {Promise<Document[]>} Array of LangChain documents
459
+ */
460
+ async load(options) {
461
+ const { resource, urls } = options ?? {};
462
+ const locale = options?.locale ?? "en-US";
463
+ const articles = urls ? await this.fetchArticlesFromURLs(urls, locale) : await this.fetchArticlesFromSitemap(resource, locale);
464
+ const nhm = new import_node_html_markdown2.NodeHtmlMarkdown();
465
+ return articles.map(
466
+ (article) => new import_documents2.Document({
467
+ pageContent: nhm.translate(article.content),
468
+ metadata: {
469
+ source: article.url,
470
+ title: article.title,
471
+ description: article.description
472
+ }
473
+ })
474
+ );
475
+ }
476
+ };
477
+ // Annotate the CommonJS export names for ESM import in node:
478
+ 0 && (module.exports = {
479
+ StripeComDocumentLoader,
480
+ StripeDocsDocumentLoader
481
+ });
482
+ //# sourceMappingURL=index.cjs.map