@fetchbrain.com/sdk 0.6.0 → 0.7.1

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.mjs CHANGED
@@ -97,6 +97,8 @@ var CircuitBreaker = class {
97
97
  };
98
98
 
99
99
  // src/batch.ts
100
+ var MAX_CONCURRENT_LEARN_FLUSHES = 3;
101
+ var MAX_QUEUED_LEARNS = 500;
100
102
  var DEFAULT_CONFIG2 = {
101
103
  maxSize: 50,
102
104
  maxWait: 50
@@ -178,6 +180,14 @@ var LearnBatcher = class {
178
180
  constructor(executor, config = {}, logger) {
179
181
  this.queue = [];
180
182
  this.flushTimeout = null;
183
+ /** Flushes whose API call has not settled yet (awaited by forceFlush). */
184
+ this.inFlight = /* @__PURE__ */ new Set();
185
+ /**
186
+ * Callers of waitForRoom(), oldest first. A settling flush wakes only as many
187
+ * as there are free backlog slots: waking all of them would tell each one
188
+ * "room" when only some fit, and the rest would then be dropped.
189
+ */
190
+ this.roomWaiters = [];
181
191
  this.executor = executor;
182
192
  this.config = { ...DEFAULT_CONFIG2, ...config };
183
193
  this.logger = logger;
@@ -186,6 +196,10 @@ var LearnBatcher = class {
186
196
  * Add a learn entry to the batch queue
187
197
  */
188
198
  async learn(request, data) {
199
+ if (this.queue.length >= MAX_QUEUED_LEARNS) {
200
+ this.logger.debug("Learn backlog full; not learning this entry");
201
+ return { status: "rejected", learned: 0, errors: ["backlog_full"] };
202
+ }
189
203
  return new Promise((resolve, reject) => {
190
204
  this.queue.push({ entry: { request, data }, resolve, reject });
191
205
  if (this.queue.length >= this.config.maxSize) {
@@ -197,10 +211,60 @@ var LearnBatcher = class {
197
211
  }
198
212
  });
199
213
  }
214
+ /** True when another learn() would be dropped for lack of backlog room. */
215
+ isBacklogFull() {
216
+ return this.queue.length >= MAX_QUEUED_LEARNS;
217
+ }
200
218
  /**
201
- * Flush the current batch
219
+ * Wait until the backlog has room, at most `timeoutMs`. Resolves true when
220
+ * there is room. Bounded so a slow API slows the crawl but never stalls it.
202
221
  */
203
- async flush() {
222
+ async waitForRoom(timeoutMs) {
223
+ const deadline = Date.now() + timeoutMs;
224
+ while (this.isBacklogFull()) {
225
+ const remaining = deadline - Date.now();
226
+ if (remaining <= 0) return false;
227
+ await new Promise((resolve) => {
228
+ const wake = () => {
229
+ clearTimeout(timer);
230
+ resolve();
231
+ };
232
+ const timer = setTimeout(() => {
233
+ const i = this.roomWaiters.indexOf(wake);
234
+ if (i !== -1) this.roomWaiters.splice(i, 1);
235
+ resolve();
236
+ }, remaining);
237
+ this.roomWaiters.push(wake);
238
+ });
239
+ }
240
+ return true;
241
+ }
242
+ /**
243
+ * Start sending the next batch, unless MAX_CONCURRENT_LEARN_FLUSHES are
244
+ * already in flight — a settling flush starts the next one.
245
+ */
246
+ flush() {
247
+ if (this.inFlight.size >= MAX_CONCURRENT_LEARN_FLUSHES) {
248
+ if (this.flushTimeout) {
249
+ clearTimeout(this.flushTimeout);
250
+ this.flushTimeout = null;
251
+ }
252
+ return;
253
+ }
254
+ const run = this.flushOnce();
255
+ this.inFlight.add(run);
256
+ void run.finally(() => {
257
+ this.inFlight.delete(run);
258
+ if (this.queue.length >= this.config.maxSize) {
259
+ this.flush();
260
+ } else if (this.queue.length > 0 && !this.flushTimeout) {
261
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
262
+ }
263
+ const free = MAX_QUEUED_LEARNS - this.queue.length;
264
+ for (const wake of this.roomWaiters.splice(0, Math.max(0, free))) wake();
265
+ });
266
+ }
267
+ async flushOnce() {
204
268
  if (this.flushTimeout) {
205
269
  clearTimeout(this.flushTimeout);
206
270
  this.flushTimeout = null;
@@ -221,16 +285,14 @@ var LearnBatcher = class {
221
285
  r.reject(error);
222
286
  }
223
287
  }
224
- if (this.queue.length > 0) {
225
- this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
226
- }
227
288
  }
228
289
  /**
229
290
  * Force flush and wait for completion (for cleanup/shutdown)
230
291
  */
231
292
  async forceFlush() {
232
- if (this.queue.length > 0) {
233
- await this.flush();
293
+ while (this.queue.length > 0 || this.inFlight.size > 0) {
294
+ if (this.queue.length > 0) this.flush();
295
+ await Promise.allSettled([...this.inFlight]);
234
296
  }
235
297
  }
236
298
  /**
@@ -364,12 +426,17 @@ function getPlatformBuildId(env = process.env) {
364
426
 
365
427
  // src/client.ts
366
428
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
367
- var DEFAULT_TIMEOUT = 500;
429
+ var DEFAULT_TIMEOUT = 1500;
368
430
  var DEFAULT_LEARN_TIMEOUT = 5e3;
369
431
  var BULK_RECALL_TIMEOUT = 3e3;
370
- var MAX_BULK_ITEMS = 100;
432
+ var MAX_BULK_ITEMS = 90;
433
+ var KEY_REJECTED_PAUSE_MS = 6e4;
371
434
  var BULK_RECALL_CONCURRENCY = 5;
372
435
  var MAX_LEARN_ENTRIES = 50;
436
+ var MAX_LEARN_DATA_BYTES = 100 * 1024;
437
+ function isOutage(error) {
438
+ return !(error instanceof ApiError && error.status >= 400 && error.status < 500);
439
+ }
373
440
  var ASK_TIMEOUT = 1e4;
374
441
  function clampBatch(batch, cap) {
375
442
  return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
@@ -407,6 +474,16 @@ var FetchBrainClient = class {
407
474
  * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
408
475
  */
409
476
  this.learnPausedUntil = 0;
477
+ /**
478
+ * Set by a 401 (key invalid or revoked): calls answer locally until then
479
+ * instead of each paying a failing round-trip. A pause, not a permanent stop:
480
+ * a key used right after it is created can see a brief 401 while the key
481
+ * propagates, and that must not switch FetchBrain off for a whole run.
482
+ */
483
+ this.keyRejectedUntil = 0;
484
+ this.keyRejectedWarned = false;
485
+ /** The oversized-page warning is shown once per client, then logged at debug. */
486
+ this.warnedOversizeLearn = false;
410
487
  /** Warn about the learn cap once per pause, independent of the pause state. */
411
488
  this.learnCapWarnedUntil = 0;
412
489
  this.config = {
@@ -455,11 +532,35 @@ var FetchBrainClient = class {
455
532
  this.logger
456
533
  );
457
534
  }
535
+ /** True when recalls must not reach the API right now (crawl continues without). */
536
+ recallBlocked() {
537
+ return this.isKeyRejected() || this.circuitBreaker.isOpen();
538
+ }
539
+ isKeyRejected() {
540
+ return Date.now() < this.keyRejectedUntil;
541
+ }
542
+ /**
543
+ * React to a 4xx the API returned. These are not outages (they don't open the
544
+ * shared breaker). A 401 means the next calls would fail the same way, so all
545
+ * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
546
+ * pause recalls locally: a locally refused handler-time recall fails a
547
+ * fetch-skipped request, whereas the API's own answer can still succeed.)
548
+ */
549
+ noteRefusal(error) {
550
+ if (!(error instanceof ApiError) || error.status !== 401) return;
551
+ this.keyRejectedUntil = Date.now() + KEY_REJECTED_PAUSE_MS;
552
+ if (!this.keyRejectedWarned) {
553
+ this.keyRejectedWarned = true;
554
+ this.logger.warn(
555
+ "FetchBrain API key was rejected (401: invalid or revoked). FetchBrain pauses for 60s at a time while it is; the crawl continues without it."
556
+ );
557
+ }
558
+ }
458
559
  /**
459
560
  * Recall if FetchBrain "knows" a request
460
561
  */
461
562
  async recall(request) {
462
- if (this.circuitBreaker.isOpen()) {
563
+ if (this.recallBlocked()) {
463
564
  return { known: false, fallback: true };
464
565
  }
465
566
  try {
@@ -471,7 +572,7 @@ var FetchBrainClient = class {
471
572
  }
472
573
  /**
473
574
  * Recall multiple requests at once — returns ordered array matching input order.
474
- * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
575
+ * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
475
576
  * failed chunk degrades to fallback results for its own items only.
476
577
  */
477
578
  async recallBulk(requests) {
@@ -485,7 +586,7 @@ var FetchBrainClient = class {
485
586
  while (next < chunks.length) {
486
587
  const idx = next++;
487
588
  const chunk = chunks[idx];
488
- if (this.circuitBreaker.isOpen()) {
589
+ if (this.recallBlocked()) {
489
590
  chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
490
591
  continue;
491
592
  }
@@ -510,11 +611,19 @@ var FetchBrainClient = class {
510
611
  if (!this.config.learning) {
511
612
  return { status: "rejected", learned: 0 };
512
613
  }
513
- if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
614
+ if (this.isKeyRejected() || Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
514
615
  return { status: "rejected", learned: 0 };
515
616
  }
617
+ const processed = this.extractForLearning(data);
618
+ if (JSON.stringify(processed).length > MAX_LEARN_DATA_BYTES) {
619
+ const message = `A page's data is over the ${MAX_LEARN_DATA_BYTES / 1024}KB learn limit, so it was not learned and will be fetched again on later runs. Use extractForLearning to keep only the fields you need.`;
620
+ if (this.warnedOversizeLearn) this.logger.debug(message);
621
+ else this.logger.warn(message);
622
+ this.warnedOversizeLearn = true;
623
+ return { status: "rejected", learned: 0, errors: ["too_large"] };
624
+ }
516
625
  try {
517
- return await this.learnBatcher.learn(request, data);
626
+ return await this.learnBatcher.learn(request, processed);
518
627
  } catch (error) {
519
628
  if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
520
629
  return { status: "rejected", learned: 0 };
@@ -537,7 +646,7 @@ var FetchBrainClient = class {
537
646
  this.circuitBreaker.recordSuccess();
538
647
  return response;
539
648
  } catch (error) {
540
- this.circuitBreaker.recordFailure();
649
+ if (isOutage(error)) this.circuitBreaker.recordFailure();
541
650
  this.logger.warn("Stats request failed:", error);
542
651
  return null;
543
652
  }
@@ -620,19 +729,23 @@ var FetchBrainClient = class {
620
729
  }
621
730
  return results;
622
731
  } catch (error) {
623
- this.circuitBreaker.recordFailure();
732
+ if (isOutage(error)) this.circuitBreaker.recordFailure();
733
+ else this.noteRefusal(error);
624
734
  throw error;
625
735
  }
626
736
  }
737
+ /** Apply the user's extractForLearning hook to each learned record. */
738
+ extractForLearning(data) {
739
+ const extract = this.config.extractForLearning;
740
+ if (!extract) return data;
741
+ return Array.isArray(data) ? data.map((d) => extract(d)) : extract(data);
742
+ }
627
743
  /**
628
744
  * Execute a batch learn against the API
629
745
  */
630
746
  async executeBatchLearn(entries) {
631
- const processed = entries.map((e) => ({
632
- request: e.request,
633
- data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
634
- }));
635
- const request = { entries: processed };
747
+ if (entries.length === 0) return { status: "rejected", learned: 0 };
748
+ const request = { entries };
636
749
  const platformBuildId = getPlatformBuildId();
637
750
  if (this.config.refreshOnRebuild && platformBuildId) {
638
751
  request.build = platformBuildId;
@@ -650,6 +763,7 @@ var FetchBrainClient = class {
650
763
  return response;
651
764
  } catch (error) {
652
765
  if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
766
+ this.noteRefusal(error);
653
767
  if (error.code === "LEARN_CAP_EXCEEDED") {
654
768
  const now = /* @__PURE__ */ new Date();
655
769
  const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
@@ -761,6 +875,13 @@ var FetchBrainClient = class {
761
875
  /**
762
876
  * Flush pending learn requests (call before shutdown)
763
877
  */
878
+ /**
879
+ * Wait (at most `timeoutMs`) until the background learn backlog has room.
880
+ * Lets the crawler slow to the API's pace instead of queueing without limit.
881
+ */
882
+ async waitForLearnRoom(timeoutMs) {
883
+ return this.learnBatcher.waitForRoom(timeoutMs);
884
+ }
764
885
  async flushLearnBatch() {
765
886
  await this.learnBatcher.forceFlush();
766
887
  }
@@ -925,6 +1046,7 @@ var TelemetryBuffer = class {
925
1046
  this.flushTimer = setInterval(() => {
926
1047
  this.flush();
927
1048
  }, this.flushInterval);
1049
+ this.flushTimer.unref?.();
928
1050
  }
929
1051
  /**
930
1052
  * Stop the flush timer and flush remaining entries
@@ -941,6 +1063,23 @@ var TelemetryBuffer = class {
941
1063
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
942
1064
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
943
1065
  var MAX_STASH_ENTRIES = 5e3;
1066
+ var MAX_STASH_BYTES = 256 * 1024 * 1024;
1067
+ var stashBytesCap = MAX_STASH_BYTES;
1068
+ var PRE_RECALL_SLICE = 500;
1069
+ var PRE_RECALL_STASH_WAIT_MS = 3e4;
1070
+ var LEARN_ROOM_WAIT_MS = 5e3;
1071
+ function isIterableInputRejection(err) {
1072
+ if (err instanceof TypeError) return true;
1073
+ const message = err instanceof Error ? err.message : String(err);
1074
+ return /iterable|\barray\b/i.test(message);
1075
+ }
1076
+ function resolveHandlerKey(crawler) {
1077
+ const c = crawler;
1078
+ for (const key of ["userProvidedRequestHandler", "requestHandler", "userDefinedRequestHandler"]) {
1079
+ if (typeof c[key] === "function") return key;
1080
+ }
1081
+ return null;
1082
+ }
944
1083
  function buildRawRequest(request) {
945
1084
  const r = request;
946
1085
  let headers;
@@ -1050,7 +1189,15 @@ var FetchBrain = class {
1050
1189
  // enqueue-time fetch skipped, but remembered data gone by execution
1051
1190
  startTime: 0
1052
1191
  };
1053
- const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
1192
+ const pendingLearns = /* @__PURE__ */ new Set();
1193
+ if ("adaptiveRequestHandler" in crawler) {
1194
+ logger.warn(
1195
+ "AdaptivePlaywrightCrawler is not supported yet \u2014 FetchBrain left this crawler unmodified"
1196
+ );
1197
+ return Object.assign(crawler, { fetchBrain: client });
1198
+ }
1199
+ const handlerKey = resolveHandlerKey(crawler);
1200
+ const originalHandler = handlerKey ? crawler[handlerKey] : void 0;
1054
1201
  if (!originalHandler) {
1055
1202
  logger.warn("No request handler found on crawler, returning unmodified");
1056
1203
  return Object.assign(crawler, { fetchBrain: client });
@@ -1058,26 +1205,40 @@ var FetchBrain = class {
1058
1205
  const crawlerType = crawler.constructor?.name || "Unknown";
1059
1206
  const warnedKeys = /* @__PURE__ */ new Set();
1060
1207
  const preRecalledData = /* @__PURE__ */ new Map();
1208
+ let stashBytes = 0;
1209
+ let crawlStarted = false;
1210
+ const stashDelete = (key) => {
1211
+ const entry = preRecalledData.get(key);
1212
+ if (!entry) return false;
1213
+ preRecalledData.delete(key);
1214
+ stashBytes -= entry.bytes;
1215
+ return true;
1216
+ };
1061
1217
  const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
1062
1218
  const stashSet = (key, data) => {
1063
- if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
1219
+ const reStash = stashDelete(key);
1220
+ const bytes = JSON.stringify(data).length;
1221
+ while (preRecalledData.size > 0 && (!reStash && preRecalledData.size >= MAX_STASH_ENTRIES || stashBytes + bytes > stashBytesCap)) {
1064
1222
  const oldest = preRecalledData.keys().next().value;
1065
- if (oldest !== void 0) preRecalledData.delete(oldest);
1223
+ if (oldest === void 0) break;
1224
+ stashDelete(oldest);
1066
1225
  }
1067
- preRecalledData.set(key, data);
1226
+ preRecalledData.set(key, { data, bytes });
1227
+ stashBytes += bytes;
1068
1228
  };
1069
1229
  const stashTake = (r) => {
1070
1230
  for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
1071
- const data = preRecalledData.get(key);
1072
- if (data) {
1073
- preRecalledData.delete(key);
1074
- return data;
1231
+ const entry = preRecalledData.get(key);
1232
+ if (entry) {
1233
+ stashDelete(key);
1234
+ return entry.data;
1075
1235
  }
1076
1236
  }
1077
1237
  return void 0;
1078
1238
  };
1079
1239
  const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
1080
1240
  const wrappedHandler = async (context) => {
1241
+ crawlStarted = true;
1081
1242
  const { request } = context;
1082
1243
  const url = request.url;
1083
1244
  const label = request.label;
@@ -1178,12 +1339,11 @@ var FetchBrain = class {
1178
1339
  } else {
1179
1340
  logger.debug(`Learning: ${url}`);
1180
1341
  }
1342
+ const learnItems = [];
1181
1343
  if (originalPushData && config.learning !== false) {
1182
1344
  context.pushData = async (data) => {
1183
- const shouldLearn = !usedAIData && !aiResult.known;
1184
- if (shouldLearn) {
1185
- runStats.learned++;
1186
- await client.learn(rawRequest, data);
1345
+ if (!usedAIData && !aiResult.known) {
1346
+ learnItems.push(...Array.isArray(data) ? data : [data]);
1187
1347
  }
1188
1348
  return originalPushData.call(context, data);
1189
1349
  };
@@ -1192,11 +1352,20 @@ var FetchBrain = class {
1192
1352
  request: rawRequest,
1193
1353
  client,
1194
1354
  learning: config.learning !== false,
1195
- aiKnown: aiResult.known
1355
+ aiKnown: aiResult.known,
1356
+ items: learnItems
1196
1357
  };
1197
1358
  await asyncContext.run(requestContext, async () => {
1198
1359
  await originalHandler.call(crawler, context);
1199
1360
  });
1361
+ if (learnItems.length > 0 && !usedAIData && !aiResult.known) {
1362
+ await client.waitForLearnRoom(LEARN_ROOM_WAIT_MS);
1363
+ const pending = client.learn(rawRequest, learnItems.length === 1 ? learnItems[0] : learnItems).then((res) => {
1364
+ if (res.status !== "rejected") runStats.learned += learnItems.length;
1365
+ }).catch((learnErr) => logger.debug(`Learn failed: ${learnErr}`));
1366
+ pendingLearns.add(pending);
1367
+ void pending.finally(() => pendingLearns.delete(pending));
1368
+ }
1200
1369
  if (telemetryConfig.enabled) {
1201
1370
  try {
1202
1371
  const telemetry = await collectTelemetry(
@@ -1275,12 +1444,8 @@ var FetchBrain = class {
1275
1444
  }
1276
1445
  };
1277
1446
  const crawlerAny = crawler;
1278
- if ("requestHandler" in crawlerAny) {
1279
- crawlerAny.requestHandler = wrappedHandler;
1280
- }
1281
- if ("userDefinedRequestHandler" in crawlerAny) {
1282
- crawlerAny.userDefinedRequestHandler = wrappedHandler;
1283
- }
1447
+ crawlerAny[handlerKey] = wrappedHandler;
1448
+ logger.debug(`Wrapped ${handlerKey}`);
1284
1449
  if (typeof crawlerAny.run === "function") {
1285
1450
  const originalRun = crawlerAny.run.bind(crawlerAny);
1286
1451
  crawlerAny.run = async (...args) => {
@@ -1291,6 +1456,7 @@ var FetchBrain = class {
1291
1456
  } finally {
1292
1457
  logger.debug("Flushing pending learn requests on crawl complete");
1293
1458
  await client.flushLearnBatch();
1459
+ await Promise.allSettled([...pendingLearns]);
1294
1460
  if (telemetryConfig.enabled) {
1295
1461
  logger.debug("Telemetry: flushing on crawl complete");
1296
1462
  await telemetryBuffer.stop();
@@ -1313,24 +1479,11 @@ var FetchBrain = class {
1313
1479
  "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."
1314
1480
  );
1315
1481
  }
1316
- crawlerAny.addRequests = async (requests, options) => {
1317
- if (!Array.isArray(requests) || requests.length === 0) {
1318
- return originalAddRequests(requests, options);
1319
- }
1320
- const retryOnBlocked = Boolean(
1321
- crawlerAny.retryOnBlocked
1322
- );
1323
- const batch = requests.map((r) => {
1324
- if (typeof r === "string") return { url: r };
1325
- if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
1326
- return { ...r };
1327
- }
1328
- return r;
1329
- });
1482
+ const preRecallSlice = async (slice, retryOnBlocked) => {
1330
1483
  try {
1331
1484
  const candidateIdx = [];
1332
- for (let i = 0; i < batch.length; i++) {
1333
- const r = batch[i];
1485
+ for (let i = 0; i < slice.length; i++) {
1486
+ const r = slice[i];
1334
1487
  if (!r || typeof r.url !== "string") continue;
1335
1488
  const prior = r.userData?.__fetchBrainResult;
1336
1489
  if (prior) {
@@ -1346,14 +1499,14 @@ var FetchBrain = class {
1346
1499
  }
1347
1500
  if (candidateIdx.length > 0) {
1348
1501
  const rawRequests = candidateIdx.map(
1349
- (i) => buildRawRequest(batch[i])
1502
+ (i) => buildRawRequest(slice[i])
1350
1503
  );
1351
1504
  const results = await client.recallBulk(rawRequests);
1352
1505
  let known = 0;
1353
1506
  candidateIdx.forEach((reqIdx, j) => {
1354
1507
  const result = results[j];
1355
1508
  if (!result || result.fallback) return;
1356
- const r = batch[reqIdx];
1509
+ const r = slice[reqIdx];
1357
1510
  if (result.known && result.data) {
1358
1511
  r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
1359
1512
  stashSet(stashKey(rawRequests[j]), result.data);
@@ -1372,7 +1525,62 @@ var FetchBrain = class {
1372
1525
  } catch (err) {
1373
1526
  logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
1374
1527
  }
1375
- return originalAddRequests(batch, options);
1528
+ };
1529
+ const waitForStashRoom = async (needed, state) => {
1530
+ if (!crawlStarted) return;
1531
+ const deadline = Date.now() + PRE_RECALL_STASH_WAIT_MS;
1532
+ const hasRoom = () => preRecalledData.size + needed <= MAX_STASH_ENTRIES && stashBytes < stashBytesCap;
1533
+ while (!state.gaveUp && !hasRoom()) {
1534
+ if (Date.now() >= deadline) {
1535
+ state.gaveUp = true;
1536
+ logger.debug("preRecall: stash still full after waiting; continuing (oldest payloads may be evicted)");
1537
+ return;
1538
+ }
1539
+ await new Promise((r) => setTimeout(r, 50));
1540
+ }
1541
+ };
1542
+ crawlerAny.addRequests = async (requests, options) => {
1543
+ if (!Array.isArray(requests) || requests.length === 0) {
1544
+ return originalAddRequests(requests, options);
1545
+ }
1546
+ const retryOnBlocked = Boolean(
1547
+ crawlerAny.retryOnBlocked
1548
+ );
1549
+ const batch = requests.map((r) => {
1550
+ if (typeof r === "string") return { url: r };
1551
+ if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
1552
+ return { ...r };
1553
+ }
1554
+ return r;
1555
+ });
1556
+ if (batch.length <= PRE_RECALL_SLICE) {
1557
+ await preRecallSlice(batch, retryOnBlocked);
1558
+ return originalAddRequests(batch, options);
1559
+ }
1560
+ const state = { gaveUp: false };
1561
+ let started = false;
1562
+ async function* lazilyRecalled() {
1563
+ started = true;
1564
+ for (let i = 0; i < batch.length; i += PRE_RECALL_SLICE) {
1565
+ const slice = batch.slice(i, i + PRE_RECALL_SLICE);
1566
+ await waitForStashRoom(slice.length, state);
1567
+ await preRecallSlice(slice, retryOnBlocked);
1568
+ yield* slice;
1569
+ }
1570
+ }
1571
+ try {
1572
+ return await originalAddRequests(lazilyRecalled(), options);
1573
+ } catch (err) {
1574
+ if (started || !isIterableInputRejection(err)) throw err;
1575
+ logger.debug(
1576
+ "preRecall: this Crawlee version does not accept lazy request lists; pre-recalling eagerly"
1577
+ );
1578
+ const eager = batch.slice(0, MAX_STASH_ENTRIES);
1579
+ for (let i = 0; i < eager.length && stashBytes < stashBytesCap; i += PRE_RECALL_SLICE) {
1580
+ await preRecallSlice(eager.slice(i, i + PRE_RECALL_SLICE), retryOnBlocked);
1581
+ }
1582
+ return originalAddRequests(batch, options);
1583
+ }
1376
1584
  };
1377
1585
  }
1378
1586
  return Object.assign(crawler, { fetchBrain: client });
@@ -1384,10 +1592,7 @@ function createFetchBrain(config) {
1384
1592
  async function pushData(data, dataset, datasetName) {
1385
1593
  const ctx = getCurrentContext();
1386
1594
  if (ctx && ctx.learning && !ctx.aiKnown) {
1387
- const items = Array.isArray(data) ? data : [data];
1388
- for (const item of items) {
1389
- await ctx.client.learn(ctx.request, item);
1390
- }
1595
+ ctx.items.push(...Array.isArray(data) ? data : [data]);
1391
1596
  }
1392
1597
  if (datasetName && dataset.open) {
1393
1598
  const namedDataset = await dataset.open(datasetName);