@fetchbrain.com/sdk 0.1.6 → 0.1.7
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 +10 -5
- package/dist/index.d.mts +31 -8
- package/dist/index.d.ts +31 -8
- package/dist/index.js +199 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +199 -25
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -2
package/dist/index.mjs
CHANGED
|
@@ -182,39 +182,146 @@ var RequestBatcher = class {
|
|
|
182
182
|
this.queue = [];
|
|
183
183
|
}
|
|
184
184
|
};
|
|
185
|
+
var LearnBatcher = class {
|
|
186
|
+
constructor(executor, config = {}, logger) {
|
|
187
|
+
this.queue = [];
|
|
188
|
+
this.flushTimeout = null;
|
|
189
|
+
this.executor = executor;
|
|
190
|
+
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
191
|
+
this.logger = logger;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Add a learn entry to the batch queue
|
|
195
|
+
*/
|
|
196
|
+
async learn(url, data) {
|
|
197
|
+
return new Promise((resolve, reject) => {
|
|
198
|
+
this.queue.push({ entry: { url, data }, resolve, reject });
|
|
199
|
+
if (this.queue.length >= this.config.maxSize) {
|
|
200
|
+
this.flush();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
if (!this.flushTimeout) {
|
|
204
|
+
this.flushTimeout = setTimeout(() => {
|
|
205
|
+
this.flush();
|
|
206
|
+
}, this.config.maxWait);
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Flush the current batch
|
|
212
|
+
*/
|
|
213
|
+
async flush() {
|
|
214
|
+
if (this.flushTimeout) {
|
|
215
|
+
clearTimeout(this.flushTimeout);
|
|
216
|
+
this.flushTimeout = null;
|
|
217
|
+
}
|
|
218
|
+
if (this.queue.length === 0) {
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const batch = this.queue.splice(0, this.config.maxSize);
|
|
222
|
+
const entries = batch.map((r) => r.entry);
|
|
223
|
+
this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
|
|
224
|
+
try {
|
|
225
|
+
const result = await this.executor(entries);
|
|
226
|
+
for (const request of batch) {
|
|
227
|
+
request.resolve(result);
|
|
228
|
+
}
|
|
229
|
+
} catch (error) {
|
|
230
|
+
for (const request of batch) {
|
|
231
|
+
request.reject(error);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (this.queue.length > 0) {
|
|
235
|
+
this.flushTimeout = setTimeout(() => {
|
|
236
|
+
this.flush();
|
|
237
|
+
}, this.config.maxWait);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Force flush and wait for completion (for cleanup/shutdown)
|
|
242
|
+
*/
|
|
243
|
+
async forceFlush() {
|
|
244
|
+
if (this.queue.length > 0) {
|
|
245
|
+
await this.flush();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Get current queue size
|
|
250
|
+
*/
|
|
251
|
+
getQueueSize() {
|
|
252
|
+
return this.queue.length;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Clear the queue (for cleanup)
|
|
256
|
+
*/
|
|
257
|
+
clear() {
|
|
258
|
+
if (this.flushTimeout) {
|
|
259
|
+
clearTimeout(this.flushTimeout);
|
|
260
|
+
this.flushTimeout = null;
|
|
261
|
+
}
|
|
262
|
+
for (const request of this.queue) {
|
|
263
|
+
request.resolve({ status: "rejected", learned: 0 });
|
|
264
|
+
}
|
|
265
|
+
this.queue = [];
|
|
266
|
+
}
|
|
267
|
+
};
|
|
185
268
|
|
|
186
269
|
// src/logger.ts
|
|
187
|
-
var
|
|
270
|
+
var COLORS = {
|
|
271
|
+
reset: "\x1B[0m",
|
|
272
|
+
cyan: "\x1B[36m",
|
|
273
|
+
green: "\x1B[32m",
|
|
274
|
+
yellow: "\x1B[33m",
|
|
275
|
+
red: "\x1B[31m",
|
|
276
|
+
gray: "\x1B[90m"
|
|
277
|
+
};
|
|
188
278
|
var LOG_LEVELS = {
|
|
189
279
|
debug: 0,
|
|
190
280
|
info: 1,
|
|
191
281
|
warn: 2,
|
|
192
282
|
error: 3
|
|
193
283
|
};
|
|
284
|
+
var LEVEL_COLORS = {
|
|
285
|
+
debug: COLORS.gray,
|
|
286
|
+
info: COLORS.green,
|
|
287
|
+
warn: COLORS.yellow,
|
|
288
|
+
error: COLORS.red
|
|
289
|
+
};
|
|
290
|
+
var LEVEL_LABELS = {
|
|
291
|
+
debug: "DEBUG",
|
|
292
|
+
info: "INFO ",
|
|
293
|
+
warn: "WARN ",
|
|
294
|
+
error: "ERROR"
|
|
295
|
+
};
|
|
194
296
|
function createLogger(minLevel = "info", enabled = true) {
|
|
195
297
|
const shouldLog = (level) => {
|
|
196
298
|
if (!enabled) return false;
|
|
197
299
|
return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
|
|
198
300
|
};
|
|
301
|
+
const formatLog = (level, message) => {
|
|
302
|
+
const levelColor = LEVEL_COLORS[level];
|
|
303
|
+
const label = LEVEL_LABELS[level];
|
|
304
|
+
return `${levelColor}${label}${COLORS.reset} ${COLORS.cyan}FetchBrain:${COLORS.reset} ${message}`;
|
|
305
|
+
};
|
|
199
306
|
return {
|
|
200
307
|
debug: (message, ...args) => {
|
|
201
308
|
if (shouldLog("debug")) {
|
|
202
|
-
console.debug(
|
|
309
|
+
console.debug(formatLog("debug", message), ...args);
|
|
203
310
|
}
|
|
204
311
|
},
|
|
205
312
|
info: (message, ...args) => {
|
|
206
313
|
if (shouldLog("info")) {
|
|
207
|
-
console.info(
|
|
314
|
+
console.info(formatLog("info", message), ...args);
|
|
208
315
|
}
|
|
209
316
|
},
|
|
210
317
|
warn: (message, ...args) => {
|
|
211
318
|
if (shouldLog("warn")) {
|
|
212
|
-
console.warn(
|
|
319
|
+
console.warn(formatLog("warn", message), ...args);
|
|
213
320
|
}
|
|
214
321
|
},
|
|
215
322
|
error: (message, ...args) => {
|
|
216
323
|
if (shouldLog("error")) {
|
|
217
|
-
console.error(
|
|
324
|
+
console.error(formatLog("error", message), ...args);
|
|
218
325
|
}
|
|
219
326
|
}
|
|
220
327
|
};
|
|
@@ -223,6 +330,7 @@ function createLogger(minLevel = "info", enabled = true) {
|
|
|
223
330
|
// src/client.ts
|
|
224
331
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
225
332
|
var DEFAULT_TIMEOUT = 500;
|
|
333
|
+
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
226
334
|
var currentContext = {};
|
|
227
335
|
function setScrapeContext(ctx) {
|
|
228
336
|
currentContext = ctx;
|
|
@@ -238,17 +346,28 @@ var FetchBrainClient = class {
|
|
|
238
346
|
intelligence: config.intelligence || "high",
|
|
239
347
|
learning: config.learning ?? true,
|
|
240
348
|
alwaysRun: config.alwaysRun ?? false,
|
|
241
|
-
|
|
349
|
+
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
242
350
|
timeout: config.timeout || DEFAULT_TIMEOUT,
|
|
243
351
|
debug: config.debug || false,
|
|
244
352
|
extractForLearning: config.extractForLearning,
|
|
245
|
-
|
|
353
|
+
learnUrlField: config.learnUrlField,
|
|
354
|
+
telemetry: config.telemetry ?? { enabled: true },
|
|
355
|
+
batch: config.batch,
|
|
356
|
+
circuitBreaker: config.circuitBreaker
|
|
246
357
|
};
|
|
247
358
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
248
|
-
this.circuitBreaker = new CircuitBreaker(
|
|
359
|
+
this.circuitBreaker = new CircuitBreaker(
|
|
360
|
+
this.config.circuitBreaker,
|
|
361
|
+
this.logger
|
|
362
|
+
);
|
|
249
363
|
this.batcher = new RequestBatcher(
|
|
250
364
|
(urls) => this.executeBatchQuery(urls),
|
|
251
|
-
|
|
365
|
+
this.config.batch,
|
|
366
|
+
this.logger
|
|
367
|
+
);
|
|
368
|
+
this.learnBatcher = new LearnBatcher(
|
|
369
|
+
(entries) => this.executeBatchLearn(entries),
|
|
370
|
+
this.config.batch,
|
|
252
371
|
this.logger
|
|
253
372
|
);
|
|
254
373
|
}
|
|
@@ -287,7 +406,7 @@ var FetchBrainClient = class {
|
|
|
287
406
|
}
|
|
288
407
|
}
|
|
289
408
|
/**
|
|
290
|
-
* "Teach" FetchBrain new data
|
|
409
|
+
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
291
410
|
*/
|
|
292
411
|
async learn(url, data) {
|
|
293
412
|
if (!this.config.learning) {
|
|
@@ -298,18 +417,10 @@ var FetchBrainClient = class {
|
|
|
298
417
|
return { status: "rejected", learned: 0 };
|
|
299
418
|
}
|
|
300
419
|
try {
|
|
301
|
-
const
|
|
302
|
-
const response = await this.makeRequest("/v1/learn", {
|
|
303
|
-
method: "POST",
|
|
304
|
-
body: JSON.stringify({
|
|
305
|
-
entries: [{ url, data: extractedData }]
|
|
306
|
-
})
|
|
307
|
-
});
|
|
308
|
-
this.circuitBreaker.recordSuccess();
|
|
420
|
+
const response = await this.learnBatcher.learn(url, data);
|
|
309
421
|
this.logger.debug(`Learned data for: ${url}`);
|
|
310
422
|
return response;
|
|
311
423
|
} catch (error) {
|
|
312
|
-
this.circuitBreaker.recordFailure();
|
|
313
424
|
this.logger.warn(`Learn failed for ${url}:`, error);
|
|
314
425
|
return { status: "rejected", learned: 0 };
|
|
315
426
|
}
|
|
@@ -342,7 +453,7 @@ var FetchBrainClient = class {
|
|
|
342
453
|
urls,
|
|
343
454
|
intelligence: this.config.intelligence
|
|
344
455
|
};
|
|
345
|
-
if (this.config.
|
|
456
|
+
if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
|
|
346
457
|
request.build = process.env.APIFY_ACTOR_BUILD_ID;
|
|
347
458
|
}
|
|
348
459
|
try {
|
|
@@ -367,13 +478,43 @@ var FetchBrainClient = class {
|
|
|
367
478
|
throw error;
|
|
368
479
|
}
|
|
369
480
|
}
|
|
481
|
+
/**
|
|
482
|
+
* Execute a batch learn against the API
|
|
483
|
+
*/
|
|
484
|
+
async executeBatchLearn(entries) {
|
|
485
|
+
const processedEntries = entries.map((entry) => ({
|
|
486
|
+
url: entry.url,
|
|
487
|
+
data: this.config.extractForLearning ? this.config.extractForLearning(entry.data) : entry.data
|
|
488
|
+
}));
|
|
489
|
+
try {
|
|
490
|
+
const response = await this.makeRequest(
|
|
491
|
+
"/v1/learn",
|
|
492
|
+
{
|
|
493
|
+
method: "POST",
|
|
494
|
+
body: JSON.stringify({
|
|
495
|
+
entries: processedEntries
|
|
496
|
+
})
|
|
497
|
+
},
|
|
498
|
+
DEFAULT_LEARN_TIMEOUT
|
|
499
|
+
);
|
|
500
|
+
this.circuitBreaker.recordSuccess();
|
|
501
|
+
this.logger.debug(`Batch learned ${entries.length} entries`);
|
|
502
|
+
return response;
|
|
503
|
+
} catch (error) {
|
|
504
|
+
this.circuitBreaker.recordFailure();
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
370
508
|
/**
|
|
371
509
|
* Make an HTTP request to the API
|
|
372
510
|
*/
|
|
373
|
-
async makeRequest(path, options) {
|
|
511
|
+
async makeRequest(path, options, timeout) {
|
|
374
512
|
const url = `${this.config.baseUrl}${path}`;
|
|
375
513
|
const controller = new AbortController();
|
|
376
|
-
const timeoutId = setTimeout(
|
|
514
|
+
const timeoutId = setTimeout(
|
|
515
|
+
() => controller.abort(),
|
|
516
|
+
timeout ?? this.config.timeout
|
|
517
|
+
);
|
|
377
518
|
const contextHeaders = {
|
|
378
519
|
"X-FB-SDK": "js",
|
|
379
520
|
"X-FB-Node": process.version || "unknown",
|
|
@@ -439,6 +580,13 @@ var FetchBrainClient = class {
|
|
|
439
580
|
*/
|
|
440
581
|
clearBatch() {
|
|
441
582
|
this.batcher.clear();
|
|
583
|
+
this.learnBatcher.clear();
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Flush pending learn requests (call before shutdown)
|
|
587
|
+
*/
|
|
588
|
+
async flushLearnBatch() {
|
|
589
|
+
await this.learnBatcher.forceFlush();
|
|
442
590
|
}
|
|
443
591
|
/**
|
|
444
592
|
* Send telemetry data to the API
|
|
@@ -682,6 +830,16 @@ var FetchBrain = class {
|
|
|
682
830
|
}
|
|
683
831
|
}
|
|
684
832
|
});
|
|
833
|
+
const runStats = {
|
|
834
|
+
totalRequests: 0,
|
|
835
|
+
aiKnown: 0,
|
|
836
|
+
aiSkipped: 0,
|
|
837
|
+
// AI knew + skipped scraping
|
|
838
|
+
learned: 0,
|
|
839
|
+
scraped: 0,
|
|
840
|
+
// Actually ran handler
|
|
841
|
+
startTime: 0
|
|
842
|
+
};
|
|
685
843
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
686
844
|
if (!originalHandler) {
|
|
687
845
|
logger.warn("No request handler found on crawler, returning unmodified");
|
|
@@ -693,6 +851,7 @@ var FetchBrain = class {
|
|
|
693
851
|
const url = request.url;
|
|
694
852
|
const label = request.label;
|
|
695
853
|
const startTime = Date.now();
|
|
854
|
+
runStats.totalRequests++;
|
|
696
855
|
setScrapeContext({
|
|
697
856
|
crawler: crawlerType,
|
|
698
857
|
label,
|
|
@@ -724,15 +883,19 @@ var FetchBrain = class {
|
|
|
724
883
|
const handlerLabel = request.label;
|
|
725
884
|
const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
|
|
726
885
|
if (aiResult.known && aiResult.data && !runHandler) {
|
|
886
|
+
runStats.aiKnown++;
|
|
887
|
+
runStats.aiSkipped++;
|
|
727
888
|
logger.info(
|
|
728
|
-
`
|
|
889
|
+
`AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
729
890
|
);
|
|
730
891
|
if (originalPushData) {
|
|
731
892
|
await originalPushData.call(context, aiResult.data);
|
|
732
893
|
}
|
|
733
894
|
return;
|
|
734
895
|
}
|
|
896
|
+
runStats.scraped++;
|
|
735
897
|
if (aiResult.known) {
|
|
898
|
+
runStats.aiKnown++;
|
|
736
899
|
logger.info(
|
|
737
900
|
`Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
|
|
738
901
|
);
|
|
@@ -744,8 +907,9 @@ var FetchBrain = class {
|
|
|
744
907
|
context.pushData = async (data) => {
|
|
745
908
|
const shouldLearn = !usedAIData && !aiResult.known;
|
|
746
909
|
if (shouldLearn) {
|
|
747
|
-
|
|
748
|
-
|
|
910
|
+
runStats.learned++;
|
|
911
|
+
const requestUrl = requestContextMap.get(context) || url;
|
|
912
|
+
await client.learn(requestUrl, data);
|
|
749
913
|
}
|
|
750
914
|
return originalPushData.call(context, data);
|
|
751
915
|
};
|
|
@@ -844,14 +1008,24 @@ var FetchBrain = class {
|
|
|
844
1008
|
if (typeof crawlerAny.run === "function") {
|
|
845
1009
|
const originalRun = crawlerAny.run.bind(crawlerAny);
|
|
846
1010
|
crawlerAny.run = async (...args) => {
|
|
1011
|
+
runStats.startTime = Date.now();
|
|
847
1012
|
try {
|
|
848
1013
|
const result = await originalRun(...args);
|
|
849
1014
|
return result;
|
|
850
1015
|
} finally {
|
|
1016
|
+
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1017
|
+
await client.flushLearnBatch();
|
|
851
1018
|
if (config.telemetry?.enabled) {
|
|
852
1019
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
853
1020
|
await telemetryBuffer.stop();
|
|
854
1021
|
}
|
|
1022
|
+
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1023
|
+
1
|
|
1024
|
+
);
|
|
1025
|
+
const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
|
|
1026
|
+
logger.info(
|
|
1027
|
+
`Finished! AI known: ${runStats.aiKnown}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
|
|
1028
|
+
);
|
|
855
1029
|
}
|
|
856
1030
|
};
|
|
857
1031
|
}
|