@fetchbrain.com/sdk 0.3.2 → 0.5.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
@@ -214,11 +214,71 @@ interface FetchBrainConfig {
214
214
  memory?: MemoryDepth; // How far back the brain recalls
215
215
  learning?: boolean; // Enable AI learning (default: true)
216
216
  alwaysRun?: boolean | string | string[]; // Which handlers to run (default: false)
217
+ skipLabels?: string[]; // Labels that bypass FetchBrain entirely (default: none)
218
+ preRecall?: boolean; // Recall requests in bulk as they're enqueued (default: true)
219
+ onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when known data is delivered
217
220
  timeout?: number; // Request timeout in ms (default: 500)
218
221
  debug?: boolean; // Enable debug logging
219
222
  }
220
223
  ```
221
224
 
225
+ ### Recall at enqueue time (`preRecall`)
226
+
227
+ In `HttpCrawler`/`CheerioCrawler`, Crawlee performs the HTTP request *before*
228
+ your request handler runs — so a recall inside the handler is too late to
229
+ save the fetch. With `preRecall` (on by default), the SDK checks the brain
230
+ the moment requests enter the queue: each `crawler.addRequests()` array
231
+ becomes a single bulk recall, known requests are enqueued with Crawlee's
232
+ `skipNavigation` so their fetch never happens, and unknown requests carry
233
+ their recall result with them so the handler doesn't ask twice. Enqueue in
234
+ batches (one `addRequests` call per page of discovered items) to get the
235
+ most out of it. If the brain is unreachable, requests are enqueued unchanged
236
+ and your crawl proceeds at native speed — same graceful degradation as
237
+ everywhere else.
238
+
239
+ Things to know:
240
+
241
+ - **Scope** — pre-recall applies to arrays passed to `crawler.addRequests()`
242
+ or `crawler.run(requests)`. Crawlee's context-level `enqueueLinks()` and
243
+ context `addRequests()` reach the queue by other paths and are not
244
+ pre-recalled (they still get handler-time recall). Inside a handler,
245
+ enqueue follow-ups with `context.crawler.addRequests([...])` to keep the
246
+ benefit — as in the example above.
247
+ - **Metering** — recall queries are counted when requests are enqueued, so
248
+ duplicates the queue later drops still count as queries.
249
+ - **Snapshot semantics** — the recall result is as of enqueue time. Anything
250
+ learned between enqueue and execution isn't picked up; the request is
251
+ simply scraped and re-learned.
252
+ - **Expired memory** — if a request skipped its fetch at enqueue but its
253
+ remembered data genuinely expired before it executed (e.g. across a process
254
+ restart), it fails once without retries and lands in your
255
+ `failedRequestHandler`, so the missing record is visible to your error
256
+ tooling. It will be re-scraped on a future run. (If the data merely couldn't
257
+ be restored because the API was briefly unreachable, the request fails
258
+ retryable and the next attempt restores it.)
259
+ - **`retryOnBlocked` crawlers** — Crawlee's blocked-request detection needs a
260
+ fetched response, so on these crawlers known requests keep their fetch;
261
+ recalled data still replaces the handler (no second recall, no re-scrape).
262
+
263
+ ### Reacting to recalled records (`onRecalled`)
264
+
265
+ When the brain knows a request, your handler is skipped and the remembered
266
+ data is pushed for you — which also skips any per-record bookkeeping living
267
+ in that handler (billing events, counters, follow-up enqueues). `onRecalled`
268
+ runs once per recalled record with `{ url, label, userData, data }` — both
269
+ when the handler is auto-skipped and when your own handler calls
270
+ `context.brain.use()`:
271
+
272
+ ```typescript
273
+ FetchBrain.enhance(crawler, {
274
+ onRecalled: async ({ userData }) => {
275
+ await Actor.charge({ eventName: "product-detail", count: 1 });
276
+ },
277
+ });
278
+ ```
279
+
280
+ Hook errors are swallowed (logged at debug) — they never break the crawl.
281
+
222
282
  Fine-grained routing control with `alwaysRun` — run every handler, none, or
223
283
  only specific labels when a request is known:
224
284
 
@@ -226,6 +286,15 @@ only specific labels when a request is known:
226
286
  FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
227
287
  ```
