@fetchbrain.com/sdk 0.4.0 → 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 +64 -5
- package/dist/index.d.mts +5 -3
- package/dist/index.d.ts +5 -3
- package/dist/index.js +190 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +190 -20
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +1 -1
- package/dist/mock/index.d.ts +1 -1
- package/dist/{types-D8djjVGS.d.mts → types-BbLgy1no.d.mts} +41 -1
- package/dist/{types-D8djjVGS.d.ts → types-BbLgy1no.d.ts} +41 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -344,7 +344,14 @@ 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
356
|
constructor(status, statusText, serverError) {
|
|
350
357
|
super(`API error: ${status} ${statusText}`);
|
|
@@ -377,7 +384,11 @@ var FetchBrainClient = class {
|
|
|
377
384
|
// opt-in
|
|
378
385
|
batch: config.batch,
|
|
379
386
|
circuitBreaker: config.circuitBreaker,
|
|
380
|
-
skipLabels: config.skipLabels
|
|
387
|
+
skipLabels: config.skipLabels,
|
|
388
|
+
// enhance-only; stored so getConfig() round-trips
|
|
389
|
+
preRecall: config.preRecall,
|
|
390
|
+
// enhance-only; stored so getConfig() round-trips
|
|
391
|
+
onRecalled: config.onRecalled
|
|
381
392
|
// enhance-only; stored so getConfig() round-trips
|
|
382
393
|
};
|
|
383
394
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
@@ -387,12 +398,12 @@ var FetchBrainClient = class {
|
|
|
387
398
|
);
|
|
388
399
|
this.batcher = new RequestBatcher(
|
|
389
400
|
(items) => this.executeBatchQuery(items),
|
|
390
|
-
this.config.batch,
|
|
401
|
+
clampBatch(this.config.batch, MAX_BULK_ITEMS),
|
|
391
402
|
this.logger
|
|
392
403
|
);
|
|
393
404
|
this.learnBatcher = new LearnBatcher(
|
|
394
405
|
(entries) => this.executeBatchLearn(entries),
|
|
395
|
-
this.config.batch,
|
|
406
|
+
clampBatch(this.config.batch, MAX_LEARN_ENTRIES),
|
|
396
407
|
this.logger
|
|
397
408
|
);
|
|
398
409
|
}
|
|
@@ -411,19 +422,38 @@ var FetchBrainClient = class {
|
|
|
411
422
|
}
|
|
412
423
|
}
|
|
413
424
|
/**
|
|
414
|
-
* Recall multiple requests at once — returns ordered array matching input order
|
|
425
|
+
* Recall multiple requests at once — returns ordered array matching input order.
|
|
426
|
+
* Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
|
|
427
|
+
* failed chunk degrades to fallback results for its own items only.
|
|
415
428
|
*/
|
|
416
429
|
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 }));
|
|
430
|
+
const chunks = [];
|
|
431
|
+
for (let start = 0; start < requests.length; start += MAX_BULK_ITEMS) {
|
|
432
|
+
chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
|
|
426
433
|
}
|
|
434
|
+
const chunkResults = new Array(chunks.length);
|
|
435
|
+
let next = 0;
|
|
436
|
+
const worker = async () => {
|
|
437
|
+
while (next < chunks.length) {
|
|
438
|
+
const idx = next++;
|
|
439
|
+
const chunk = chunks[idx];
|
|
440
|
+
if (this.circuitBreaker.isOpen()) {
|
|
441
|
+
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
try {
|
|
445
|
+
const items = chunk.map((request, i) => ({ ref: String(i), request }));
|
|
446
|
+
const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
|
|
447
|
+
chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
|
|
448
|
+
} catch {
|
|
449
|
+
chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
await Promise.all(
|
|
454
|
+
Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
|
|
455
|
+
);
|
|
456
|
+
return chunkResults.flat();
|
|
427
457
|
}
|
|
428
458
|
/**
|
|
429
459
|
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
@@ -511,7 +541,7 @@ var FetchBrainClient = class {
|
|
|
511
541
|
/**
|
|
512
542
|
* Execute a batch query against the API
|
|
513
543
|
*/
|
|
514
|
-
async executeBatchQuery(items) {
|
|
544
|
+
async executeBatchQuery(items, timeout) {
|
|
515
545
|
const results = /* @__PURE__ */ new Map();
|
|
516
546
|
const request = {
|
|
517
547
|
items,
|
|
@@ -522,10 +552,14 @@ var FetchBrainClient = class {
|
|
|
522
552
|
request.build = platformBuildId;
|
|
523
553
|
}
|
|
524
554
|
try {
|
|
525
|
-
const response = await this.makeRequest(
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
555
|
+
const response = await this.makeRequest(
|
|
556
|
+
"/v1/recall",
|
|
557
|
+
{
|
|
558
|
+
method: "POST",
|
|
559
|
+
body: JSON.stringify(request)
|
|
560
|
+
},
|
|
561
|
+
timeout
|
|
562
|
+
);
|
|
529
563
|
this.circuitBreaker.recordSuccess();
|
|
530
564
|
for (const item of response.known) {
|
|
531
565
|
results.set(item.ref, { known: true, data: item.data });
|
|
@@ -828,6 +862,7 @@ var TelemetryBuffer = class {
|
|
|
828
862
|
// src/enhance.ts
|
|
829
863
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
830
864
|
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
865
|
+
var MAX_STASH_ENTRIES = 5e3;
|
|
831
866
|
function buildRawRequest(request) {
|
|
832
867
|
const r = request;
|
|
833
868
|
let headers;
|
|
@@ -933,6 +968,8 @@ var FetchBrain = class {
|
|
|
933
968
|
// Actually ran handler
|
|
934
969
|
bypassed: 0,
|
|
935
970
|
// skipLabels match — ran handler outside FetchBrain
|
|
971
|
+
dropped: 0,
|
|
972
|
+
// enqueue-time fetch skipped, but remembered data gone by execution
|
|
936
973
|
startTime: 0
|
|
937
974
|
};
|
|
938
975
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
@@ -942,6 +979,25 @@ var FetchBrain = class {
|
|
|
942
979
|
}
|
|
943
980
|
const crawlerType = crawler.constructor?.name || "Unknown";
|
|
944
981
|
const warnedKeys = /* @__PURE__ */ new Set();
|
|
982
|
+
const preRecalledData = /* @__PURE__ */ new Map();
|
|
983
|
+
const stashKey = (r) => `${(r.method ?? "GET").toUpperCase()} ${r.uniqueKey ?? r.url}`;
|
|
984
|
+
const stashSet = (key, data) => {
|
|
985
|
+
if (!preRecalledData.delete(key) && preRecalledData.size >= MAX_STASH_ENTRIES) {
|
|
986
|
+
const oldest = preRecalledData.keys().next().value;
|
|
987
|
+
if (oldest !== void 0) preRecalledData.delete(oldest);
|
|
988
|
+
}
|
|
989
|
+
preRecalledData.set(key, data);
|
|
990
|
+
};
|
|
991
|
+
const stashTake = (r) => {
|
|
992
|
+
for (const key of [stashKey(r), `${(r.method ?? "GET").toUpperCase()} ${r.url}`]) {
|
|
993
|
+
const data = preRecalledData.get(key);
|
|
994
|
+
if (data) {
|
|
995
|
+
preRecalledData.delete(key);
|
|
996
|
+
return data;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return void 0;
|
|
1000
|
+
};
|
|
945
1001
|
const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
|
|
946
1002
|
const wrappedHandler = async (context) => {
|
|
947
1003
|
const { request } = context;
|
|
@@ -962,10 +1018,50 @@ var FetchBrain = class {
|
|
|
962
1018
|
});
|
|
963
1019
|
const rawRequest = buildRawRequest(request);
|
|
964
1020
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
|
|
1021
|
+
let consumedStash;
|
|
965
1022
|
try {
|
|
966
|
-
const
|
|
1023
|
+
const preRecalled = request.userData?.__fetchBrainResult;
|
|
1024
|
+
let aiResult;
|
|
1025
|
+
if (preRecalled?.known) {
|
|
1026
|
+
const stashedData = stashTake(rawRequest);
|
|
1027
|
+
if (stashedData) {
|
|
1028
|
+
consumedStash = stashedData;
|
|
1029
|
+
aiResult = { known: true, data: stashedData };
|
|
1030
|
+
} else {
|
|
1031
|
+
aiResult = await client.recall(rawRequest);
|
|
1032
|
+
}
|
|
1033
|
+
} else if (preRecalled) {
|
|
1034
|
+
aiResult = preRecalled;
|
|
1035
|
+
} else {
|
|
1036
|
+
aiResult = await client.recall(rawRequest);
|
|
1037
|
+
}
|
|
1038
|
+
if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
|
|
1039
|
+
if (aiResult.fallback) {
|
|
1040
|
+
throw new Error(
|
|
1041
|
+
`FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
runStats.dropped++;
|
|
1045
|
+
request.noRetry = true;
|
|
1046
|
+
throw new Error(
|
|
1047
|
+
`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.`
|
|
1048
|
+
);
|
|
1049
|
+
}
|
|
967
1050
|
let usedAIData = false;
|
|
968
1051
|
const originalPushData = context.pushData;
|
|
1052
|
+
const fireOnRecalled = async (data) => {
|
|
1053
|
+
if (!config.onRecalled) return;
|
|
1054
|
+
try {
|
|
1055
|
+
await config.onRecalled({
|
|
1056
|
+
url,
|
|
1057
|
+
label: request.label,
|
|
1058
|
+
userData: rawRequest.userData,
|
|
1059
|
+
data
|
|
1060
|
+
});
|
|
1061
|
+
} catch (hookErr) {
|
|
1062
|
+
logger.debug(`onRecalled hook error: ${hookErr}`);
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
969
1065
|
context.brain = {
|
|
970
1066
|
known: aiResult.known,
|
|
971
1067
|
data: aiResult.data,
|
|
@@ -974,6 +1070,7 @@ var FetchBrain = class {
|
|
|
974
1070
|
usedAIData = true;
|
|
975
1071
|
await originalPushData.call(context, aiResult.data);
|
|
976
1072
|
logger.info(`Used brain data: ${url}`);
|
|
1073
|
+
await fireOnRecalled(aiResult.data);
|
|
977
1074
|
}
|
|
978
1075
|
}
|
|
979
1076
|
};
|
|
@@ -991,6 +1088,7 @@ var FetchBrain = class {
|
|
|
991
1088
|
if (originalPushData) {
|
|
992
1089
|
await originalPushData.call(context, aiResult.data);
|
|
993
1090
|
}
|
|
1091
|
+
await fireOnRecalled(aiResult.data);
|
|
994
1092
|
return;
|
|
995
1093
|
}
|
|
996
1094
|
runStats.scraped++;
|
|
@@ -1063,6 +1161,9 @@ var FetchBrain = class {
|
|
|
1063
1161
|
}
|
|
1064
1162
|
}
|
|
1065
1163
|
} catch (err) {
|
|
1164
|
+
if (consumedStash) {
|
|
1165
|
+
stashSet(stashKey(rawRequest), consumedStash);
|
|
1166
|
+
}
|
|
1066
1167
|
if (telemetryConfig.enabled) {
|
|
1067
1168
|
try {
|
|
1068
1169
|
const telemetry = await collectTelemetry(
|
|
@@ -1122,11 +1223,80 @@ var FetchBrain = class {
|
|
|
1122
1223
|
const managedRequests = runStats.totalRequests - runStats.bypassed;
|
|
1123
1224
|
const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
|
|
1124
1225
|
logger.info(
|
|
1125
|
-
`\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + `, duration: ${duration}s`
|
|
1226
|
+
`\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
1227
|
);
|
|
1127
1228
|
}
|
|
1128
1229
|
};
|
|
1129
1230
|
}
|
|
1231
|
+
if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
|
|
1232
|
+
const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
|
|
1233
|
+
if (crawlerAny.retryOnBlocked) {
|
|
1234
|
+
logger.info(
|
|
1235
|
+
"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."
|
|
1236
|
+
);
|
|
1237
|
+
}
|
|
1238
|
+
crawlerAny.addRequests = async (requests, options) => {
|
|
1239
|
+
if (!Array.isArray(requests) || requests.length === 0) {
|
|
1240
|
+
return originalAddRequests(requests, options);
|
|
1241
|
+
}
|
|
1242
|
+
const retryOnBlocked = Boolean(
|
|
1243
|
+
crawlerAny.retryOnBlocked
|
|
1244
|
+
);
|
|
1245
|
+
const batch = requests.map((r) => {
|
|
1246
|
+
if (typeof r === "string") return { url: r };
|
|
1247
|
+
if (r && typeof r === "object" && Object.getPrototypeOf(r) === Object.prototype) {
|
|
1248
|
+
return { ...r };
|
|
1249
|
+
}
|
|
1250
|
+
return r;
|
|
1251
|
+
});
|
|
1252
|
+
try {
|
|
1253
|
+
const candidateIdx = [];
|
|
1254
|
+
for (let i = 0; i < batch.length; i++) {
|
|
1255
|
+
const r = batch[i];
|
|
1256
|
+
if (!r || typeof r.url !== "string") continue;
|
|
1257
|
+
const prior = r.userData?.__fetchBrainResult;
|
|
1258
|
+
if (prior) {
|
|
1259
|
+
if (prior.known && r.skipNavigation) r.skipNavigation = false;
|
|
1260
|
+
const rest = { ...r.userData };
|
|
1261
|
+
delete rest.__fetchBrainResult;
|
|
1262
|
+
r.userData = rest;
|
|
1263
|
+
}
|
|
1264
|
+
if (r.skipNavigation) continue;
|
|
1265
|
+
if (skipLabels && skipLabels.has(r.label || "default")) continue;
|
|
1266
|
+
if ((r.method ?? "GET").toUpperCase() !== "GET" && !r.uniqueKey) continue;
|
|
1267
|
+
candidateIdx.push(i);
|
|
1268
|
+
}
|
|
1269
|
+
if (candidateIdx.length > 0) {
|
|
1270
|
+
const rawRequests = candidateIdx.map(
|
|
1271
|
+
(i) => buildRawRequest(batch[i])
|
|
1272
|
+
);
|
|
1273
|
+
const results = await client.recallBulk(rawRequests);
|
|
1274
|
+
let known = 0;
|
|
1275
|
+
candidateIdx.forEach((reqIdx, j) => {
|
|
1276
|
+
const result = results[j];
|
|
1277
|
+
if (!result || result.fallback) return;
|
|
1278
|
+
const r = batch[reqIdx];
|
|
1279
|
+
if (result.known && result.data) {
|
|
1280
|
+
r.userData = { ...r.userData, __fetchBrainResult: { known: true } };
|
|
1281
|
+
stashSet(stashKey(rawRequests[j]), result.data);
|
|
1282
|
+
if (!retryOnBlocked && !shouldRunHandler(config.alwaysRun, r.label)) {
|
|
1283
|
+
r.skipNavigation = true;
|
|
1284
|
+
known++;
|
|
1285
|
+
}
|
|
1286
|
+
} else {
|
|
1287
|
+
r.userData = { ...r.userData, __fetchBrainResult: { known: false } };
|
|
1288
|
+
}
|
|
1289
|
+
});
|
|
1290
|
+
logger.debug(
|
|
1291
|
+
`Pre-recalled ${candidateIdx.length} enqueued request(s): ${known} known (fetch skipped)`
|
|
1292
|
+
);
|
|
1293
|
+
}
|
|
1294
|
+
} catch (err) {
|
|
1295
|
+
logger.debug(`Pre-recall failed, falling back to handler-time recall: ${err}`);
|
|
1296
|
+
}
|
|
1297
|
+
return originalAddRequests(batch, options);
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1130
1300
|
return Object.assign(crawler, { fetchBrain: client });
|
|
1131
1301
|
}
|
|
1132
1302
|
};
|