@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,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-BgqTjfAN.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 };
@@ -1,396 +0,0 @@
1
- /**
2
- * FetchBrain SDK Types
3
- *
4
- * Type definitions for the FetchBrain SDK — memory for your scrapers.
5
- */
6
- /** How far back the brain recalls: fresh=1h, recent=24h, standard=7d, deep=30d */
7
- type MemoryDepth = "fresh" | "recent" | "standard" | "deep";
8
- /** Options for change detection. */
9
- interface ChangeDetectionConfig {
10
- /** Relearn known `alwaysRun` pages and report what changed (default: false). */
11
- enabled?: boolean;
12
- /** Field names to ignore when comparing versions (e.g. "scrapedAt"). */
13
- ignoreFields?: string[];
14
- }
15
- /** A scraper-drift finding: a field whose fill rate or type shifted. */
16
- interface DriftItem {
17
- label: string;
18
- field: string;
19
- kind: "fill_drop" | "missing" | "type_changed";
20
- /** Fill rate 0..1 (or a type name for type_changed). */
21
- from: number | string;
22
- to: number | string;
23
- }
24
- /** A run-level flag returned by the run report. */
25
- interface RunFlag {
26
- label: string;
27
- kind: "empty_pages" | "failed_pages";
28
- rate: number;
29
- }
30
- /** Per-label page counts in a run report. */
31
- interface RunLabelCounts {
32
- scraped: number;
33
- empty: number;
34
- failed: number;
35
- }
36
- /** End-of-run report body (counts and labels only). */
37
- interface RunReport {
38
- runId: string;
39
- build?: string;
40
- startedAt?: string;
41
- endedAt?: string;
42
- scraped: number;
43
- learned: number;
44
- recalled: number;
45
- /** Recalled pages whose fetch was skipped (pre-recalled at enqueue). Per run() call. */
46
- requestsSkipped?: number;
47
- /** Recalled pages that were fetched first (recall happened in the handler). Per run() call. */
48
- lateRecalls?: number;
49
- /** Pages handled outside FetchBrain (`skipLabels`). Per run() call. */
50
- bypassed?: number;
51
- labels?: Record<string, RunLabelCounts>;
52
- }
53
- /** Change counts accumulated by a client, once per learn HTTP batch. */
54
- interface ChangeStats {
55
- changed: number;
56
- unchanged: number;
57
- firstSeen: number;
58
- drift: DriftItem[];
59
- }
60
- /** Configuration for FetchBrain SDK */
61
- interface FetchBrainConfig {
62
- /** API key for authentication */
63
- apiKey: string;
64
- /**
65
- * Name this scraper so it gets its own memory (otherwise every scraper on
66
- * your account outside Apify shares one default memory). Same as setting the
67
- * FETCHBRAIN_SCRAPER_ID env var; a valid option wins, an empty or invalid one
68
- * falls back to the env var. Lowercase letters, digits, '.', '_' and '-',
69
- * max 64, starting with a letter or digit. Invalid names are ignored with a
70
- * warning. On Apify a name overrides the actor id.
71
- */
72
- scraper?: string;
73
- /**
74
- * Change detection: relearn known pages your `alwaysRun` handlers re-scrape so
75
- * FetchBrain can tell what changed since last time. Off by default. Relearning
76
- * counts toward your learn usage.
77
- */
78
- changeDetection?: ChangeDetectionConfig;
79
- /**
80
- * Send a small end-of-run report so FetchBrain can flag runs where many pages
81
- * came back empty or failed. It contains exactly: the run id, start and end
82
- * timestamps, scraped/learned/recalled counts, per-label page counts
83
- * (scraped/empty/failed), and the build id only with `refreshOnRebuild`.
84
- * No URLs or data. Default: true. Set false to disable. Separate from telemetry.
85
- */
86
- reportRuns?: boolean;
87
- /** Base URL for API (defaults to production) */
88
- baseUrl?: string;
89
- /** How far back the brain recalls: fresh=1h, recent=24h, standard=7d, deep=30d */
90
- memory?: MemoryDepth;
91
- /** Teach the brain from scraped data (default: true) */
92
- learning?: boolean;
93
- /**
94
- * Control which handlers run when the brain knows the request.
95
- * - false: Auto-skip all handlers when the request is known (default)
96
- * - true: Always run all handlers
97
- * - string[]: Only run handlers with these labels (e.g., ['listing', 'category'])
98
- * - 'default': Only run the default handler
99
- *
100
- * Recalled data always available via context.brain
101
- */
102
- alwaysRun?: boolean | string | string[];
103
- /**
104
- * Labels that bypass FetchBrain entirely — no recall round-trip, no learn, no brain context.
105
- * Use for dynamic requests (search, listing, pagination) that must always run live and should
106
- * never be remembered: unlike `alwaysRun` (which still recalls + can learn), these skip the
107
- * recall network round-trip and the learn write altogether, removing per-request overhead for
108
- * 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.
111
- */
112
- skipLabels?: string[];
113
- /**
114
- * Recall requests in bulk as they are enqueued (default: true).
115
- *
116
- * In HttpCrawler/CheerioCrawler the HTTP fetch happens BEFORE the request handler runs,
117
- * so a recall inside the handler is too late to save the fetch. With preRecall the SDK
118
- * wraps `crawler.addRequests()` (which `run(requests)` also goes through), recalls the
119
- * whole batch in one API call, marks known requests with `skipNavigation` so Crawlee
120
- * never fetches them, and stashes the result so the handler does no second recall.
121
- *
122
- * Scope: applies to ARRAY input passed to `crawler.addRequests()` / `run(requests)`.
123
- * Crawlee's context-level `enqueueLinks()` and context `addRequests()` reach the queue
124
- * via other paths and are not pre-recalled (they still get handler-time recall) — in a
125
- * handler, enqueue follow-ups with `context.crawler.addRequests([...])` instead.
126
- * Note known recalls are counted at enqueue time, so known requests the queue later
127
- * dedups still count as recalls. The recall result is a snapshot as of enqueue: data learned
128
- * between enqueue and execution is not picked up (the request is simply scraped and
129
- * re-learned). If a request skipped its fetch but its remembered data expired before
130
- * execution (e.g. across a process restart), it fails once without retries and lands
131
- * in your `failedRequestHandler`; it will be re-scraped on a future run. A transient
132
- * API outage during that restore is retried normally instead.
133
- * On crawlers with `retryOnBlocked` the fetch is never skipped (Crawlee's blocked-check
134
- * needs a response); recalled data still replaces the handler.
135
- * Set to false to restore handler-time recall only.
136
- */
137
- preRecall?: boolean;
138
- /**
139
- * Called whenever recalled data is delivered in place of a live scrape — the handler
140
- * was auto-skipped and the remembered data pushed, or your handler called
141
- * `context.brain.use()`. Use it for per-record bookkeeping that normally lives in your
142
- * handler — e.g. metrics or counters. Errors are swallowed: a hook failure never
143
- * breaks the crawl.
144
- */
145
- onRecalled?: (event: RecalledEvent) => void | Promise<void>;
146
- /** Transform each pushed record before the brain learns it */
147
- extractForLearning?: (data: unknown) => Record<string, unknown>;
148
- /**
149
- * If true, scope both learn and recall to the current build version.
150
- * Recall only returns known data from the same build; learn stores new
151
- * data tagged with it. When a scraper updates, it will re-scrape instead
152
- * of using stale data, and freshly learned data won't be masked by an
153
- * older build's memory.
154
- * Uses the platform's native build identifier, auto-detected from the environment.
155
- * Default: false
156
- */
157
- refreshOnRebuild?: boolean;
158
- /**
159
- * Request timeout in ms (default: 1500ms; see DEFAULT_TIMEOUT in client.ts).
160
- * Accepts 1-2147483647; anything else (0, negative, NaN, Infinity) uses the default.
161
- */
162
- timeout?: number;
163
- /**
164
- * ask() timeout in ms (default: 60000). Answer mode can take tens of seconds.
165
- * A per-call `timeout` passed to ask() wins over this. Both accept 1-2147483647;
166
- * anything else (0, negative, NaN, Infinity) uses the default.
167
- */
168
- askTimeout?: number;
169
- /** Enable debug logging */
170
- debug?: boolean;
171
- /**
172
- * Controls how a request appears in FetchBrain's log lines and error messages (it changes output
173
- * only; recall and learn still send the request to the API). Return the text to print
174
- * in place of the URL, or `undefined` to print the line without it. If it throws (or
175
- * returns anything but a non-empty string), the URL is omitted, never shown raw, and
176
- * the crawl continues. Default: the request URL.
177
- */
178
- logUrl?: (request: LogUrlRequest) => string | undefined;
179
- /**
180
- * Field name to use as URL for learning.
181
- * Note: accepted and stored, but not currently applied by the SDK.
182
- */
183
- learnUrlField?: string;
184
- /**
185
- * Batching configuration for high-performance crawling
186
- */
187
- batch?: Partial<BatchConfig>;
188
- /**
189
- * Circuit breaker configuration for stability
190
- */
191
- 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;
198
- }
199
- /**
200
- * What one remembered request holds: the record the page pushed, or every
201
- * record when the page pushed several (a listing page). Recalled arrays are
202
- * pushed as-is — Crawlee's pushData accepts both shapes.
203
- */
204
- type LearnedData = Record<string, unknown> | Record<string, unknown>[];
205
- /** The request passed to `logUrl` (userData excludes FetchBrain's own bookkeeping keys) */
206
- interface LogUrlRequest {
207
- url: string;
208
- uniqueKey: string;
209
- label?: string;
210
- userData: Record<string, unknown>;
211
- }
212
- /** Info passed to `onRecalled` when remembered data is delivered in place of a live scrape */
213
- interface RecalledEvent {
214
- url: string;
215
- label?: string;
216
- userData?: Record<string, unknown>;
217
- data: LearnedData;
218
- }
219
- /** The raw request the SDK forwards; the API derives identity from a subset. */
220
- interface RawRequest {
221
- url: string;
222
- method?: string;
223
- uniqueKey?: string;
224
- body?: string;
225
- headers?: Record<string, string>;
226
- userData?: Record<string, unknown>;
227
- label?: string;
228
- }
229
- /** Recall request to the API */
230
- interface RecallRequest {
231
- items: {
232
- ref: string;
233
- request: RawRequest;
234
- }[];
235
- memory: MemoryDepth;
236
- build?: string;
237
- }
238
- /** Single recall result (matched by ref) */
239
- interface RecallResultItem {
240
- ref: string;
241
- data?: LearnedData;
242
- }
243
- /** Recall response from the API */
244
- interface RecallResponse {
245
- known: {
246
- ref: string;
247
- data: LearnedData;
248
- }[];
249
- unknown: string[];
250
- }
251
- /** Learn request to the API */
252
- interface LearnRequest {
253
- entries: {
254
- request: RawRequest;
255
- data: LearnedData;
256
- }[];
257
- build?: string;
258
- ignore?: string[];
259
- }
260
- /** Learn response from the API */
261
- interface LearnResponse {
262
- learned: number;
263
- status: "success" | "partial" | "rejected";
264
- errors?: string[];
265
- changed?: number;
266
- unchanged?: number;
267
- firstSeen?: number;
268
- changedByLabel?: Record<string, number>;
269
- drift?: DriftItem[];
270
- }
271
- /** Stats response from the API */
272
- interface StatsResponse {
273
- queries: number;
274
- known: number;
275
- recallRate: number;
276
- learned: number;
277
- period: string;
278
- }
279
- /** Result of a recall */
280
- interface RecallResult {
281
- known: boolean;
282
- data?: LearnedData;
283
- fallback?: boolean;
284
- }
285
- /** Response from a natural-language ask, answered from everything the account has learned */
286
- interface AskResponse {
287
- sources: {
288
- score: number;
289
- url?: string;
290
- data: unknown;
291
- }[];
292
- answer?: string;
293
- /**
294
- * "ok" — answered; "rejected" — the API refused this request (bad input,
295
- * unknown model slug, byok not linked — see `error`); "unavailable" — the
296
- * API is degraded or unreachable.
297
- */
298
- status: "ok" | "unavailable" | "rejected";
299
- /** Why the request was rejected (only when status is "rejected"). */
300
- error?: string;
301
- /** Slug of the generation model actually used (answer mode; reveals fallbacks). */
302
- model?: string;
303
- /** Ask credits this ask used (present when status is "ok"). */
304
- credits?: number;
305
- /**
306
- * Why `model` isn't the one you asked for: "busy" — it was at capacity;
307
- * "unavailable" — it failed. The default model answered, at its own credits.
308
- * "provider_error" — your linked model (`model: "byok"`) didn't answer: no
309
- * `answer`, the `sources` are still returned, and `code` says why.
310
- */
311
- fallback?: "busy" | "unavailable" | "provider_error";
312
- /** With `fallback: "provider_error"`: why your linked model didn't answer. */
313
- code?: "BYOK_KEY_INVALID" | "BYOK_PROVIDER_BUSY" | "BYOK_PROVIDER_FAILED";
314
- }
315
- /** Circuit breaker states */
316
- type CircuitState = "closed" | "open" | "half-open";
317
- /** Circuit breaker configuration */
318
- interface CircuitBreakerConfig {
319
- /** Number of failures before opening circuit */
320
- failureThreshold: number;
321
- /** Time to wait before trying half-open state (ms) */
322
- resetTimeout: number;
323
- /** Number of successful calls to close circuit from half-open */
324
- successThreshold: number;
325
- }
326
- /** Batch configuration */
327
- interface BatchConfig {
328
- /** Max items per batch */
329
- maxSize: number;
330
- /** Max wait time before flushing (ms) */
331
- maxWait: number;
332
- }
333
- /** Log levels */
334
- type LogLevel = "debug" | "info" | "warn" | "error";
335
- /** Logger interface */
336
- interface Logger {
337
- debug: (message: string, ...args: unknown[]) => void;
338
- info: (message: string, ...args: unknown[]) => void;
339
- warn: (message: string, ...args: unknown[]) => void;
340
- error: (message: string, ...args: unknown[]) => void;
341
- }
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
-
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 };