@fetchbrain.com/sdk 0.4.0 → 0.5.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/README.md +344 -153
- package/dist/index.d.mts +19 -9
- package/dist/index.d.ts +19 -9
- package/dist/index.js +242 -24
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +242 -24
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +17 -5
- package/dist/mock/index.d.ts +17 -5
- package/dist/mock/index.js +22 -12
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +22 -12
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-D8djjVGS.d.mts → types-BMwfPE5J.d.mts} +62 -20
- package/dist/{types-D8djjVGS.d.ts → types-BMwfPE5J.d.ts} +62 -20
- package/package.json +1 -3
package/dist/index.mjs
CHANGED
|
@@ -344,15 +344,33 @@ function getPlatformBuildId(env = process.env) {
|
|
|
344
344
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
345
345
|
var DEFAULT_TIMEOUT = 500;
|
|
346
346
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
347
|
+
var BULK_RECALL_TIMEOUT = 3e3;
|
|
348
|
+
var MAX_BULK_ITEMS = 100;
|
|
349
|
+
var BULK_RECALL_CONCURRENCY = 5;
|
|
350
|
+
var MAX_LEARN_ENTRIES = 50;
|
|
347
351
|
var ASK_TIMEOUT = 1e4;
|
|
352
|
+
function clampBatch(batch, cap) {
|
|
353
|
+
return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
|
|
354
|
+
}
|
|
348
355
|
var ApiError = class extends Error {
|
|
349
|
-
constructor(status, statusText, serverError) {
|
|
356
|
+
constructor(status, statusText, serverError, code, retryAfterSec) {
|
|
350
357
|
super(`API error: ${status} ${statusText}`);
|
|
351
358
|
this.status = status;
|
|
352
359
|
this.serverError = serverError;
|
|
360
|
+
this.code = code;
|
|
361
|
+
this.retryAfterSec = retryAfterSec;
|
|
353
362
|
this.name = "ApiError";
|
|
354
363
|
}
|
|
355
364
|
};
|
|
365
|
+
function parseRetryAfter(header) {
|
|
366
|
+
if (!header) return void 0;
|
|
367
|
+
const secs = Number(header);
|
|
368
|
+
if (Number.isFinite(secs)) return secs > 0 ? secs : void 0;
|
|
369
|
+
const at = Date.parse(header);
|
|
370
|
+
if (Number.isNaN(at)) return void 0;
|
|
371
|
+
const delta = (at - Date.now()) / 1e3;
|
|
372
|
+
return delta > 0 ? delta : void 0;
|
|
373
|
+
}
|
|
356
374
|
var currentContext = {};
|
|
357
375
|
function setScrapeContext(ctx) {
|
|
358
376
|
currentContext = ctx;
|
|
@@ -362,6 +380,13 @@ function clearScrapeContext() {
|
|
|
362
380
|
}
|
|
363
381
|
var FetchBrainClient = class {
|
|
364
382
|
constructor(config) {
|
|
383
|
+
/**
|
|
384
|
+
* Epoch ms until which learns are paused after the API reported the monthly
|
|
385
|
+
* learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
|
|
386
|
+
*/
|
|
387
|
+
this.learnPausedUntil = 0;
|
|
388
|
+
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
389
|
+
this.learnCapWarnedUntil = 0;
|
|
365
390
|
this.config = {
|
|
366
391
|
apiKey: config.apiKey,
|
|
367
392
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
@@ -377,7 +402,11 @@ var FetchBrainClient = class {
|
|
|
377
402
|
// opt-in
|
|
378
403
|
batch: config.batch,
|
|
379
404
|
circuitBreaker: config.circuitBreaker,
|
|
380
|
-
skipLabels: config.skipLabels
|
|
405
|
+
skipLabels: config.skipLabels,
|
|
406
|
+
// enhance-only; stored so getConfig() round-trips
|
|
407
|
+
preRecall: config.preRecall,
|
|
408
|
+
// enhance-only; stored so getConfig() round-trips
|
|
409
|
+
onRecalled: config.onRecalled
|
|
381
410
|
// enhance-only; stored so getConfig() round-trips
|
|
382
411
|
};
|
|
383
412
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
@@ -387,12 +416,12 @@ var FetchBrainClient = class {
|
|
|
387
416
|
);
|
|
388
417
|
this.batcher = new RequestBatcher(
|
|
389
418
|
(items) => this.executeBatchQuery(items),
|
|
390
|
-
this.config.batch,
|
|
419
|
+
clampBatch(this.config.batch, MAX_BULK_ITEMS),
|
|
391
420
|
this.logger
|
|
392
421
|
);
|
|
393
422
|
this.learnBatcher = new LearnBatcher(
|
|
394
423
|
(entries) => this.executeBatchLearn(entries),
|
|
395
|
-
this.config.batch,
|
|
424
|
+
clampBatch(this.config.batch, MAX_LEARN_ENTRIES),
|
|
396
425
|
this.logger
|
|
397
426
|
);
|
|
398
427
|
}
|
|
@@ -411,19 +440,38 @@ var FetchBrainClient = class {
|
|
|
411
440
|
}
|
|
412
441
|
}
|
|
413
442
|
/**
|
|
414
|
-
* Recall multiple requests at once — returns ordered array matching input order
|
|
443
|
+
* Recall multiple requests at once — returns ordered array matching input order.
|
|
444
|
+
* Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
|
|
445
|
+
* failed chunk degrades to fallback results for its own items only.
|
|
415
446
|
*/
|
|
416
447
|
async recallBulk(requests) {
|
|
417
|
-
|
|
418
|
-
|
|
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 }));
|
|
448
|
+
const chunks = [];
|
|
449
|
+
for (let start = 0; start < requests.length; start += MAX_BULK_ITEMS) {
|
|
450
|
+
chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
|
|
426
451
|
}
|
|
452
|
+
const chunkResults = new Array(chunks.length);
|
|
453
|
+
let next = 0;
|
|
454
|
+
const worker = async () => {
|
|
455
|
+
while (next < chunks.length) {
|
|
456
|
+
const idx = next++;
|
|
457
|
+
const chunk = chunks[idx];
|
|
458
|
+
if (this.circuitBreaker.isOpen()) {
|
|
459
|
+
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
try {
|
|
463
|
+
const items = chunk.map((request, i) => ({ ref: String(i), request }));
|
|
464
|
+
const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
|
|
465
|
+
chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
|
|
466
|
+
} catch {
|
|
467
|
+
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
await Promise.all(
|
|
472
|
+
Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
|
|
473
|
+
);
|
|
474
|
+
return chunkResults.flat();
|
|
427
475
|
}
|
|
428
476
|
/**
|
|
429
477
|
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
@@ -432,12 +480,15 @@ var FetchBrainClient = class {
|
|
|
432
480
|
if (!this.config.learning) {
|
|
433
481
|
return { status: "rejected", learned: 0 };
|
|
434
482
|
}
|
|
435
|
-
if (this.circuitBreaker.isOpen()) {
|
|
483
|
+
if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
|
|
436
484
|
return { status: "rejected", learned: 0 };
|
|
437
485
|
}
|
|
438
486
|
try {
|
|
439
487
|
return await this.learnBatcher.learn(request, data);
|
|
440
488
|
} catch (error) {
|
|
489
|
+
if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
|
|
490
|
+
return { status: "rejected", learned: 0 };
|
|
491
|
+
}
|
|
441
492
|
this.logger.warn("Learn failed:", error);
|
|
442
493
|
return { status: "rejected", learned: 0 };
|
|
443
494
|
}
|
|
@@ -462,7 +513,7 @@ var FetchBrainClient = class {
|
|
|
462
513
|
}
|
|
463
514
|
}
|
|
464
515
|
/**
|
|
465
|
-
* Ask a natural-language question
|
|
516
|
+
* Ask a natural-language question, answered from everything the account has learned
|
|
466
517
|
*
|
|
467
518
|
* `model` picks the generation model for answer mode from the server's
|
|
468
519
|
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
@@ -511,7 +562,7 @@ var FetchBrainClient = class {
|
|
|
511
562
|
/**
|
|
512
563
|
* Execute a batch query against the API
|
|
513
564
|
*/
|
|
514
|
-
async executeBatchQuery(items) {
|
|
565
|
+
async executeBatchQuery(items, timeout) {
|
|
515
566
|
const results = /* @__PURE__ */ new Map();
|
|
516
567
|
const request = {
|
|
517
568
|
items,
|
|
@@ -522,10 +573,14 @@ var FetchBrainClient = class {
|
|
|
522
573
|
request.build = platformBuildId;
|
|
523
574
|
}
|
|
524
575
|
try {
|
|
525
|
-
const response = await this.makeRequest(
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
576
|
+
const response = await this.makeRequest(
|
|
577
|
+
"/v1/recall",
|
|
578
|
+
{
|
|
579
|
+
method: "POST",
|
|
580
|
+
body: JSON.stringify(request)
|
|
581
|
+
},
|
|
582
|
+
timeout
|
|
583
|
+
);
|
|
529
584
|
this.circuitBreaker.recordSuccess();
|
|
530
585
|
for (const item of response.known) {
|
|
531
586
|
results.set(item.ref, { known: true, data: item.data });
|
|
@@ -564,6 +619,24 @@ var FetchBrainClient = class {
|
|
|
564
619
|
this.circuitBreaker.recordSuccess();
|
|
565
620
|
return response;
|
|
566
621
|
} catch (error) {
|
|
622
|
+
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
623
|
+
if (error.code === "LEARN_CAP_EXCEEDED") {
|
|
624
|
+
const now = /* @__PURE__ */ new Date();
|
|
625
|
+
const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
|
|
626
|
+
this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
|
|
627
|
+
if (this.learnCapWarnedUntil < monthStart) {
|
|
628
|
+
this.learnCapWarnedUntil = monthStart;
|
|
629
|
+
this.logger.warn(
|
|
630
|
+
"FetchBrain monthly learning limit reached \u2014 learning is paused until the 1st (UTC); recall keeps working."
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
} else if (error.status === 429) {
|
|
634
|
+
const waitMs = Math.min(Math.max(error.retryAfterSec ?? 30, 1), 3600) * 1e3;
|
|
635
|
+
this.learnPausedUntil = Math.max(this.learnPausedUntil, Date.now() + waitMs);
|
|
636
|
+
this.logger.debug(`Learn rate-limited; pausing learns for ${waitMs / 1e3}s`);
|
|
637
|
+
}
|
|
638
|
+
throw error;
|
|
639
|
+
}
|
|
567
640
|
this.circuitBreaker.recordFailure();
|
|
568
641
|
throw error;
|
|
569
642
|
}
|
|
@@ -609,12 +682,21 @@ var FetchBrainClient = class {
|
|
|
609
682
|
});
|
|
610
683
|
if (!response.ok) {
|
|
611
684
|
let serverError;
|
|
685
|
+
let code;
|
|
612
686
|
try {
|
|
613
687
|
const errBody = await response.json();
|
|
614
688
|
if (typeof errBody.error === "string") serverError = errBody.error;
|
|
689
|
+
const specific = errBody.details?.code ?? errBody.code;
|
|
690
|
+
if (typeof specific === "string") code = specific;
|
|
615
691
|
} catch {
|
|
616
692
|
}
|
|
617
|
-
throw new ApiError(
|
|
693
|
+
throw new ApiError(
|
|
694
|
+
response.status,
|
|
695
|
+
response.statusText,
|
|
696
|
+
serverError,
|
|
697
|
+
code,
|
|
698
|
+
parseRetryAfter(response.headers.get("Retry-After"))
|
|
699
|
+
);
|
|
618
700
|
}
|
|
619
701
|
return await response.json();
|
|
620
702
|
} finally {
|
|
@@ -828,6 +910,7 @@ var TelemetryBuffer = class {
|
|
|
828
910
|
// src/enhance.ts
|
|
829
911
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
830
912
|
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
913
|
+
var MAX_STASH_ENTRIES = 5e3;
|
|
831
914
|
function buildRawRequest(request) {
|
|
832
915
|
const r = request;
|
|
833
916
|
let headers;
|
|
@@ -933,6 +1016,8 @@ var FetchBrain = class {
|
|
|
933
1016
|
// Actually ran handler
|
|
934
1017
|
bypassed: 0,
|
|
935
1018
|
// skipLabels match — ran handler outside FetchBrain
|
|
1019
|
+
dropped: 0,
|
|
1020
|
+
// enqueue-time fetch skipped, but remembered data gone by execution
|
|
936
1021
|
startTime: 0
|
|
937
1022
|
};
|
|
938
1023
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
@@ -942,6 +1027,25 @@ var FetchBrain = class {
|
|
|
942
1027
|
}
|
|
943
1028
|
const crawlerType = crawler.constructor?.name || "Unknown";
|
|
944
1029
|
const warnedKeys = /* @__PURE__ */ new Set();
|
|
1030
|
+
const preRecalledData = /* @__PURE__ */ new Map();
|
|
1031
|
+
const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
|
|
1032
|
+
const stashSet = (key, data) => {
|
|
1033
|
+
if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
|
|
1034
|
+
const oldest = preRecalledData.keys().next().value;
|
|
1035
|
+
if (oldest !== void 0) preRecalledData.delete(oldest);
|
|
1036
|
+
}
|
|
1037
|
+
preRecalledData.set(key, data);
|
|
1038
|
+
};
|
|
1039
|
+
const stashTake = (r) => {
|
|
1040
|
+
for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
|
|
1041
|
+
const data = preRecalledData.get(key);
|
|
1042
|
+
if (data) {
|
|
1043
|
+
preRecalledData.delete(key);
|
|
1044
|
+
return data;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
return void 0;
|
|
1048
|
+
};
|
|
945
1049
|
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
946
1050
|
const wrappedHandler = async (context) => {
|
|
947
1051
|
const { request } = context;
|
|
@@ -962,10 +1066,50 @@ var FetchBrain = class {
|
|
|
962
1066
|
});
|
|
963
1067
|
const rawRequest = buildRawRequest(request);
|
|
964
1068
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
|
|
1069
|
+
let consumedStash;
|
|
965
1070
|
try {
|
|
966
|
-
const
|
|
1071
|
+
const preRecalled = request.userData?.__fetchBrainResult;
|
|
1072
|
+
let aiResult;
|
|
1073
|
+
if (preRecalled?.known) {
|
|
1074
|
+
const stashedData = stashTake(rawRequest);
|
|
1075
|
+
if (stashedData) {
|
|
1076
|
+
consumedStash = stashedData;
|
|
1077
|
+
aiResult = { known: true, data: stashedData };
|
|
1078
|
+
} else {
|
|
1079
|
+
aiResult = await client.recall(rawRequest);
|
|
1080
|
+
}
|
|
1081
|
+
} else if (preRecalled) {
|
|
1082
|
+
aiResult = preRecalled;
|
|
1083
|
+
} else {
|
|
1084
|
+
aiResult = await client.recall(rawRequest);
|
|
1085
|
+
}
|
|
1086
|
+
if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
|
|
1087
|
+
if (aiResult.fallback) {
|
|
1088
|
+
throw new Error(
|
|
1089
|
+
`FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
|
|
1090
|
+
);
|
|
1091
|
+
}
|
|
1092
|
+
runStats.dropped++;
|
|
1093
|
+
request.noRetry = true;
|
|
1094
|
+
throw new Error(
|
|
1095
|
+
`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.`
|
|
1096
|
+
);
|
|
1097
|
+
}
|
|
967
1098
|
let usedAIData = false;
|
|
968
1099
|
const originalPushData = context.pushData;
|
|
1100
|
+
const fireOnRecalled = async (data) => {
|
|
1101
|
+
if (!config.onRecalled) return;
|
|
1102
|
+
try {
|
|
1103
|
+
await config.onRecalled({
|
|
1104
|
+
url,
|
|
1105
|
+
label: request.label,
|
|
1106
|
+
userData: rawRequest.userData,
|
|
1107
|
+
data
|
|
1108
|
+
});
|
|
1109
|
+
} catch (hookErr) {
|
|
1110
|
+
logger.debug(`onRecalled hook error: ${hookErr}`);
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
969
1113
|
context.brain = {
|
|
970
1114
|
known: aiResult.known,
|
|
971
1115
|
data: aiResult.data,
|
|
@@ -974,6 +1118,7 @@ var FetchBrain = class {
|
|
|
974
1118
|
usedAIData = true;
|
|
975
1119
|
await originalPushData.call(context, aiResult.data);
|
|
976
1120
|
logger.info(`Used brain data: ${url}`);
|
|
1121
|
+
await fireOnRecalled(aiResult.data);
|
|
977
1122
|
}
|
|
978
1123
|
}
|
|
979
1124
|
};
|
|
@@ -991,6 +1136,7 @@ var FetchBrain = class {
|
|
|
991
1136
|
if (originalPushData) {
|
|
992
1137
|
await originalPushData.call(context, aiResult.data);
|
|
993
1138
|
}
|
|
1139
|
+
await fireOnRecalled(aiResult.data);
|
|
994
1140
|
return;
|
|
995
1141
|
}
|
|
996
1142
|
runStats.scraped++;
|
|
@@ -1063,6 +1209,9 @@ var FetchBrain = class {
|
|
|
1063
1209
|
}
|
|
1064
1210
|
}
|
|
1065
1211
|
} catch (err) {
|
|
1212
|
+
if (consumedStash) {
|
|
1213
|
+
stashSet(stashKey(rawRequest), consumedStash);
|
|
1214
|
+
}
|
|
1066
1215
|
if (telemetryConfig.enabled) {
|
|
1067
1216
|
try {
|
|
1068
1217
|
const telemetry = await collectTelemetry(
|
|
@@ -1122,11 +1271,80 @@ var FetchBrain = class {
|
|
|
1122
1271
|
const managedRequests = runStats.totalRequests - runStats.bypassed;
|
|
1123
1272
|
const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
1124
1273
|
logger.info(
|
|
1125
|
-
`\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + `, duration: ${duration}s`
|
|
1274
|
+
`\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`
|
|
1126
1275
|
);
|
|
1127
1276
|
}
|
|
1128
1277
|
};
|
|
1129
1278
|
}
|
|
1279
|
+
if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
1280
|
+
const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
|
|
1281
|
+
if (crawlerAny.retryOnBlocked) {
|
|
1282
|
+
logger.info(
|
|
1283
|
+
"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."
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
crawlerAny.addRequests = async (requests, options) => {
|
|
1287
|
+
if (!Array.isArray(requests) || requests.length === 0) {
|
|
1288
|
+
return originalAddRequests(requests, options);
|
|
1289
|
+
}
|
|
1290
|
+
const retryOnBlocked = Boolean(
|
|
1291
|
+
crawlerAny.retryOnBlocked
|
|
1292
|
+
);
|
|
1293
|
+
const batch = requests.map((r) => {
|
|
1294
|
+
if (typeof r === "string") return { url: r };
|
|
1295
|
+
if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
|
|
1296
|
+
return { ...r };
|
|
1297
|
+
}
|
|
1298
|
+
return r;
|
|
1299
|
+
});
|
|
1300
|
+
try {
|
|
1301
|
+
const candidateIdx = [];
|
|
1302
|
+
for (let i = 0; i < batch.length; i++) {
|
|
1303
|
+
const r = batch[i];
|
|
1304
|
+
if (!r || typeof r.url !== "string") continue;
|
|
1305
|
+
const prior = r.userData?.__fetchBrainResult;
|
|
1306
|
+
if (prior) {
|
|
1307
|
+
if (prior.known && r.skipNavigation) r.skipNavigation = false;
|
|
1308
|
+
const rest = { ...r.userData };
|
|
1309
|
+
delete rest.__fetchBrainResult;
|
|
1310
|
+
r.userData = rest;
|
|
1311
|
+
}
|
|
1312
|
+
if (r.skipNavigation) continue;
|
|
1313
|
+
if (skipLabels && skipLabels.has(r.label || "default")) continue;
|
|
1314
|
+
if ((r.method ?? "GET").toUpperCase() !== "GET" && !r.uniqueKey) continue;
|
|
1315
|
+
candidateIdx.push(i);
|
|
1316
|
+
}
|
|
1317
|
+
if (candidateIdx.length > 0) {
|
|
1318
|
+
const rawRequests = candidateIdx.map(
|
|
1319
|
+
(i) => buildRawRequest(batch[i])
|
|
1320
|
+
);
|
|
1321
|
+
const results = await client.recallBulk(rawRequests);
|
|
1322
|
+
let known = 0;
|
|
1323
|
+
candidateIdx.forEach((reqIdx, j) => {
|
|
1324
|
+
const result = results[j];
|
|
1325
|
+
if (!result || result.fallback) return;
|
|
1326
|
+
const r = batch[reqIdx];
|
|
1327
|
+
if (result.known && result.data) {
|
|
1328
|
+
r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
|
|
1329
|
+
stashSet(stashKey(rawRequests[j]), result.data);
|
|
1330
|
+
if (!retryOnBlocked && !shouldRunHandler(config.alwaysRun, r.label)) {
|
|
1331
|
+
r.skipNavigation = true;
|
|
1332
|
+
known++;
|
|
1333
|
+
}
|
|
1334
|
+
} else {
|
|
1335
|
+
r.userData = { ...r.userData, __fetchBrainResult: { known: false } };
|
|
1336
|
+
}
|
|
1337
|
+
});
|
|
1338
|
+
logger.debug(
|
|
1339
|
+
`Pre-recalled ${candidateIdx.length} enqueued request(s): ${known} known (fetch skipped)`
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
} catch (err) {
|
|
1343
|
+
logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
|
|
1344
|
+
}
|
|
1345
|
+
return originalAddRequests(batch, options);
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1130
1348
|
return Object.assign(crawler, { fetchBrain: client });
|
|
1131
1349
|
}
|
|
1132
1350
|
};
|