@fetchbrain.com/sdk 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { R as RawRequest, a as RecallResult, b as LearnResponse, S as StatsResponse, A as AskResponse, F as FetchBrainConfig } from '../types-BgqTjfAN.js';
1
+ import { R as RawRequest, a as RecallResult, b as LearnResponse, S as StatsResponse, A as AskResponse, F as FetchBrainConfig } from '../types-Cfr8odPb.js';
2
2
 
3
3
  /**
4
4
  * Mock FetchBrain for unit testing
@@ -1,8 +1,58 @@
1
+ interface PatternStats {
2
+ label: string;
3
+ requests: number;
4
+ scraped: number;
5
+ blocked: number;
6
+ failed: number;
7
+ navP95?: number;
8
+ }
9
+ type PropStats = {
10
+ kind: 's';
11
+ top: Record<string, number>;
12
+ other?: number;
13
+ } | {
14
+ kind: 'n';
15
+ sum: number;
16
+ min: number;
17
+ max: number;
18
+ } | {
19
+ kind: 'b';
20
+ true: number;
21
+ false: number;
22
+ };
23
+ interface CustomStats {
24
+ count: number;
25
+ labels: Record<string, number>;
26
+ props: Record<string, PropStats>;
27
+ }
28
+
29
+ interface LabelStats {
30
+ requests: number;
31
+ scraped: number;
32
+ recalled: number;
33
+ skipped: number;
34
+ bypassed: number;
35
+ failed: number;
36
+ blocked: number;
37
+ blockedAttempts: number;
38
+ retries: number;
39
+ records: number;
40
+ bytes: number;
41
+ navP50?: number;
42
+ navP95?: number;
43
+ handlerP95?: number;
44
+ enqueued: Record<string, number>;
45
+ alreadyQueued: Record<string, number>;
46
+ /** Final status code → count, ≤20 codes, the rest under "other". */
47
+ status: Record<string, number>;
48
+ }
49
+
1
50
  /**
2
51
  * FetchBrain SDK Types
3
52
  *
4
53
  * Type definitions for the FetchBrain SDK — memory for your scrapers.
5
54
  */
55
+
6
56
  /** How far back the brain recalls: fresh=1h, recent=24h, standard=7d, deep=30d */
7
57
  type MemoryDepth = "fresh" | "recent" | "standard" | "deep";
8
58
  /** Options for change detection. */
@@ -49,6 +99,14 @@ interface RunReport {
49
99
  /** Pages handled outside FetchBrain (`skipLabels`). Per run() call. */
50
100
  bypassed?: number;
51
101
  labels?: Record<string, RunLabelCounts>;
102
+ /** Salted buyer hash (same as on analytics events). Omitted without a user id and account salt. */
103
+ client?: string;
104
+ /** Present only when analytics ran for this run. */
105
+ analytics?: {
106
+ labels: Record<string, LabelStats>;
107
+ patterns: Record<string, PatternStats>;
108
+ custom: Record<string, CustomStats>;
109
+ };
52
110
  }
53
111
  /** Change counts accumulated by a client, once per learn HTTP batch. */
