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