scrapex 1.0.0-beta.1 → 1.0.0-beta.2

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 (52) hide show
  1. package/dist/embeddings/index.cjs +52 -0
  2. package/dist/embeddings/index.d.cts +3 -0
  3. package/dist/embeddings/index.d.mts +3 -0
  4. package/dist/embeddings/index.mjs +4 -0
  5. package/dist/embeddings-BjNTQSG9.cjs +1455 -0
  6. package/dist/embeddings-BjNTQSG9.cjs.map +1 -0
  7. package/dist/embeddings-Bsymy_jA.mjs +1215 -0
  8. package/dist/embeddings-Bsymy_jA.mjs.map +1 -0
  9. package/dist/enhancer-Cs_WyWtJ.cjs +219 -0
  10. package/dist/enhancer-Cs_WyWtJ.cjs.map +1 -0
  11. package/dist/enhancer-INx5NlgO.mjs +177 -0
  12. package/dist/enhancer-INx5NlgO.mjs.map +1 -0
  13. package/dist/{enhancer-j0xqKDJm.cjs → http-base-CHLf-Tco.cjs} +36 -199
  14. package/dist/http-base-CHLf-Tco.cjs.map +1 -0
  15. package/dist/{enhancer-ByjRD-t5.mjs → http-base-DM7YNo6X.mjs} +25 -176
  16. package/dist/http-base-DM7YNo6X.mjs.map +1 -0
  17. package/dist/{index-CDgcRnig.d.cts → index-Bvseqli-.d.cts} +1 -1
  18. package/dist/{index-CDgcRnig.d.cts.map → index-Bvseqli-.d.cts.map} +1 -1
  19. package/dist/{index-piS5wtki.d.mts → index-CIFjNySr.d.mts} +1 -1
  20. package/dist/{index-piS5wtki.d.mts.map → index-CIFjNySr.d.mts.map} +1 -1
  21. package/dist/index-D6qfjmZQ.d.mts +401 -0
  22. package/dist/index-D6qfjmZQ.d.mts.map +1 -0
  23. package/dist/index-RFSpP5g8.d.cts +401 -0
  24. package/dist/index-RFSpP5g8.d.cts.map +1 -0
  25. package/dist/index.cjs +39 -1074
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +3 -260
  28. package/dist/index.d.cts.map +1 -1
  29. package/dist/index.d.mts +3 -260
  30. package/dist/index.d.mts.map +1 -1
  31. package/dist/index.mjs +4 -1039
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/llm/index.cjs +7 -6
  34. package/dist/llm/index.cjs.map +1 -1
  35. package/dist/llm/index.d.cts +1 -1
  36. package/dist/llm/index.d.mts +1 -1
  37. package/dist/llm/index.mjs +2 -1
  38. package/dist/llm/index.mjs.map +1 -1
  39. package/dist/parsers/index.d.cts +1 -1
  40. package/dist/parsers/index.d.mts +1 -1
  41. package/dist/parsers/index.mjs +1 -1
  42. package/dist/{parsers-CwkYnyWY.mjs → parsers-DsawHeo0.mjs} +1 -1
  43. package/dist/{parsers-CwkYnyWY.mjs.map → parsers-DsawHeo0.mjs.map} +1 -1
  44. package/dist/{types-CadAXrme.d.mts → types-BOcHQU9s.d.mts} +308 -151
  45. package/dist/types-BOcHQU9s.d.mts.map +1 -0
  46. package/dist/{types-DPEtPihB.d.cts → types-DutdBpqd.d.cts} +308 -151
  47. package/dist/types-DutdBpqd.d.cts.map +1 -0
  48. package/package.json +1 -1
  49. package/dist/enhancer-ByjRD-t5.mjs.map +0 -1
  50. package/dist/enhancer-j0xqKDJm.cjs.map +0 -1
  51. package/dist/types-CadAXrme.d.mts.map +0 -1
  52. package/dist/types-DPEtPihB.d.cts.map +0 -1
@@ -0,0 +1,1455 @@
1
+ const require_parsers = require('./parsers-Bneuws8x.cjs');
2
+ const require_http_base = require('./http-base-CHLf-Tco.cjs');
3
+ let node_crypto = require("node:crypto");
4
+
5
+ //#region src/embeddings/aggregation.ts
6
+ /**
7
+ * Aggregate multiple embedding vectors into a single vector or return all.
8
+ *
9
+ * @param vectors - Array of embedding vectors (must all have same dimensions)
10
+ * @param strategy - Aggregation strategy
11
+ * @returns Aggregated result based on strategy
12
+ */
13
+ function aggregateVectors(vectors, strategy = "average") {
14
+ if (vectors.length === 0) throw new Error("Cannot aggregate empty vector array");
15
+ const firstVector = vectors[0];
16
+ if (!firstVector) throw new Error("Cannot aggregate empty vector array");
17
+ const dimensions = firstVector.length;
18
+ for (let i = 1; i < vectors.length; i++) {
19
+ const vec = vectors[i];
20
+ if (!vec || vec.length !== dimensions) throw new Error(`Vector dimension mismatch: expected ${dimensions}, got ${vec?.length ?? 0} at index ${i}`);
21
+ }
22
+ switch (strategy) {
23
+ case "average": return {
24
+ type: "single",
25
+ vector: averageVectors(vectors),
26
+ dimensions
27
+ };
28
+ case "max": return {
29
+ type: "single",
30
+ vector: maxPoolVectors(vectors),
31
+ dimensions
32
+ };
33
+ case "first": return {
34
+ type: "single",
35
+ vector: firstVector,
36
+ dimensions
37
+ };
38
+ case "all": return {
39
+ type: "multiple",
40
+ vectors,
41
+ dimensions
42
+ };
43
+ default: {
44
+ const _exhaustive = strategy;
45
+ throw new Error(`Unknown aggregation strategy: ${_exhaustive}`);
46
+ }
47
+ }
48
+ }
49
+ /**
50
+ * Compute element-wise average of vectors.
51
+ */
52
+ function averageVectors(vectors) {
53
+ const first = vectors[0];
54
+ if (!first || vectors.length === 1) return first ?? [];
55
+ const dimensions = first.length;
56
+ const count = vectors.length;
57
+ const result = new Array(dimensions).fill(0);
58
+ for (const vector of vectors) for (let i = 0; i < dimensions; i++) {
59
+ const val = result[i];
60
+ if (val !== void 0) result[i] = val + (vector[i] ?? 0);
61
+ }
62
+ for (let i = 0; i < dimensions; i++) {
63
+ const val = result[i];
64
+ if (val !== void 0) result[i] = val / count;
65
+ }
66
+ return result;
67
+ }
68
+ /**
69
+ * Compute element-wise maximum of vectors (max pooling).
70
+ */
71
+ function maxPoolVectors(vectors) {
72
+ const first = vectors[0];
73
+ if (!first || vectors.length === 1) return first ?? [];
74
+ const dimensions = first.length;
75
+ const result = [...first];
76
+ for (let v = 1; v < vectors.length; v++) {
77
+ const vec = vectors[v];
78
+ if (!vec) continue;
79
+ for (let i = 0; i < dimensions; i++) {
80
+ const val = vec[i] ?? 0;
81
+ if (val > (result[i] ?? 0)) result[i] = val;
82
+ }
83
+ }
84
+ return result;
85
+ }
86
+ /**
87
+ * Normalize a vector to unit length (L2 normalization).
88
+ */
89
+ function normalizeVector(vector) {
90
+ const magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));
91
+ if (magnitude === 0) return vector;
92
+ return vector.map((val) => val / magnitude);
93
+ }
94
+ /**
95
+ * Compute cosine similarity between two vectors.
96
+ * Both vectors should be normalized for accurate results.
97
+ */
98
+ function cosineSimilarity(a, b) {
99
+ if (a.length !== b.length) throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
100
+ let dot = 0;
101
+ let magnitudeA = 0;
102
+ let magnitudeB = 0;
103
+ for (let i = 0; i < a.length; i++) {
104
+ const aVal = a[i] ?? 0;
105
+ const bVal = b[i] ?? 0;
106
+ dot += aVal * bVal;
107
+ magnitudeA += aVal * aVal;
108
+ magnitudeB += bVal * bVal;
109
+ }
110
+ const magnitude = Math.sqrt(magnitudeA) * Math.sqrt(magnitudeB);
111
+ if (magnitude === 0) return 0;
112
+ return dot / magnitude;
113
+ }
114
+ /**
115
+ * Compute euclidean distance between two vectors.
116
+ */
117
+ function euclideanDistance(a, b) {
118
+ if (a.length !== b.length) throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
119
+ let sum = 0;
120
+ for (let i = 0; i < a.length; i++) {
121
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
122
+ sum += diff * diff;
123
+ }
124
+ return Math.sqrt(sum);
125
+ }
126
+ /**
127
+ * Compute dot product of two vectors.
128
+ */
129
+ function dotProduct(a, b) {
130
+ if (a.length !== b.length) throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
131
+ let result = 0;
132
+ for (let i = 0; i < a.length; i++) {
133
+ const aVal = a[i] ?? 0;
134
+ const bVal = b[i] ?? 0;
135
+ result += aVal * bVal;
136
+ }
137
+ return result;
138
+ }
139
+ /**
140
+ * Get the dimensions of a vector or set of vectors.
141
+ */
142
+ function getDimensions(vectors) {
143
+ if (vectors.length === 0) return 0;
144
+ const first = vectors[0];
145
+ if (typeof first === "number") return vectors.length;
146
+ return first?.length ?? 0;
147
+ }
148
+
149
+ //#endregion
150
+ //#region src/embeddings/cache.ts
151
+ /**
152
+ * Default maximum cache entries.
153
+ */
154
+ const DEFAULT_MAX_ENTRIES = 1e3;
155
+ /**
156
+ * Default TTL in milliseconds (1 hour).
157
+ */
158
+ const DEFAULT_TTL_MS = 3600 * 1e3;
159
+ /**
160
+ * Generate a content-addressable cache key.
161
+ * Key is based on content hash and embedding configuration.
162
+ * Note: custom RegExp patterns are serialized by source+flags; different
163
+ * constructions can yield different cache keys even if equivalent.
164
+ */
165
+ function generateCacheKey(params) {
166
+ const hash = (0, node_crypto.createHash)("sha256");
167
+ const fingerprint = stableStringify({
168
+ providerKey: params.providerKey,
169
+ model: params.model ?? "provider-default",
170
+ dimensions: params.dimensions ?? "default",
171
+ aggregation: params.aggregation ?? "average",
172
+ input: serializeInputConfig(params.input),
173
+ chunking: serializeChunkingConfig(params.chunking),
174
+ safety: serializeSafetyConfig(params.safety),
175
+ cacheKeySalt: params.cacheKeySalt
176
+ });
177
+ hash.update(fingerprint);
178
+ hash.update("\0");
179
+ hash.update(params.content);
180
+ return hash.digest("hex");
181
+ }
182
+ /**
183
+ * Generate a checksum for content verification.
184
+ */
185
+ function generateChecksum(content) {
186
+ return (0, node_crypto.createHash)("sha256").update(content).digest("hex").slice(0, 16);
187
+ }
188
+ function serializeInputConfig(config) {
189
+ if (!config) return void 0;
190
+ return normalizeObject({
191
+ type: config.type ?? "textContent",
192
+ hasTransform: Boolean(config.transform),
193
+ hasCustomText: Boolean(config.customText)
194
+ });
195
+ }
196
+ function serializeChunkingConfig(config) {
197
+ if (!config) return void 0;
198
+ return normalizeObject({
199
+ size: config.size,
200
+ overlap: config.overlap,
201
+ tokenizer: getTokenizerId(config.tokenizer),
202
+ maxInputLength: config.maxInputLength
203
+ });
204
+ }
205
+ function serializeSafetyConfig(config) {
206
+ if (!config) return void 0;
207
+ return normalizeObject({
208
+ piiRedaction: serializePiiConfig(config.piiRedaction),
209
+ minTextLength: config.minTextLength,
210
+ maxTokens: config.maxTokens
211
+ });
212
+ }
213
+ function serializePiiConfig(config) {
214
+ if (!config) return void 0;
215
+ return normalizeObject({
216
+ email: config.email ?? false,
217
+ phone: config.phone ?? false,
218
+ creditCard: config.creditCard ?? false,
219
+ ssn: config.ssn ?? false,
220
+ ipAddress: config.ipAddress ?? false,
221
+ customPatterns: config.customPatterns?.map((pattern) => `${pattern.source}/${pattern.flags}`)
222
+ });
223
+ }
224
+ function getTokenizerId(tokenizer) {
225
+ if (!tokenizer || tokenizer === "heuristic") return "heuristic";
226
+ if (tokenizer === "tiktoken") return "tiktoken";
227
+ return "custom";
228
+ }
229
+ function stableStringify(value) {
230
+ return stringifyNormalized(normalizeValue(value));
231
+ }
232
+ function normalizeValue(value) {
233
+ if (value === void 0) return void 0;
234
+ if (value === null) return null;
235
+ if (Array.isArray(value)) return value.map((entry) => normalizeValue(entry)).filter((entry) => entry !== void 0);
236
+ if (typeof value === "object") return normalizeObject(value);
237
+ return value;
238
+ }
239
+ function normalizeObject(value) {
240
+ const normalized = {};
241
+ for (const key of Object.keys(value).sort()) {
242
+ const entry = normalizeValue(value[key]);
243
+ if (entry !== void 0) normalized[key] = entry;
244
+ }
245
+ return normalized;
246
+ }
247
+ function stringifyNormalized(value) {
248
+ if (value === void 0) return "undefined";
249
+ if (value === null) return "null";
250
+ if (typeof value === "string") return JSON.stringify(value);
251
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
252
+ if (Array.isArray(value)) return `[${value.map((entry) => stringifyNormalized(entry)).join(",")}]`;
253
+ if (typeof value === "object") {
254
+ const obj = value;
255
+ return `{${Object.keys(obj).sort().map((key) => `${JSON.stringify(key)}:${stringifyNormalized(obj[key])}`).join(",")}}`;
256
+ }
257
+ return JSON.stringify(value);
258
+ }
259
+ /**
260
+ * In-memory LRU cache with TTL support.
261
+ * Content-addressable: uses content hash as key, not URL.
262
+ */
263
+ var InMemoryEmbeddingCache = class {
264
+ cache;
265
+ maxEntries;
266
+ defaultTtlMs;
267
+ constructor(options) {
268
+ this.cache = /* @__PURE__ */ new Map();
269
+ this.maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
270
+ this.defaultTtlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
271
+ }
272
+ async get(key) {
273
+ const entry = this.cache.get(key);
274
+ if (!entry) return;
275
+ const now = Date.now();
276
+ if (now > entry.expiresAt) {
277
+ this.cache.delete(key);
278
+ return;
279
+ }
280
+ entry.accessedAt = now;
281
+ return entry.value;
282
+ }
283
+ async set(key, value, options) {
284
+ const now = Date.now();
285
+ const ttl = options?.ttlMs ?? this.defaultTtlMs;
286
+ if (this.cache.size >= this.maxEntries && !this.cache.has(key)) this.evictLRU();
287
+ this.cache.set(key, {
288
+ value,
289
+ createdAt: now,
290
+ expiresAt: now + ttl,
291
+ accessedAt: now
292
+ });
293
+ }
294
+ async delete(key) {
295
+ return this.cache.delete(key);
296
+ }
297
+ async clear() {
298
+ this.cache.clear();
299
+ }
300
+ /**
301
+ * Get cache statistics.
302
+ */
303
+ getStats() {
304
+ const now = Date.now();
305
+ let expired = 0;
306
+ for (const entry of this.cache.values()) if (now > entry.expiresAt) expired++;
307
+ return {
308
+ size: this.cache.size,
309
+ maxEntries: this.maxEntries,
310
+ expired,
311
+ utilization: this.cache.size / this.maxEntries
312
+ };
313
+ }
314
+ /**
315
+ * Evict expired entries.
316
+ */
317
+ cleanup() {
318
+ const now = Date.now();
319
+ let evicted = 0;
320
+ for (const [key, entry] of this.cache.entries()) if (now > entry.expiresAt) {
321
+ this.cache.delete(key);
322
+ evicted++;
323
+ }
324
+ return evicted;
325
+ }
326
+ /**
327
+ * Evict least recently used entry.
328
+ */
329
+ evictLRU() {
330
+ let oldestKey = null;
331
+ let oldestAccess = Number.POSITIVE_INFINITY;
332
+ for (const [key, entry] of this.cache.entries()) if (entry.accessedAt < oldestAccess) {
333
+ oldestAccess = entry.accessedAt;
334
+ oldestKey = key;
335
+ }
336
+ if (oldestKey) this.cache.delete(oldestKey);
337
+ }
338
+ };
339
+ /**
340
+ * Validate that a cached result matches expected parameters.
341
+ */
342
+ function validateCachedResult(result, expectedDimensions) {
343
+ if (result.status !== "success") return true;
344
+ if (!expectedDimensions) return true;
345
+ if (result.aggregation === "all") {
346
+ const firstVec = result.vectors[0];
347
+ if (!firstVec) return false;
348
+ return firstVec.length === expectedDimensions;
349
+ }
350
+ return result.vector.length === expectedDimensions;
351
+ }
352
+ /**
353
+ * Create a no-op cache that never stores anything.
354
+ * Useful for disabling caching while maintaining interface compatibility.
355
+ */
356
+ function createNoOpCache() {
357
+ return {
358
+ async get() {},
359
+ async set() {},
360
+ async delete() {
361
+ return false;
362
+ },
363
+ async clear() {}
364
+ };
365
+ }
366
+ /**
367
+ * Default in-memory cache instance.
368
+ * Optimized for moderate cache sizes (default 1000 entries).
369
+ */
370
+ let defaultCache = null;
371
+ /**
372
+ * Get or create the default cache instance.
373
+ */
374
+ function getDefaultCache() {
375
+ if (!defaultCache) defaultCache = new InMemoryEmbeddingCache();
376
+ return defaultCache;
377
+ }
378
+ /**
379
+ * Reset the default cache (mainly for testing).
380
+ */
381
+ async function resetDefaultCache() {
382
+ if (defaultCache) await defaultCache.clear();
383
+ defaultCache = null;
384
+ }
385
+
386
+ //#endregion
387
+ //#region src/embeddings/chunking.ts
388
+ /**
389
+ * Default chunk size in tokens.
390
+ */
391
+ const DEFAULT_CHUNK_SIZE$1 = 500;
392
+ /**
393
+ * Default overlap in tokens.
394
+ */
395
+ const DEFAULT_OVERLAP = 50;
396
+ /**
397
+ * Default maximum input length in characters.
398
+ */
399
+ const DEFAULT_MAX_INPUT_LENGTH = 1e5;
400
+ /**
401
+ * Heuristic token counting: approximately 4 characters per token.
402
+ * This is a reasonable approximation for English text.
403
+ */
404
+ function heuristicTokenCount(text) {
405
+ return Math.ceil(text.length / 4);
406
+ }
407
+ /**
408
+ * Convert token count to approximate character count.
409
+ */
410
+ function tokensToChars(tokens) {
411
+ return tokens * 4;
412
+ }
413
+ /**
414
+ * Create a tokenizer function based on configuration.
415
+ */
416
+ function createTokenizer(config) {
417
+ if (!config || config === "heuristic") return heuristicTokenCount;
418
+ if (config === "tiktoken") return heuristicTokenCount;
419
+ return config;
420
+ }
421
+ /**
422
+ * Find a natural break point in text (sentence or word boundary).
423
+ * Prefers common sentence boundaries (Latin + CJK), falls back to word boundaries.
424
+ */
425
+ function findBreakPoint(text, targetIndex) {
426
+ const searchStart = Math.max(0, targetIndex - Math.floor(targetIndex * .2));
427
+ const searchEnd = Math.min(text.length, targetIndex + Math.floor(targetIndex * .2));
428
+ const searchText = text.slice(searchStart, searchEnd);
429
+ const sentenceMatch = /[.!?。!?]\s*/g;
430
+ let lastSentenceEnd = -1;
431
+ for (const match of searchText.matchAll(sentenceMatch)) {
432
+ const absolutePos = searchStart + match.index + match[0].length;
433
+ if (absolutePos <= targetIndex) lastSentenceEnd = absolutePos;
434
+ }
435
+ if (lastSentenceEnd !== -1) return lastSentenceEnd;
436
+ const wordBoundary = text.lastIndexOf(" ", targetIndex);
437
+ if (wordBoundary > searchStart) return wordBoundary + 1;
438
+ return targetIndex;
439
+ }
440
+ /**
441
+ * Split text into overlapping chunks optimized for embedding.
442
+ * Respects sentence boundaries when possible.
443
+ */
444
+ function chunkText(text, config) {
445
+ const chunkSize = config?.size ?? DEFAULT_CHUNK_SIZE$1;
446
+ const rawOverlap = config?.overlap ?? DEFAULT_OVERLAP;
447
+ const safeOverlap = Math.max(0, rawOverlap);
448
+ const overlap = Math.min(safeOverlap, Math.max(0, chunkSize - 1));
449
+ const maxInputLength = config?.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH;
450
+ const tokenizer = createTokenizer(config?.tokenizer);
451
+ const normalizedText = (text.length > maxInputLength ? text.slice(0, maxInputLength) : text).replace(/\s+/g, " ").trim();
452
+ if (!normalizedText) return [];
453
+ const totalTokens = tokenizer(normalizedText);
454
+ if (totalTokens <= chunkSize) return [{
455
+ text: normalizedText,
456
+ startIndex: 0,
457
+ endIndex: normalizedText.length,
458
+ tokens: totalTokens
459
+ }];
460
+ const chunks = [];
461
+ const chunkSizeChars = tokensToChars(chunkSize);
462
+ const overlapChars = tokensToChars(overlap);
463
+ let startIndex = 0;
464
+ while (startIndex < normalizedText.length) {
465
+ const targetEnd = Math.min(startIndex + chunkSizeChars, normalizedText.length);
466
+ const endIndex = targetEnd < normalizedText.length ? findBreakPoint(normalizedText, targetEnd) : targetEnd;
467
+ const chunkText$1 = normalizedText.slice(startIndex, endIndex).trim();
468
+ if (chunkText$1) chunks.push({
469
+ text: chunkText$1,
470
+ startIndex,
471
+ endIndex,
472
+ tokens: tokenizer(chunkText$1)
473
+ });
474
+ if (endIndex >= normalizedText.length) break;
475
+ const nextStart = endIndex - overlapChars;
476
+ startIndex = Math.max(nextStart, startIndex + 1);
477
+ if (startIndex < normalizedText.length) {
478
+ const spaceIndex = normalizedText.indexOf(" ", startIndex);
479
+ if (spaceIndex !== -1 && spaceIndex < startIndex + overlapChars) startIndex = spaceIndex + 1;
480
+ }
481
+ }
482
+ return chunks;
483
+ }
484
+ /**
485
+ * Estimate total tokens for a text without chunking.
486
+ */
487
+ function estimateTokens(text, tokenizer) {
488
+ return createTokenizer(tokenizer)(text);
489
+ }
490
+ /**
491
+ * Check if text needs chunking based on token count.
492
+ */
493
+ function needsChunking(text, maxTokens = DEFAULT_CHUNK_SIZE$1, tokenizer) {
494
+ return createTokenizer(tokenizer)(text) > maxTokens;
495
+ }
496
+ /**
497
+ * Get statistics about potential chunking.
498
+ */
499
+ function getChunkingStats(text, config) {
500
+ const maxInputLength = config?.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH;
501
+ const chunkSize = config?.size ?? DEFAULT_CHUNK_SIZE$1;
502
+ const overlap = config?.overlap ?? DEFAULT_OVERLAP;
503
+ const tokenizer = createTokenizer(config?.tokenizer);
504
+ const inputLength = text.length;
505
+ const willTruncate = inputLength > maxInputLength;
506
+ const processedLength = willTruncate ? maxInputLength : inputLength;
507
+ const estimatedTokens = tokenizer(text.slice(0, processedLength).replace(/\s+/g, " ").trim());
508
+ let estimatedChunks = 1;
509
+ if (estimatedTokens > chunkSize) {
510
+ const clampedOverlap = Math.min(overlap, Math.max(0, chunkSize - 1));
511
+ const effectiveChunkSize = Math.max(1, chunkSize - clampedOverlap);
512
+ estimatedChunks = Math.ceil((estimatedTokens - clampedOverlap) / effectiveChunkSize);
513
+ }
514
+ return {
515
+ inputLength,
516
+ estimatedTokens,
517
+ estimatedChunks,
518
+ willTruncate
519
+ };
520
+ }
521
+
522
+ //#endregion
523
+ //#region src/embeddings/input.ts
524
+ /**
525
+ * Select and prepare input text for embedding based on configuration.
526
+ *
527
+ * @param data - Scraped data to extract input from
528
+ * @param config - Input configuration
529
+ * @returns Selected and prepared text, or undefined if no valid input
530
+ */
531
+ function selectInput(data, config) {
532
+ if (config?.transform) return normalizeText(config.transform(data));
533
+ if (config?.type === "custom" && config.customText) return normalizeText(config.customText);
534
+ const type = config?.type ?? "textContent";
535
+ switch (type) {
536
+ case "textContent": return selectTextContent(data);
537
+ case "title+summary": return selectTitleSummary(data);
538
+ case "custom": return selectTextContent(data);
539
+ default: {
540
+ const _exhaustive = type;
541
+ throw new Error(`Unknown input type: ${_exhaustive}`);
542
+ }
543
+ }
544
+ }
545
+ /**
546
+ * Select textContent as input.
547
+ */
548
+ function selectTextContent(data) {
549
+ if (data.textContent) return normalizeText(data.textContent);
550
+ if (data.content) return normalizeText(stripMarkdown(data.content));
551
+ if (data.excerpt) return normalizeText(data.excerpt);
552
+ if (data.description) return normalizeText(data.description);
553
+ }
554
+ /**
555
+ * Select title + summary (or fallbacks) as input.
556
+ * Optimized for semantic search and classification.
557
+ */
558
+ function selectTitleSummary(data) {
559
+ const parts = [];
560
+ if (data.title) parts.push(data.title);
561
+ if (data.summary) parts.push(data.summary);
562
+ else if (data.excerpt) parts.push(data.excerpt);
563
+ else if (data.description) parts.push(data.description);
564
+ if (parts.length === 0) return;
565
+ return normalizeText(parts.join("\n\n"));
566
+ }
567
+ /**
568
+ * Normalize text for embedding:
569
+ * - Collapse whitespace
570
+ * - Trim leading/trailing whitespace
571
+ * - Remove control characters
572
+ */
573
+ function normalizeText(text) {
574
+ if (!text) return "";
575
+ 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();
576
+ }
577
+ /**
578
+ * Basic markdown stripping for when we need plain text from content.
579
+ * Not comprehensive, but handles common cases.
580
+ */
581
+ function stripMarkdown(markdown) {
582
+ 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, "");
583
+ }
584
+ /**
585
+ * Check if the selected input meets minimum requirements.
586
+ */
587
+ function validateInput(text, minLength = 10) {
588
+ if (!text) return {
589
+ valid: false,
590
+ reason: "No input text available"
591
+ };
592
+ if (text.length < minLength) return {
593
+ valid: false,
594
+ reason: `Input too short (${text.length} < ${minLength} characters)`
595
+ };
596
+ const wordCount = text.split(/\s+/).filter((w) => w.length > 1).length;
597
+ if (wordCount < 3) return {
598
+ valid: false,
599
+ reason: `Input has too few words (${wordCount} < 3)`
600
+ };
601
+ return {
602
+ valid: true,
603
+ text,
604
+ wordCount,
605
+ charCount: text.length
606
+ };
607
+ }
608
+ /**
609
+ * Get a preview of what input would be selected.
610
+ * Useful for debugging and testing.
611
+ */
612
+ function previewInput(data, config, maxLength = 200) {
613
+ const input = selectInput(data, config);
614
+ if (!input) return "[No input available]";
615
+ if (input.length <= maxLength) return input;
616
+ return `${input.slice(0, maxLength)}...`;
617
+ }
618
+
619
+ //#endregion
620
+ //#region src/embeddings/providers/base.ts
621
+ /**
622
+ * Generate a stable cache key identifier for provider configuration.
623
+ */
624
+ function getProviderCacheKey(config) {
625
+ switch (config.type) {
626
+ case "http": return `http:${config.config.baseUrl.replace(/\/$/, "")}:${config.config.model}`;
627
+ case "custom": return `custom:${config.provider.name}`;
628
+ default: {
629
+ const _exhaustive = config;
630
+ return String(_exhaustive);
631
+ }
632
+ }
633
+ }
634
+ /**
635
+ * Get default model for a provider type.
636
+ */
637
+ function getDefaultModel(providerType) {
638
+ switch (providerType) {
639
+ case "openai": return "text-embedding-3-small";
640
+ case "azure": return "text-embedding-ada-002";
641
+ case "transformers": return "Xenova/all-MiniLM-L6-v2";
642
+ default: return "default";
643
+ }
644
+ }
645
+
646
+ //#endregion
647
+ //#region src/embeddings/providers/http.ts
648
+ /**
649
+ * HTTP-based Embedding Provider using native fetch.
650
+ * Provides a unified interface for any REST-based embedding API.
651
+ */
652
+ /**
653
+ * HTTP-based embedding provider.
654
+ * Works with any REST API using native fetch.
655
+ */
656
+ var HttpEmbeddingProvider = class extends require_http_base.BaseHttpProvider {
657
+ name = "http-embedding";
658
+ requestBuilder;
659
+ responseMapper;
660
+ constructor(config) {
661
+ super(config);
662
+ this.requestBuilder = config.requestBuilder ?? ((texts, model) => ({
663
+ input: texts,
664
+ model
665
+ }));
666
+ this.responseMapper = config.responseMapper ?? ((response) => {
667
+ const resp = response;
668
+ if (Array.isArray(resp.data)) return resp.data.map((item) => item.embedding);
669
+ if (Array.isArray(resp.embeddings)) return resp.embeddings;
670
+ if (Array.isArray(resp.embedding)) return [resp.embedding];
671
+ if (Array.isArray(response)) return response;
672
+ throw new require_http_base.ScrapeError("Unable to parse embedding response. Provide a custom responseMapper.", "VALIDATION_ERROR");
673
+ });
674
+ }
675
+ /**
676
+ * Generate embeddings for one or more texts.
677
+ */
678
+ async embed(texts, options) {
679
+ const model = options.model || this.model;
680
+ const body = this.requestBuilder(texts, model);
681
+ const { data } = await this.fetch(this.baseUrl, {
682
+ body,
683
+ signal: options.signal
684
+ });
685
+ const embeddings = this.responseMapper(data);
686
+ if (embeddings.length !== texts.length) throw new require_http_base.ScrapeError(`Embedding count mismatch: expected ${texts.length}, got ${embeddings.length}`, "VALIDATION_ERROR");
687
+ return { embeddings };
688
+ }
689
+ };
690
+ /**
691
+ * Create a generic HTTP embedding provider.
692
+ */
693
+ function createHttpEmbedding(config) {
694
+ return new HttpEmbeddingProvider(config);
695
+ }
696
+
697
+ //#endregion
698
+ //#region src/embeddings/providers/presets.ts
699
+ /**
700
+ * Create an OpenAI embedding provider.
701
+ *
702
+ * @example
703
+ * ```ts
704
+ * const provider = createOpenAIEmbedding({ apiKey: 'sk-...' });
705
+ * const { embeddings } = await provider.embed(['Hello'], { model: 'text-embedding-3-small' });
706
+ * ```
707
+ */
708
+ function createOpenAIEmbedding(options) {
709
+ const apiKey = options?.apiKey ?? process.env.OPENAI_API_KEY;
710
+ if (!apiKey) throw new Error("OpenAI API key required. Set OPENAI_API_KEY env var or pass apiKey option.");
711
+ const headers = { Authorization: `Bearer ${apiKey}` };
712
+ if (options?.organization) headers["OpenAI-Organization"] = options.organization;
713
+ return new HttpEmbeddingProvider({
714
+ baseUrl: options?.baseUrl ?? "https://api.openai.com/v1/embeddings",
715
+ model: options?.model ?? "text-embedding-3-small",
716
+ headers,
717
+ requestBuilder: (texts, model) => ({
718
+ input: texts,
719
+ model
720
+ }),
721
+ responseMapper: (res) => res.data.map((item) => item.embedding)
722
+ });
723
+ }
724
+ /**
725
+ * Create an Azure OpenAI embedding provider.
726
+ *
727
+ * @example
728
+ * ```ts
729
+ * const provider = createAzureEmbedding({
730
+ * endpoint: 'https://my-resource.openai.azure.com',
731
+ * deploymentName: 'text-embedding-ada-002',
732
+ * apiVersion: '2023-05-15',
733
+ * });
734
+ * ```
735
+ */
736
+ function createAzureEmbedding(options) {
737
+ const apiKey = options.apiKey ?? process.env.AZURE_OPENAI_API_KEY;
738
+ if (!apiKey) throw new Error("Azure OpenAI API key required. Set AZURE_OPENAI_API_KEY env var or pass apiKey option.");
739
+ return new HttpEmbeddingProvider({
740
+ baseUrl: `${options.endpoint.replace(/\/$/, "")}/openai/deployments/${options.deploymentName}/embeddings?api-version=${options.apiVersion}`,
741
+ model: options.deploymentName,
742
+ headers: { "api-key": apiKey },
743
+ requestBuilder: (texts) => ({ input: texts }),
744
+ responseMapper: (res) => res.data.map((item) => item.embedding)
745
+ });
746
+ }
747
+ /**
748
+ * Create an Ollama embedding provider for local models.
749
+ *
750
+ * LIMITATION: Ollama's /api/embeddings endpoint processes one text at a time,
751
+ * not batches. When multiple chunks are embedded, each chunk triggers a
752
+ * separate HTTP request. This is handled transparently by the pipeline's
753
+ * sequential chunk processing, but may be slower than batch-capable providers.
754
+ * For high-throughput scenarios, consider using OpenAI, Cohere, or HuggingFace
755
+ * which support batch embedding in a single request.
756
+ *
757
+ * @example
758
+ * ```ts
759
+ * const provider = createOllamaEmbedding({ model: 'nomic-embed-text' });
760
+ * ```
761
+ */
762
+ function createOllamaEmbedding(options) {
763
+ return new HttpEmbeddingProvider({
764
+ baseUrl: options?.baseUrl ?? "http://localhost:11434/api/embeddings",
765
+ model: options?.model ?? "nomic-embed-text",
766
+ requireHttps: false,
767
+ allowPrivate: true,
768
+ requestBuilder: (texts, model) => ({
769
+ model,
770
+ prompt: texts[0]
771
+ }),
772
+ responseMapper: (res) => [res.embedding]
773
+ });
774
+ }
775
+ /**
776
+ * Create a HuggingFace Inference API embedding provider.
777
+ *
778
+ * @example
779
+ * ```ts
780
+ * const provider = createHuggingFaceEmbedding({
781
+ * model: 'sentence-transformers/all-MiniLM-L6-v2',
782
+ * });
783
+ * ```
784
+ */
785
+ function createHuggingFaceEmbedding(options) {
786
+ const apiKey = options.apiKey ?? process.env.HF_TOKEN ?? process.env.HUGGINGFACE_API_KEY;
787
+ const headers = {};
788
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
789
+ return new HttpEmbeddingProvider({
790
+ baseUrl: `https://api-inference.huggingface.co/models/${options.model}`,
791
+ model: options.model,
792
+ headers,
793
+ requestBuilder: (texts) => ({ inputs: texts }),
794
+ responseMapper: (response) => {
795
+ if (Array.isArray(response)) {
796
+ if (Array.isArray(response[0]) && typeof response[0][0] === "number") return response;
797
+ return [response];
798
+ }
799
+ throw new Error("Unexpected HuggingFace response format");
800
+ }
801
+ });
802
+ }
803
+ /**
804
+ * Create a Cohere embedding provider.
805
+ *
806
+ * @example
807
+ * ```ts
808
+ * const provider = createCohereEmbedding({ model: 'embed-english-v3.0' });
809
+ * ```
810
+ */
811
+ function createCohereEmbedding(options) {
812
+ const apiKey = options?.apiKey ?? process.env.COHERE_API_KEY;
813
+ if (!apiKey) throw new Error("Cohere API key required. Set COHERE_API_KEY env var or pass apiKey option.");
814
+ return new HttpEmbeddingProvider({
815
+ baseUrl: "https://api.cohere.ai/v1/embed",
816
+ model: options?.model ?? "embed-english-v3.0",
817
+ headers: { Authorization: `Bearer ${apiKey}` },
818
+ requestBuilder: (texts, model) => ({
819
+ texts,
820
+ model,
821
+ input_type: options?.inputType ?? "search_document"
822
+ }),
823
+ responseMapper: (res) => res.embeddings
824
+ });
825
+ }
826
+ /**
827
+ * Create a local Transformers.js embedding provider.
828
+ * Uses dependency injection - user provides the imported transformers module.
829
+ *
830
+ * @example
831
+ * ```typescript
832
+ * import * as transformers from '@huggingface/transformers';
833
+ * import { createTransformersEmbedding } from 'scrapex/embeddings';
834
+ *
835
+ * const provider = createTransformersEmbedding(transformers, {
836
+ * model: 'Xenova/all-MiniLM-L6-v2',
837
+ * });
838
+ * ```
839
+ *
840
+ * Required Node.js dependencies:
841
+ * ```
842
+ * npm install @huggingface/transformers onnxruntime-node
843
+ * ```
844
+ */
845
+ function createTransformersEmbedding(transformers, options) {
846
+ let pipeline = null;
847
+ let currentModel = null;
848
+ const config = {
849
+ model: options?.model ?? "Xenova/all-MiniLM-L6-v2",
850
+ quantized: options?.quantized ?? true,
851
+ pooling: options?.pooling ?? "mean",
852
+ normalize: options?.normalize ?? true
853
+ };
854
+ return {
855
+ name: "transformers",
856
+ async embed(texts, request) {
857
+ const model = request.model || config.model;
858
+ if (!pipeline || currentModel !== model) {
859
+ const cacheDir = options?.cacheDir;
860
+ const env = transformers.env;
861
+ const priorCacheDir = env?.cacheDir;
862
+ if (cacheDir && env) env.cacheDir = cacheDir;
863
+ try {
864
+ pipeline = await transformers.pipeline("feature-extraction", model, { quantized: config.quantized });
865
+ } finally {
866
+ if (cacheDir && env) if (priorCacheDir === void 0) delete env.cacheDir;
867
+ else env.cacheDir = priorCacheDir;
868
+ }
869
+ currentModel = model;
870
+ }
871
+ const embeddings = [];
872
+ for (const text of texts) {
873
+ const output = await pipeline(text, {
874
+ pooling: config.pooling,
875
+ normalize: config.normalize
876
+ });
877
+ embeddings.push(Array.from(output.data));
878
+ }
879
+ return { embeddings };
880
+ }
881
+ };
882
+ }
883
+ /** Recommended models for Transformers.js */
884
+ const TRANSFORMERS_MODELS = {
885
+ DEFAULT: "Xenova/all-MiniLM-L6-v2",
886
+ QUALITY: "Xenova/all-mpnet-base-v2",
887
+ RETRIEVAL: "Xenova/bge-small-en-v1.5",
888
+ MULTILINGUAL: "Xenova/multilingual-e5-small"
889
+ };
890
+
891
+ //#endregion
892
+ //#region src/embeddings/providers/index.ts
893
+ /**
894
+ * Create an embedding provider from configuration.
895
+ * This is the main factory function for creating providers.
896
+ */
897
+ function createEmbeddingProvider(config) {
898
+ switch (config.type) {
899
+ case "http": return createHttpEmbedding(config.config);
900
+ case "custom": return config.provider;
901
+ default: throw new require_http_base.ScrapeError(`Unknown embedding provider type: ${config.type}`, "VALIDATION_ERROR");
902
+ }
903
+ }
904
+ /**
905
+ * Type guard to check if a value is an EmbeddingProvider.
906
+ */
907
+ function isEmbeddingProvider(value) {
908
+ return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && "embed" in value && typeof value.embed === "function";
909
+ }
910
+
911
+ //#endregion
912
+ //#region src/embeddings/safety.ts
913
+ /**
914
+ * PII redaction patterns with high precision to minimize false positives.
915
+ * Patterns are designed to match common formats while avoiding over-matching.
916
+ */
917
+ const EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
918
+ const PHONE_PATTERN = /(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/g;
919
+ 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;
920
+ const SSN_PATTERN = /\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b/g;
921
+ 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;
922
+ const REDACTED = "[REDACTED]";
923
+ /**
924
+ * Create a redaction function based on configuration.
925
+ * Returns a function that applies all configured PII patterns.
926
+ */
927
+ function createPiiRedactor(config) {
928
+ const patterns = [];
929
+ if (config.creditCard) patterns.push({
930
+ name: "creditCard",
931
+ pattern: CREDIT_CARD_PATTERN
932
+ });
933
+ if (config.email) patterns.push({
934
+ name: "email",
935
+ pattern: EMAIL_PATTERN
936
+ });
937
+ if (config.phone) patterns.push({
938
+ name: "phone",
939
+ pattern: PHONE_PATTERN
940
+ });
941
+ if (config.ssn) patterns.push({
942
+ name: "ssn",
943
+ pattern: SSN_PATTERN
944
+ });
945
+ if (config.ipAddress) patterns.push({
946
+ name: "ipAddress",
947
+ pattern: IPV4_PATTERN
948
+ });
949
+ if (config.customPatterns) for (let i = 0; i < config.customPatterns.length; i++) {
950
+ const customPattern = config.customPatterns[i];
951
+ if (customPattern) patterns.push({
952
+ name: `custom_${i}`,
953
+ pattern: customPattern
954
+ });
955
+ }
956
+ return (text) => {
957
+ let redactedText = text;
958
+ let totalRedactions = 0;
959
+ const redactionsByType = {};
960
+ for (const { name, pattern } of patterns) {
961
+ pattern.lastIndex = 0;
962
+ const matchCount = text.match(pattern)?.length ?? 0;
963
+ if (matchCount > 0) {
964
+ redactedText = redactedText.replace(pattern, REDACTED);
965
+ totalRedactions += matchCount;
966
+ redactionsByType[name] = (redactionsByType[name] ?? 0) + matchCount;
967
+ }
968
+ }
969
+ return {
970
+ text: redactedText,
971
+ redacted: totalRedactions > 0,
972
+ redactionCount: totalRedactions,
973
+ redactionsByType
974
+ };
975
+ };
976
+ }
977
+ /**
978
+ * Simple redaction that applies all default patterns.
979
+ * Use createPiiRedactor() for fine-grained control.
980
+ */
981
+ function redactPii(text) {
982
+ return createPiiRedactor({
983
+ email: true,
984
+ phone: true,
985
+ creditCard: true,
986
+ ssn: true,
987
+ ipAddress: true
988
+ })(text);
989
+ }
990
+ /**
991
+ * Check if text contains any PII.
992
+ * Useful for validation before sending to external APIs.
993
+ */
994
+ function containsPii(text, config) {
995
+ const fullConfig = {
996
+ email: config?.email ?? true,
997
+ phone: config?.phone ?? true,
998
+ creditCard: config?.creditCard ?? true,
999
+ ssn: config?.ssn ?? true,
1000
+ ipAddress: config?.ipAddress ?? true,
1001
+ customPatterns: config?.customPatterns
1002
+ };
1003
+ const patterns = [];
1004
+ if (fullConfig.email) patterns.push(EMAIL_PATTERN);
1005
+ if (fullConfig.phone) patterns.push(PHONE_PATTERN);
1006
+ if (fullConfig.creditCard) patterns.push(CREDIT_CARD_PATTERN);
1007
+ if (fullConfig.ssn) patterns.push(SSN_PATTERN);
1008
+ if (fullConfig.ipAddress) patterns.push(IPV4_PATTERN);
1009
+ if (fullConfig.customPatterns) patterns.push(...fullConfig.customPatterns);
1010
+ for (const pattern of patterns) {
1011
+ pattern.lastIndex = 0;
1012
+ if (pattern.test(text)) return true;
1013
+ }
1014
+ return false;
1015
+ }
1016
+
1017
+ //#endregion
1018
+ //#region src/embeddings/pipeline.ts
1019
+ const DEFAULT_CHUNK_SIZE = 500;
1020
+ /**
1021
+ * Get the effective model for embedding.
1022
+ * Prioritizes: explicit options.model > provider config model
1023
+ */
1024
+ function getEffectiveModel(providerConfig, explicitModel) {
1025
+ if (explicitModel) return explicitModel;
1026
+ if (providerConfig.type === "http") return providerConfig.config.model;
1027
+ }
1028
+ /**
1029
+ * Generate embeddings for scraped data.
1030
+ * This is the main entry point for the embedding pipeline.
1031
+ */
1032
+ async function generateEmbeddings(data, options) {
1033
+ const startTime = Date.now();
1034
+ try {
1035
+ const provider = createEmbeddingProvider(options.provider);
1036
+ const model = getEffectiveModel(options.provider, options.model);
1037
+ const validation = validateInput(selectInput(data, options.input), options.safety?.minTextLength ?? 10);
1038
+ if (!validation.valid) return createSkippedResult(validation.reason, { model });
1039
+ const originalInput = validation.text;
1040
+ let inputText = validation.text;
1041
+ let piiRedacted = false;
1042
+ if (options.safety?.piiRedaction) {
1043
+ const redactionResult = createPiiRedactor(options.safety.piiRedaction)(inputText);
1044
+ inputText = redactionResult.text;
1045
+ piiRedacted = redactionResult.redacted;
1046
+ }
1047
+ const effectiveChunking = applyMaxTokensToChunking(options.chunking, options.safety?.maxTokens);
1048
+ const cacheKey = generateCacheKey({
1049
+ providerKey: getProviderCacheKey(options.provider),
1050
+ model,
1051
+ dimensions: options.output?.dimensions,
1052
+ aggregation: options.output?.aggregation,
1053
+ input: options.input,
1054
+ chunking: effectiveChunking,
1055
+ safety: options.safety,
1056
+ cacheKeySalt: options.cache?.cacheKeySalt,
1057
+ content: inputText
1058
+ });
1059
+ const cache = options.cache?.store ?? getDefaultCache();
1060
+ const cachedResult = await cache.get(cacheKey);
1061
+ if (cachedResult && cachedResult.status === "success") {
1062
+ if (options.onMetrics) options.onMetrics({
1063
+ provider: provider.name,
1064
+ model,
1065
+ inputTokens: estimateTokens(inputText),
1066
+ outputDimensions: getDimensions(cachedResult.aggregation === "all" ? cachedResult.vectors : cachedResult.vector),
1067
+ chunks: cachedResult.source.chunks,
1068
+ latencyMs: Date.now() - startTime,
1069
+ cached: true,
1070
+ retries: 0,
1071
+ piiRedacted
1072
+ });
1073
+ return {
1074
+ ...cachedResult,
1075
+ source: {
1076
+ ...cachedResult.source,
1077
+ cached: true
1078
+ }
1079
+ };
1080
+ }
1081
+ const chunks = chunkText(inputText, effectiveChunking);
1082
+ const callbackChunks = options.onChunk && options.safety?.allowSensitiveCallbacks ? chunkText(originalInput, effectiveChunking) : null;
1083
+ if (chunks.length === 0) return createSkippedResult("No content after chunking", { model });
1084
+ const sharedState = options.resilience?.state;
1085
+ const rateLimiter = sharedState?.rateLimiter ?? (options.resilience?.rateLimit ? new require_http_base.RateLimiter(options.resilience.rateLimit) : null);
1086
+ const circuitBreaker = sharedState?.circuitBreaker ?? (options.resilience?.circuitBreaker ? new require_http_base.CircuitBreaker(options.resilience.circuitBreaker) : null);
1087
+ const concurrency = options.resilience?.concurrency ?? 1;
1088
+ const semaphore = sharedState?.semaphore ?? new require_http_base.Semaphore(concurrency);
1089
+ const embeddings = [];
1090
+ let totalTokens = 0;
1091
+ let retryCount = 0;
1092
+ for (let i = 0; i < chunks.length; i++) {
1093
+ const chunk = chunks[i];
1094
+ if (!chunk) continue;
1095
+ if (rateLimiter) await rateLimiter.acquire();
1096
+ if (circuitBreaker?.isOpen()) return createSkippedResult("Circuit breaker is open", {
1097
+ model,
1098
+ chunks: i
1099
+ });
1100
+ await semaphore.execute(async () => {
1101
+ const { result: result$1 } = await require_http_base.withResilience(async (signal) => {
1102
+ return provider.embed([chunk.text], {
1103
+ model,
1104
+ dimensions: options.output?.dimensions,
1105
+ signal
1106
+ });
1107
+ }, options.resilience, {
1108
+ circuitBreaker: circuitBreaker ?? void 0,
1109
+ rateLimiter: void 0,
1110
+ semaphore: void 0
1111
+ }, { onRetry: () => {
1112
+ retryCount++;
1113
+ } });
1114
+ if (result$1.usage) totalTokens += result$1.usage.totalTokens;
1115
+ else totalTokens += chunk.tokens;
1116
+ const embedding = result$1.embeddings[0];
1117
+ if (embedding) {
1118
+ embeddings.push(embedding);
1119
+ if (options.onChunk) {
1120
+ const callbackText = callbackChunks?.[i]?.text ?? chunk.text;
1121
+ options.onChunk(callbackText, embedding);
1122
+ }
1123
+ }
1124
+ });
1125
+ }
1126
+ const aggregation = options.output?.aggregation ?? "average";
1127
+ const aggregated = aggregateVectors(embeddings, aggregation);
1128
+ const source = {
1129
+ model,
1130
+ chunks: chunks.length,
1131
+ tokens: totalTokens || estimateTokens(inputText),
1132
+ checksum: generateChecksum(inputText),
1133
+ cached: false,
1134
+ latencyMs: Date.now() - startTime
1135
+ };
1136
+ let result;
1137
+ if (aggregated.type === "single") result = {
1138
+ status: "success",
1139
+ aggregation,
1140
+ vector: aggregated.vector,
1141
+ source
1142
+ };
1143
+ else result = {
1144
+ status: "success",
1145
+ aggregation: "all",
1146
+ vectors: aggregated.vectors,
1147
+ source
1148
+ };
1149
+ await cache.set(cacheKey, result, { ttlMs: options.cache?.ttlMs });
1150
+ if (options.onMetrics) {
1151
+ const metrics = {
1152
+ provider: provider.name,
1153
+ model,
1154
+ inputTokens: source.tokens,
1155
+ outputDimensions: aggregated.dimensions,
1156
+ chunks: chunks.length,
1157
+ latencyMs: source.latencyMs,
1158
+ cached: false,
1159
+ retries: retryCount,
1160
+ piiRedacted
1161
+ };
1162
+ options.onMetrics(metrics);
1163
+ }
1164
+ return result;
1165
+ } catch (error) {
1166
+ const reason = error instanceof Error ? error.message : String(error);
1167
+ if (error instanceof require_http_base.ScrapeError && ["INVALID_URL", "BLOCKED"].includes(error.code)) throw error;
1168
+ return createSkippedResult(reason, { latencyMs: Date.now() - startTime });
1169
+ }
1170
+ }
1171
+ function applyMaxTokensToChunking(chunking, maxTokens) {
1172
+ if (!maxTokens || maxTokens <= 0) return chunking;
1173
+ const baseSize = chunking?.size ?? DEFAULT_CHUNK_SIZE;
1174
+ const baseOverlap = chunking?.overlap ?? 50;
1175
+ const clampedSize = Math.min(baseSize, maxTokens);
1176
+ const clampedOverlap = Math.min(baseOverlap, Math.max(0, clampedSize - 1));
1177
+ return {
1178
+ ...chunking,
1179
+ size: clampedSize,
1180
+ overlap: clampedOverlap
1181
+ };
1182
+ }
1183
+ /**
1184
+ * Embed arbitrary text directly.
1185
+ * Standalone function for embedding text outside of scrape().
1186
+ */
1187
+ async function embed(text, options) {
1188
+ return generateEmbeddings({ textContent: text }, {
1189
+ ...options,
1190
+ input: {
1191
+ ...options.input,
1192
+ type: "textContent"
1193
+ }
1194
+ });
1195
+ }
1196
+ /**
1197
+ * Embed from existing ScrapedData.
1198
+ * Useful when you've already scraped and want to add embeddings later.
1199
+ */
1200
+ async function embedScrapedData(data, options) {
1201
+ return generateEmbeddings(data, options);
1202
+ }
1203
+ /**
1204
+ * Create a skipped result with reason.
1205
+ */
1206
+ function createSkippedResult(reason, partialSource) {
1207
+ return {
1208
+ status: "skipped",
1209
+ reason,
1210
+ source: partialSource ?? {}
1211
+ };
1212
+ }
1213
+
1214
+ //#endregion
1215
+ Object.defineProperty(exports, 'HttpEmbeddingProvider', {
1216
+ enumerable: true,
1217
+ get: function () {
1218
+ return HttpEmbeddingProvider;
1219
+ }
1220
+ });
1221
+ Object.defineProperty(exports, 'InMemoryEmbeddingCache', {
1222
+ enumerable: true,
1223
+ get: function () {
1224
+ return InMemoryEmbeddingCache;
1225
+ }
1226
+ });
1227
+ Object.defineProperty(exports, 'TRANSFORMERS_MODELS', {
1228
+ enumerable: true,
1229
+ get: function () {
1230
+ return TRANSFORMERS_MODELS;
1231
+ }
1232
+ });
1233
+ Object.defineProperty(exports, 'aggregateVectors', {
1234
+ enumerable: true,
1235
+ get: function () {
1236
+ return aggregateVectors;
1237
+ }
1238
+ });
1239
+ Object.defineProperty(exports, 'chunkText', {
1240
+ enumerable: true,
1241
+ get: function () {
1242
+ return chunkText;
1243
+ }
1244
+ });
1245
+ Object.defineProperty(exports, 'containsPii', {
1246
+ enumerable: true,
1247
+ get: function () {
1248
+ return containsPii;
1249
+ }
1250
+ });
1251
+ Object.defineProperty(exports, 'cosineSimilarity', {
1252
+ enumerable: true,
1253
+ get: function () {
1254
+ return cosineSimilarity;
1255
+ }
1256
+ });
1257
+ Object.defineProperty(exports, 'createAzureEmbedding', {
1258
+ enumerable: true,
1259
+ get: function () {
1260
+ return createAzureEmbedding;
1261
+ }
1262
+ });
1263
+ Object.defineProperty(exports, 'createCohereEmbedding', {
1264
+ enumerable: true,
1265
+ get: function () {
1266
+ return createCohereEmbedding;
1267
+ }
1268
+ });
1269
+ Object.defineProperty(exports, 'createEmbeddingProvider', {
1270
+ enumerable: true,
1271
+ get: function () {
1272
+ return createEmbeddingProvider;
1273
+ }
1274
+ });
1275
+ Object.defineProperty(exports, 'createHttpEmbedding', {
1276
+ enumerable: true,
1277
+ get: function () {
1278
+ return createHttpEmbedding;
1279
+ }
1280
+ });
1281
+ Object.defineProperty(exports, 'createHuggingFaceEmbedding', {
1282
+ enumerable: true,
1283
+ get: function () {
1284
+ return createHuggingFaceEmbedding;
1285
+ }
1286
+ });
1287
+ Object.defineProperty(exports, 'createNoOpCache', {
1288
+ enumerable: true,
1289
+ get: function () {
1290
+ return createNoOpCache;
1291
+ }
1292
+ });
1293
+ Object.defineProperty(exports, 'createOllamaEmbedding', {
1294
+ enumerable: true,
1295
+ get: function () {
1296
+ return createOllamaEmbedding;
1297
+ }
1298
+ });
1299
+ Object.defineProperty(exports, 'createOpenAIEmbedding', {
1300
+ enumerable: true,
1301
+ get: function () {
1302
+ return createOpenAIEmbedding;
1303
+ }
1304
+ });
1305
+ Object.defineProperty(exports, 'createPiiRedactor', {
1306
+ enumerable: true,
1307
+ get: function () {
1308
+ return createPiiRedactor;
1309
+ }
1310
+ });
1311
+ Object.defineProperty(exports, 'createTokenizer', {
1312
+ enumerable: true,
1313
+ get: function () {
1314
+ return createTokenizer;
1315
+ }
1316
+ });
1317
+ Object.defineProperty(exports, 'createTransformersEmbedding', {
1318
+ enumerable: true,
1319
+ get: function () {
1320
+ return createTransformersEmbedding;
1321
+ }
1322
+ });
1323
+ Object.defineProperty(exports, 'dotProduct', {
1324
+ enumerable: true,
1325
+ get: function () {
1326
+ return dotProduct;
1327
+ }
1328
+ });
1329
+ Object.defineProperty(exports, 'embed', {
1330
+ enumerable: true,
1331
+ get: function () {
1332
+ return embed;
1333
+ }
1334
+ });
1335
+ Object.defineProperty(exports, 'embedScrapedData', {
1336
+ enumerable: true,
1337
+ get: function () {
1338
+ return embedScrapedData;
1339
+ }
1340
+ });
1341
+ Object.defineProperty(exports, 'estimateTokens', {
1342
+ enumerable: true,
1343
+ get: function () {
1344
+ return estimateTokens;
1345
+ }
1346
+ });
1347
+ Object.defineProperty(exports, 'euclideanDistance', {
1348
+ enumerable: true,
1349
+ get: function () {
1350
+ return euclideanDistance;
1351
+ }
1352
+ });
1353
+ Object.defineProperty(exports, 'generateCacheKey', {
1354
+ enumerable: true,
1355
+ get: function () {
1356
+ return generateCacheKey;
1357
+ }
1358
+ });
1359
+ Object.defineProperty(exports, 'generateChecksum', {
1360
+ enumerable: true,
1361
+ get: function () {
1362
+ return generateChecksum;
1363
+ }
1364
+ });
1365
+ Object.defineProperty(exports, 'generateEmbeddings', {
1366
+ enumerable: true,
1367
+ get: function () {
1368
+ return generateEmbeddings;
1369
+ }
1370
+ });
1371
+ Object.defineProperty(exports, 'getChunkingStats', {
1372
+ enumerable: true,
1373
+ get: function () {
1374
+ return getChunkingStats;
1375
+ }
1376
+ });
1377
+ Object.defineProperty(exports, 'getDefaultCache', {
1378
+ enumerable: true,
1379
+ get: function () {
1380
+ return getDefaultCache;
1381
+ }
1382
+ });
1383
+ Object.defineProperty(exports, 'getDefaultModel', {
1384
+ enumerable: true,
1385
+ get: function () {
1386
+ return getDefaultModel;
1387
+ }
1388
+ });
1389
+ Object.defineProperty(exports, 'getDimensions', {
1390
+ enumerable: true,
1391
+ get: function () {
1392
+ return getDimensions;
1393
+ }
1394
+ });
1395
+ Object.defineProperty(exports, 'heuristicTokenCount', {
1396
+ enumerable: true,
1397
+ get: function () {
1398
+ return heuristicTokenCount;
1399
+ }
1400
+ });
1401
+ Object.defineProperty(exports, 'isEmbeddingProvider', {
1402
+ enumerable: true,
1403
+ get: function () {
1404
+ return isEmbeddingProvider;
1405
+ }
1406
+ });
1407
+ Object.defineProperty(exports, 'needsChunking', {
1408
+ enumerable: true,
1409
+ get: function () {
1410
+ return needsChunking;
1411
+ }
1412
+ });
1413
+ Object.defineProperty(exports, 'normalizeVector', {
1414
+ enumerable: true,
1415
+ get: function () {
1416
+ return normalizeVector;
1417
+ }
1418
+ });
1419
+ Object.defineProperty(exports, 'previewInput', {
1420
+ enumerable: true,
1421
+ get: function () {
1422
+ return previewInput;
1423
+ }
1424
+ });
1425
+ Object.defineProperty(exports, 'redactPii', {
1426
+ enumerable: true,
1427
+ get: function () {
1428
+ return redactPii;
1429
+ }
1430
+ });
1431
+ Object.defineProperty(exports, 'resetDefaultCache', {
1432
+ enumerable: true,
1433
+ get: function () {
1434
+ return resetDefaultCache;
1435
+ }
1436
+ });
1437
+ Object.defineProperty(exports, 'selectInput', {
1438
+ enumerable: true,
1439
+ get: function () {
1440
+ return selectInput;
1441
+ }
1442
+ });
1443
+ Object.defineProperty(exports, 'validateCachedResult', {
1444
+ enumerable: true,
1445
+ get: function () {
1446
+ return validateCachedResult;
1447
+ }
1448
+ });
1449
+ Object.defineProperty(exports, 'validateInput', {
1450
+ enumerable: true,
1451
+ get: function () {
1452
+ return validateInput;
1453
+ }
1454
+ });
1455
+ //# sourceMappingURL=embeddings-BjNTQSG9.cjs.map