228
288
 
289
+ For dynamic requests that must always run live and aren't worth remembering
290
+ (search results, pagination), use `skipLabels` instead: where `alwaysRun`
291
+ still recalls (and can learn), `skipLabels` bypasses FetchBrain entirely —
292
+ no recall round-trip, no learn — so those requests run at native speed:
293
+
294
+ ```typescript
295
+ FetchBrain.enhance(crawler, { skipLabels: ["search", "pagination"] });
296
+ ```
297
+
229
298
  ## Ask your brain anything
230
299
 
231
300
  This is where the pool pays off twice: `ask()` searches across everything
@@ -297,11 +366,11 @@ const crawler = FetchBrain.enhance(
297
366
 
298
367
  ### `context.brain` Properties
299
368
 
300
- | Property | Type | Description |
301
- | --------- | -------- | ---------------------------------- |
302
- | `known` | boolean | Whether the brain knows this URL |
303
- | `data` | object | Brain data (if known) |
304
- | `use()` | function | Push brain data and skip scraping |
369
+ | Property | Type | Description |
370
+ | -------- | -------- | --------------------------------- |
371
+ | `known` | boolean | Whether the brain knows this URL |
372
+ | `data` | object | Brain data (if known) |
373
+ | `use()` | function | Push brain data and skip scraping |
305
374
 
306
375
  ## Using Dataset.pushData
307
376
 
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-BOfLGSkb.mjs';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-BOfLGSkb.mjs';
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-BbLgy1no.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-BbLgy1no.mjs';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -21,7 +21,9 @@ declare class FetchBrainClient {
21
21
  */
22
22
  recall(request: RawRequest): Promise<RecallResult>;
23
23
  /**
24
- * Recall multiple requests at once — returns ordered array matching input order
24
+ * Recall multiple requests at once — returns ordered array matching input order.
25
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
26
+ * failed chunk degrades to fallback results for its own items only.
25
27
  */
26
28
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
27
29
  /**
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-BOfLGSkb.js';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-BOfLGSkb.js';
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-BbLgy1no.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-BbLgy1no.js';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -21,7 +21,9 @@ declare class FetchBrainClient {
21
21
  */
22
22
  recall(request: RawRequest): Promise<RecallResult>;
23
23
  /**
24
- * Recall multiple requests at once — returns ordered array matching input order
24
+ * Recall multiple requests at once — returns ordered array matching input order.
25
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
26
+ * failed chunk degrades to fallback results for its own items only.
25
27
  */
26
28
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
27
29
  /**
package/dist/index.js CHANGED
@@ -346,7 +346,14 @@ function getPlatformBuildId(env = process.env) {
346
346
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
347
347
  var DEFAULT_TIMEOUT = 500;
348
348
  var DEFAULT_LEARN_TIMEOUT = 5e3;
349
+ var BULK_RECALL_TIMEOUT = 3e3;
350
+ var MAX_BULK_ITEMS = 100;
351
+ var BULK_RECALL_CONCURRENCY = 5;
352
+ var MAX_LEARN_ENTRIES = 50;
349
353
  var ASK_TIMEOUT = 1e4;
354
+ function clampBatch(batch, cap) {
355
+ return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
356
+ }
350
357
  var ApiError = class extends Error {
351
358
  constructor(status, statusText, serverError) {
352
359
  super(`API error: ${status} ${statusText}`);
@@ -378,7 +385,13 @@ var FetchBrainClient = class {
378
385
  telemetry: config.telemetry ?? { enabled: false },
379
386
  // opt-in
380
387
  batch: config.batch,
381
- circuitBreaker: config.circuitBreaker
388
+ circuitBreaker: config.circuitBreaker,
389
+ skipLabels: config.skipLabels,
390
+ // enhance-only; stored so getConfig() round-trips
391
+ preRecall: config.preRecall,
392
+ // enhance-only; stored so getConfig() round-trips
393
+ onRecalled: config.onRecalled
394
+ // enhance-only; stored so getConfig() round-trips
382
395
  };
383
396
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
384
397
  this.circuitBreaker = new CircuitBreaker(
@@ -387,12 +400,12 @@ var FetchBrainClient = class {
387
400
  );
388
401
  this.batcher = new RequestBatcher(
389
402
  (items) => this.executeBatchQuery(items),
390
- this.config.batch,
403
+ clampBatch(this.config.batch, MAX_BULK_ITEMS),
391
404
  this.logger
392
405
  );
393
406
  this.learnBatcher = new LearnBatcher(
394
407
  (entries) => this.executeBatchLearn(entries),
395
- this.config.batch,
408
+ clampBatch(this.config.batch, MAX_LEARN_ENTRIES),
396
409
  this.logger
397
410
  );
398
411
  }
@@ -411,19 +424,38 @@ var FetchBrainClient = class {
411
424
  }
412
425
  }
413
426
  /**
414
- * Recall multiple requests at once — returns ordered array matching input order
427
+ * Recall multiple requests at once — returns ordered array matching input order.
428
+ * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
429
+ * failed chunk degrades to fallback results for its own items only.
415
430
  */
416
431
  async recallBulk(requests) {
417
- if (this.circuitBreaker.isOpen()) {
418
- return requests.map(() => ({ known: false, fallback: true }));
419
- }
420
- try {
421
- const items = requests.map((request, i) => ({ ref: String(i), request }));
422
- const results = await this.executeBatchQuery(items);
423
- return items.map((i) => results.get(i.ref) ?? { known: false });
424
- } catch {
425
- return requests.map(() => ({ known: false, fallback: true }));
432
+ const chunks = [];
433
+ for (let start = 0; start < requests.length; start += MAX_BULK_ITEMS) {
434
+ chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
426
435
  }
436
+ const chunkResults = new Array(chunks.length);
437
+ let next = 0;
438
+ const worker = async () => {
439
+ while (next < chunks.length) {
440
+ const idx = next++;
441
+ const chunk = chunks[idx];
442
+ if (this.circuitBreaker.isOpen()) {
443
+ chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
444
+ continue;
445
+ }
446
+ try {
447
+ const items = chunk.map((request, i) => ({ ref: String(i), request }));
448
+ const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
449
+ chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
450
+ } catch {
451
+ chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
452
+ }
453
+ }
454
+ };
455
+ await Promise.all(
456
+ Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
457
+ );
458
+ return chunkResults.flat();
427
459
  }
428
460
  /**
429
461
  * "Teach" FetchBrain new data (batched for high-concurrency)
@@ -511,7 +543,7 @@ var FetchBrainClient = class {
511
543
  /**
512
544
  * Execute a batch query against the API
513
545
  */
514
- async executeBatchQuery(items) {
546
+ async executeBatchQuery(items, timeout) {
515
547
  const results = /* @__PURE__ */ new Map();
516
548
  const request = {
517
549
  items,
@@ -522,10 +554,14 @@ var FetchBrainClient = class {
522
554
  request.build = platformBuildId;
523
555
  }
524
556
  try {
525
- const response = await this.makeRequest("/v1/recall", {
526
- method: "POST",
527
- body: JSON.stringify(request)
528
- });
557
+ const response = await this.makeRequest(
558
+ "/v1/recall",
559
+ {
560
+ method: "POST",
561
+ body: JSON.stringify(request)
562
+ },
563
+ timeout
564
+ );
529
565
  this.circuitBreaker.recordSuccess();
530
566
  for (const item of response.known) {
531
567
  results.set(item.ref, { known: true, data: item.data });
@@ -828,6 +864,7 @@ var TelemetryBuffer = class {
828
864
  // src/enhance.ts
829
865
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
830
866
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
867
+ var MAX_STASH_ENTRIES = 5e3;
831
868
  function buildRawRequest(request) {
832
869
  const r = request;
833
870
  let headers;
@@ -931,6 +968,10 @@ var FetchBrain = class {
931
968
  learned: 0,
932
969
  scraped: 0,
933
970
  // Actually ran handler
971
+ bypassed: 0,
972
+ // skipLabels match — ran handler outside FetchBrain
973
+ dropped: 0,
974
+ // enqueue-time fetch skipped, but remembered data gone by execution
934
975
  startTime: 0
935
976
  };
936
977
  const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
@@ -940,12 +981,38 @@ var FetchBrain = class {
940
981
  }
941
982
  const crawlerType = crawler.constructor?.name || "Unknown";
942
983
  const warnedKeys = /* @__PURE__ */ new Set();
984
+ const preRecalledData = /* @__PURE__ */ new Map();
985
+ const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
986
+ const stashSet = (key, data) => {
987
+ if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
988
+ const oldest = preRecalledData.keys().next().value;
989
+ if (oldest !== void 0) preRecalledData.delete(oldest);
990
+ }
991
+ preRecalledData.set(key, data);
992
+ };
993
+ const stashTake = (r) => {
994
+ for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
995
+ const data = preRecalledData.get(key);
996
+ if (data) {
997
+ preRecalledData.delete(key);
998
+ return data;
999
+ }
1000
+ }
1001
+ return void 0;
1002
+ };
1003
+ const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
943
1004
  const wrappedHandler = async (context) => {
944
1005
  const { request } = context;
945
1006
  const url = request.url;
946
1007
  const label = request.label;
947
1008
  const startTime = Date.now();
948
1009
  runStats.totalRequests++;
1010
+ if (skipLabels && skipLabels.has(label || "default")) {
1011
+ runStats.bypassed++;
1012
+ logger.debug(`Bypassing FetchBrain for [${label || "default"}]: ${url}`);
1013
+ await originalHandler.call(crawler, context);
1014
+ return;
1015
+ }
949
1016
  setScrapeContext({
950
1017
  crawler: crawlerType,
951
1018
  label,
@@ -953,10 +1020,50 @@ var FetchBrain = class {
953
1020
  });
954
1021
  const rawRequest = buildRawRequest(request);
955
1022
  warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
1023
+ let consumedStash;
956
1024
  try {
957
- const aiResult = await client.recall(rawRequest);
1025
+ const preRecalled = request.userData?.__fetchBrainResult;
1026
+ let aiResult;
1027
+ if (preRecalled?.known) {
1028
+ const stashedData = stashTake(rawRequest);
1029
+ if (stashedData) {
1030
+ consumedStash = stashedData;
1031
+ aiResult = { known: true, data: stashedData };
1032
+ } else {
1033
+ aiResult = await client.recall(rawRequest);
1034
+ }
1035
+ } else if (preRecalled) {
1036
+ aiResult = preRecalled;
1037
+ } else {
1038
+ aiResult = await client.recall(rawRequest);
1039
+ }
1040
+ if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1041
+ if (aiResult.fallback) {
1042
+ throw new Error(
1043
+ `FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1044
+ );
1045
+ }
1046
+ runStats.dropped++;
1047
+ request.noRetry = true;
1048
+ throw new Error(
1049
+ `FetchBrain: ${url} skipped its fetch at enqueue time but its remembered data is no longer available \u2014 failing without retries; it will be re-scraped on a future run.`
1050
+ );
1051
+ }
958
1052
  let usedAIData = false;
959
1053
  const originalPushData = context.pushData;
1054
+ const fireOnRecalled = async (data) => {
1055
+ if (!config.onRecalled) return;
1056
+ try {
1057
+ await config.onRecalled({
1058
+ url,
1059
+ label: request.label,
1060
+ userData: rawRequest.userData,
1061
+ data
1062
+ });
1063
+ } catch (hookErr) {
1064
+ logger.debug(`onRecalled hook error: ${hookErr}`);
1065
+ }
1066
+ };
960
1067
  context.brain = {
961
1068
  known: aiResult.known,
962
1069
  data: aiResult.data,
@@ -965,6 +1072,7 @@ var FetchBrain = class {
965
1072
  usedAIData = true;
966
1073
  await originalPushData.call(context, aiResult.data);
967
1074
  logger.info(`Used brain data: ${url}`);
1075
+ await fireOnRecalled(aiResult.data);
968
1076
  }
969
1077
  }
970
1078
  };
@@ -982,6 +1090,7 @@ var FetchBrain = class {
982
1090
  if (originalPushData) {
983
1091
  await originalPushData.call(context, aiResult.data);
984
1092
  }
1093
+ await fireOnRecalled(aiResult.data);
985
1094
  return;
986
1095
  }
987
1096
  runStats.scraped++;
@@ -1054,6 +1163,9 @@ var FetchBrain = class {
1054
1163
  }
1055
1164
  }
1056
1165
  } catch (err) {
1166
+ if (consumedStash) {
1167
+ stashSet(stashKey(rawRequest), consumedStash);
1168
+ }
1057
1169
  if (telemetryConfig.enabled) {
1058
1170
  try {
1059
1171
  const telemetry = await collectTelemetry(
@@ -1110,13 +1222,83 @@ var FetchBrain = class {
1110
1222
  const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1111
1223
  1
1112
1224
  );
1113
- const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
1225
+ const managedRequests = runStats.totalRequests - runStats.bypassed;
1226
+ const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1114
1227
  logger.info(
1115
- `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
1228
+ `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + `, duration: ${duration}s`
1116
1229
  );
1117
1230
  }
1118
1231
  };
1119
1232
  }
1233
+ if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
1234
+ const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
1235
+ if (crawlerAny.retryOnBlocked) {
1236
+ logger.info(
1237
+ "preRecall: this crawler uses retryOnBlocked, whose blocked-check needs a fetched response \u2014 known requests will keep their fetch; recalled data still replaces the handler."
1238
+ );
1239
+ }
1240
+ crawlerAny.addRequests = async (requests, options) => {
1241
+ if (!Array.isArray(requests) || requests.length === 0) {
1242
+ return originalAddRequests(requests, options);
1243
+ }
1244
+ const retryOnBlocked = Boolean(
1245
+ crawlerAny.retryOnBlocked
1246
+ );
1247
+ const batch = requests.map((r) => {
1248
+ if (typeof r === "string") return { url: r };
1249
+ if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
1250
+ return { ...r };
1251
+ }
1252
+ return r;
1253
+ });
1254
+ try {
1255
+ const candidateIdx = [];
1256
+ for (let i = 0; i < batch.length; i++) {
1257
+ const r = batch[i];
1258
+ if (!r || typeof r.url !== "string") continue;
1259
+ const prior = r.userData?.__fetchBrainResult;
1260
+ if (prior) {
1261
+ if (prior.known && r.skipNavigation) r.skipNavigation = false;
1262
+ const rest = { ...r.userData };
1263
+ delete rest.__fetchBrainResult;
1264
+ r.userData = rest;
1265
+ }
1266
+ if (r.skipNavigation) continue;
1267
+ if (skipLabels && skipLabels.has(r.label || "default")) continue;
1268
+ if ((r.method ?? "GET").toUpperCase() !== "GET" && !r.uniqueKey) continue;
1269
+ candidateIdx.push(i);
1270
+ }
1271
+ if (candidateIdx.length > 0) {
1272
+ const rawRequests = candidateIdx.map(
1273
+ (i) => buildRawRequest(batch[i])
1274
+ );
1275
+ const results = await client.recallBulk(rawRequests);
1276
+ let known = 0;
1277
+ candidateIdx.forEach((reqIdx, j) => {
1278
+ const result = results[j];
1279
+ if (!result || result.fallback) return;
1280
+ const r = batch[reqIdx];
1281
+ if (result.known && result.data) {
1282
+ r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
1283
+ stashSet(stashKey(rawRequests[j]), result.data);
1284
+ if (!retryOnBlocked && !shouldRunHandler(config.alwaysRun, r.label)) {
1285
+ r.skipNavigation = true;
1286
+ known++;
1287
+ }
1288
+ } else {
1289
+ r.userData = { ...r.userData, __fetchBrainResult: { known: false } };
1290
+ }
1291
+ });
1292
+ logger.debug(
1293
+ `Pre-recalled ${candidateIdx.length} enqueued request(s): ${known} known (fetch skipped)`
1294
+ );
1295
+ }
1296
+ } catch (err) {
1297
+ logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
1298
+ }
1299
+ return originalAddRequests(batch, options);
1300
+ };
1301
+ }
1120
1302
  return Object.assign(crawler, { fetchBrain: client });
1121
1303
  }
1122
1304
  };