@fetchbrain.com/sdk 0.5.1 → 0.7.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/README.md CHANGED
@@ -5,9 +5,9 @@
5
5
  <img src="logo/fetchbrain-logo-primary.svg" alt="FetchBrain" width="340">
6
6
  </picture>
7
7
 
8
- **Make your scrapers smarter with every run.**
8
+ **Never pay twice for the same page.**
9
9
 
10
- *Your crawler teaches it once. It recalls it on every run after.*
10
+ *Your scraper learns a page once; within your memory depth, later runs recall it — and known pages you add with `crawler.addRequests()` skip the fetch.*
11
11
 
12
12
  [![CI](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [![npm version](https://badge.fury.io/js/@fetchbrain.com%2Fsdk.svg)](https://www.npmjs.com/package/@fetchbrain.com/sdk) [![TypeScript](https://img.shields.io/badge/TypeScript-first-3178C6.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
13
13
 
@@ -21,12 +21,12 @@ Every scraping run re-fetches thousands of pages you already scraped last
21
21
  time — paying for proxies, browsers, retries, and CAPTCHAs to learn things
22
22
  you already know.
23
23
 
24
- FetchBrain gives each of your scrapers a **memory**. Before each request, a
24
+ FetchBrain gives your scrapers a **memory**, private to your account. Before each request, a
25
25
  crawler asks *"do I already know this request?"* — known requests come back
26
- **in milliseconds** without your scraper fetching the page; unknown ones run
26
+ **from memory** (those you add with `crawler.addRequests()` skip the fetch entirely); unknown ones run
27
27
  normally and are learned. Memory grows run after run, and `ask()` answers
28
28
  plain-English questions from what you've learned — a data asset that
29
- compounds instead of costs. **Learning is always free.**
29
+ compounds instead of costs. **Learning is never billed.**
30
30
 
31
31
  ```text
32
32
  $ node scraper.js # first run — the brain learns
@@ -56,7 +56,7 @@ FetchBrain.enhance(crawler, { apiKey: process.env.FETCHBRAIN_API_KEY });
56
56
 
57
57
  await crawler.run(["https://example.com/"]);
58
58
  // Run 1: your scraper fetches the page and teaches your brain
59
- // Run 2: recalled from memory in milliseconds, no HTTP request to example.com
59
+ // Run 2: recalled from memory, no HTTP request to example.com
60
60
  ```
61
61
 
62
62
  ## One line to adopt
@@ -85,10 +85,10 @@ That's it. Your handler only runs when there's something new to learn.
85
85
 
86
86
  | | Without | With FetchBrain |
87
87
  | --- | --- | --- |
88
- | **Repeat requests** | Full fetch, every run | Recalled in milliseconds |
88
+ | **Repeat requests** | Full fetch, every run | Recalled from memory |
89
89
  | **Proxy & compute spend** | Pay per fetch, every run | Pay only for what it knows |
90
90
  | **Blocks & CAPTCHAs** | Every run risks them | Pre-recalled known requests skip the fetch |
91
- | **When the service is down** | — | Your crawl runs normally (circuit breaker, 500ms timeout) |
91
+ | **When the service is down** | — | Your crawl runs normally (circuit breaker, 1.5s timeout) |
92
92
  | **Testing** | Mock it yourself | `MockFetchBrain` ships in the box |
93
93
 
94
94
  - **Recall before you fetch** — known requests are answered from memory; when they're recalled at enqueue time, the page is never fetched ([caveats](#recall-at-enqueue-time-prerecall))
@@ -109,13 +109,13 @@ freshness-critical monitoring where you always need the live value.
109
109
  Everywhere else, it compounds:
110
110
 
111
111
  **Data-service teams & aggregators** — each scraper fetches an expensive
112
- request once and recalls it on every run after, so per-run proxy and compute
112
+ request once and recalls it on later runs within your memory depth, so per-run proxy and compute
113
113
  cost falls as coverage grows — and `ask()` turns what they've collected into
114
114
  memory you can ask questions of, with no warehouse to run.
115
115
 
116
116
  **Product teams & AI agents** — apps and browsing agents that re-hit the same
117
- requests get them back in milliseconds, straight from memory: no fetch, no
118
- proxy, no block. The more often a scraper revisits the same requests, the more
117
+ requests get them back straight from memory: known pages you add with
118
+ `crawler.addRequests()` skip the fetch, so they cost no proxy traffic. The more often a scraper revisits the same requests, the more
119
119
  its memory pays off.
120
120
 
121
121
  **Recurring crawls of stable data** — catalogs, specs, listings, company and
@@ -123,7 +123,7 @@ reference data barely change between runs, so recall skips the fetch and each
123
123
  scheduled run costs less. Keep volatile fields on `memory: "fresh"` so you
124
124
  never trade accuracy for speed.
125
125
 
126
- **Solo scraper developers** — start free: learning never costs anything, and
126
+ **Solo scraper developers** — start free: learning is never billed, and
127
127
  the requests you've already made come back from memory instead of getting
128
128
  blocked or throttled. One line to add, one brain that grows with everything
129
129
  you scrape.
@@ -160,7 +160,7 @@ await crawler.run(urls);
160
160
  ## How it works
161
161
 
162
162
  ```
163
- Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in milliseconds, no fetch
163
+ Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data from memory (pre-recalled requests skip the fetch)
164
164
  │
165
165
  └──▶ NO ──▶ your handler runs ──▶ brain learns, free
166
166
  ```
@@ -171,8 +171,8 @@ Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES
171
171
 
172
172
  Memory is always private to your account. Within it, scoping depends on
173
173
  where the scraper runs ([details](#do-my-scrapers-share-memory)): on Apify
174
- each actor has its own memory; everywhere else, all scrapers under one API
175
- key share one memory.
174
+ each actor has its own memory; everywhere else, scrapers share one default
175
+ memory unless you [name them](#name-your-scraper-scraper).
176
176
 
177
177
  ### Memory depth
178
178
 
@@ -243,6 +243,7 @@ interface FetchBrainConfig {
243
243
  apiKey: string;
244
244
 
245
245
  // Optional
246
+ scraper?: string; // Name this scraper so it gets its own memory (or set FETCHBRAIN_SCRAPER_ID)
246
247
  baseUrl?: string; // API URL (default: https://api.fetchbrain.com)
247
248
  memory?: MemoryDepth; // How far back the brain recalls (default: "recent")
248
249
  learning?: boolean; // Teach the brain from scraped data (default: true)
@@ -252,7 +253,7 @@ interface FetchBrainConfig {
252
253
  onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when recalled data is delivered
253
254
  extractForLearning?: (data: unknown) => Record<string, unknown>; // Transform each record before it is learned
254
255
  refreshOnRebuild?: boolean; // Scope learn, recall and ask to the current build (*_BUILD_ID env var) (default: false)
255
- timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 500)
256
+ timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 1500)
256
257
  batch?: { maxSize?: number; maxWait?: number }; // Request batching (default: 50 items / 50ms)
257
258
  circuitBreaker?: {
258
259
  failureThreshold?: number; // Failures before the circuit opens (default: 3)
@@ -265,6 +266,33 @@ interface FetchBrainConfig {
265
266
  }
266
267
  ```
267
268
 
269
+ ### Name your scraper (`scraper`)
270
+
271
+ Memory is private to your account. Outside Apify, every scraper on the
272
+ account shares one default memory unless you name it:
273
+
274
+ ```typescript
275
+ FetchBrain.enhance(crawler, { apiKey, scraper: "shop-a" });
276
+ // or, with no code change: FETCHBRAIN_SCRAPER_ID=shop-a node crawl.js
277
+ ```
278
+
279
+ - A named scraper learns and recalls only its own memory, so `shop-a` and
280
+ `shop-b` never see each other's pages.
281
+ - Names use lowercase letters, digits, `.`, `_` and `-`, up to 64 characters,
282
+ and must start with a letter or digit. Uppercase is lowercased. An invalid
283
+ name is ignored with a warning: an invalid `scraper` option falls back to
284
+ `FETCHBRAIN_SCRAPER_ID` if that is valid, otherwise the scraper keeps using
285
+ the default memory.
286
+ - A new name starts empty. What you learned before naming stays in the default
287
+ memory, which unnamed scrapers keep using.
288
+ - On Apify, memory is already per actor. Setting a name there replaces the
289
+ actor id, so that actor's existing memory goes cold.
290
+ - A valid `scraper` option wins over the environment variable; an empty one
291
+ doesn't hide it. SDK 0.3.0 and later
292
+ also forward `FETCHBRAIN_SCRAPER_ID`, but before this release only on a
293
+ best-effort basis: many other `*_ID` variables can push it out of the
294
+ header. Upgrade to guarantee delivery.
295
+
268
296
  ### Recall at enqueue time (`preRecall`)
269
297
 
270
298
  In `HttpCrawler`/`CheerioCrawler`, Crawlee performs the HTTP request *before*
@@ -272,7 +300,7 @@ your request handler runs — so a recall inside the handler is too late to
272
300
  save the fetch. With `preRecall` (on by default), the SDK checks the brain
273
301
  the moment requests enter the queue: each `crawler.addRequests()` array
274
302
  becomes a single bulk recall, known requests are enqueued with Crawlee's
275
- `skipNavigation` so their fetch never happens, and unknown requests carry
303
+ `skipNavigation` so they're skipped before they're fetched, and unknown requests carry
276
304
  their recall result with them so the handler doesn't ask twice. Enqueue in
277
305
  batches (one `addRequests` call per page of discovered items) to get the
278
306
  most out of it. If the brain is unreachable, requests are enqueued unchanged
@@ -399,6 +427,25 @@ paid plan, `"byok"` with no linked provider — the response comes back with
399
427
  `status: "unavailable"`, which means the API itself is degraded or
400
428
  unreachable.
401
429
 
430
+ ## What gets learned from a page
431
+
432
+ - Everything a request's handler pushes is learned **together, once the handler
433
+ succeeds**. A listing page that pushes 20 products is remembered as those 20
434
+ products and recalled as all 20, in order.
435
+ - A handler that throws (even after pushing) teaches nothing for that request,
436
+ so a half-parsed page is never remembered; the retry learns it.
437
+ - Learning happens in the background: `pushData` never waits for it, and
438
+ `crawler.run()` delivers every pending learn before it resolves. If the API
439
+ falls behind, a handler waits briefly (at most 5s, counted toward Crawlee's
440
+ `requestHandlerTimeoutSecs`) for learns to catch up;
441
+ past that the page is not learned, and the crawl carries on.
442
+ - A page's data is learned whole or not at all, up to **100KB** (after
443
+ `extractForLearning`). A page over the limit is not learned and is fetched
444
+ again on later runs; the SDK warns the first time. A listing of many records
445
+ can pass 100KB even when each record is small — use `extractForLearning` to
446
+ keep only the fields you need.
447
+ - The run summary's `learned` counts only records from learns the API accepted.
448
+
402
449
  ## Learning with `Dataset.pushData`
403
450
 
404
451
  > **Important:** the brain learns only from `context.pushData()` or the
@@ -465,11 +512,11 @@ Timeouts per call type:
465
512
 
466
513
  | Call | Timeout |
467
514
  | --- | --- |
468
- | Recall in the handler (batched) | `timeout` option, default 500ms |
515
+ | Recall in the handler (batched) | `timeout` option, default 1.5s |
469
516
  | Recall at enqueue (`preRecall`, bulk) | 3s per chunk of up to 100 requests |
470
517
  | Learn (batched, sent in the background) | 5s |
471
518
  | `ask()` | 10s |
472
- | `stats()` and telemetry | `timeout` option, default 500ms |
519
+ | `stats()` and telemetry | `timeout` option, default 1.5s |
473
520
 
474
521
  A FetchBrain outage costs you *optimization*, not your crawl: SDK calls
475
522
  degrade gracefully instead of throwing into it. The one deliberate
@@ -493,7 +540,8 @@ Every API call (recall, learn, ask, stats, telemetry) sends these headers:
493
540
  | `X-FB-Label` | the request's Crawlee label, while a request is being handled |
494
541
 
495
542
  `X-FB-Context` carries your platform identifiers; the API uses
496
- `APIFY_ACTOR_ID` from it to scope memory per Apify actor (other `*_ID`
543
+ `FETCHBRAIN_SCRAPER_ID` (your scraper name, sent first) and otherwise
544
+ `APIFY_ACTOR_ID` from it to scope memory per scraper (other `*_ID`
497
545
  variables do not affect scoping) and `*BUILD_ID` for `refreshOnRebuild`. It includes
498
546
  every environment variable whose name ends in `_ID`, plus `NODE_ENV`,
499
547
  `REGION` and `CI`, except names containing `TOKEN`, `SECRET`, `PASSWORD`,
@@ -632,8 +680,10 @@ simulate the learning limit). It isn't included in the npm package.
632
680
  It depends on where they run. Memory is always private to your account.
633
681
  - **On Apify**, each actor (`APIFY_ACTOR_ID`) has its own memory: recall and
634
682
  SDK `ask()` calls from inside an actor only see what that actor learned.
635
- - **Everywhere else**, all scrapers using the same API key share one memory —
636
- scraper A can recall what scraper B learned.
683
+ - **Everywhere else**, scrapers share one default memory, so scraper A can
684
+ recall what scraper B learned, unless you name them with `scraper` /
685
+ `FETCHBRAIN_SCRAPER_ID` (see [Name your scraper](#name-your-scraper-scraper)).
686
+ - **A named scraper** (anywhere, including Apify) only sees its own memory.
637
687
  - **Ask Your Brain in the dashboard** (and `ask()` calls with no platform
638
688
  context) answers across everything your account has indexed.
639
689
 
@@ -646,7 +696,7 @@ headers including platform identifiers (env vars ending in `_ID`, plus
646
696
  telemetry, the fields in [Telemetry](#telemetry-opt-in) too.
647
697
 
648
698
  **What does learning cost?**
649
- Nothing. Learning is always free — you pay only for known recalls.
699
+ Nothing. Learning is never billed — you pay only for known recalls.
650
700
 
651
701
  **What if the data changed since the brain learned it?**
652
702
  That's what memory depth is for: pick `fresh` (1h) for volatile data, or
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BMwfPE5J.mjs';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BMwfPE5J.mjs';
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 CircuitState, T as TelemetryData, c as TelemetryConfig, d as CircuitBreakerConfig, e as Logger, B as BatchConfig, f as LogLevel } from './types-CSG4BekA.mjs';
2
+ export { j as LearnRequest, M as MemoryDepth, g as RecallRequest, h as RecallResponse, i as RecallResultItem, k as RecalledEvent, l as TelemetryRequest, m as TelemetryResponse } from './types-CSG4BekA.mjs';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -20,23 +20,46 @@ declare class FetchBrainClient {
20
20
  * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
21
21
  */
22
22
  private learnPausedUntil;
23
+ /**
24
+ * Set by a 401 (key invalid or revoked): calls answer locally until then
25
+ * instead of each paying a failing round-trip. A pause, not a permanent stop:
26
+ * a key used right after it is created can see a brief 401 while the key
27
+ * propagates, and that must not switch FetchBrain off for a whole run.
28
+ */
29
+ private keyRejectedUntil;
30
+ private keyRejectedWarned;
31
+ /** The oversized-page warning is shown once per client, then logged at debug. */
32
+ private warnedOversizeLearn;
23
33
  /** Warn about the learn cap once per pause, independent of the pause state. */
24
34
  private learnCapWarnedUntil;
35
+ /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
36
+ private scraperName;
25
37
  constructor(config: FetchBrainConfig);
38
+ /** True when recalls must not reach the API right now (crawl continues without). */
39
+ private recallBlocked;
40
+ private isKeyRejected;
41
+ /**
42
+ * React to a 4xx the API returned. These are not outages (they don't open the
43
+ * shared breaker). A 401 means the next calls would fail the same way, so all
44
+ * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
45
+ * pause recalls locally: a locally refused handler-time recall fails a
46
+ * fetch-skipped request, whereas the API's own answer can still succeed.)
47
+ */
48
+ private noteRefusal;
26
49
  /**
27
50
  * Recall if FetchBrain "knows" a request
28
51
  */
29
52
  recall(request: RawRequest): Promise<RecallResult>;
30
53
  /**
31
54
  * Recall multiple requests at once — returns ordered array matching input order.
32
- * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
55
+ * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
33
56
  * failed chunk degrades to fallback results for its own items only.
34
57
  */
35
58
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
36
59
  /**
37
60
  * "Teach" FetchBrain new data (batched for high-concurrency)
38
61
  */
39
- learn(request: RawRequest, data: Record<string, unknown>): Promise<LearnResponse>;
62
+ learn(request: RawRequest, data: LearnedData): Promise<LearnResponse>;
40
63
  /**
41
64
  * Get usage statistics
42
65
  */
@@ -58,6 +81,8 @@ declare class FetchBrainClient {
58
81
  * Execute a batch query against the API
59
82
  */
60
83
  private executeBatchQuery;
84
+ /** Apply the user's extractForLearning hook to each learned record. */
85
+ private extractForLearning;
61
86
  /**
62
87
  * Execute a batch learn against the API
63
88
  */
@@ -89,6 +114,11 @@ declare class FetchBrainClient {
89
114
  /**
90
115
  * Flush pending learn requests (call before shutdown)
91
116
  */
117
+ /**
118
+ * Wait (at most `timeoutMs`) until the background learn backlog has room.
119
+ * Lets the crawler slow to the API's pace instead of queueing without limit.
120
+ */
121
+ waitForLearnRoom(timeoutMs: number): Promise<boolean>;
92
122
  flushLearnBatch(): Promise<void>;
93
123
  /**
94
124
  * Send telemetry data to the API
@@ -114,6 +144,8 @@ interface RequestContext {
114
144
  client: FetchBrainClient;
115
145
  learning: boolean;
116
146
  aiKnown: boolean;
147
+ /** Items this request pushed; learned together once the handler succeeds. */
148
+ items: Record<string, unknown>[];
117
149
  }
118
150
  /**
119
151
  * Get the current request context (used by pushData wrapper)
@@ -126,7 +158,7 @@ interface FetchBrainContext {
126
158
  /** Whether the brain knows this URL */
127
159
  known: boolean;
128
160
  /** Brain data if known */
129
- data?: Record<string, unknown>;
161
+ data?: LearnedData;
130
162
  /** Use brain data and skip scraping (call in handler to early return) */
131
163
  use: () => Promise<void>;
132
164
  }
@@ -148,7 +180,7 @@ declare class FetchBrain {
148
180
  memory?: string;
149
181
  }): Promise<{
150
182
  known: boolean;
151
- data: Record<string, unknown> | undefined;
183
+ data: LearnedData | undefined;
152
184
  }>;
153
185
  /**
154
186
  * "Teach" FetchBrain new data
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BMwfPE5J.js';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BMwfPE5J.js';
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 CircuitState, T as TelemetryData, c as TelemetryConfig, d as CircuitBreakerConfig, e as Logger, B as BatchConfig, f as LogLevel } from './types-CSG4BekA.js';
2
+ export { j as LearnRequest, M as MemoryDepth, g as RecallRequest, h as RecallResponse, i as RecallResultItem, k as RecalledEvent, l as TelemetryRequest, m as TelemetryResponse } from './types-CSG4BekA.js';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -20,23 +20,46 @@ declare class FetchBrainClient {
20
20
  * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
21
21
  */
22
22
  private learnPausedUntil;
23
+ /**
24
+ * Set by a 401 (key invalid or revoked): calls answer locally until then
25
+ * instead of each paying a failing round-trip. A pause, not a permanent stop:
26
+ * a key used right after it is created can see a brief 401 while the key
27
+ * propagates, and that must not switch FetchBrain off for a whole run.
28
+ */
29
+ private keyRejectedUntil;
30
+ private keyRejectedWarned;
31
+ /** The oversized-page warning is shown once per client, then logged at debug. */
32
+ private warnedOversizeLearn;
23
33
  /** Warn about the learn cap once per pause, independent of the pause state. */
24
34
  private learnCapWarnedUntil;
35
+ /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
36
+ private scraperName;
25
37
  constructor(config: FetchBrainConfig);
38
+ /** True when recalls must not reach the API right now (crawl continues without). */
39
+ private recallBlocked;
40
+ private isKeyRejected;
41
+ /**
42
+ * React to a 4xx the API returned. These are not outages (they don't open the
43
+ * shared breaker). A 401 means the next calls would fail the same way, so all
44
+ * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
45
+ * pause recalls locally: a locally refused handler-time recall fails a
46
+ * fetch-skipped request, whereas the API's own answer can still succeed.)
47
+ */
48
+ private noteRefusal;
26
49
  /**
27
50
  * Recall if FetchBrain "knows" a request
28
51
  */
29
52
  recall(request: RawRequest): Promise<RecallResult>;
30
53
  /**
31
54
  * Recall multiple requests at once — returns ordered array matching input order.
32
- * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
55
+ * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
33
56
  * failed chunk degrades to fallback results for its own items only.
34
57
  */
35
58
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
36
59
  /**
37
60
  * "Teach" FetchBrain new data (batched for high-concurrency)
38
61
  */
39
- learn(request: RawRequest, data: Record<string, unknown>): Promise<LearnResponse>;
62
+ learn(request: RawRequest, data: LearnedData): Promise<LearnResponse>;
40
63
  /**
41
64
  * Get usage statistics
42
65
  */
@@ -58,6 +81,8 @@ declare class FetchBrainClient {
58
81
  * Execute a batch query against the API
59
82
  */
60
83
  private executeBatchQuery;
84
+ /** Apply the user's extractForLearning hook to each learned record. */
85
+ private extractForLearning;
61
86
  /**
62
87
  * Execute a batch learn against the API
63
88
  */
@@ -89,6 +114,11 @@ declare class FetchBrainClient {
89
114
  /**
90
115
  * Flush pending learn requests (call before shutdown)
91
116
  */
117
+ /**
118
+ * Wait (at most `timeoutMs`) until the background learn backlog has room.
119
+ * Lets the crawler slow to the API's pace instead of queueing without limit.
120
+ */
121
+ waitForLearnRoom(timeoutMs: number): Promise<boolean>;
92
122
  flushLearnBatch(): Promise<void>;
93
123
  /**
94
124
  * Send telemetry data to the API
@@ -114,6 +144,8 @@ interface RequestContext {
114
144
  client: FetchBrainClient;
115
145
  learning: boolean;
116
146
  aiKnown: boolean;
147
+ /** Items this request pushed; learned together once the handler succeeds. */
148
+ items: Record<string, unknown>[];
117
149
  }
118
150
  /**
119
151
  * Get the current request context (used by pushData wrapper)
@@ -126,7 +158,7 @@ interface FetchBrainContext {
126
158
  /** Whether the brain knows this URL */
127
159
  known: boolean;
128
160
  /** Brain data if known */
129
- data?: Record<string, unknown>;
161
+ data?: LearnedData;
130
162
  /** Use brain data and skip scraping (call in handler to early return) */
131
163
  use: () => Promise<void>;
132
164
  }
@@ -148,7 +180,7 @@ declare class FetchBrain {
148
180
  memory?: string;
149
181
  }): Promise<{
150
182
  known: boolean;
151
- data: Record<string, unknown> | undefined;
183
+ data: LearnedData | undefined;
152
184
  }>;
153
185
  /**
154
186
  * "Teach" FetchBrain new data