54
112
  interface ChangeStats {
@@ -56,11 +114,21 @@ interface ChangeStats {
56
114
  unchanged: number;
57
115
  firstSeen: number;
58
116
  drift: DriftItem[];
117
+ /** recall:false: learned pages memory already knew. Optional for older snapshots. */
118
+ known?: number;
59
119
  }
60
120
  /** Configuration for FetchBrain SDK */
61
121
  interface FetchBrainConfig {
62
122
  /** API key for authentication */
63
123
  apiKey: string;
124
+ /**
125
+ * Recall known pages and skip their fetches (default: true). With `false`
126
+ * FetchBrain never recalls or skips: every page is fetched, handled and learned
127
+ * (sent with `observe: true` and your `memory` depth), and the run summary shows
128
+ * how many fetches recall would have skipped. `alwaysRun` and `preRecall` have no
129
+ * effect. Independent of `learning`.
130
+ */
131
+ recall?: boolean;
64
132
  /**
65
133
  * Name this scraper so it gets its own memory (otherwise every scraper on
66
134
  * your account outside Apify shares one default memory). Same as setting the
@@ -81,7 +149,7 @@ interface FetchBrainConfig {
81
149
  * came back empty or failed. It contains exactly: the run id, start and end
82
150
  * timestamps, scraped/learned/recalled counts, per-label page counts
83
151
  * (scraped/empty/failed), and the build id only with `refreshOnRebuild`.
84
- * No URLs or data. Default: true. Set false to disable. Separate from telemetry.
152
+ * No URLs or data. Default: true. Set false to disable.
85
153
  */
86
154
  reportRuns?: boolean;
87
155
  /** Base URL for API (defaults to production) */
@@ -106,8 +174,7 @@ interface FetchBrainConfig {
106
174
  * never be remembered: unlike `alwaysRun` (which still recalls + can learn), these skip the
107
175
  * recall network round-trip and the learn write altogether, removing per-request overhead for
108
176
  * requests whose data is not worth remembering. Matches the request `label` (unlabeled = "default").
109
- * A label listed in both `skipLabels` and `alwaysRun` is bypassed. Bypassed requests are also
110
- * excluded from telemetry.
177
+ * A label listed in both `skipLabels` and `alwaysRun` is bypassed.
111
178
  */
112
179
  skipLabels?: string[];
113
180
  /**
@@ -189,12 +256,18 @@ interface FetchBrainConfig {
189
256
  * Circuit breaker configuration for stability
190
257
  */
191
258
  circuitBreaker?: Partial<CircuitBreakerConfig>;
192
- /**
193
- * Telemetry configuration — opt-in, pseudonymous (sent with your API key).
194
- * Helps improve proxy recommendations, detect blocks, optimize configs.
195
- * Default: disabled. See the README "Telemetry (opt-in)" section for every field sent.
196
- */
197
- telemetry?: TelemetryConfig;
259
+ /** Scraper analytics. Off by default. */
260
+ analytics?: AnalyticsConfig;
261
+ }
262
+ /** Scraper analytics options. */
263
+ interface AnalyticsConfig {
264
+ enabled: boolean;
265
+ /** Up to 3 keys attached to each event for this request (values ≤64 characters). */
266
+ context?: (request: {
267
+ url: string;
268
+ label?: string;
269
+ userData: Record<string, unknown>;
270
+ }) => Record<string, unknown>;
198
271
  }
199
272
  /**
200
273
  * What one remembered request holds: the record the page pushed, or every
@@ -256,6 +329,10 @@ interface LearnRequest {
256
329
  }[];
257
330
  build?: string;
258
331
  ignore?: string[];
332
+ /** recall:false: learn without the hot recall copy; the response reports `known`. */
333
+ observe?: boolean;
334
+ /** Memory depth `known` is judged against (recall:false). */
335
+ memory?: MemoryDepth;
259
336
  }
260
337
  /** Learn response from the API */
261
338
  interface LearnResponse {
@@ -267,6 +344,8 @@ interface LearnResponse {
267
344
  firstSeen?: number;
268
345
  changedByLabel?: Record<string, number>;
269
346
  drift?: DriftItem[];
347
+ /** recall:false: entries memory already knew (fetches recall would have skipped). */
348
+ known?: number;
270
349
  }
271
350
  /** Stats response from the API */
272
351
  interface StatsResponse {
@@ -339,58 +418,5 @@ interface Logger {
339
418
  warn: (message: string, ...args: unknown[]) => void;
340
419
  error: (message: string, ...args: unknown[]) => void;
341
420
  }
342
- /**
343
- * Telemetry configuration — opt-in, pseudonymous diagnostics sent with your API key.
344
- * When enabled, each sub-flag defaults to true.
345
- */
346
- interface TelemetryConfig {
347
- /** Enable telemetry collection (default: false — opt-in) */
348
- enabled: boolean;
349
- /** Share performance metrics: timings, retries, status codes, content size (default: true) */
350
- sharePerformance?: boolean;
351
- /** Share proxy info: country, locally-derived type, success (never proxy URL/IP) (default: true) */
352
- shareProxyInfo?: boolean;
353
- /** Share block indicators derived from status codes and error categories (default: true) */
354
- shareSitePatterns?: boolean;
355
- }
356
- /**
357
- * Telemetry data collected from Crawlee context.
358
- * No raw URLs, bodies, proxy URLs/IPs or error messages. The hostname, generalized
359
- * path and request label are sent as-is, linked to your API key.
360
- */
361
- interface TelemetryData {
362
- domain: string;
363
- urlHash: string;
364
- urlPattern?: string;
365
- responseTimeMs?: number;
366
- totalTimeMs?: number;
367
- statusCode?: number;
368
- contentSize?: number;
369
- retryCount?: number;
370
- proxyCountry?: string;
371
- proxyType?: string;
372
- proxySuccess?: boolean;
373
- sessionAge?: number;
374
- sessionErrorScore?: number;
375
- cookieCount?: number;
376
- blocked?: boolean;
377
- blockType?: string;
378
- crawlerType?: string;
379
- requestLabel?: string;
380
- timestamp: string;
381
- }
382
- /**
383
- * Telemetry request to the API
384
- */
385
- interface TelemetryRequest {
386
- entries: TelemetryData[];
387
- }
388
- /**
389
- * Telemetry response from the API
390
- */
391
- interface TelemetryResponse {
392
- received: number;
393
- status: "success" | "partial" | "error";
394
- }
395
421
 
396
- export type { AskResponse as A, BatchConfig as B, ChangeStats as C, DriftItem as D, FetchBrainConfig as F, LearnedData as L, MemoryDepth as M, RawRequest as R, StatsResponse as S, TelemetryData as T, RecallResult as a, LearnResponse as b, RunReport as c, RunFlag as d, CircuitState as e, TelemetryConfig as f, CircuitBreakerConfig as g, Logger as h, LogLevel as i, RecallRequest as j, RecallResponse as k, RecallResultItem as l, LearnRequest as m, RecalledEvent as n, LogUrlRequest as o, ChangeDetectionConfig as p, TelemetryRequest as q, TelemetryResponse as r };
422
+ export type { AskResponse as A, BatchConfig as B, ChangeStats as C, DriftItem as D, FetchBrainConfig as F, LearnedData as L, MemoryDepth as M, RawRequest as R, StatsResponse as S, RecallResult as a, LearnResponse as b, RunReport as c, RunFlag as d, CircuitState as e, CircuitBreakerConfig as f, Logger as g, LogLevel as h, AnalyticsConfig as i, RecallRequest as j, RecallResponse as k, RecallResultItem as l, LearnRequest as m, RecalledEvent as n, LogUrlRequest as o, ChangeDetectionConfig as p };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fetchbrain.com/sdk",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "FetchBrain SDK — make your Crawlee scrapers smarter with every run; recall before you fetch, teach what you learn.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -22,7 +22,7 @@
22
22
  "dist"
23
23
  ],
24
24
  "scripts": {
25
- "build": "tsup",
25
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
26
26
  "dev": "tsup --watch",
27
27
  "test": "vitest run",
28
28
  "test:watch": "vitest",
@@ -31,7 +31,9 @@
31
31
  "typecheck": "tsc --noEmit",
32
32
  "prepublishOnly": "npm run build",
33
33
  "mock-server": "tsx src/mock/server.ts",
34
- "prepare": "husky"
34
+ "prepare": "husky",
35
+ "bench:analytics": "tsx bench/analytics-bench.ts",
36
+ "size:analytics": "npm run build && node scripts/check-analytics-size.mjs"
35
37
  },
36
38
  "keywords": [
37
39
  "scraping",
package/dist/index.d.mts DELETED
@@ -1,449 +0,0 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-BgqTjfAN.mjs';
2
- export { p as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, o as LogUrlRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, q as TelemetryRequest, r as TelemetryResponse } from './types-BgqTjfAN.mjs';
3
-
4
- declare class FetchBrainClient {
5
- private config;
6
- private circuitBreaker;
7
- /**
8
- * ask() has its own breaker: slow or failing asks must not pause recall/learn,
9
- * and an open recall breaker must not block ask.
10
- */
11
- private askCircuitBreaker;
12
- private batcher;
13
- private learnBatcher;
14
- private logger;
15
- /**
16
- * Epoch ms until which learns are paused after the API reported the monthly
17
- * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
18
- */
19
- private learnPausedUntil;
20
- /**
21
- * Set by a 401 (key invalid or revoked): calls answer locally until then
22
- * instead of each paying a failing round-trip. A pause, not a permanent stop:
23
- * a key used right after it is created can see a brief 401 while the key
24
- * propagates, and that must not switch FetchBrain off for a whole run.
25
- */
26
- private keyRejectedUntil;
27
- private keyRejectedWarned;
28
- /** The oversized-page warning is shown once per client, then logged at debug. */
29
- private warnedOversizeLearn;
30
- /** Warn about the learn cap once per pause, independent of the pause state. */
31
- private learnCapWarnedUntil;
32
- /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
33
- private scraperName;
34
- /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
35
- private changeStats;
36
- constructor(config: FetchBrainConfig);
37
- /** True when recalls must not reach the API right now (crawl continues without). */
38
- private recallBlocked;
39
- private isKeyRejected;
40
- /**
41
- * React to a 4xx the API returned. These are not outages (they don't open the
42
- * shared breaker). A 401 means the next calls would fail the same way, so all
43
- * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
44
- * pause recalls locally: a locally refused handler-time recall fails a
45
- * fetch-skipped request, whereas the API's own answer can still succeed.)
46
- */
47
- private noteRefusal;
48
- /**
49
- * Recall if FetchBrain "knows" a request
50
- */
51
- recall(request: RawRequest): Promise<RecallResult>;
52
- /**
53
- * Recall multiple requests at once — returns ordered array matching input order.
54
- * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
55
- * failed chunk degrades to fallback results for its own items only.
56
- */
57
- recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
58
- /**
59
- * "Teach" FetchBrain new data (batched for high-concurrency)
60
- */
61
- learn(request: RawRequest, data: LearnedData): Promise<LearnResponse>;
62
- /**
63
- * Get usage statistics
64
- */
65
- stats(): Promise<StatsResponse | null>;
66
- /**
67
- * Ask a natural-language question, answered from everything the account has learned
68
- *
69
- * `model` picks the generation model for answer mode from the server's
70
- * menu (e.g. "llama-3.3-70b", "glm-5.3" — larger models use more Ask
71
- * credits), or "byok" to answer with your own linked provider model.
72
- * Omit it for the default model.
73
- *
74
- * `timeout` (ms, 1-2147483647) overrides the `askTimeout` option for this call;
75
- * an invalid value falls back to `askTimeout`.
76
- */
77
- ask(question: string, opts?: {
78
- answer?: boolean;
79
- limit?: number;
80
- model?: string;
81
- timeout?: number;
82
- }): Promise<AskResponse>;
83
- /**
84
- * Execute a batch query against the API
85
- */
86
- private executeBatchQuery;
87
- /** Apply the user's extractForLearning hook to each learned record. */
88
- private extractForLearning;
89
- /**
90
- * Execute a batch learn against the API
91
- */
92
- private executeBatchLearn;
93
- /**
94
- * POST one learn batch, retrying once after a jittered wait on a timeout,
95
- * network error or 5xx. Learns run off the crawl's hot path, so a short
96
- * stall is not an outage: in the 2026-11-28 load test one storage shard
97
- * paused for ~5 s, the ~3 learns a run keeps in flight all timed out
98
- * together, and that opened the breaker shared with recall. Only a batch
99
- * that fails twice reaches executeBatchLearn's breaker accounting.
100
- */
101
- private sendLearnWithRetry;
102
- /** Fold one batch response into the change totals (called once per HTTP batch). */
103
- private accumulateChanges;
104
- /** Change counts so far (a copy). */
105
- getChangeStats(): ChangeStats;
106
- /**
107
- * Send the end-of-run report. Counts and labels only. Never throws: on
108
- * failure or timeout it returns no flags.
109
- */
110
- reportRun(report: RunReport, timeoutMs?: number): Promise<RunFlag[]>;
111
- /**
112
- * Make an HTTP request to the API
113
- */
114
- private makeRequest;
115
- /**
116
- * Get the current configuration
117
- */
118
- getConfig(): FetchBrainConfig;
119
- /**
120
- * Get the circuit breaker state
121
- */
122
- getCircuitState(): {
123
- state: CircuitState;
124
- failures: number;
125
- successes: number;
126
- };
127
- /**
128
- * Reset the circuit breaker (for testing)
129
- */
130
- resetCircuit(): void;
131
- /**
132
- * Clear pending batched requests
133
- */
134
- clearBatch(): void;
135
- /**
136
- * Flush pending learn requests (call before shutdown)
137
- */
138
- /**
139
- * Wait (at most `timeoutMs`) until the background learn backlog has room.
140
- * Lets the crawler slow to the API's pace instead of queueing without limit.
141
- */
142
- waitForLearnRoom(timeoutMs: number): Promise<boolean>;
143
- flushLearnBatch(): Promise<void>;
144
- /**
145
- * Send telemetry data to the API
146
- * This is fire-and-forget - failures are silently ignored
147
- */
148
- sendTelemetry(entries: TelemetryData[]): Promise<void>;
149
- /**
150
- * Check if telemetry is enabled
151
- */
152
- isTelemetryEnabled(): boolean;
153
- /**
154
- * Get telemetry config
155
- */
156
- getTelemetryConfig(): TelemetryConfig;
157
- }
158
-
159
- /**
160
- * Async context for tracking current request
161
- * This allows Dataset.pushData interception even when called statically
162
- */
163
- interface RequestContext {
164
- request: RawRequest;
165
- client: FetchBrainClient;
166
- learning: boolean;
167
- aiKnown: boolean;
168
- /** Known page re-scraped with change detection on: its items are relearned. */
169
- relearn: boolean;
170
- /** Items this request pushed; learned together once the handler succeeds. */
171
- items: Record<string, unknown>[];
172
- }
173
- /**
174
- * Get the current request context (used by pushData wrapper)
175
- */
176
- declare function getCurrentContext(): RequestContext | undefined;
177
- /**
178
- * Brain context available in request handler
179
- */
180
- interface FetchBrainContext {
181
- /** Whether the brain knows this URL */
182
- known: boolean;
183
- /** Brain data if known */
184
- data?: LearnedData;
185
- /** Use brain data and skip scraping (call in handler to early return) */
186
- use: () => Promise<void>;
187
- }
188
- /**
189
- * FetchBrain main class
190
- *
191
- * Provides the static enhance() method to wrap Crawlee crawlers
192
- * with brain recall and learning
193
- */
194
- declare class FetchBrain {
195
- private client;
196
- private logger;
197
- constructor(config: FetchBrainConfig);
198
- /**
199
- * Recall whether FetchBrain "knows" a URL
200
- */
201
- recall(options: {
202
- url: string;
203
- memory?: string;
204
- }): Promise<{
205
- known: boolean;
206
- data: LearnedData | undefined;
207
- }>;
208
- /**
209
- * "Teach" FetchBrain new data
210
- */
211
- learn(options: {
212
- url: string;
213
- data: Record<string, unknown>;
214
- }): Promise<LearnResponse>;
215
- /**
216
- * Get usage statistics
217
- */
218
- stats(): Promise<StatsResponse | null>;
219
- /**
220
- * Enhance a Crawlee crawler with FetchBrain optimization
221
- *
222
- * This wraps the crawler's request handler to:
223
- * 1. Recall the brain before making requests (brain knows = skip request)
224
- * 2. Teach the brain after successful requests (learning)
225
- *
226
- * @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
227
- * @param config - FetchBrain configuration
228
- * @returns Enhanced crawler with same interface
229
- */
230
- static enhance<T>(crawler: T, config: FetchBrainConfig): T & {
231
- fetchBrain: FetchBrainClient;
232
- };
233
- }
234
- /**
235
- * Create a standalone FetchBrain client without crawler enhancement
236
- */
237
- declare function createFetchBrain(config: FetchBrainConfig): FetchBrain;
238
- /**
239
- * Dataset interface for pushData wrapper
240
- */
241
- interface DatasetLike {
242
- pushData: (data: Record<string, unknown> | Record<string, unknown>[]) => Promise<void>;
243
- open?: (name?: string | null) => Promise<DatasetLike>;
244
- }
245
- /**
246
- * Learning-aware pushData wrapper
247
- *
248
- * Use this instead of Dataset.pushData() so the brain learns from what you push.
249
- * Works with both static Dataset class and dataset instances.
250
- *
251
- * @example
252
- * ```typescript
253
- * import { Dataset } from 'crawlee';
254
- * import { pushData } from '@fetchbrain.com/sdk';
255
- *
256
- * // Default dataset:
257
- * await pushData(data, Dataset);
258
- *
259
- * // Named dataset (opens automatically):
260
- * await pushData(data, Dataset, 'products');
261
- *
262
- * // Pre-opened dataset instance:
263
- * const myDataset = await Dataset.open('products');
264
- * await pushData(data, myDataset);
265
- * ```
266
- */
267
- declare function pushData(data: Record<string, unknown> | Record<string, unknown>[], dataset: DatasetLike, datasetName?: string): Promise<void>;
268
-
269
- /**
270
- * Circuit Breaker Pattern Implementation
271
- *
272
- * Protects scrapers from API failures:
273
- * - CLOSED: Normal operation, requests pass through
274
- * - OPEN: API failing, skip all requests (scraper continues normally)
275
- * - HALF-OPEN: Testing if API recovered
276
- */
277
- declare class CircuitBreaker {
278
- private state;
279
- private failures;
280
- private successes;
281
- private lastFailureTime;
282
- private config;
283
- private logger;
284
- private name?;
285
- /**
286
- * `name` labels this breaker's log lines when a client runs more than one
287
- * (the ask breaker opening must not read as if recall and learn stopped).
288
- */
289
- constructor(config: Partial<CircuitBreakerConfig> | undefined, logger: Logger, name?: string);
290
- private label;
291
- /**
292
- * Check if requests should be allowed through
293
- */
294
- isOpen(): boolean;
295
- /**
296
- * Record a successful API call
297
- */
298
- recordSuccess(): void;
299
- /**
300
- * Record a failed API call
301
- */
302
- recordFailure(): void;
303
- /**
304
- * Reset the circuit breaker to closed state
305
- */
306
- reset(): void;
307
- /**
308
- * Get current circuit state
309
- */
310
- getState(): CircuitState;
311
- /**
312
- * Get statistics about the circuit breaker
313
- */
314
- getStats(): {
315
- state: CircuitState;
316
- failures: number;
317
- successes: number;
318
- };
319
- }
320
-
321
- type BatchExecutor = (items: {
322
- ref: string;
323
- request: RawRequest;
324
- }[]) => Promise<Map<string, RecallResult>>;
325
- /**
326
- * Request Batcher
327
- *
328
- * Batches individual URL queries into bulk API calls to reduce connections.
329
- * Important for high-concurrency scrapers (50-100+ concurrent requests).
330
- */
331
- declare class RequestBatcher {
332
- private queue;
333
- private flushTimeout;
334
- private config;
335
- private executor;
336
- private logger;
337
- private refSeq;
338
- constructor(executor: BatchExecutor, config: Partial<BatchConfig> | undefined, logger: Logger);
339
- /**
340
- * Add a request to the batch queue
341
- */
342
- query(request: RawRequest): Promise<RecallResult>;
343
- /**
344
- * Flush the current batch
345
- */
346
- private flush;
347
- /**
348
- * Get current queue size
349
- */
350
- getQueueSize(): number;
351
- /**
352
- * Clear the queue (for cleanup)
353
- */
354
- clear(): void;
355
- }
356
-
357
- /**
358
- * Creates a logger with the specified minimum level
359
- * Matches Crawlee log style: "INFO FetchBrain: message"
360
- */
361
- declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
362
-
363
- /**
364
- * Telemetry Collection Module
365
- *
366
- * Collects opt-in, pseudonymous performance and behavior data from Crawlee contexts
367
- * (sent with the API key, so linked to the account). Raw URLs, bodies, proxy URLs/IPs
368
- * and error messages are not collected; hostname, path pattern and label are.
369
- */
370
-
371
- /**
372
- * Crawlee-like context interface (subset of what we need)
373
- * This allows the telemetry to work with any Crawlee crawler type
374
- */
375
- interface CrawleeContext {
376
- request: {
377
- url: string;
378
- retryCount?: number;
379
- label?: string;
380
- userData?: Record<string, unknown>;
381
- };
382
- response?: {
383
- status?: number;
384
- statusCode?: number;
385
- headers?: Record<string, string> | Headers;
386
- };
387
- proxyInfo?: {
388
- url?: string;
389
- hostname?: string;
390
- countryCode?: string;
391
- };
392
- session?: {
393
- errorScore?: number;
394
- usageCount?: number;
395
- };
396
- crawler?: {
397
- constructor?: {
398
- name?: string;
399
- };
400
- };
401
- }
402
- /**
403
- * Additional timing info that can be passed separately
404
- */
405
- interface RequestTiming {
406
- startTime?: number;
407
- endTime?: number;
408
- responseTime?: number;
409
- contentSize?: number;
410
- }
411
- /**
412
- * Collect telemetry from a Crawlee context
413
- * Returns sanitized data safe for transmission
414
- */
415
- declare function collectTelemetry(context: CrawleeContext, timing?: RequestTiming, config?: TelemetryConfig, error?: Error): Promise<TelemetryData | null>;
416
- /**
417
- * Telemetry buffer for batching before send
418
- */
419
- declare class TelemetryBuffer {
420
- private buffer;
421
- private readonly maxSize;
422
- private readonly flushInterval;
423
- private flushTimer?;
424
- private flushCallback?;
425
- constructor(options?: {
426
- maxSize?: number;
427
- flushInterval?: number;
428
- onFlush?: (entries: TelemetryData[]) => Promise<void>;
429
- });
430
- /**
431
- * Add telemetry entry to buffer
432
- */
433
- add(entry: TelemetryData | null): void;
434
- /**
435
- * Flush buffer and send telemetry
436
- */
437
- flush(): Promise<TelemetryData[]>;
438
- /**
439
- * Get current buffer size
440
- */
441
- get size(): number;
442
- private startFlushTimer;
443
- /**
444
- * Stop the flush timer and flush remaining entries
445
- */
446
- stop(): Promise<void>;
447
- }
448
-
449
- export { AskResponse, BatchConfig, ChangeStats, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, RunFlag, RunReport, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };