scrapex 0.5.3 → 1.0.0-beta.1

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.
Files changed (47) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +551 -145
  3. package/dist/enhancer-ByjRD-t5.mjs +769 -0
  4. package/dist/enhancer-ByjRD-t5.mjs.map +1 -0
  5. package/dist/enhancer-j0xqKDJm.cjs +847 -0
  6. package/dist/enhancer-j0xqKDJm.cjs.map +1 -0
  7. package/dist/index-CDgcRnig.d.cts +268 -0
  8. package/dist/index-CDgcRnig.d.cts.map +1 -0
  9. package/dist/index-piS5wtki.d.mts +268 -0
  10. package/dist/index-piS5wtki.d.mts.map +1 -0
  11. package/dist/index.cjs +2007 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +580 -0
  14. package/dist/index.d.cts.map +1 -0
  15. package/dist/index.d.mts +580 -0
  16. package/dist/index.d.mts.map +1 -0
  17. package/dist/index.mjs +1956 -0
  18. package/dist/index.mjs.map +1 -0
  19. package/dist/llm/index.cjs +334 -0
  20. package/dist/llm/index.cjs.map +1 -0
  21. package/dist/llm/index.d.cts +258 -0
  22. package/dist/llm/index.d.cts.map +1 -0
  23. package/dist/llm/index.d.mts +258 -0
  24. package/dist/llm/index.d.mts.map +1 -0
  25. package/dist/llm/index.mjs +317 -0
  26. package/dist/llm/index.mjs.map +1 -0
  27. package/dist/parsers/index.cjs +11 -0
  28. package/dist/parsers/index.d.cts +2 -0
  29. package/dist/parsers/index.d.mts +2 -0
  30. package/dist/parsers/index.mjs +3 -0
  31. package/dist/parsers-Bneuws8x.cjs +569 -0
  32. package/dist/parsers-Bneuws8x.cjs.map +1 -0
  33. package/dist/parsers-CwkYnyWY.mjs +482 -0
  34. package/dist/parsers-CwkYnyWY.mjs.map +1 -0
  35. package/dist/types-CadAXrme.d.mts +674 -0
  36. package/dist/types-CadAXrme.d.mts.map +1 -0
  37. package/dist/types-DPEtPihB.d.cts +674 -0
  38. package/dist/types-DPEtPihB.d.cts.map +1 -0
  39. package/package.json +79 -100
  40. package/dist/index.d.ts +0 -45
  41. package/dist/index.js +0 -8
  42. package/dist/scrapex.cjs.development.js +0 -1130
  43. package/dist/scrapex.cjs.development.js.map +0 -1
  44. package/dist/scrapex.cjs.production.min.js +0 -2
  45. package/dist/scrapex.cjs.production.min.js.map +0 -1
  46. package/dist/scrapex.esm.js +0 -1122
  47. package/dist/scrapex.esm.js.map +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,1956 @@
1
+ import { c as BaseHttpProvider, d as Semaphore, f as withResilience, l as CircuitBreaker, n as enhance, p as ScrapeError, r as extract, u as RateLimiter } from "./enhancer-ByjRD-t5.mjs";
2
+ import { t as RSSParser } from "./parsers-CwkYnyWY.mjs";
3
+ import * as cheerio from "cheerio";
4
+ import { createHash } from "node:crypto";
5
+ import { Readability } from "@mozilla/readability";
6
+ import TurndownService from "turndown";
7
+
8
+ //#region src/core/context.ts
9
+ let jsdomModule = null;
10
+ /**
11
+ * Preload JSDOM module (called once during scrape initialization)
12
+ */
13
+ async function preloadJsdom() {
14
+ if (!jsdomModule) jsdomModule = await import("jsdom");
15
+ }
16
+ /**
17
+ * Create an extraction context with lazy JSDOM loading.
18
+ *
19
+ * Cheerio is always available for fast DOM queries.
20
+ * JSDOM is only loaded when getDocument() is called (for Readability).
21
+ */
22
+ function createExtractionContext(url, finalUrl, html, options) {
23
+ let document = null;
24
+ return {
25
+ url,
26
+ finalUrl,
27
+ html,
28
+ $: cheerio.load(html),
29
+ options,
30
+ results: {},
31
+ getDocument() {
32
+ if (!document) {
33
+ if (!jsdomModule) throw new Error("JSDOM not preloaded. Call preloadJsdom() before using getDocument().");
34
+ document = new jsdomModule.JSDOM(html, { url: finalUrl }).window.document;
35
+ }
36
+ return document;
37
+ }
38
+ };
39
+ }
40
+ /**
41
+ * Merge partial results into the context
42
+ */
43
+ function mergeResults(context, extracted) {
44
+ return {
45
+ ...context,
46
+ results: {
47
+ ...context.results,
48
+ ...extracted,
49
+ custom: extracted.custom || context.results.custom ? {
50
+ ...context.results.custom,
51
+ ...extracted.custom
52
+ } : void 0
53
+ }
54
+ };
55
+ }
56
+
57
+ //#endregion
58
+ //#region src/embeddings/aggregation.ts
59
+ /**
60
+ * Aggregate multiple embedding vectors into a single vector or return all.
61
+ *
62
+ * @param vectors - Array of embedding vectors (must all have same dimensions)
63
+ * @param strategy - Aggregation strategy
64
+ * @returns Aggregated result based on strategy
65
+ */
66
+ function aggregateVectors(vectors, strategy = "average") {
67
+ if (vectors.length === 0) throw new Error("Cannot aggregate empty vector array");
68
+ const firstVector = vectors[0];
69
+ if (!firstVector) throw new Error("Cannot aggregate empty vector array");
70
+ const dimensions = firstVector.length;
71
+ for (let i = 1; i < vectors.length; i++) {
72
+ const vec = vectors[i];
73
+ if (!vec || vec.length !== dimensions) throw new Error(`Vector dimension mismatch: expected ${dimensions}, got ${vec?.length ?? 0} at index ${i}`);
74
+ }
75
+ switch (strategy) {
76
+ case "average": return {
77
+ type: "single",
78
+ vector: averageVectors(vectors),
79
+ dimensions
80
+ };
81
+ case "max": return {
82
+ type: "single",
83
+ vector: maxPoolVectors(vectors),
84
+ dimensions
85
+ };
86
+ case "first": return {
87
+ type: "single",
88
+ vector: firstVector,
89
+ dimensions
90
+ };
91
+ case "all": return {
92
+ type: "multiple",
93
+ vectors,
94
+ dimensions
95
+ };
96
+ default: {
97
+ const _exhaustive = strategy;
98
+ throw new Error(`Unknown aggregation strategy: ${_exhaustive}`);
99
+ }
100
+ }
101
+ }
102
+ /**
103
+ * Compute element-wise average of vectors.
104
+ */
105
+ function averageVectors(vectors) {
106
+ const first = vectors[0];
107
+ if (!first || vectors.length === 1) return first ?? [];
108
+ const dimensions = first.length;
109
+ const count = vectors.length;
110
+ const result = new Array(dimensions).fill(0);
111
+ for (const vector of vectors) for (let i = 0; i < dimensions; i++) {
112
+ const val = result[i];
113
+ if (val !== void 0) result[i] = val + (vector[i] ?? 0);
114
+ }
115
+ for (let i = 0; i < dimensions; i++) {
116
+ const val = result[i];
117
+ if (val !== void 0) result[i] = val / count;
118
+ }
119
+ return result;
120
+ }
121
+ /**
122
+ * Compute element-wise maximum of vectors (max pooling).
123
+ */
124
+ function maxPoolVectors(vectors) {
125
+ const first = vectors[0];
126
+ if (!first || vectors.length === 1) return first ?? [];
127
+ const dimensions = first.length;
128
+ const result = [...first];
129
+ for (let v = 1; v < vectors.length; v++) {
130
+ const vec = vectors[v];
131
+ if (!vec) continue;
132
+ for (let i = 0; i < dimensions; i++) {
133
+ const val = vec[i] ?? 0;
134
+ if (val > (result[i] ?? 0)) result[i] = val;
135
+ }
136
+ }
137
+ return result;
138
+ }
139
+ /**
140
+ * Compute cosine similarity between two vectors.
141
+ * Both vectors should be normalized for accurate results.
142
+ */
143
+ function cosineSimilarity(a, b) {
144
+ if (a.length !== b.length) throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
145
+ let dot = 0;
146
+ let magnitudeA = 0;
147
+ let magnitudeB = 0;
148
+ for (let i = 0; i < a.length; i++) {
149
+ const aVal = a[i] ?? 0;
150
+ const bVal = b[i] ?? 0;
151
+ dot += aVal * bVal;
152
+ magnitudeA += aVal * aVal;
153
+ magnitudeB += bVal * bVal;
154
+ }
155
+ const magnitude = Math.sqrt(magnitudeA) * Math.sqrt(magnitudeB);
156
+ if (magnitude === 0) return 0;
157
+ return dot / magnitude;
158
+ }
159
+ /**
160
+ * Get the dimensions of a vector or set of vectors.
161
+ */
162
+ function getDimensions(vectors) {
163
+ if (vectors.length === 0) return 0;
164
+ const first = vectors[0];
165
+ if (typeof first === "number") return vectors.length;
166
+ return first?.length ?? 0;
167
+ }
168
+
169
+ //#endregion
170
+ //#region src/embeddings/cache.ts
171
+ /**
172
+ * Default maximum cache entries.
173
+ */
174
+ const DEFAULT_MAX_ENTRIES = 1e3;
175
+ /**
176
+ * Default TTL in milliseconds (1 hour).
177
+ */
178
+ const DEFAULT_TTL_MS = 3600 * 1e3;
179
+ /**
180
+ * Generate a content-addressable cache key.
181
+ * Key is based on content hash and embedding configuration.
182
+ * Note: custom RegExp patterns are serialized by source+flags; different
183
+ * constructions can yield different cache keys even if equivalent.
184
+ */
185
+ function generateCacheKey(params) {
186
+ const hash = createHash("sha256");
187
+ const fingerprint = stableStringify({
188
+ providerKey: params.providerKey,
189
+ model: params.model ?? "provider-default",
190
+ dimensions: params.dimensions ?? "default",
191
+ aggregation: params.aggregation ?? "average",
192
+ input: serializeInputConfig(params.input),
193
+ chunking: serializeChunkingConfig(params.chunking),
194
+ safety: serializeSafetyConfig(params.safety),
195
+ cacheKeySalt: params.cacheKeySalt
196
+ });
197
+ hash.update(fingerprint);
198
+ hash.update("\0");
199
+ hash.update(params.content);
200
+ return hash.digest("hex");
201
+ }
202
+ /**
203
+ * Generate a checksum for content verification.
204
+ */
205
+ function generateChecksum(content) {
206
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
207
+ }
208
+ function serializeInputConfig(config) {
209
+ if (!config) return void 0;
210
+ return normalizeObject({
211
+ type: config.type ?? "textContent",
212
+ hasTransform: Boolean(config.transform),
213
+ hasCustomText: Boolean(config.customText)
214
+ });
215
+ }
216
+ function serializeChunkingConfig(config) {
217
+ if (!config) return void 0;
218
+ return normalizeObject({
219
+ size: config.size,
220
+ overlap: config.overlap,
221
+ tokenizer: getTokenizerId(config.tokenizer),
222
+ maxInputLength: config.maxInputLength
223
+ });
224
+ }
225
+ function serializeSafetyConfig(config) {
226
+ if (!config) return void 0;
227
+ return normalizeObject({
228
+ piiRedaction: serializePiiConfig(config.piiRedaction),
229
+ minTextLength: config.minTextLength,
230
+ maxTokens: config.maxTokens
231
+ });
232
+ }
233
+ function serializePiiConfig(config) {
234
+ if (!config) return void 0;
235
+ return normalizeObject({
236
+ email: config.email ?? false,
237
+ phone: config.phone ?? false,
238
+ creditCard: config.creditCard ?? false,
239
+ ssn: config.ssn ?? false,
240
+ ipAddress: config.ipAddress ?? false,
241
+ customPatterns: config.customPatterns?.map((pattern) => `${pattern.source}/${pattern.flags}`)
242
+ });
243
+ }
244
+ function getTokenizerId(tokenizer) {
245
+ if (!tokenizer || tokenizer === "heuristic") return "heuristic";
246
+ if (tokenizer === "tiktoken") return "tiktoken";
247
+ return "custom";
248
+ }
249
+ function stableStringify(value) {
250
+ return stringifyNormalized(normalizeValue(value));
251
+ }
252
+ function normalizeValue(value) {
253
+ if (value === void 0) return void 0;
254
+ if (value === null) return null;
255
+ if (Array.isArray(value)) return value.map((entry) => normalizeValue(entry)).filter((entry) => entry !== void 0);
256
+ if (typeof value === "object") return normalizeObject(value);
257
+ return value;
258
+ }
259
+ function normalizeObject(value) {
260
+ const normalized = {};
261
+ for (const key of Object.keys(value).sort()) {
262
+ const entry = normalizeValue(value[key]);
263
+ if (entry !== void 0) normalized[key] = entry;
264
+ }
265
+ return normalized;
266
+ }
267
+ function stringifyNormalized(value) {
268
+ if (value === void 0) return "undefined";
269
+ if (value === null) return "null";
270
+ if (typeof value === "string") return JSON.stringify(value);
271
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
272
+ if (Array.isArray(value)) return `[${value.map((entry) => stringifyNormalized(entry)).join(",")}]`;
273
+ if (typeof value === "object") {
274
+ const obj = value;
275
+ return `{${Object.keys(obj).sort().map((key) => `${JSON.stringify(key)}:${stringifyNormalized(obj[key])}`).join(",")}}`;
276
+ }
277
+ return JSON.stringify(value);
278
+ }
279
+ /**
280
+ * In-memory LRU cache with TTL support.
281
+ * Content-addressable: uses content hash as key, not URL.
282
+ */
283
+ var InMemoryEmbeddingCache = class {
284
+ cache;
285
+ maxEntries;
286
+ defaultTtlMs;
287
+ constructor(options) {
288
+ this.cache = /* @__PURE__ */ new Map();
289
+ this.maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
290
+ this.defaultTtlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
291
+ }
292
+ async get(key) {
293
+ const entry = this.cache.get(key);
294
+ if (!entry) return;
295
+ const now = Date.now();
296
+ if (now > entry.expiresAt) {
297
+ this.cache.delete(key);
298
+ return;
299
+ }
300
+ entry.accessedAt = now;
301
+ return entry.value;
302
+ }
303
+ async set(key, value, options) {
304
+ const now = Date.now();
305
+ const ttl = options?.ttlMs ?? this.defaultTtlMs;
306
+ if (this.cache.size >= this.maxEntries && !this.cache.has(key)) this.evictLRU();
307
+ this.cache.set(key, {
308
+ value,
309
+ createdAt: now,
310
+ expiresAt: now + ttl,
311
+ accessedAt: now
312
+ });
313
+ }
314
+ async delete(key) {
315
+ return this.cache.delete(key);
316
+ }
317
+ async clear() {
318
+ this.cache.clear();
319
+ }
320
+ /**
321
+ * Get cache statistics.
322
+ */
323
+ getStats() {
324
+ const now = Date.now();
325
+ let expired = 0;
326
+ for (const entry of this.cache.values()) if (now > entry.expiresAt) expired++;
327
+ return {
328
+ size: this.cache.size,
329
+ maxEntries: this.maxEntries,
330
+ expired,
331
+ utilization: this.cache.size / this.maxEntries
332
+ };
333
+ }
334
+ /**
335
+ * Evict expired entries.
336
+ */
337
+ cleanup() {
338
+ const now = Date.now();
339
+ let evicted = 0;
340
+ for (const [key, entry] of this.cache.entries()) if (now > entry.expiresAt) {
341
+ this.cache.delete(key);
342
+ evicted++;
343
+ }
344
+ return evicted;
345
+ }
346
+ /**
347
+ * Evict least recently used entry.
348
+ */
349
+ evictLRU() {
350
+ let oldestKey = null;
351
+ let oldestAccess = Number.POSITIVE_INFINITY;
352
+ for (const [key, entry] of this.cache.entries()) if (entry.accessedAt < oldestAccess) {
353
+ oldestAccess = entry.accessedAt;
354
+ oldestKey = key;
355
+ }
356
+ if (oldestKey) this.cache.delete(oldestKey);
357
+ }
358
+ };
359
+ /**
360
+ * Default in-memory cache instance.
361
+ * Optimized for moderate cache sizes (default 1000 entries).
362
+ */
363
+ let defaultCache = null;
364
+ /**
365
+ * Get or create the default cache instance.
366
+ */
367
+ function getDefaultCache() {
368
+ if (!defaultCache) defaultCache = new InMemoryEmbeddingCache();
369
+ return defaultCache;
370
+ }
371
+
372
+ //#endregion
373
+ //#region src/embeddings/chunking.ts
374
+ /**
375
+ * Default chunk size in tokens.
376
+ */
377
+ const DEFAULT_CHUNK_SIZE$1 = 500;
378
+ /**
379
+ * Default overlap in tokens.
380
+ */
381
+ const DEFAULT_OVERLAP = 50;
382
+ /**
383
+ * Default maximum input length in characters.
384
+ */
385
+ const DEFAULT_MAX_INPUT_LENGTH = 1e5;
386
+ /**
387
+ * Heuristic token counting: approximately 4 characters per token.
388
+ * This is a reasonable approximation for English text.
389
+ */
390
+ function heuristicTokenCount(text) {
391
+ return Math.ceil(text.length / 4);
392
+ }
393
+ /**
394
+ * Convert token count to approximate character count.
395
+ */
396
+ function tokensToChars(tokens) {
397
+ return tokens * 4;
398
+ }
399
+ /**
400
+ * Create a tokenizer function based on configuration.
401
+ */
402
+ function createTokenizer(config) {
403
+ if (!config || config === "heuristic") return heuristicTokenCount;
404
+ if (config === "tiktoken") return heuristicTokenCount;
405
+ return config;
406
+ }
407
+ /**
408
+ * Find a natural break point in text (sentence or word boundary).
409
+ * Prefers common sentence boundaries (Latin + CJK), falls back to word boundaries.
410
+ */
411
+ function findBreakPoint(text, targetIndex) {
412
+ const searchStart = Math.max(0, targetIndex - Math.floor(targetIndex * .2));
413
+ const searchEnd = Math.min(text.length, targetIndex + Math.floor(targetIndex * .2));
414
+ const searchText = text.slice(searchStart, searchEnd);
415
+ const sentenceMatch = /[.!?。!?]\s*/g;
416
+ let lastSentenceEnd = -1;
417
+ for (const match of searchText.matchAll(sentenceMatch)) {
418
+ const absolutePos = searchStart + match.index + match[0].length;
419
+ if (absolutePos <= targetIndex) lastSentenceEnd = absolutePos;
420
+ }
421
+ if (lastSentenceEnd !== -1) return lastSentenceEnd;
422
+ const wordBoundary = text.lastIndexOf(" ", targetIndex);
423
+ if (wordBoundary > searchStart) return wordBoundary + 1;
424
+ return targetIndex;
425
+ }
426
+ /**
427
+ * Split text into overlapping chunks optimized for embedding.
428
+ * Respects sentence boundaries when possible.
429
+ */
430
+ function chunkText(text, config) {
431
+ const chunkSize = config?.size ?? DEFAULT_CHUNK_SIZE$1;
432
+ const rawOverlap = config?.overlap ?? DEFAULT_OVERLAP;
433
+ const safeOverlap = Math.max(0, rawOverlap);
434
+ const overlap = Math.min(safeOverlap, Math.max(0, chunkSize - 1));
435
+ const maxInputLength = config?.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH;
436
+ const tokenizer = createTokenizer(config?.tokenizer);
437
+ const normalizedText = (text.length > maxInputLength ? text.slice(0, maxInputLength) : text).replace(/\s+/g, " ").trim();
438
+ if (!normalizedText) return [];
439
+ const totalTokens = tokenizer(normalizedText);
440
+ if (totalTokens <= chunkSize) return [{
441
+ text: normalizedText,
442
+ startIndex: 0,
443
+ endIndex: normalizedText.length,
444
+ tokens: totalTokens
445
+ }];
446
+ const chunks = [];
447
+ const chunkSizeChars = tokensToChars(chunkSize);
448
+ const overlapChars = tokensToChars(overlap);
449
+ let startIndex = 0;
450
+ while (startIndex < normalizedText.length) {
451
+ const targetEnd = Math.min(startIndex + chunkSizeChars, normalizedText.length);
452
+ const endIndex = targetEnd < normalizedText.length ? findBreakPoint(normalizedText, targetEnd) : targetEnd;
453
+ const chunkText$1 = normalizedText.slice(startIndex, endIndex).trim();
454
+ if (chunkText$1) chunks.push({
455
+ text: chunkText$1,
456
+ startIndex,
457
+ endIndex,
458
+ tokens: tokenizer(chunkText$1)
459
+ });
460
+ if (endIndex >= normalizedText.length) break;
461
+ const nextStart = endIndex - overlapChars;
462
+ startIndex = Math.max(nextStart, startIndex + 1);
463
+ if (startIndex < normalizedText.length) {
464
+ const spaceIndex = normalizedText.indexOf(" ", startIndex);
465
+ if (spaceIndex !== -1 && spaceIndex < startIndex + overlapChars) startIndex = spaceIndex + 1;
466
+ }
467
+ }
468
+ return chunks;
469
+ }
470
+ /**
471
+ * Estimate total tokens for a text without chunking.
472
+ */
473
+ function estimateTokens(text, tokenizer) {
474
+ return createTokenizer(tokenizer)(text);
475
+ }
476
+
477
+ //#endregion
478
+ //#region src/embeddings/input.ts
479
+ /**
480
+ * Select and prepare input text for embedding based on configuration.
481
+ *
482
+ * @param data - Scraped data to extract input from
483
+ * @param config - Input configuration
484
+ * @returns Selected and prepared text, or undefined if no valid input
485
+ */
486
+ function selectInput(data, config) {
487
+ if (config?.transform) return normalizeText(config.transform(data));
488
+ if (config?.type === "custom" && config.customText) return normalizeText(config.customText);
489
+ const type = config?.type ?? "textContent";
490
+ switch (type) {
491
+ case "textContent": return selectTextContent(data);
492
+ case "title+summary": return selectTitleSummary(data);
493
+ case "custom": return selectTextContent(data);
494
+ default: {
495
+ const _exhaustive = type;
496
+ throw new Error(`Unknown input type: ${_exhaustive}`);
497
+ }
498
+ }
499
+ }
500
+ /**
501
+ * Select textContent as input.
502
+ */
503
+ function selectTextContent(data) {
504
+ if (data.textContent) return normalizeText(data.textContent);
505
+ if (data.content) return normalizeText(stripMarkdown(data.content));
506
+ if (data.excerpt) return normalizeText(data.excerpt);
507
+ if (data.description) return normalizeText(data.description);
508
+ }
509
+ /**
510
+ * Select title + summary (or fallbacks) as input.
511
+ * Optimized for semantic search and classification.
512
+ */
513
+ function selectTitleSummary(data) {
514
+ const parts = [];
515
+ if (data.title) parts.push(data.title);
516
+ if (data.summary) parts.push(data.summary);
517
+ else if (data.excerpt) parts.push(data.excerpt);
518
+ else if (data.description) parts.push(data.description);
519
+ if (parts.length === 0) return;
520
+ return normalizeText(parts.join("\n\n"));
521
+ }
522
+ /**
523
+ * Normalize text for embedding:
524
+ * - Collapse whitespace
525
+ * - Trim leading/trailing whitespace
526
+ * - Remove control characters
527
+ */
528
+ function normalizeText(text) {
529
+ if (!text) return "";
530
+ return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").split("\n").map((line) => line.trim()).join("\n").trim();
531
+ }
532
+ /**
533
+ * Basic markdown stripping for when we need plain text from content.
534
+ * Not comprehensive, but handles common cases.
535
+ */
536
+ function stripMarkdown(markdown) {
537
+ return markdown.replace(/```[\s\S]*?```/g, "").replace(/`[^`]+`/g, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1").replace(/^#{1,6}\s+/gm, "").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\*([^*]+)\*/g, "$1").replace(/__([^_]+)__/g, "$1").replace(/_([^_]+)_/g, "$1").replace(/^>\s+/gm, "").replace(/^[-*_]{3,}$/gm, "").replace(/^[\s]*[-*+]\s+/gm, "").replace(/^[\s]*\d+\.\s+/gm, "");
538
+ }
539
+ /**
540
+ * Check if the selected input meets minimum requirements.
541
+ */
542
+ function validateInput(text, minLength = 10) {
543
+ if (!text) return {
544
+ valid: false,
545
+ reason: "No input text available"
546
+ };
547
+ if (text.length < minLength) return {
548
+ valid: false,
549
+ reason: `Input too short (${text.length} < ${minLength} characters)`
550
+ };
551
+ const wordCount = text.split(/\s+/).filter((w) => w.length > 1).length;
552
+ if (wordCount < 3) return {
553
+ valid: false,
554
+ reason: `Input has too few words (${wordCount} < 3)`
555
+ };
556
+ return {
557
+ valid: true,
558
+ text,
559
+ wordCount,
560
+ charCount: text.length
561
+ };
562
+ }
563
+
564
+ //#endregion
565
+ //#region src/embeddings/providers/base.ts
566
+ /**
567
+ * Generate a stable cache key identifier for provider configuration.
568
+ */
569
+ function getProviderCacheKey(config) {
570
+ switch (config.type) {
571
+ case "http": return `http:${config.config.baseUrl.replace(/\/$/, "")}:${config.config.model}`;
572
+ case "custom": return `custom:${config.provider.name}`;
573
+ default: {
574
+ const _exhaustive = config;
575
+ return String(_exhaustive);
576
+ }
577
+ }
578
+ }
579
+
580
+ //#endregion
581
+ //#region src/embeddings/providers/http.ts
582
+ /**
583
+ * HTTP-based Embedding Provider using native fetch.
584
+ * Provides a unified interface for any REST-based embedding API.
585
+ */
586
+ /**
587
+ * HTTP-based embedding provider.
588
+ * Works with any REST API using native fetch.
589
+ */
590
+ var HttpEmbeddingProvider = class extends BaseHttpProvider {
591
+ name = "http-embedding";
592
+ requestBuilder;
593
+ responseMapper;
594
+ constructor(config) {
595
+ super(config);
596
+ this.requestBuilder = config.requestBuilder ?? ((texts, model) => ({
597
+ input: texts,
598
+ model
599
+ }));
600
+ this.responseMapper = config.responseMapper ?? ((response) => {
601
+ const resp = response;
602
+ if (Array.isArray(resp.data)) return resp.data.map((item) => item.embedding);
603
+ if (Array.isArray(resp.embeddings)) return resp.embeddings;
604
+ if (Array.isArray(resp.embedding)) return [resp.embedding];
605
+ if (Array.isArray(response)) return response;
606
+ throw new ScrapeError("Unable to parse embedding response. Provide a custom responseMapper.", "VALIDATION_ERROR");
607
+ });
608
+ }
609
+ /**
610
+ * Generate embeddings for one or more texts.
611
+ */
612
+ async embed(texts, options) {
613
+ const model = options.model || this.model;
614
+ const body = this.requestBuilder(texts, model);
615
+ const { data } = await this.fetch(this.baseUrl, {
616
+ body,
617
+ signal: options.signal
618
+ });
619
+ const embeddings = this.responseMapper(data);
620
+ if (embeddings.length !== texts.length) throw new ScrapeError(`Embedding count mismatch: expected ${texts.length}, got ${embeddings.length}`, "VALIDATION_ERROR");
621
+ return { embeddings };
622
+ }
623
+ };
624
+ /**
625
+ * Create a generic HTTP embedding provider.
626
+ */
627
+ function createHttpEmbedding(config) {
628
+ return new HttpEmbeddingProvider(config);
629
+ }
630
+
631
+ //#endregion
632
+ //#region src/embeddings/providers/presets.ts
633
+ /**
634
+ * Create an OpenAI embedding provider.
635
+ *
636
+ * @example
637
+ * ```ts
638
+ * const provider = createOpenAIEmbedding({ apiKey: 'sk-...' });
639
+ * const { embeddings } = await provider.embed(['Hello'], { model: 'text-embedding-3-small' });
640
+ * ```
641
+ */
642
+ function createOpenAIEmbedding(options) {
643
+ const apiKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
644
+ if (!apiKey) throw new Error("OpenAI API key required. Set OPENAI_API_KEY env var or pass apiKey option.");
645
+ const headers = { Authorization: `Bearer ${apiKey}` };
646
+ if (options?.organization) headers["OpenAI-Organization"] = options.organization;
647
+ return new HttpEmbeddingProvider({
648
+ baseUrl: options?.baseUrl ?? "https://api.openai.com/v1/embeddings",
649
+ model: options?.model ?? "text-embedding-3-small",
650
+ headers,
651
+ requestBuilder: (texts, model) => ({
652
+ input: texts,
653
+ model
654
+ }),
655
+ responseMapper: (res) => res.data.map((item) => item.embedding)
656
+ });
657
+ }
658
+ /**
659
+ * Create an Azure OpenAI embedding provider.
660
+ *
661
+ * @example
662
+ * ```ts
663
+ * const provider = createAzureEmbedding({
664
+ * endpoint: 'https://my-resource.openai.azure.com',
665
+ * deploymentName: 'text-embedding-ada-002',
666
+ * apiVersion: '2023-05-15',
667
+ * });
668
+ * ```
669
+ */
670
+ function createAzureEmbedding(options) {
671
+ const apiKey = options.apiKey ?? process.env.AZURE_OPENAI_API_KEY;
672
+ if (!apiKey) throw new Error("Azure OpenAI API key required. Set AZURE_OPENAI_API_KEY env var or pass apiKey option.");
673
+ return new HttpEmbeddingProvider({
674
+ baseUrl: `${options.endpoint.replace(/\/$/, "")}/openai/deployments/${options.deploymentName}/embeddings?api-version=${options.apiVersion}`,
675
+ model: options.deploymentName,
676
+ headers: { "api-key": apiKey },
677
+ requestBuilder: (texts) => ({ input: texts }),
678
+ responseMapper: (res) => res.data.map((item) => item.embedding)
679
+ });
680
+ }
681
+ /**
682
+ * Create an Ollama embedding provider for local models.
683
+ *
684
+ * LIMITATION: Ollama's /api/embeddings endpoint processes one text at a time,
685
+ * not batches. When multiple chunks are embedded, each chunk triggers a
686
+ * separate HTTP request. This is handled transparently by the pipeline's
687
+ * sequential chunk processing, but may be slower than batch-capable providers.
688
+ * For high-throughput scenarios, consider using OpenAI, Cohere, or HuggingFace
689
+ * which support batch embedding in a single request.
690
+ *
691
+ * @example
692
+ * ```ts
693
+ * const provider = createOllamaEmbedding({ model: 'nomic-embed-text' });
694
+ * ```
695
+ */
696
+ function createOllamaEmbedding(options) {
697
+ return new HttpEmbeddingProvider({
698
+ baseUrl: options?.baseUrl ?? "http://localhost:11434/api/embeddings",
699
+ model: options?.model ?? "nomic-embed-text",
700
+ requireHttps: false,
701
+ allowPrivate: true,
702
+ requestBuilder: (texts, model) => ({
703
+ model,
704
+ prompt: texts[0]
705
+ }),
706
+ responseMapper: (res) => [res.embedding]
707
+ });
708
+ }
709
+ /**
710
+ * Create a HuggingFace Inference API embedding provider.
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * const provider = createHuggingFaceEmbedding({
715
+ * model: 'sentence-transformers/all-MiniLM-L6-v2',
716
+ * });
717
+ * ```
718
+ */
719
+ function createHuggingFaceEmbedding(options) {
720
+ const apiKey = options.apiKey ?? process.env.HF_TOKEN ?? process.env.HUGGINGFACE_API_KEY;
721
+ const headers = {};
722
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
723
+ return new HttpEmbeddingProvider({
724
+ baseUrl: `https://api-inference.huggingface.co/models/${options.model}`,
725
+ model: options.model,
726
+ headers,
727
+ requestBuilder: (texts) => ({ inputs: texts }),
728
+ responseMapper: (response) => {
729
+ if (Array.isArray(response)) {
730
+ if (Array.isArray(response[0]) && typeof response[0][0] === "number") return response;
731
+ return [response];
732
+ }
733
+ throw new Error("Unexpected HuggingFace response format");
734
+ }
735
+ });
736
+ }
737
+ /**
738
+ * Create a local Transformers.js embedding provider.
739
+ * Uses dependency injection - user provides the imported transformers module.
740
+ *
741
+ * @example
742
+ * ```typescript
743
+ * import * as transformers from '@huggingface/transformers';
744
+ * import { createTransformersEmbedding } from 'scrapex/embeddings';
745
+ *
746
+ * const provider = createTransformersEmbedding(transformers, {
747
+ * model: 'Xenova/all-MiniLM-L6-v2',
748
+ * });
749
+ * ```
750
+ *
751
+ * Required Node.js dependencies:
752
+ * ```
753
+ * npm install @huggingface/transformers onnxruntime-node
754
+ * ```
755
+ */
756
+ function createTransformersEmbedding(transformers, options) {
757
+ let pipeline = null;
758
+ let currentModel = null;
759
+ const config = {
760
+ model: options?.model ?? "Xenova/all-MiniLM-L6-v2",
761
+ quantized: options?.quantized ?? true,
762
+ pooling: options?.pooling ?? "mean",
763
+ normalize: options?.normalize ?? true
764
+ };
765
+ return {
766
+ name: "transformers",
767
+ async embed(texts, request) {
768
+ const model = request.model || config.model;
769
+ if (!pipeline || currentModel !== model) {
770
+ const cacheDir = options?.cacheDir;
771
+ const env = transformers.env;
772
+ const priorCacheDir = env?.cacheDir;
773
+ if (cacheDir && env) env.cacheDir = cacheDir;
774
+ try {
775
+ pipeline = await transformers.pipeline("feature-extraction", model, { quantized: config.quantized });
776
+ } finally {
777
+ if (cacheDir && env) if (priorCacheDir === void 0) delete env.cacheDir;
778
+ else env.cacheDir = priorCacheDir;
779
+ }
780
+ currentModel = model;
781
+ }
782
+ const embeddings = [];
783
+ for (const text of texts) {
784
+ const output = await pipeline(text, {
785
+ pooling: config.pooling,
786
+ normalize: config.normalize
787
+ });
788
+ embeddings.push(Array.from(output.data));
789
+ }
790
+ return { embeddings };
791
+ }
792
+ };
793
+ }
794
+ /** Recommended models for Transformers.js */
795
+ const TRANSFORMERS_MODELS = {
796
+ DEFAULT: "Xenova/all-MiniLM-L6-v2",
797
+ QUALITY: "Xenova/all-mpnet-base-v2",
798
+ RETRIEVAL: "Xenova/bge-small-en-v1.5",
799
+ MULTILINGUAL: "Xenova/multilingual-e5-small"
800
+ };
801
+
802
+ //#endregion
803
+ //#region src/embeddings/providers/index.ts
804
+ /**
805
+ * Create an embedding provider from configuration.
806
+ * This is the main factory function for creating providers.
807
+ */
808
+ function createEmbeddingProvider(config) {
809
+ switch (config.type) {
810
+ case "http": return createHttpEmbedding(config.config);
811
+ case "custom": return config.provider;
812
+ default: throw new ScrapeError(`Unknown embedding provider type: ${config.type}`, "VALIDATION_ERROR");
813
+ }
814
+ }
815
+
816
+ //#endregion
817
+ //#region src/embeddings/safety.ts
818
+ /**
819
+ * PII redaction patterns with high precision to minimize false positives.
820
+ * Patterns are designed to match common formats while avoiding over-matching.
821
+ */
822
+ const EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
823
+ const PHONE_PATTERN = /(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/g;
824
+ const CREDIT_CARD_PATTERN = /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|(?:[0-9]{4}[-\s]){3}[0-9]{4}|[0-9]{13,19})\b/g;
825
+ const SSN_PATTERN = /\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b/g;
826
+ const IPV4_PATTERN = /\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g;
827
+ const REDACTED = "[REDACTED]";
828
+ /**
829
+ * Create a redaction function based on configuration.
830
+ * Returns a function that applies all configured PII patterns.
831
+ */
832
+ function createPiiRedactor(config) {
833
+ const patterns = [];
834
+ if (config.creditCard) patterns.push({
835
+ name: "creditCard",
836
+ pattern: CREDIT_CARD_PATTERN
837
+ });
838
+ if (config.email) patterns.push({
839
+ name: "email",
840
+ pattern: EMAIL_PATTERN
841
+ });
842
+ if (config.phone) patterns.push({
843
+ name: "phone",
844
+ pattern: PHONE_PATTERN
845
+ });
846
+ if (config.ssn) patterns.push({
847
+ name: "ssn",
848
+ pattern: SSN_PATTERN
849
+ });
850
+ if (config.ipAddress) patterns.push({
851
+ name: "ipAddress",
852
+ pattern: IPV4_PATTERN
853
+ });
854
+ if (config.customPatterns) for (let i = 0; i < config.customPatterns.length; i++) {
855
+ const customPattern = config.customPatterns[i];
856
+ if (customPattern) patterns.push({
857
+ name: `custom_${i}`,
858
+ pattern: customPattern
859
+ });
860
+ }
861
+ return (text) => {
862
+ let redactedText = text;
863
+ let totalRedactions = 0;
864
+ const redactionsByType = {};
865
+ for (const { name, pattern } of patterns) {
866
+ pattern.lastIndex = 0;
867
+ const matchCount = text.match(pattern)?.length ?? 0;
868
+ if (matchCount > 0) {
869
+ redactedText = redactedText.replace(pattern, REDACTED);
870
+ totalRedactions += matchCount;
871
+ redactionsByType[name] = (redactionsByType[name] ?? 0) + matchCount;
872
+ }
873
+ }
874
+ return {
875
+ text: redactedText,
876
+ redacted: totalRedactions > 0,
877
+ redactionCount: totalRedactions,
878
+ redactionsByType
879
+ };
880
+ };
881
+ }
882
+ /**
883
+ * Simple redaction that applies all default patterns.
884
+ * Use createPiiRedactor() for fine-grained control.
885
+ */
886
+ function redactPii(text) {
887
+ return createPiiRedactor({
888
+ email: true,
889
+ phone: true,
890
+ creditCard: true,
891
+ ssn: true,
892
+ ipAddress: true
893
+ })(text);
894
+ }
895
+
896
+ //#endregion
897
+ //#region src/embeddings/pipeline.ts
898
+ const DEFAULT_CHUNK_SIZE = 500;
899
+ /**
900
+ * Get the effective model for embedding.
901
+ * Prioritizes: explicit options.model > provider config model
902
+ */
903
+ function getEffectiveModel(providerConfig, explicitModel) {
904
+ if (explicitModel) return explicitModel;
905
+ if (providerConfig.type === "http") return providerConfig.config.model;
906
+ }
907
+ /**
908
+ * Generate embeddings for scraped data.
909
+ * This is the main entry point for the embedding pipeline.
910
+ */
911
+ async function generateEmbeddings(data, options) {
912
+ const startTime = Date.now();
913
+ try {
914
+ const provider = createEmbeddingProvider(options.provider);
915
+ const model = getEffectiveModel(options.provider, options.model);
916
+ const validation = validateInput(selectInput(data, options.input), options.safety?.minTextLength ?? 10);
917
+ if (!validation.valid) return createSkippedResult(validation.reason, { model });
918
+ const originalInput = validation.text;
919
+ let inputText = validation.text;
920
+ let piiRedacted = false;
921
+ if (options.safety?.piiRedaction) {
922
+ const redactionResult = createPiiRedactor(options.safety.piiRedaction)(inputText);
923
+ inputText = redactionResult.text;
924
+ piiRedacted = redactionResult.redacted;
925
+ }
926
+ const effectiveChunking = applyMaxTokensToChunking(options.chunking, options.safety?.maxTokens);
927
+ const cacheKey = generateCacheKey({
928
+ providerKey: getProviderCacheKey(options.provider),
929
+ model,
930
+ dimensions: options.output?.dimensions,
931
+ aggregation: options.output?.aggregation,
932
+ input: options.input,
933
+ chunking: effectiveChunking,
934
+ safety: options.safety,
935
+ cacheKeySalt: options.cache?.cacheKeySalt,
936
+ content: inputText
937
+ });
938
+ const cache = options.cache?.store ?? getDefaultCache();
939
+ const cachedResult = await cache.get(cacheKey);
940
+ if (cachedResult && cachedResult.status === "success") {
941
+ if (options.onMetrics) options.onMetrics({
942
+ provider: provider.name,
943
+ model,
944
+ inputTokens: estimateTokens(inputText),
945
+ outputDimensions: getDimensions(cachedResult.aggregation === "all" ? cachedResult.vectors : cachedResult.vector),
946
+ chunks: cachedResult.source.chunks,
947
+ latencyMs: Date.now() - startTime,
948
+ cached: true,
949
+ retries: 0,
950
+ piiRedacted
951
+ });
952
+ return {
953
+ ...cachedResult,
954
+ source: {
955
+ ...cachedResult.source,
956
+ cached: true
957
+ }
958
+ };
959
+ }
960
+ const chunks = chunkText(inputText, effectiveChunking);
961
+ const callbackChunks = options.onChunk && options.safety?.allowSensitiveCallbacks ? chunkText(originalInput, effectiveChunking) : null;
962
+ if (chunks.length === 0) return createSkippedResult("No content after chunking", { model });
963
+ const sharedState = options.resilience?.state;
964
+ const rateLimiter = sharedState?.rateLimiter ?? (options.resilience?.rateLimit ? new RateLimiter(options.resilience.rateLimit) : null);
965
+ const circuitBreaker = sharedState?.circuitBreaker ?? (options.resilience?.circuitBreaker ? new CircuitBreaker(options.resilience.circuitBreaker) : null);
966
+ const concurrency = options.resilience?.concurrency ?? 1;
967
+ const semaphore = sharedState?.semaphore ?? new Semaphore(concurrency);
968
+ const embeddings = [];
969
+ let totalTokens = 0;
970
+ let retryCount = 0;
971
+ for (let i = 0; i < chunks.length; i++) {
972
+ const chunk = chunks[i];
973
+ if (!chunk) continue;
974
+ if (rateLimiter) await rateLimiter.acquire();
975
+ if (circuitBreaker?.isOpen()) return createSkippedResult("Circuit breaker is open", {
976
+ model,
977
+ chunks: i
978
+ });
979
+ await semaphore.execute(async () => {
980
+ const { result: result$1 } = await withResilience(async (signal) => {
981
+ return provider.embed([chunk.text], {
982
+ model,
983
+ dimensions: options.output?.dimensions,
984
+ signal
985
+ });
986
+ }, options.resilience, {
987
+ circuitBreaker: circuitBreaker ?? void 0,
988
+ rateLimiter: void 0,
989
+ semaphore: void 0
990
+ }, { onRetry: () => {
991
+ retryCount++;
992
+ } });
993
+ if (result$1.usage) totalTokens += result$1.usage.totalTokens;
994
+ else totalTokens += chunk.tokens;
995
+ const embedding = result$1.embeddings[0];
996
+ if (embedding) {
997
+ embeddings.push(embedding);
998
+ if (options.onChunk) {
999
+ const callbackText = callbackChunks?.[i]?.text ?? chunk.text;
1000
+ options.onChunk(callbackText, embedding);
1001
+ }
1002
+ }
1003
+ });
1004
+ }
1005
+ const aggregation = options.output?.aggregation ?? "average";
1006
+ const aggregated = aggregateVectors(embeddings, aggregation);
1007
+ const source = {
1008
+ model,
1009
+ chunks: chunks.length,
1010
+ tokens: totalTokens || estimateTokens(inputText),
1011
+ checksum: generateChecksum(inputText),
1012
+ cached: false,
1013
+ latencyMs: Date.now() - startTime
1014
+ };
1015
+ let result;
1016
+ if (aggregated.type === "single") result = {
1017
+ status: "success",
1018
+ aggregation,
1019
+ vector: aggregated.vector,
1020
+ source
1021
+ };
1022
+ else result = {
1023
+ status: "success",
1024
+ aggregation: "all",
1025
+ vectors: aggregated.vectors,
1026
+ source
1027
+ };
1028
+ await cache.set(cacheKey, result, { ttlMs: options.cache?.ttlMs });
1029
+ if (options.onMetrics) {
1030
+ const metrics = {
1031
+ provider: provider.name,
1032
+ model,
1033
+ inputTokens: source.tokens,
1034
+ outputDimensions: aggregated.dimensions,
1035
+ chunks: chunks.length,
1036
+ latencyMs: source.latencyMs,
1037
+ cached: false,
1038
+ retries: retryCount,
1039
+ piiRedacted
1040
+ };
1041
+ options.onMetrics(metrics);
1042
+ }
1043
+ return result;
1044
+ } catch (error) {
1045
+ const reason = error instanceof Error ? error.message : String(error);
1046
+ if (error instanceof ScrapeError && ["INVALID_URL", "BLOCKED"].includes(error.code)) throw error;
1047
+ return createSkippedResult(reason, { latencyMs: Date.now() - startTime });
1048
+ }
1049
+ }
1050
+ function applyMaxTokensToChunking(chunking, maxTokens) {
1051
+ if (!maxTokens || maxTokens <= 0) return chunking;
1052
+ const baseSize = chunking?.size ?? DEFAULT_CHUNK_SIZE;
1053
+ const baseOverlap = chunking?.overlap ?? 50;
1054
+ const clampedSize = Math.min(baseSize, maxTokens);
1055
+ const clampedOverlap = Math.min(baseOverlap, Math.max(0, clampedSize - 1));
1056
+ return {
1057
+ ...chunking,
1058
+ size: clampedSize,
1059
+ overlap: clampedOverlap
1060
+ };
1061
+ }
1062
+ /**
1063
+ * Embed arbitrary text directly.
1064
+ * Standalone function for embedding text outside of scrape().
1065
+ */
1066
+ async function embed(text, options) {
1067
+ return generateEmbeddings({ textContent: text }, {
1068
+ ...options,
1069
+ input: {
1070
+ ...options.input,
1071
+ type: "textContent"
1072
+ }
1073
+ });
1074
+ }
1075
+ /**
1076
+ * Embed from existing ScrapedData.
1077
+ * Useful when you've already scraped and want to add embeddings later.
1078
+ */
1079
+ async function embedScrapedData(data, options) {
1080
+ return generateEmbeddings(data, options);
1081
+ }
1082
+ /**
1083
+ * Create a skipped result with reason.
1084
+ */
1085
+ function createSkippedResult(reason, partialSource) {
1086
+ return {
1087
+ status: "skipped",
1088
+ reason,
1089
+ source: partialSource ?? {}
1090
+ };
1091
+ }
1092
+
1093
+ //#endregion
1094
+ //#region src/extractors/content.ts
1095
+ const turndown = new TurndownService({
1096
+ headingStyle: "atx",
1097
+ codeBlockStyle: "fenced",
1098
+ bulletListMarker: "-",
1099
+ emDelimiter: "_",
1100
+ strongDelimiter: "**",
1101
+ linkStyle: "inlined"
1102
+ });
1103
+ turndown.remove([
1104
+ "script",
1105
+ "style",
1106
+ "noscript",
1107
+ "iframe",
1108
+ "nav",
1109
+ "footer"
1110
+ ]);
1111
+ /**
1112
+ * Extracts main content using Mozilla Readability.
1113
+ * Converts HTML to Markdown for LLM consumption.
1114
+ */
1115
+ var ContentExtractor = class {
1116
+ name = "content";
1117
+ priority = 50;
1118
+ async extract(context) {
1119
+ const { options } = context;
1120
+ if (options.extractContent === false) return {};
1121
+ const article = new Readability(context.getDocument().cloneNode(true)).parse();
1122
+ if (!article || !article.content) return this.extractFallback(context);
1123
+ let content = turndown.turndown(article.content);
1124
+ const maxLength = options.maxContentLength ?? 5e4;
1125
+ if (content.length > maxLength) content = `${content.slice(0, maxLength)}\n\n[Content truncated...]`;
1126
+ const textContent = (article.textContent ?? "").trim();
1127
+ const excerpt = this.createExcerpt(textContent);
1128
+ const wordCount = textContent.split(/\s+/).filter(Boolean).length;
1129
+ const contentType = this.detectContentType(context);
1130
+ return {
1131
+ content,
1132
+ textContent,
1133
+ excerpt: article.excerpt || excerpt,
1134
+ wordCount,
1135
+ contentType,
1136
+ title: article.title || void 0,
1137
+ author: article.byline || void 0,
1138
+ siteName: article.siteName || void 0
1139
+ };
1140
+ }
1141
+ extractFallback(context) {
1142
+ const { $ } = context;
1143
+ const bodyHtml = $("body").html() || "";
1144
+ const content = turndown.turndown(bodyHtml);
1145
+ const textContent = $("body").text().replace(/\s+/g, " ").trim();
1146
+ return {
1147
+ content: content.slice(0, context.options.maxContentLength ?? 5e4),
1148
+ textContent,
1149
+ excerpt: this.createExcerpt(textContent),
1150
+ wordCount: textContent.split(/\s+/).filter(Boolean).length,
1151
+ contentType: "unknown"
1152
+ };
1153
+ }
1154
+ createExcerpt(text, maxLength = 300) {
1155
+ if (text.length <= maxLength) return text;
1156
+ const truncated = text.slice(0, maxLength);
1157
+ const lastSpace = truncated.lastIndexOf(" ");
1158
+ return `${lastSpace > 0 ? truncated.slice(0, lastSpace) : truncated}...`;
1159
+ }
1160
+ detectContentType(context) {
1161
+ const { $, finalUrl } = context;
1162
+ const url = finalUrl.toLowerCase();
1163
+ if (url.includes("github.com") && !url.includes("/blob/") && !url.includes("/issues/")) {
1164
+ if ($("meta[property=\"og:type\"]").attr("content") === "object" || url.match(/github\.com\/[^/]+\/[^/]+\/?$/)) return "repo";
1165
+ }
1166
+ if (url.includes("npmjs.com/package/")) return "package";
1167
+ if (url.includes("pypi.org/project/")) return "package";
1168
+ if (url.includes("/docs/") || url.includes(".readthedocs.") || url.includes("/documentation/")) return "docs";
1169
+ if (url.includes("youtube.com") || url.includes("vimeo.com") || url.includes("youtu.be")) return "video";
1170
+ const hasPrice = $("[class*=\"price\"], [data-price], [itemprop=\"price\"]").length > 0;
1171
+ const hasAddToCart = $("[class*=\"cart\"], [class*=\"buy\"], button:contains(\"Add\")").length > 0;
1172
+ if (hasPrice || hasAddToCart) return "product";
1173
+ const ogType = $("meta[property=\"og:type\"]").attr("content")?.toLowerCase();
1174
+ if (ogType === "article" || ogType === "blog" || ogType === "news") return "article";
1175
+ const hasArticleTag = $("article").length > 0;
1176
+ const hasDateline = $("time[datetime], [class*=\"date\"], [class*=\"byline\"]").length > 0;
1177
+ if (hasArticleTag && hasDateline) return "article";
1178
+ return "unknown";
1179
+ }
1180
+ };
1181
+
1182
+ //#endregion
1183
+ //#region src/utils/url.ts
1184
+ /**
1185
+ * Common tracking parameters to remove from URLs
1186
+ */
1187
+ const TRACKING_PARAMS = [
1188
+ "utm_source",
1189
+ "utm_medium",
1190
+ "utm_campaign",
1191
+ "utm_term",
1192
+ "utm_content",
1193
+ "utm_id",
1194
+ "ref",
1195
+ "fbclid",
1196
+ "gclid",
1197
+ "gclsrc",
1198
+ "dclid",
1199
+ "msclkid",
1200
+ "mc_cid",
1201
+ "mc_eid",
1202
+ "_ga",
1203
+ "_gl",
1204
+ "source",
1205
+ "referrer"
1206
+ ];
1207
+ /**
1208
+ * Validate if a string is a valid URL
1209
+ */
1210
+ function isValidUrl(url) {
1211
+ try {
1212
+ const parsed = new URL(url);
1213
+ return ["http:", "https:"].includes(parsed.protocol);
1214
+ } catch {
1215
+ return false;
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Normalize URL by removing tracking params and trailing slashes
1220
+ */
1221
+ function normalizeUrl(url) {
1222
+ try {
1223
+ const parsed = new URL(url);
1224
+ for (const param of TRACKING_PARAMS) parsed.searchParams.delete(param);
1225
+ let normalized = parsed.toString();
1226
+ if (normalized.endsWith("/") && parsed.pathname !== "/") normalized = normalized.slice(0, -1);
1227
+ return normalized;
1228
+ } catch {
1229
+ return url;
1230
+ }
1231
+ }
1232
+ /**
1233
+ * Extract domain from URL (without www prefix)
1234
+ */
1235
+ function extractDomain(url) {
1236
+ try {
1237
+ return new URL(url).hostname.replace(/^www\./, "");
1238
+ } catch {
1239
+ return "";
1240
+ }
1241
+ }
1242
+ /**
1243
+ * Resolve a potentially relative URL against a base URL
1244
+ */
1245
+ function resolveUrl(url, baseUrl) {
1246
+ if (!url) return void 0;
1247
+ try {
1248
+ return new URL(url, baseUrl).href;
1249
+ } catch {
1250
+ return url;
1251
+ }
1252
+ }
1253
+ /**
1254
+ * Check if a URL is external relative to a domain
1255
+ */
1256
+ function isExternalUrl(url, baseDomain) {
1257
+ try {
1258
+ return new URL(url).hostname.replace(/^www\./, "") !== baseDomain;
1259
+ } catch {
1260
+ return false;
1261
+ }
1262
+ }
1263
+ /**
1264
+ * Extract protocol from URL
1265
+ */
1266
+ function getProtocol(url) {
1267
+ try {
1268
+ return new URL(url).protocol;
1269
+ } catch {
1270
+ return "";
1271
+ }
1272
+ }
1273
+ /**
1274
+ * Get the path portion of a URL
1275
+ */
1276
+ function getPath(url) {
1277
+ try {
1278
+ return new URL(url).pathname;
1279
+ } catch {
1280
+ return "";
1281
+ }
1282
+ }
1283
+ /**
1284
+ * Check if URL matches a pattern (supports * wildcard)
1285
+ */
1286
+ function matchesUrlPattern(url, pattern) {
1287
+ if (!pattern.includes("*")) return url === pattern || url.startsWith(pattern);
1288
+ const regexPattern = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
1289
+ return (/* @__PURE__ */ new RegExp(`^${regexPattern}`)).test(url);
1290
+ }
1291
+
1292
+ //#endregion
1293
+ //#region src/extractors/favicon.ts
1294
+ /**
1295
+ * Extracts favicon URL from the page.
1296
+ * Checks multiple sources in order of preference.
1297
+ */
1298
+ var FaviconExtractor = class {
1299
+ name = "favicon";
1300
+ priority = 70;
1301
+ async extract(context) {
1302
+ const { $, finalUrl } = context;
1303
+ for (const selector of [
1304
+ "link[rel=\"icon\"][type=\"image/svg+xml\"]",
1305
+ "link[rel=\"icon\"][sizes=\"192x192\"]",
1306
+ "link[rel=\"icon\"][sizes=\"180x180\"]",
1307
+ "link[rel=\"icon\"][sizes=\"128x128\"]",
1308
+ "link[rel=\"icon\"][sizes=\"96x96\"]",
1309
+ "link[rel=\"apple-touch-icon\"][sizes=\"180x180\"]",
1310
+ "link[rel=\"apple-touch-icon\"]",
1311
+ "link[rel=\"icon\"][sizes=\"32x32\"]",
1312
+ "link[rel=\"icon\"]",
1313
+ "link[rel=\"shortcut icon\"]"
1314
+ ]) {
1315
+ const href = $(selector).first().attr("href");
1316
+ if (href) return { favicon: resolveUrl(finalUrl, href) };
1317
+ }
1318
+ try {
1319
+ const url = new URL(finalUrl);
1320
+ return { favicon: `${url.protocol}//${url.host}/favicon.ico` };
1321
+ } catch {
1322
+ return {};
1323
+ }
1324
+ }
1325
+ };
1326
+
1327
+ //#endregion
1328
+ //#region src/extractors/jsonld.ts
1329
+ /**
1330
+ * Extracts JSON-LD structured data from the page.
1331
+ * Also extracts additional metadata from structured data.
1332
+ */
1333
+ var JsonLdExtractor = class {
1334
+ name = "jsonld";
1335
+ priority = 80;
1336
+ async extract(context) {
1337
+ const { $ } = context;
1338
+ const jsonLd = [];
1339
+ $("script[type=\"application/ld+json\"]").each((_, el) => {
1340
+ const content = $(el).html();
1341
+ if (!content) return;
1342
+ try {
1343
+ const parsed = JSON.parse(content);
1344
+ if (Array.isArray(parsed)) jsonLd.push(...parsed);
1345
+ else if (typeof parsed === "object" && parsed !== null) jsonLd.push(parsed);
1346
+ } catch {}
1347
+ });
1348
+ if (jsonLd.length === 0) return {};
1349
+ return {
1350
+ jsonLd,
1351
+ ...this.extractMetadata(jsonLd)
1352
+ };
1353
+ }
1354
+ extractMetadata(jsonLd) {
1355
+ const result = {};
1356
+ for (const item of jsonLd) {
1357
+ const type = this.getType(item);
1358
+ if (type?.match(/Article|BlogPosting|NewsArticle|WebPage/i)) {
1359
+ result.title = result.title || this.getString(item, "headline", "name");
1360
+ result.description = result.description || this.getString(item, "description");
1361
+ result.author = result.author || this.getAuthor(item);
1362
+ result.publishedAt = result.publishedAt || this.getString(item, "datePublished");
1363
+ result.modifiedAt = result.modifiedAt || this.getString(item, "dateModified");
1364
+ result.image = result.image || this.getImage(item);
1365
+ }
1366
+ if (type === "Organization") result.siteName = result.siteName || this.getString(item, "name");
1367
+ if (type === "Product") {
1368
+ result.title = result.title || this.getString(item, "name");
1369
+ result.description = result.description || this.getString(item, "description");
1370
+ result.image = result.image || this.getImage(item);
1371
+ }
1372
+ if (type === "SoftwareApplication") {
1373
+ result.title = result.title || this.getString(item, "name");
1374
+ result.description = result.description || this.getString(item, "description");
1375
+ }
1376
+ const keywords = this.getKeywords(item);
1377
+ if (keywords.length > 0) result.keywords = [...result.keywords || [], ...keywords];
1378
+ }
1379
+ if (result.keywords) result.keywords = [...new Set(result.keywords)];
1380
+ return result;
1381
+ }
1382
+ getType(item) {
1383
+ const type = item["@type"];
1384
+ if (typeof type === "string") return type;
1385
+ if (Array.isArray(type)) return type[0];
1386
+ }
1387
+ getString(item, ...keys) {
1388
+ for (const key of keys) {
1389
+ const value = item[key];
1390
+ if (typeof value === "string") return value;
1391
+ if (typeof value === "object" && value !== null && "@value" in value) return String(value["@value"]);
1392
+ }
1393
+ }
1394
+ getAuthor(item) {
1395
+ const author = item.author;
1396
+ if (typeof author === "string") return author;
1397
+ if (Array.isArray(author)) return author.map((a) => typeof a === "string" ? a : this.getString(a, "name")).filter(Boolean).join(", ") || void 0;
1398
+ if (typeof author === "object" && author !== null) {
1399
+ const authorObj = author;
1400
+ return this.getString(authorObj, "name") || void 0;
1401
+ }
1402
+ }
1403
+ getImage(item) {
1404
+ const image = item.image;
1405
+ if (typeof image === "string") return image;
1406
+ if (Array.isArray(image) && image.length > 0) return this.getImage({ image: image[0] });
1407
+ if (typeof image === "object" && image !== null) {
1408
+ const imageObj = image;
1409
+ return this.getString(imageObj, "url", "contentUrl") || void 0;
1410
+ }
1411
+ }
1412
+ getKeywords(item) {
1413
+ const keywords = item.keywords;
1414
+ if (typeof keywords === "string") return keywords.split(",").map((k) => k.trim()).filter(Boolean);
1415
+ if (Array.isArray(keywords)) return keywords.filter((k) => typeof k === "string");
1416
+ return [];
1417
+ }
1418
+ };
1419
+
1420
+ //#endregion
1421
+ //#region src/extractors/links.ts
1422
+ /**
1423
+ * Extracts links from the page content.
1424
+ * Filters out navigation/footer links and focuses on content links.
1425
+ */
1426
+ var LinksExtractor = class {
1427
+ name = "links";
1428
+ priority = 30;
1429
+ async extract(context) {
1430
+ const { $, finalUrl } = context;
1431
+ const links = [];
1432
+ const seen = /* @__PURE__ */ new Set();
1433
+ const contentArea = $("article, main, [role=\"main\"]").first();
1434
+ const container = contentArea.length > 0 ? contentArea : $("body");
1435
+ const skipSelectors = "nav, header, footer, aside, [role=\"navigation\"], [class*=\"nav\"], [class*=\"footer\"], [class*=\"header\"], [class*=\"sidebar\"], [class*=\"menu\"]";
1436
+ container.find("a[href]").each((_, el) => {
1437
+ const $el = $(el);
1438
+ if ($el.closest(skipSelectors).length > 0) return;
1439
+ const href = $el.attr("href");
1440
+ if (!href) return;
1441
+ if (href.startsWith("#") || href.startsWith("javascript:") || href.startsWith("mailto:") || href.startsWith("tel:")) return;
1442
+ const resolvedUrl = resolveUrl(href, finalUrl);
1443
+ if (!resolvedUrl || !isValidUrl(resolvedUrl)) return;
1444
+ if (seen.has(resolvedUrl)) return;
1445
+ seen.add(resolvedUrl);
1446
+ const text = $el.text().trim() || $el.attr("title") || $el.attr("aria-label") || "";
1447
+ if (text.length < 2) return;
1448
+ const baseDomain = extractDomain(finalUrl);
1449
+ links.push({
1450
+ url: resolvedUrl,
1451
+ text: text.slice(0, 200),
1452
+ isExternal: isExternalUrl(resolvedUrl, baseDomain)
1453
+ });
1454
+ });
1455
+ return { links: links.slice(0, 100) };
1456
+ }
1457
+ };
1458
+
1459
+ //#endregion
1460
+ //#region src/extractors/meta.ts
1461
+ /**
1462
+ * Extracts metadata from HTML meta tags, Open Graph, and Twitter cards.
1463
+ * Runs first to provide basic metadata for other extractors.
1464
+ */
1465
+ var MetaExtractor = class {
1466
+ name = "meta";
1467
+ priority = 100;
1468
+ async extract(context) {
1469
+ const { $ } = context;
1470
+ const getMeta = (nameOrProperty) => {
1471
+ return ($(`meta[name="${nameOrProperty}"]`).attr("content") || $(`meta[property="${nameOrProperty}"]`).attr("content") || $(`meta[itemprop="${nameOrProperty}"]`).attr("content"))?.trim() || void 0;
1472
+ };
1473
+ const title = getMeta("og:title") || getMeta("twitter:title") || $("title").first().text().trim() || "";
1474
+ const description = getMeta("og:description") || getMeta("twitter:description") || getMeta("description") || "";
1475
+ const image = getMeta("og:image") || getMeta("twitter:image") || getMeta("twitter:image:src") || void 0;
1476
+ const canonicalUrl = $("link[rel=\"canonical\"]").attr("href") || getMeta("og:url") || context.finalUrl;
1477
+ const author = getMeta("author") || getMeta("article:author") || getMeta("twitter:creator") || $("[rel=\"author\"]").first().text().trim() || void 0;
1478
+ const siteName = getMeta("og:site_name") || getMeta("application-name") || void 0;
1479
+ const publishedAt = getMeta("article:published_time") || getMeta("datePublished") || getMeta("date") || $("time[datetime]").first().attr("datetime") || void 0;
1480
+ const modifiedAt = getMeta("article:modified_time") || getMeta("dateModified") || void 0;
1481
+ const language = $("html").attr("lang") || getMeta("og:locale") || getMeta("language") || void 0;
1482
+ const keywordsRaw = getMeta("keywords") || getMeta("article:tag") || "";
1483
+ return {
1484
+ title,
1485
+ description,
1486
+ image,
1487
+ canonicalUrl,
1488
+ author,
1489
+ siteName,
1490
+ publishedAt,
1491
+ modifiedAt,
1492
+ language,
1493
+ keywords: keywordsRaw ? keywordsRaw.split(",").map((k) => k.trim()).filter(Boolean) : []
1494
+ };
1495
+ }
1496
+ };
1497
+
1498
+ //#endregion
1499
+ //#region src/extractors/index.ts
1500
+ /**
1501
+ * Default extractors in priority order.
1502
+ * Higher priority runs first.
1503
+ */
1504
+ function createDefaultExtractors() {
1505
+ return [
1506
+ new MetaExtractor(),
1507
+ new JsonLdExtractor(),
1508
+ new FaviconExtractor(),
1509
+ new ContentExtractor(),
1510
+ new LinksExtractor()
1511
+ ];
1512
+ }
1513
+ /**
1514
+ * Sort extractors by priority (higher first).
1515
+ */
1516
+ function sortExtractors(extractors) {
1517
+ return [...extractors].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
1518
+ }
1519
+
1520
+ //#endregion
1521
+ //#region src/fetchers/types.ts
1522
+ /**
1523
+ * Default user agent string
1524
+ */
1525
+ const DEFAULT_USER_AGENT = "Scrapex-Bot/2.0 (+https://github.com/developer-rakeshpaul/scrapex)";
1526
+ /**
1527
+ * Default timeout in milliseconds
1528
+ */
1529
+ const DEFAULT_TIMEOUT = 1e4;
1530
+
1531
+ //#endregion
1532
+ //#region src/fetchers/fetch.ts
1533
+ /**
1534
+ * Default fetcher using native fetch API.
1535
+ * Works in Node.js 18+ without polyfills.
1536
+ */
1537
+ var NativeFetcher = class {
1538
+ name = "native-fetch";
1539
+ async fetch(url, options = {}) {
1540
+ const { timeout = DEFAULT_TIMEOUT, userAgent = DEFAULT_USER_AGENT, headers = {} } = options;
1541
+ let parsedUrl;
1542
+ try {
1543
+ parsedUrl = new URL(url);
1544
+ } catch {
1545
+ throw new ScrapeError(`Invalid URL: ${url}`, "INVALID_URL");
1546
+ }
1547
+ if (!["http:", "https:"].includes(parsedUrl.protocol)) throw new ScrapeError(`Invalid protocol: ${parsedUrl.protocol}`, "INVALID_URL");
1548
+ const controller = new AbortController();
1549
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1550
+ try {
1551
+ const response = await fetch(url, {
1552
+ signal: controller.signal,
1553
+ headers: {
1554
+ "User-Agent": userAgent,
1555
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
1556
+ "Accept-Language": "en-US,en;q=0.5",
1557
+ ...headers
1558
+ },
1559
+ redirect: "follow"
1560
+ });
1561
+ clearTimeout(timeoutId);
1562
+ if (!response.ok) {
1563
+ if (response.status === 404) throw new ScrapeError(`Page not found: ${url}`, "NOT_FOUND", 404);
1564
+ if (response.status === 403 || response.status === 401) throw new ScrapeError(`Access blocked: ${url}`, "BLOCKED", response.status);
1565
+ if (response.status === 429) throw new ScrapeError(`Rate limited: ${url}`, "BLOCKED", 429);
1566
+ throw new ScrapeError(`HTTP error ${response.status}: ${url}`, "FETCH_FAILED", response.status);
1567
+ }
1568
+ const contentType = response.headers.get("content-type") || "";
1569
+ if (options.allowedContentTypes) {
1570
+ if (!options.allowedContentTypes.some((type) => contentType.toLowerCase().includes(type.toLowerCase()))) throw new ScrapeError(`Unexpected content type: ${contentType}`, "PARSE_ERROR");
1571
+ } else if (!contentType.includes("text/html") && !contentType.includes("application/xhtml")) throw new ScrapeError(`Unexpected content type: ${contentType}`, "PARSE_ERROR");
1572
+ const html = await response.text();
1573
+ const responseHeaders = {};
1574
+ response.headers.forEach((value, key) => {
1575
+ responseHeaders[key] = value;
1576
+ });
1577
+ return {
1578
+ html,
1579
+ finalUrl: response.url,
1580
+ statusCode: response.status,
1581
+ contentType,
1582
+ headers: responseHeaders
1583
+ };
1584
+ } catch (error) {
1585
+ clearTimeout(timeoutId);
1586
+ if (error instanceof ScrapeError) throw error;
1587
+ if (error instanceof Error && error.name === "AbortError") throw new ScrapeError(`Request timed out after ${timeout}ms`, "TIMEOUT");
1588
+ if (error instanceof Error) throw new ScrapeError(`Fetch failed: ${error.message}`, "FETCH_FAILED", void 0, error);
1589
+ throw new ScrapeError("Unknown fetch error", "FETCH_FAILED");
1590
+ }
1591
+ }
1592
+ };
1593
+ /**
1594
+ * Default fetcher instance
1595
+ */
1596
+ const defaultFetcher = new NativeFetcher();
1597
+
1598
+ //#endregion
1599
+ //#region src/fetchers/robots.ts
1600
+ /**
1601
+ * Check if URL is allowed by robots.txt
1602
+ *
1603
+ * @param url - The URL to check
1604
+ * @param userAgent - User agent to check rules for
1605
+ * @returns Whether the URL is allowed and optional reason
1606
+ */
1607
+ async function checkRobotsTxt(url, userAgent = DEFAULT_USER_AGENT) {
1608
+ try {
1609
+ const parsedUrl = new URL(url);
1610
+ const robotsUrl = `${parsedUrl.protocol}//${parsedUrl.host}/robots.txt`;
1611
+ const response = await fetch(robotsUrl, {
1612
+ headers: { "User-Agent": userAgent },
1613
+ signal: AbortSignal.timeout(5e3)
1614
+ });
1615
+ if (!response.ok) return { allowed: true };
1616
+ const allowed = isPathAllowed(parseRobotsTxt(await response.text(), userAgent), parsedUrl.pathname + parsedUrl.search);
1617
+ return {
1618
+ allowed,
1619
+ reason: allowed ? void 0 : "Blocked by robots.txt"
1620
+ };
1621
+ } catch {
1622
+ return { allowed: true };
1623
+ }
1624
+ }
1625
+ /**
1626
+ * Parse robots.txt content for a specific user agent
1627
+ */
1628
+ function parseRobotsTxt(content, userAgent) {
1629
+ const rules = {
1630
+ disallow: [],
1631
+ allow: []
1632
+ };
1633
+ const lines = content.split("\n");
1634
+ const botName = userAgent.split(/[\s/]/)[0]?.toLowerCase() || "";
1635
+ let currentAgent = "";
1636
+ let isMatchingAgent = false;
1637
+ let hasFoundSpecificAgent = false;
1638
+ for (const rawLine of lines) {
1639
+ const line = rawLine.trim();
1640
+ if (!line || line.startsWith("#")) continue;
1641
+ const colonIndex = line.indexOf(":");
1642
+ if (colonIndex === -1) continue;
1643
+ const directive = line.slice(0, colonIndex).trim().toLowerCase();
1644
+ const value = line.slice(colonIndex + 1).trim();
1645
+ if (directive === "user-agent") {
1646
+ currentAgent = value.toLowerCase();
1647
+ isMatchingAgent = currentAgent === "*" || currentAgent === botName || botName.includes(currentAgent);
1648
+ if (currentAgent !== "*" && isMatchingAgent) {
1649
+ hasFoundSpecificAgent = true;
1650
+ rules.disallow = [];
1651
+ rules.allow = [];
1652
+ }
1653
+ } else if (isMatchingAgent && (!hasFoundSpecificAgent || currentAgent !== "*")) {
1654
+ if (directive === "disallow" && value) rules.disallow.push(value);
1655
+ else if (directive === "allow" && value) rules.allow.push(value);
1656
+ }
1657
+ }
1658
+ return rules;
1659
+ }
1660
+ /**
1661
+ * Check if a path is allowed based on robots.txt rules
1662
+ */
1663
+ function isPathAllowed(rules, path) {
1664
+ if (rules.disallow.length === 0 && rules.allow.length === 0) return true;
1665
+ for (const pattern of rules.allow) if (matchesPattern(path, pattern)) return true;
1666
+ for (const pattern of rules.disallow) if (matchesPattern(path, pattern)) return false;
1667
+ return true;
1668
+ }
1669
+ /**
1670
+ * Check if a path matches a robots.txt pattern
1671
+ */
1672
+ function matchesPattern(path, pattern) {
1673
+ if (!pattern) return false;
1674
+ if (pattern.endsWith("*")) return path.startsWith(pattern.slice(0, -1));
1675
+ if (pattern.endsWith("$")) return path === pattern.slice(0, -1);
1676
+ if (pattern.includes("*")) return (/* @__PURE__ */ new RegExp(`^${pattern.replace(/\*/g, ".*").replace(/\?/g, "\\?")}.*`)).test(path);
1677
+ return path.startsWith(pattern);
1678
+ }
1679
+
1680
+ //#endregion
1681
+ //#region src/core/scrape.ts
1682
+ /**
1683
+ * Scrape a URL and extract metadata and content.
1684
+ *
1685
+ * @param url - The URL to scrape
1686
+ * @param options - Scraping options
1687
+ * @returns Scraped data with metadata and content
1688
+ *
1689
+ * @example
1690
+ * ```ts
1691
+ * const result = await scrape('https://example.com/article');
1692
+ * console.log(result.title, result.content);
1693
+ * ```
1694
+ */
1695
+ async function scrape(url, options = {}) {
1696
+ const startTime = Date.now();
1697
+ if (!isValidUrl(url)) throw new ScrapeError("Invalid URL provided", "INVALID_URL");
1698
+ const normalizedUrl = normalizeUrl(url);
1699
+ if (options.respectRobots) {
1700
+ const robotsResult = await checkRobotsTxt(normalizedUrl, options.userAgent);
1701
+ if (!robotsResult.allowed) throw new ScrapeError(`URL blocked by robots.txt: ${robotsResult.reason || "disallowed"}`, "ROBOTS_BLOCKED");
1702
+ }
1703
+ const fetchResult = await (options.fetcher ?? defaultFetcher).fetch(normalizedUrl, {
1704
+ timeout: options.timeout,
1705
+ userAgent: options.userAgent
1706
+ });
1707
+ await preloadJsdom();
1708
+ let context = createExtractionContext(normalizedUrl, fetchResult.finalUrl, fetchResult.html, options);
1709
+ let extractors;
1710
+ if (options.replaceDefaultExtractors) extractors = options.extractors ?? [];
1711
+ else {
1712
+ const defaults = createDefaultExtractors();
1713
+ extractors = options.extractors ? [...defaults, ...options.extractors] : defaults;
1714
+ }
1715
+ extractors = sortExtractors(extractors);
1716
+ for (const extractor of extractors) try {
1717
+ const extracted = await extractor.extract(context);
1718
+ context = mergeResults(context, extracted);
1719
+ } catch (error) {
1720
+ console.error(`Extractor "${extractor.name}" failed:`, error);
1721
+ context = mergeResults(context, { error: context.results.error ? `${context.results.error}; ${extractor.name}: ${error instanceof Error ? error.message : String(error)}` : `${extractor.name}: ${error instanceof Error ? error.message : String(error)}` });
1722
+ }
1723
+ const intermediateResult = {
1724
+ url: normalizedUrl,
1725
+ canonicalUrl: context.results.canonicalUrl || fetchResult.finalUrl,
1726
+ domain: extractDomain(fetchResult.finalUrl),
1727
+ title: context.results.title || "",
1728
+ description: context.results.description || "",
1729
+ image: context.results.image,
1730
+ favicon: context.results.favicon,
1731
+ content: context.results.content || "",
1732
+ textContent: context.results.textContent || "",
1733
+ excerpt: context.results.excerpt || "",
1734
+ wordCount: context.results.wordCount || 0,
1735
+ author: context.results.author,
1736
+ publishedAt: context.results.publishedAt,
1737
+ modifiedAt: context.results.modifiedAt,
1738
+ siteName: context.results.siteName,
1739
+ language: context.results.language,
1740
+ contentType: context.results.contentType || "unknown",
1741
+ keywords: context.results.keywords || [],
1742
+ jsonLd: context.results.jsonLd,
1743
+ links: context.results.links,
1744
+ custom: context.results.custom,
1745
+ scrapedAt: (/* @__PURE__ */ new Date()).toISOString(),
1746
+ scrapeTimeMs: 0,
1747
+ error: context.results.error
1748
+ };
1749
+ if (options.llm && options.enhance && options.enhance.length > 0) try {
1750
+ const enhanced = await enhance(intermediateResult, options.llm, options.enhance);
1751
+ Object.assign(intermediateResult, enhanced);
1752
+ } catch (error) {
1753
+ console.error("LLM enhancement failed:", error);
1754
+ intermediateResult.error = intermediateResult.error ? `${intermediateResult.error}; LLM: ${error instanceof Error ? error.message : String(error)}` : `LLM: ${error instanceof Error ? error.message : String(error)}`;
1755
+ }
1756
+ if (options.llm && options.extract) try {
1757
+ intermediateResult.extracted = await extract(intermediateResult, options.llm, options.extract);
1758
+ } catch (error) {
1759
+ console.error("LLM extraction failed:", error);
1760
+ intermediateResult.error = intermediateResult.error ? `${intermediateResult.error}; LLM extraction: ${error instanceof Error ? error.message : String(error)}` : `LLM extraction: ${error instanceof Error ? error.message : String(error)}`;
1761
+ }
1762
+ if (options.embeddings) intermediateResult.embeddings = await generateEmbeddings(intermediateResult, options.embeddings);
1763
+ const scrapeTimeMs = Date.now() - startTime;
1764
+ return {
1765
+ ...intermediateResult,
1766
+ scrapeTimeMs
1767
+ };
1768
+ }
1769
+ /**
1770
+ * Scrape from raw HTML string (no fetch).
1771
+ *
1772
+ * @param html - The HTML content
1773
+ * @param url - The URL (for resolving relative links)
1774
+ * @param options - Scraping options
1775
+ * @returns Scraped data with metadata and content
1776
+ *
1777
+ * @example
1778
+ * ```ts
1779
+ * const html = await fetchSomehow('https://example.com');
1780
+ * const result = await scrapeHtml(html, 'https://example.com');
1781
+ * ```
1782
+ */
1783
+ async function scrapeHtml(html, url, options = {}) {
1784
+ const startTime = Date.now();
1785
+ if (!isValidUrl(url)) throw new ScrapeError("Invalid URL provided", "INVALID_URL");
1786
+ const normalizedUrl = normalizeUrl(url);
1787
+ await preloadJsdom();
1788
+ let context = createExtractionContext(normalizedUrl, normalizedUrl, html, options);
1789
+ let extractors;
1790
+ if (options.replaceDefaultExtractors) extractors = options.extractors ?? [];
1791
+ else {
1792
+ const defaults = createDefaultExtractors();
1793
+ extractors = options.extractors ? [...defaults, ...options.extractors] : defaults;
1794
+ }
1795
+ extractors = sortExtractors(extractors);
1796
+ for (const extractor of extractors) try {
1797
+ const extracted = await extractor.extract(context);
1798
+ context = mergeResults(context, extracted);
1799
+ } catch (error) {
1800
+ console.error(`Extractor "${extractor.name}" failed:`, error);
1801
+ context = mergeResults(context, { error: context.results.error ? `${context.results.error}; ${extractor.name}: ${error instanceof Error ? error.message : String(error)}` : `${extractor.name}: ${error instanceof Error ? error.message : String(error)}` });
1802
+ }
1803
+ const domain = extractDomain(normalizedUrl);
1804
+ const intermediateResult = {
1805
+ url: normalizedUrl,
1806
+ canonicalUrl: context.results.canonicalUrl || normalizedUrl,
1807
+ domain,
1808
+ title: context.results.title || "",
1809
+ description: context.results.description || "",
1810
+ image: context.results.image,
1811
+ favicon: context.results.favicon,
1812
+ content: context.results.content || "",
1813
+ textContent: context.results.textContent || "",
1814
+ excerpt: context.results.excerpt || "",
1815
+ wordCount: context.results.wordCount || 0,
1816
+ author: context.results.author,
1817
+ publishedAt: context.results.publishedAt,
1818
+ modifiedAt: context.results.modifiedAt,
1819
+ siteName: context.results.siteName,
1820
+ language: context.results.language,
1821
+ contentType: context.results.contentType || "unknown",
1822
+ keywords: context.results.keywords || [],
1823
+ jsonLd: context.results.jsonLd,
1824
+ links: context.results.links,
1825
+ summary: context.results.summary,
1826
+ suggestedTags: context.results.suggestedTags,
1827
+ entities: context.results.entities,
1828
+ extracted: context.results.extracted,
1829
+ custom: context.results.custom,
1830
+ scrapedAt: (/* @__PURE__ */ new Date()).toISOString(),
1831
+ scrapeTimeMs: 0,
1832
+ error: context.results.error
1833
+ };
1834
+ if (options.embeddings) intermediateResult.embeddings = await generateEmbeddings(intermediateResult, options.embeddings);
1835
+ const scrapeTimeMs = Date.now() - startTime;
1836
+ return {
1837
+ ...intermediateResult,
1838
+ scrapeTimeMs
1839
+ };
1840
+ }
1841
+
1842
+ //#endregion
1843
+ //#region src/utils/feed.ts
1844
+ /**
1845
+ * Fetch and parse an RSS/Atom feed from a URL.
1846
+ * Uses scrapex's fetcher infrastructure for consistent behavior.
1847
+ */
1848
+ async function fetchFeed(url, options) {
1849
+ const result = await (options?.fetcher || defaultFetcher).fetch(url, {
1850
+ timeout: options?.timeout,
1851
+ userAgent: options?.userAgent,
1852
+ allowedContentTypes: [
1853
+ "application/rss+xml",
1854
+ "application/atom+xml",
1855
+ "application/rdf+xml",
1856
+ "application/xml",
1857
+ "text/xml",
1858
+ "text/html"
1859
+ ]
1860
+ });
1861
+ return new RSSParser(options?.parserOptions).parse(result.html, url);
1862
+ }
1863
+ /**
1864
+ * Detect RSS/Atom feed URLs from HTML.
1865
+ * Supports RSS, Atom, and RDF feed types.
1866
+ */
1867
+ function discoverFeeds(html, baseUrl) {
1868
+ const $ = cheerio.load(html);
1869
+ const feeds = [];
1870
+ const seen = /* @__PURE__ */ new Set();
1871
+ $([
1872
+ "link[type=\"application/rss+xml\"]",
1873
+ "link[type=\"application/atom+xml\"]",
1874
+ "link[type=\"application/rdf+xml\"]",
1875
+ "link[rel=\"alternate\"][type*=\"xml\"]"
1876
+ ].join(", ")).each((_, el) => {
1877
+ const href = $(el).attr("href");
1878
+ if (href) try {
1879
+ const resolved = new URL(href, baseUrl).href;
1880
+ if (!seen.has(resolved)) {
1881
+ seen.add(resolved);
1882
+ feeds.push(resolved);
1883
+ }
1884
+ } catch {}
1885
+ });
1886
+ return feeds;
1887
+ }
1888
+ /**
1889
+ * Filter feed items by date range.
1890
+ * Items without publishedAt are included by default.
1891
+ */
1892
+ function filterByDate(items, options) {
1893
+ const { after, before, includeUndated = true } = options;
1894
+ return items.filter((item) => {
1895
+ if (!item.publishedAt) return includeUndated;
1896
+ const date = new Date(item.publishedAt);
1897
+ if (after && date < after) return false;
1898
+ if (before && date > before) return false;
1899
+ return true;
1900
+ });
1901
+ }
1902
+ /**
1903
+ * Convert feed items to markdown for LLM consumption.
1904
+ * Uses ISO 8601 date format for consistency across environments.
1905
+ */
1906
+ function feedToMarkdown(feed, options) {
1907
+ const { includeContent = false, maxItems } = options || {};
1908
+ const lines = [`# ${feed.title}`, ""];
1909
+ if (feed.description) lines.push(feed.description, "");
1910
+ const items = maxItems ? feed.items.slice(0, maxItems) : feed.items;
1911
+ for (const item of items) {
1912
+ lines.push(`## ${item.title}`);
1913
+ if (item.publishedAt) {
1914
+ const date = item.publishedAt.split("T")[0];
1915
+ lines.push(`*${date}*`);
1916
+ }
1917
+ lines.push("");
1918
+ if (includeContent && item.content) lines.push(item.content);
1919
+ else if (item.description) lines.push(item.description);
1920
+ if (item.link) lines.push(`[Read more](${item.link})`, "");
1921
+ else lines.push("");
1922
+ }
1923
+ return lines.join("\n");
1924
+ }
1925
+ /**
1926
+ * Extract plain text from feed items for LLM processing.
1927
+ * Concatenates title, description, and content.
1928
+ */
1929
+ function feedToText(feed, options) {
1930
+ const { maxItems, separator = "\n\n---\n\n" } = options || {};
1931
+ return (maxItems ? feed.items.slice(0, maxItems) : feed.items).map((item) => {
1932
+ const parts = [item.title];
1933
+ if (item.description) parts.push(item.description);
1934
+ if (item.content) parts.push(item.content);
1935
+ return parts.join("\n\n");
1936
+ }).join(separator);
1937
+ }
1938
+ /**
1939
+ * Paginate through a feed using rel="next" links (RFC 5005).
1940
+ * Returns an async generator that yields each page.
1941
+ */
1942
+ async function* paginateFeed(url, options) {
1943
+ const { maxPages = 10, ...fetchOptions } = options || {};
1944
+ let currentUrl = url;
1945
+ let pageCount = 0;
1946
+ while (currentUrl && pageCount < maxPages) {
1947
+ const result = await fetchFeed(currentUrl, fetchOptions);
1948
+ yield result.data;
1949
+ currentUrl = result.data.next;
1950
+ pageCount++;
1951
+ }
1952
+ }
1953
+
1954
+ //#endregion
1955
+ export { ContentExtractor, DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, FaviconExtractor, InMemoryEmbeddingCache, JsonLdExtractor, LinksExtractor, MetaExtractor, NativeFetcher, RSSParser, ScrapeError, TRANSFORMERS_MODELS, aggregateVectors, checkRobotsTxt, chunkText, cosineSimilarity, createAzureEmbedding, createDefaultExtractors, createEmbeddingProvider, createExtractionContext, createHttpEmbedding, createHuggingFaceEmbedding, createOllamaEmbedding, createOpenAIEmbedding, createPiiRedactor, createTransformersEmbedding, defaultFetcher, discoverFeeds, embed, embedScrapedData, estimateTokens, extractDomain, feedToMarkdown, feedToText, fetchFeed, filterByDate, generateEmbeddings, getPath, getProtocol, isExternalUrl, isValidUrl, matchesUrlPattern, mergeResults, normalizeUrl, paginateFeed, redactPii, resolveUrl, scrape, scrapeHtml, sortExtractors };
1956
+ //# sourceMappingURL=index.mjs.map