@fetchbrain.com/sdk 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,891 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+
3
+ // src/enhance.ts
4
+
5
+ // src/circuit-breaker.ts
6
+ var DEFAULT_CONFIG = {
7
+ failureThreshold: 3,
8
+ resetTimeout: 3e4,
9
+ // 30 seconds
10
+ successThreshold: 1
11
+ };
12
+ var CircuitBreaker = class {
13
+ constructor(config = {}, logger) {
14
+ this.state = "closed";
15
+ this.failures = 0;
16
+ this.successes = 0;
17
+ this.lastFailureTime = 0;
18
+ this.config = { ...DEFAULT_CONFIG, ...config };
19
+ this.logger = logger;
20
+ }
21
+ /**
22
+ * Check if requests should be allowed through
23
+ */
24
+ isOpen() {
25
+ if (this.state === "closed") {
26
+ return false;
27
+ }
28
+ if (this.state === "open") {
29
+ const now = Date.now();
30
+ if (now - this.lastFailureTime >= this.config.resetTimeout) {
31
+ this.logger.info("Circuit transitioning to half-open, testing API...");
32
+ this.state = "half-open";
33
+ this.successes = 0;
34
+ return false;
35
+ }
36
+ return true;
37
+ }
38
+ return false;
39
+ }
40
+ /**
41
+ * Record a successful API call
42
+ */
43
+ recordSuccess() {
44
+ if (this.state === "half-open") {
45
+ this.successes++;
46
+ if (this.successes >= this.config.successThreshold) {
47
+ this.logger.info("API recovered, circuit closed");
48
+ this.reset();
49
+ }
50
+ } else if (this.state === "closed") {
51
+ this.failures = 0;
52
+ }
53
+ }
54
+ /**
55
+ * Record a failed API call
56
+ */
57
+ recordFailure() {
58
+ this.failures++;
59
+ this.lastFailureTime = Date.now();
60
+ if (this.state === "half-open") {
61
+ this.logger.warn("API still failing, circuit reopened");
62
+ this.state = "open";
63
+ return;
64
+ }
65
+ if (this.failures >= this.config.failureThreshold) {
66
+ this.logger.warn(
67
+ `Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
68
+ );
69
+ this.state = "open";
70
+ }
71
+ }
72
+ /**
73
+ * Reset the circuit breaker to closed state
74
+ */
75
+ reset() {
76
+ this.state = "closed";
77
+ this.failures = 0;
78
+ this.successes = 0;
79
+ this.lastFailureTime = 0;
80
+ }
81
+ /**
82
+ * Get current circuit state
83
+ */
84
+ getState() {
85
+ return this.state;
86
+ }
87
+ /**
88
+ * Get statistics about the circuit breaker
89
+ */
90
+ getStats() {
91
+ return {
92
+ state: this.state,
93
+ failures: this.failures,
94
+ successes: this.successes
95
+ };
96
+ }
97
+ };
98
+
99
+ // src/batch.ts
100
+ var DEFAULT_CONFIG2 = {
101
+ maxSize: 50,
102
+ maxWait: 50
103
+ // 50ms
104
+ };
105
+ var RequestBatcher = class {
106
+ constructor(executor, config = {}, logger) {
107
+ this.queue = [];
108
+ this.flushTimeout = null;
109
+ this.executor = executor;
110
+ this.config = { ...DEFAULT_CONFIG2, ...config };
111
+ this.logger = logger;
112
+ }
113
+ /**
114
+ * Add a URL to the batch queue
115
+ */
116
+ async query(url) {
117
+ return new Promise((resolve, reject) => {
118
+ this.queue.push({ url, resolve, reject });
119
+ if (this.queue.length >= this.config.maxSize) {
120
+ this.flush();
121
+ return;
122
+ }
123
+ if (!this.flushTimeout) {
124
+ this.flushTimeout = setTimeout(() => {
125
+ this.flush();
126
+ }, this.config.maxWait);
127
+ }
128
+ });
129
+ }
130
+ /**
131
+ * Flush the current batch
132
+ */
133
+ async flush() {
134
+ if (this.flushTimeout) {
135
+ clearTimeout(this.flushTimeout);
136
+ this.flushTimeout = null;
137
+ }
138
+ if (this.queue.length === 0) {
139
+ return;
140
+ }
141
+ const batch = this.queue.splice(0, this.config.maxSize);
142
+ const urls = batch.map((r) => r.url);
143
+ this.logger.debug(`Flushing batch of ${urls.length} URLs`);
144
+ try {
145
+ const results = await this.executor(urls);
146
+ for (const request of batch) {
147
+ const result = results.get(request.url);
148
+ if (result) {
149
+ request.resolve(result);
150
+ } else {
151
+ request.resolve({ known: false });
152
+ }
153
+ }
154
+ } catch (error) {
155
+ for (const request of batch) {
156
+ request.reject(error);
157
+ }
158
+ }
159
+ if (this.queue.length > 0) {
160
+ this.flushTimeout = setTimeout(() => {
161
+ this.flush();
162
+ }, this.config.maxWait);
163
+ }
164
+ }
165
+ /**
166
+ * Get current queue size
167
+ */
168
+ getQueueSize() {
169
+ return this.queue.length;
170
+ }
171
+ /**
172
+ * Clear the queue (for cleanup)
173
+ */
174
+ clear() {
175
+ if (this.flushTimeout) {
176
+ clearTimeout(this.flushTimeout);
177
+ this.flushTimeout = null;
178
+ }
179
+ for (const request of this.queue) {
180
+ request.resolve({ known: false, fallback: true });
181
+ }
182
+ this.queue = [];
183
+ }
184
+ };
185
+
186
+ // src/logger.ts
187
+ var LOG_PREFIX = "[FetchBrain]";
188
+ var LOG_LEVELS = {
189
+ debug: 0,
190
+ info: 1,
191
+ warn: 2,
192
+ error: 3
193
+ };
194
+ function createLogger(minLevel = "info", enabled = true) {
195
+ const shouldLog = (level) => {
196
+ if (!enabled) return false;
197
+ return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
198
+ };
199
+ return {
200
+ debug: (message, ...args) => {
201
+ if (shouldLog("debug")) {
202
+ console.debug(`${LOG_PREFIX} ${message}`, ...args);
203
+ }
204
+ },
205
+ info: (message, ...args) => {
206
+ if (shouldLog("info")) {
207
+ console.info(`${LOG_PREFIX} ${message}`, ...args);
208
+ }
209
+ },
210
+ warn: (message, ...args) => {
211
+ if (shouldLog("warn")) {
212
+ console.warn(`${LOG_PREFIX} ${message}`, ...args);
213
+ }
214
+ },
215
+ error: (message, ...args) => {
216
+ if (shouldLog("error")) {
217
+ console.error(`${LOG_PREFIX} ${message}`, ...args);
218
+ }
219
+ }
220
+ };
221
+ }
222
+
223
+ // src/client.ts
224
+ var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
225
+ var DEFAULT_TIMEOUT = 500;
226
+ var currentContext = {};
227
+ function setScrapeContext(ctx) {
228
+ currentContext = ctx;
229
+ }
230
+ function clearScrapeContext() {
231
+ currentContext = {};
232
+ }
233
+ var FetchBrainClient = class {
234
+ constructor(config) {
235
+ this.config = {
236
+ apiKey: config.apiKey,
237
+ baseUrl: config.baseUrl || DEFAULT_BASE_URL,
238
+ intelligence: config.intelligence || "high",
239
+ learning: config.learning ?? true,
240
+ alwaysRun: config.alwaysRun ?? false,
241
+ strictBuildMatch: config.strictBuildMatch ?? false,
242
+ timeout: config.timeout || DEFAULT_TIMEOUT,
243
+ debug: config.debug || false,
244
+ extractForLearning: config.extractForLearning,
245
+ telemetry: config.telemetry ?? { enabled: true }
246
+ };
247
+ this.logger = createLogger(this.config.debug ? "debug" : "info", true);
248
+ this.circuitBreaker = new CircuitBreaker({}, this.logger);
249
+ this.batcher = new RequestBatcher(
250
+ (urls) => this.executeBatchQuery(urls),
251
+ {},
252
+ this.logger
253
+ );
254
+ }
255
+ /**
256
+ * Query if FetchBrain "knows" a URL
257
+ */
258
+ async query(url) {
259
+ if (this.circuitBreaker.isOpen()) {
260
+ this.logger.debug(`Circuit open, skipping query for: ${url}`);
261
+ return { known: false, fallback: true };
262
+ }
263
+ try {
264
+ return await this.batcher.query(url);
265
+ } catch (error) {
266
+ this.logger.debug(`Query failed for ${url}:`, error);
267
+ return { known: false, fallback: true };
268
+ }
269
+ }
270
+ /**
271
+ * Query multiple URLs at once (bypass batcher for bulk operations)
272
+ */
273
+ async queryBulk(urls) {
274
+ if (this.circuitBreaker.isOpen()) {
275
+ this.logger.debug(`Circuit open, skipping bulk query`);
276
+ return new Map(
277
+ urls.map((url) => [url, { known: false, fallback: true }])
278
+ );
279
+ }
280
+ try {
281
+ return await this.executeBatchQuery(urls);
282
+ } catch (error) {
283
+ this.logger.debug(`Bulk query failed:`, error);
284
+ return new Map(
285
+ urls.map((url) => [url, { known: false, fallback: true }])
286
+ );
287
+ }
288
+ }
289
+ /**
290
+ * "Teach" FetchBrain new data
291
+ */
292
+ async learn(url, data) {
293
+ if (!this.config.learning) {
294
+ return { status: "rejected", learned: 0 };
295
+ }
296
+ if (this.circuitBreaker.isOpen()) {
297
+ this.logger.debug(`Circuit open, skipping learn for: ${url}`);
298
+ return { status: "rejected", learned: 0 };
299
+ }
300
+ try {
301
+ const extractedData = this.config.extractForLearning ? this.config.extractForLearning(data) : data;
302
+ const response = await this.makeRequest("/v1/learn", {
303
+ method: "POST",
304
+ body: JSON.stringify({
305
+ entries: [{ url, data: extractedData }]
306
+ })
307
+ });
308
+ this.circuitBreaker.recordSuccess();
309
+ this.logger.debug(`Learned data for: ${url}`);
310
+ return response;
311
+ } catch (error) {
312
+ this.circuitBreaker.recordFailure();
313
+ this.logger.warn(`Learn failed for ${url}:`, error);
314
+ return { status: "rejected", learned: 0 };
315
+ }
316
+ }
317
+ /**
318
+ * Get usage statistics
319
+ */
320
+ async stats() {
321
+ if (this.circuitBreaker.isOpen()) {
322
+ return null;
323
+ }
324
+ try {
325
+ const response = await this.makeRequest("/v1/stats", {
326
+ method: "GET"
327
+ });
328
+ this.circuitBreaker.recordSuccess();
329
+ return response;
330
+ } catch (error) {
331
+ this.circuitBreaker.recordFailure();
332
+ this.logger.warn("Stats request failed:", error);
333
+ return null;
334
+ }
335
+ }
336
+ /**
337
+ * Execute a batch query against the API
338
+ */
339
+ async executeBatchQuery(urls) {
340
+ const results = /* @__PURE__ */ new Map();
341
+ const request = {
342
+ urls,
343
+ intelligence: this.config.intelligence
344
+ };
345
+ if (this.config.strictBuildMatch && process.env.APIFY_ACTOR_BUILD_ID) {
346
+ request.build = process.env.APIFY_ACTOR_BUILD_ID;
347
+ }
348
+ try {
349
+ const response = await this.makeRequest("/v1/query", {
350
+ method: "POST",
351
+ body: JSON.stringify(request)
352
+ });
353
+ this.circuitBreaker.recordSuccess();
354
+ for (const item of response.known) {
355
+ results.set(item.url, {
356
+ known: true,
357
+ data: item.data,
358
+ confidence: item.confidence
359
+ });
360
+ }
361
+ for (const url of response.unknown) {
362
+ results.set(url, { known: false });
363
+ }
364
+ return results;
365
+ } catch (error) {
366
+ this.circuitBreaker.recordFailure();
367
+ throw error;
368
+ }
369
+ }
370
+ /**
371
+ * Make an HTTP request to the API
372
+ */
373
+ async makeRequest(path, options) {
374
+ const url = `${this.config.baseUrl}${path}`;
375
+ const controller = new AbortController();
376
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
377
+ const contextHeaders = {
378
+ "X-FB-SDK": "js",
379
+ "X-FB-Node": process.version || "unknown",
380
+ "X-FB-Platform": process.platform || "unknown"
381
+ };
382
+ if (process.env.NODE_ENV) {
383
+ contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
384
+ }
385
+ if (process.env.APIFY_ACTOR_ID) {
386
+ contextHeaders["X-FB-Apify"] = process.env.APIFY_ACTOR_ID;
387
+ }
388
+ if (process.env.APIFY_ACTOR_BUILD_ID) {
389
+ contextHeaders["X-FB-Build"] = process.env.APIFY_ACTOR_BUILD_ID;
390
+ }
391
+ if (process.env.APIFY_ACTOR_RUN_ID) {
392
+ contextHeaders["X-FB-Apify-Run"] = process.env.APIFY_ACTOR_RUN_ID;
393
+ }
394
+ if (currentContext.crawler) {
395
+ contextHeaders["X-FB-Crawler"] = currentContext.crawler;
396
+ }
397
+ if (currentContext.label) {
398
+ contextHeaders["X-FB-Label"] = currentContext.label;
399
+ }
400
+ try {
401
+ const response = await fetch(url, {
402
+ ...options,
403
+ headers: {
404
+ Authorization: `Bearer ${this.config.apiKey}`,
405
+ "Content-Type": "application/json",
406
+ ...contextHeaders,
407
+ ...options.headers
408
+ },
409
+ signal: controller.signal
410
+ });
411
+ if (!response.ok) {
412
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
413
+ }
414
+ return await response.json();
415
+ } finally {
416
+ clearTimeout(timeoutId);
417
+ }
418
+ }
419
+ /**
420
+ * Get the current configuration
421
+ */
422
+ getConfig() {
423
+ return { ...this.config };
424
+ }
425
+ /**
426
+ * Get the circuit breaker state
427
+ */
428
+ getCircuitState() {
429
+ return this.circuitBreaker.getStats();
430
+ }
431
+ /**
432
+ * Reset the circuit breaker (for testing)
433
+ */
434
+ resetCircuit() {
435
+ this.circuitBreaker.reset();
436
+ }
437
+ /**
438
+ * Clear pending batched requests
439
+ */
440
+ clearBatch() {
441
+ this.batcher.clear();
442
+ }
443
+ /**
444
+ * Send telemetry data to the API
445
+ * This is fire-and-forget - failures are silently ignored
446
+ */
447
+ async sendTelemetry(entries) {
448
+ if (!this.config.telemetry?.enabled || entries.length === 0) {
449
+ return;
450
+ }
451
+ try {
452
+ await this.makeRequest("/v1/telemetry", {
453
+ method: "POST",
454
+ body: JSON.stringify({ entries })
455
+ });
456
+ } catch {
457
+ }
458
+ }
459
+ /**
460
+ * Check if telemetry is enabled
461
+ */
462
+ isTelemetryEnabled() {
463
+ return this.config.telemetry?.enabled ?? false;
464
+ }
465
+ /**
466
+ * Get telemetry config
467
+ */
468
+ getTelemetryConfig() {
469
+ return this.config.telemetry;
470
+ }
471
+ };
472
+
473
+ // src/telemetry.ts
474
+ async function hashString(str) {
475
+ const encoder = new TextEncoder();
476
+ const data = encoder.encode(str);
477
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
478
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
479
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
480
+ }
481
+ function extractDomain(url) {
482
+ try {
483
+ return new URL(url).hostname;
484
+ } catch {
485
+ return "unknown";
486
+ }
487
+ }
488
+ function generalizeUrlPath(url) {
489
+ try {
490
+ const parsed = new URL(url);
491
+ const path = parsed.pathname;
492
+ return path.replace(/\/\d+/g, "/*").replace(/\/[a-f0-9-]{36}/gi, "/*").replace(/\/[a-zA-Z0-9]{20,}/g, "/*").replace(/\?.*$/, "");
493
+ } catch {
494
+ return "/*";
495
+ }
496
+ }
497
+ function detectBlockType(statusCode, errorMessage) {
498
+ if (!statusCode && !errorMessage) return void 0;
499
+ if (statusCode === 403) return "403";
500
+ if (statusCode === 429) return "429";
501
+ if (statusCode === 503) return "503";
502
+ if (statusCode && statusCode >= 400) return `${statusCode}`;
503
+ const msg = errorMessage?.toLowerCase() || "";
504
+ if (msg.includes("captcha")) return "captcha";
505
+ if (msg.includes("timeout")) return "timeout";
506
+ if (msg.includes("blocked")) return "blocked";
507
+ if (msg.includes("rate limit")) return "429";
508
+ return void 0;
509
+ }
510
+ function extractProxyType(proxyUrl) {
511
+ if (!proxyUrl) return void 0;
512
+ const url = proxyUrl.toLowerCase();
513
+ if (url.includes("residential")) return "residential";
514
+ if (url.includes("mobile")) return "mobile";
515
+ if (url.includes("datacenter") || url.includes("dc")) return "datacenter";
516
+ if (url.includes("bright") || url.includes("oxylabs") || url.includes("smartproxy")) {
517
+ return "residential";
518
+ }
519
+ return "datacenter";
520
+ }
521
+ async function collectTelemetry(context, timing, config, error) {
522
+ if (!config?.enabled) {
523
+ return null;
524
+ }
525
+ const url = context.request.url;
526
+ const statusCode = context.response?.status || context.response?.statusCode;
527
+ const telemetry = {
528
+ domain: extractDomain(url),
529
+ urlHash: await hashString(url),
530
+ urlPattern: generalizeUrlPath(url),
531
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
532
+ };
533
+ if (config.sharePerformance !== false) {
534
+ telemetry.statusCode = statusCode;
535
+ telemetry.retryCount = context.request.retryCount;
536
+ if (timing) {
537
+ telemetry.responseTimeMs = timing.responseTime;
538
+ telemetry.totalTimeMs = timing.endTime && timing.startTime ? timing.endTime - timing.startTime : void 0;
539
+ telemetry.contentSize = timing.contentSize;
540
+ }
541
+ }
542
+ if (config.shareProxyInfo !== false && context.proxyInfo) {
543
+ telemetry.proxyCountry = context.proxyInfo.countryCode;
544
+ telemetry.proxyType = extractProxyType(context.proxyInfo.url);
545
+ telemetry.proxySuccess = statusCode ? statusCode < 400 : void 0;
546
+ }
547
+ if (config.shareSitePatterns !== false) {
548
+ const isBlocked = statusCode && (statusCode === 403 || statusCode === 429 || statusCode >= 500);
549
+ telemetry.blocked = isBlocked || !!error;
550
+ telemetry.blockType = detectBlockType(statusCode, error?.message);
551
+ }
552
+ if (context.session) {
553
+ telemetry.sessionAge = context.session.usageCount;
554
+ telemetry.sessionErrorScore = context.session.errorScore;
555
+ }
556
+ telemetry.crawlerType = context.crawler?.constructor?.name?.replace("Crawler", "").toLowerCase();
557
+ telemetry.requestLabel = context.request.label;
558
+ return telemetry;
559
+ }
560
+ var TelemetryBuffer = class {
561
+ constructor(options = {}) {
562
+ this.buffer = [];
563
+ this.maxSize = options.maxSize ?? 50;
564
+ this.flushInterval = options.flushInterval ?? 3e4;
565
+ this.flushCallback = options.onFlush;
566
+ this.startFlushTimer();
567
+ }
568
+ /**
569
+ * Add telemetry entry to buffer
570
+ */
571
+ add(entry) {
572
+ if (!entry) return;
573
+ this.buffer.push(entry);
574
+ if (this.buffer.length >= this.maxSize) {
575
+ this.flush();
576
+ }
577
+ }
578
+ /**
579
+ * Flush buffer and send telemetry
580
+ */
581
+ async flush() {
582
+ if (this.buffer.length === 0) return [];
583
+ const entries = [...this.buffer];
584
+ this.buffer = [];
585
+ if (this.flushCallback) {
586
+ try {
587
+ await this.flushCallback(entries);
588
+ } catch (err) {
589
+ console.debug("Telemetry flush failed:", err);
590
+ }
591
+ }
592
+ return entries;
593
+ }
594
+ /**
595
+ * Get current buffer size
596
+ */
597
+ get size() {
598
+ return this.buffer.length;
599
+ }
600
+ startFlushTimer() {
601
+ this.flushTimer = setInterval(() => {
602
+ this.flush();
603
+ }, this.flushInterval);
604
+ }
605
+ /**
606
+ * Stop the flush timer and flush remaining entries
607
+ */
608
+ async stop() {
609
+ if (this.flushTimer) {
610
+ clearInterval(this.flushTimer);
611
+ }
612
+ await this.flush();
613
+ }
614
+ };
615
+
616
+ // src/enhance.ts
617
+ var asyncContext = new AsyncLocalStorage();
618
+ function getCurrentContext() {
619
+ return asyncContext.getStore();
620
+ }
621
+ function shouldRunHandler(alwaysRun, label) {
622
+ if (alwaysRun === void 0 || alwaysRun === false) {
623
+ return false;
624
+ }
625
+ if (alwaysRun === true) {
626
+ return true;
627
+ }
628
+ const labels = Array.isArray(alwaysRun) ? alwaysRun : [alwaysRun];
629
+ const requestLabel = label || "default";
630
+ return labels.includes(requestLabel);
631
+ }
632
+ var requestContextMap = /* @__PURE__ */ new WeakMap();
633
+ var FetchBrain = class {
634
+ constructor(config) {
635
+ this.client = new FetchBrainClient(config);
636
+ this.logger = createLogger(config.debug ? "debug" : "info", true);
637
+ }
638
+ /**
639
+ * Query if FetchBrain "knows" a URL
640
+ */
641
+ async query(options) {
642
+ const result = await this.client.query(options.url);
643
+ return {
644
+ known: result.known,
645
+ data: result.data,
646
+ confidence: result.confidence
647
+ };
648
+ }
649
+ /**
650
+ * "Teach" FetchBrain new data
651
+ */
652
+ async learn(options) {
653
+ return this.client.learn(options.url, options.data);
654
+ }
655
+ /**
656
+ * Get usage statistics
657
+ */
658
+ async stats() {
659
+ return this.client.stats();
660
+ }
661
+ /**
662
+ * Enhance a Crawlee crawler with FetchBrain optimization
663
+ *
664
+ * This wraps the crawler's request handler to:
665
+ * 1. Query AI before making requests (AI knows = skip request)
666
+ * 2. Teach AI after successful requests (learning)
667
+ *
668
+ * @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
669
+ * @param config - FetchBrain configuration
670
+ * @returns Enhanced crawler with same interface
671
+ */
672
+ static enhance(crawler, config) {
673
+ const client = new FetchBrainClient(config);
674
+ const logger = createLogger(config.debug ? "debug" : "info", true);
675
+ const telemetryBuffer = new TelemetryBuffer({
676
+ maxSize: 50,
677
+ flushInterval: 3e4,
678
+ onFlush: async (entries) => {
679
+ if (config.telemetry?.enabled) {
680
+ await client.sendTelemetry(entries);
681
+ logger.debug(`Telemetry: sent ${entries.length} entries`);
682
+ }
683
+ }
684
+ });
685
+ const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
686
+ if (!originalHandler) {
687
+ logger.warn("No request handler found on crawler, returning unmodified");
688
+ return Object.assign(crawler, { fetchBrain: client });
689
+ }
690
+ const crawlerType = crawler.constructor?.name || "Unknown";
691
+ const wrappedHandler = async (context) => {
692
+ const { request } = context;
693
+ const url = request.url;
694
+ const label = request.label;
695
+ const startTime = Date.now();
696
+ setScrapeContext({
697
+ crawler: crawlerType,
698
+ label,
699
+ url
700
+ });
701
+ try {
702
+ const aiResult = await client.query(url);
703
+ let usedAIData = false;
704
+ const originalPushData = context.pushData;
705
+ context.ai = {
706
+ known: aiResult.known,
707
+ data: aiResult.data,
708
+ confidence: aiResult.confidence,
709
+ useAIData: async () => {
710
+ if (aiResult.known && aiResult.data && originalPushData) {
711
+ usedAIData = true;
712
+ await originalPushData.call(context, aiResult.data);
713
+ logger.info(
714
+ `Used AI data: ${url} (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
715
+ );
716
+ }
717
+ }
718
+ };
719
+ request.userData = {
720
+ ...request.userData,
721
+ fetchBrainKnown: aiResult.known,
722
+ fetchBrainData: aiResult.data
723
+ };
724
+ const handlerLabel = request.label;
725
+ const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
726
+ if (aiResult.known && aiResult.data && !runHandler) {
727
+ logger.info(
728
+ `Optimized: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
729
+ );
730
+ if (originalPushData) {
731
+ await originalPushData.call(context, aiResult.data);
732
+ }
733
+ return;
734
+ }
735
+ if (aiResult.known) {
736
+ logger.info(
737
+ `Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
738
+ );
739
+ } else {
740
+ logger.debug(`Learning: ${url}`);
741
+ }
742
+ requestContextMap.set(context, url);
743
+ if (originalPushData && config.learning !== false) {
744
+ context.pushData = async (data) => {
745
+ const shouldLearn = !usedAIData && !aiResult.known;
746
+ if (shouldLearn) {
747
+ const currentUrl = requestContextMap.get(context) || url;
748
+ await client.learn(currentUrl, data);
749
+ }
750
+ return originalPushData.call(context, data);
751
+ };
752
+ }
753
+ const requestContext = {
754
+ url,
755
+ client,
756
+ learning: config.learning !== false,
757
+ aiKnown: aiResult.known
758
+ };
759
+ await asyncContext.run(requestContext, async () => {
760
+ await originalHandler.call(crawler, context);
761
+ });
762
+ requestContextMap.delete(context);
763
+ if (config.telemetry?.enabled) {
764
+ try {
765
+ const telemetry = await collectTelemetry(
766
+ {
767
+ request: {
768
+ url,
769
+ retryCount: request.retryCount,
770
+ label,
771
+ userData: request.userData
772
+ },
773
+ response: {
774
+ statusCode: context.response?.statusCode || context.response?.status
775
+ },
776
+ proxyInfo: context.proxyInfo ? {
777
+ url: context.proxyInfo.url,
778
+ hostname: context.proxyInfo.hostname,
779
+ countryCode: context.proxyInfo.countryCode
780
+ } : void 0,
781
+ session: context.session ? {
782
+ errorScore: context.session.errorScore,
783
+ usageCount: context.session.usageCount
784
+ } : void 0,
785
+ crawler: {
786
+ constructor: { name: crawlerType }
787
+ }
788
+ },
789
+ {
790
+ startTime,
791
+ endTime: Date.now(),
792
+ responseTime: Date.now() - startTime,
793
+ contentSize: context.response?.body?.length
794
+ },
795
+ config.telemetry
796
+ );
797
+ if (telemetry) {
798
+ telemetryBuffer.add(telemetry);
799
+ }
800
+ } catch (err) {
801
+ logger.debug(`Telemetry collection error: ${err}`);
802
+ }
803
+ }
804
+ } catch (err) {
805
+ if (config.telemetry?.enabled) {
806
+ try {
807
+ const telemetry = await collectTelemetry(
808
+ {
809
+ request: {
810
+ url,
811
+ retryCount: request.retryCount,
812
+ label
813
+ },
814
+ crawler: {
815
+ constructor: { name: crawlerType }
816
+ }
817
+ },
818
+ {
819
+ startTime,
820
+ endTime: Date.now(),
821
+ responseTime: Date.now() - startTime
822
+ },
823
+ config.telemetry,
824
+ err instanceof Error ? err : new Error(String(err))
825
+ );
826
+ if (telemetry) {
827
+ telemetryBuffer.add(telemetry);
828
+ }
829
+ } catch {
830
+ }
831
+ }
832
+ throw err;
833
+ } finally {
834
+ clearScrapeContext();
835
+ }
836
+ };
837
+ const crawlerAny = crawler;
838
+ if ("requestHandler" in crawlerAny) {
839
+ crawlerAny.requestHandler = wrappedHandler;
840
+ }
841
+ if ("userDefinedRequestHandler" in crawlerAny) {
842
+ crawlerAny.userDefinedRequestHandler = wrappedHandler;
843
+ }
844
+ if (typeof crawlerAny.run === "function") {
845
+ const originalRun = crawlerAny.run.bind(crawlerAny);
846
+ crawlerAny.run = async (...args) => {
847
+ try {
848
+ const result = await originalRun(...args);
849
+ return result;
850
+ } finally {
851
+ if (config.telemetry?.enabled) {
852
+ logger.debug("Telemetry: flushing on crawl complete");
853
+ await telemetryBuffer.stop();
854
+ }
855
+ }
856
+ };
857
+ }
858
+ return Object.assign(crawler, { fetchBrain: client });
859
+ }
860
+ };
861
+ function createFetchBrain(config) {
862
+ return new FetchBrain(config);
863
+ }
864
+ async function pushData(data, dataset, datasetName) {
865
+ const ctx = getCurrentContext();
866
+ if (ctx && ctx.learning && !ctx.aiKnown) {
867
+ const items = Array.isArray(data) ? data : [data];
868
+ for (const item of items) {
869
+ await ctx.client.learn(ctx.url, item);
870
+ }
871
+ }
872
+ if (datasetName && dataset.open) {
873
+ const namedDataset = await dataset.open(datasetName);
874
+ await namedDataset.pushData(data);
875
+ } else {
876
+ await dataset.pushData(data);
877
+ }
878
+ }
879
+
880
+ // src/types.ts
881
+ var AIMemoryDepth = /* @__PURE__ */ ((AIMemoryDepth2) => {
882
+ AIMemoryDepth2[AIMemoryDepth2["REALTIME"] = 1] = "REALTIME";
883
+ AIMemoryDepth2[AIMemoryDepth2["HIGH"] = 2] = "HIGH";
884
+ AIMemoryDepth2[AIMemoryDepth2["STANDARD"] = 3] = "STANDARD";
885
+ AIMemoryDepth2[AIMemoryDepth2["DEEP"] = 4] = "DEEP";
886
+ return AIMemoryDepth2;
887
+ })(AIMemoryDepth || {});
888
+
889
+ export { AIMemoryDepth, CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
890
+ //# sourceMappingURL=index.mjs.map
891
+ //# sourceMappingURL=index.mjs.map