@fetchbrain.com/sdk 0.10.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.
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-BCbMwaYW.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-BCbMwaYW.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", "kimi-k2.5" — premium models cost extra 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 };
@@ -1,84 +0,0 @@
1
- import { R as RawRequest, a as RecallResult, b as LearnResponse, S as StatsResponse, A as AskResponse, F as FetchBrainConfig } from '../types-BCbMwaYW.mjs';
2
-
3
- /**
4
- * Mock FetchBrain for unit testing
5
- *
6
- * Use this to create a mock client that doesn't make real API calls.
7
- */
8
-
9
- interface MockFetchBrainOptions {
10
- /** Seed memory: Map<url, data> the mock already knows at construction */
11
- initialMemory?: Map<string, Record<string, unknown>>;
12
- /** @deprecated Use `initialMemory`. Still honored; on a URL in both, `initialMemory` wins. */
13
- initialKnowledge?: Map<string, Record<string, unknown>>;
14
- /** Simulate API failures */
15
- simulateFailures?: boolean;
16
- /** Failure rate (0-1) */
17
- failureRate?: number;
18
- /** Simulated latency in ms */
19
- latency?: number;
20
- /**
21
- * Simulate the monthly fair-use learn cap: once this many entries are
22
- * learned, further learns are rejected (like the real client after a
23
- * LEARN_CAP_EXCEEDED response) while recall keeps working.
24
- */
25
- learnCap?: number;
26
- }
27
- /**
28
- * Mock FetchBrain client for testing — an in-memory brain, no network
29
- */
30
- declare class MockFetchBrain {
31
- private memory;
32
- private options;
33
- private _stats;
34
- constructor(options?: MockFetchBrainOptions);
35
- private simulateLatency;
36
- private shouldFail;
37
- recall(request: RawRequest): Promise<RecallResult>;
38
- recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
39
- learn(request: RawRequest, data: Record<string, unknown>): Promise<LearnResponse>;
40
- stats(): Promise<StatsResponse>;
41
- /**
42
- * Naive ask(): substring-match the query's words against seeded data.
43
- * When `opts.answer` is truthy, also returns a canned `answer` string
44
- * built from the top source — it is NOT a real synthesized answer, just
45
- * enough of the shape for callers to test against.
46
- */
47
- ask(query: string, opts?: {
48
- answer?: boolean;
49
- limit?: number;
50
- model?: string;
51
- timeout?: number;
52
- }): Promise<AskResponse>;
53
- /**
54
- * Seed the brain with test data (url-keyed convenience API).
55
- * Accepts a single (url, data) pair or an array of entries.
56
- */
57
- seed(url: string, data: Record<string, unknown>): void;
58
- seed(entries: Array<{
59
- url: string;
60
- data: Record<string, unknown>;
61
- }>): void;
62
- /**
63
- * Clear all remembered data
64
- */
65
- clear(): void;
66
- /**
67
- * Number of entries currently in the mock's memory
68
- */
69
- getMemorySize(): number;
70
- /**
71
- * @deprecated Use `getMemorySize()`.
72
- */
73
- getKnowledgeSize(): number;
74
- /**
75
- * Check if the brain knows a URL (keys by deriveIdentity({ url }))
76
- */
77
- has(url: string): boolean;
78
- }
79
- /**
80
- * Create a mock configuration for testing
81
- */
82
- declare function createMockConfig(overrides?: Partial<FetchBrainConfig>): FetchBrainConfig;
83
-
84
- export { MockFetchBrain, type MockFetchBrainOptions, createMockConfig };