@fetchbrain.com/sdk 0.1.6 → 0.2.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 +19 -10
- package/dist/index.d.mts +27 -197
- package/dist/index.d.ts +27 -197
- package/dist/index.js +263 -87
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +263 -87
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +58 -0
- package/dist/mock/index.d.ts +58 -0
- package/dist/mock/index.js +148 -0
- package/dist/mock/index.js.map +1 -0
- package/dist/mock/index.mjs +145 -0
- package/dist/mock/index.mjs.map +1 -0
- package/dist/types-Ddu_K1Nn.d.mts +209 -0
- package/dist/types-Ddu_K1Nn.d.ts +209 -0
- package/package.json +11 -3
package/dist/index.js
CHANGED
|
@@ -108,24 +108,23 @@ var RequestBatcher = class {
|
|
|
108
108
|
constructor(executor, config = {}, logger) {
|
|
109
109
|
this.queue = [];
|
|
110
110
|
this.flushTimeout = null;
|
|
111
|
+
this.refSeq = 0;
|
|
111
112
|
this.executor = executor;
|
|
112
113
|
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
113
114
|
this.logger = logger;
|
|
114
115
|
}
|
|
115
116
|
/**
|
|
116
|
-
* Add a
|
|
117
|
+
* Add a request to the batch queue
|
|
117
118
|
*/
|
|
118
|
-
async query(
|
|
119
|
+
async query(request) {
|
|
119
120
|
return new Promise((resolve, reject) => {
|
|
120
|
-
this.queue.push({
|
|
121
|
+
this.queue.push({ ref: String(this.refSeq++), request, resolve, reject });
|
|
121
122
|
if (this.queue.length >= this.config.maxSize) {
|
|
122
123
|
this.flush();
|
|
123
124
|
return;
|
|
124
125
|
}
|
|
125
126
|
if (!this.flushTimeout) {
|
|
126
|
-
this.flushTimeout = setTimeout(() =>
|
|
127
|
-
this.flush();
|
|
128
|
-
}, this.config.maxWait);
|
|
127
|
+
this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
|
|
129
128
|
}
|
|
130
129
|
});
|
|
131
130
|
}
|
|
@@ -141,27 +140,99 @@ var RequestBatcher = class {
|
|
|
141
140
|
return;
|
|
142
141
|
}
|
|
143
142
|
const batch = this.queue.splice(0, this.config.maxSize);
|
|
144
|
-
const
|
|
145
|
-
this.logger.debug(`Flushing batch of ${
|
|
143
|
+
const items = batch.map((r) => ({ ref: r.ref, request: r.request }));
|
|
144
|
+
this.logger.debug(`Flushing batch of ${items.length} requests`);
|
|
146
145
|
try {
|
|
147
|
-
const results = await this.executor(
|
|
148
|
-
for (const
|
|
149
|
-
|
|
150
|
-
if (result) {
|
|
151
|
-
request.resolve(result);
|
|
152
|
-
} else {
|
|
153
|
-
request.resolve({ known: false });
|
|
154
|
-
}
|
|
146
|
+
const results = await this.executor(items);
|
|
147
|
+
for (const r of batch) {
|
|
148
|
+
r.resolve(results.get(r.ref) ?? { known: false });
|
|
155
149
|
}
|
|
156
150
|
} catch (error) {
|
|
157
|
-
for (const
|
|
158
|
-
|
|
151
|
+
for (const r of batch) {
|
|
152
|
+
r.reject(error);
|
|
159
153
|
}
|
|
160
154
|
}
|
|
161
155
|
if (this.queue.length > 0) {
|
|
162
|
-
this.flushTimeout = setTimeout(() =>
|
|
156
|
+
this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Get current queue size
|
|
161
|
+
*/
|
|
162
|
+
getQueueSize() {
|
|
163
|
+
return this.queue.length;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Clear the queue (for cleanup)
|
|
167
|
+
*/
|
|
168
|
+
clear() {
|
|
169
|
+
if (this.flushTimeout) {
|
|
170
|
+
clearTimeout(this.flushTimeout);
|
|
171
|
+
this.flushTimeout = null;
|
|
172
|
+
}
|
|
173
|
+
for (const r of this.queue) {
|
|
174
|
+
r.resolve({ known: false, fallback: true });
|
|
175
|
+
}
|
|
176
|
+
this.queue = [];
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
var LearnBatcher = class {
|
|
180
|
+
constructor(executor, config = {}, logger) {
|
|
181
|
+
this.queue = [];
|
|
182
|
+
this.flushTimeout = null;
|
|
183
|
+
this.executor = executor;
|
|
184
|
+
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
185
|
+
this.logger = logger;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Add a learn entry to the batch queue
|
|
189
|
+
*/
|
|
190
|
+
async learn(request, data) {
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
this.queue.push({ entry: { request, data }, resolve, reject });
|
|
193
|
+
if (this.queue.length >= this.config.maxSize) {
|
|
163
194
|
this.flush();
|
|
164
|
-
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (!this.flushTimeout) {
|
|
198
|
+
this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Flush the current batch
|
|
204
|
+
*/
|
|
205
|
+
async flush() {
|
|
206
|
+
if (this.flushTimeout) {
|
|
207
|
+
clearTimeout(this.flushTimeout);
|
|
208
|
+
this.flushTimeout = null;
|
|
209
|
+
}
|
|
210
|
+
if (this.queue.length === 0) {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const batch = this.queue.splice(0, this.config.maxSize);
|
|
214
|
+
const entries = batch.map((r) => r.entry);
|
|
215
|
+
this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
|
|
216
|
+
try {
|
|
217
|
+
const result = await this.executor(entries);
|
|
218
|
+
for (const r of batch) {
|
|
219
|
+
r.resolve(result);
|
|
220
|
+
}
|
|
221
|
+
} catch (error) {
|
|
222
|
+
for (const r of batch) {
|
|
223
|
+
r.reject(error);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (this.queue.length > 0) {
|
|
227
|
+
this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Force flush and wait for completion (for cleanup/shutdown)
|
|
232
|
+
*/
|
|
233
|
+
async forceFlush() {
|
|
234
|
+
if (this.queue.length > 0) {
|
|
235
|
+
await this.flush();
|
|
165
236
|
}
|
|
166
237
|
}
|
|
167
238
|
/**
|
|
@@ -178,45 +249,69 @@ var RequestBatcher = class {
|
|
|
178
249
|
clearTimeout(this.flushTimeout);
|
|
179
250
|
this.flushTimeout = null;
|
|
180
251
|
}
|
|
181
|
-
for (const
|
|
182
|
-
|
|
252
|
+
for (const r of this.queue) {
|
|
253
|
+
r.resolve({ status: "rejected", learned: 0 });
|
|
183
254
|
}
|
|
184
255
|
this.queue = [];
|
|
185
256
|
}
|
|
186
257
|
};
|
|
187
258
|
|
|
188
259
|
// src/logger.ts
|
|
189
|
-
var
|
|
260
|
+
var COLORS = {
|
|
261
|
+
reset: "\x1B[0m",
|
|
262
|
+
cyan: "\x1B[36m",
|
|
263
|
+
green: "\x1B[32m",
|
|
264
|
+
yellow: "\x1B[33m",
|
|
265
|
+
red: "\x1B[31m",
|
|
266
|
+
gray: "\x1B[90m"
|
|
267
|
+
};
|
|
190
268
|
var LOG_LEVELS = {
|
|
191
269
|
debug: 0,
|
|
192
270
|
info: 1,
|
|
193
271
|
warn: 2,
|
|
194
272
|
error: 3
|
|
195
273
|
};
|
|
274
|
+
var LEVEL_COLORS = {
|
|
275
|
+
debug: COLORS.gray,
|
|
276
|
+
info: COLORS.green,
|
|
277
|
+
warn: COLORS.yellow,
|
|
278
|
+
error: COLORS.red
|
|
279
|
+
};
|
|
280
|
+
var LEVEL_LABELS = {
|
|
281
|
+
debug: "DEBUG",
|
|
282
|
+
info: "INFO ",
|
|
283
|
+
warn: "WARN ",
|
|
284
|
+
error: "ERROR"
|
|
285
|
+
};
|
|
196
286
|
function createLogger(minLevel = "info", enabled = true) {
|
|
197
287
|
const shouldLog = (level) => {
|
|
198
288
|
if (!enabled) return false;
|
|
199
289
|
return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
|
|
200
290
|
};
|
|
291
|
+
const formatLog = (level, message) => {
|
|
292
|
+
const levelColor = LEVEL_COLORS[level];
|
|
293
|
+
const label = LEVEL_LABELS[level];
|
|
294
|
+
return `${levelColor}${label}${COLORS.reset} ${COLORS.cyan}FetchBrain:${COLORS.reset} ${message}`;
|
|
295
|
+
};
|
|
201
296
|
return {
|
|
202
297
|
debug: (message, ...args) => {
|
|
203
298
|
if (shouldLog("debug")) {
|
|
204
|
-
console.debug(
|
|
299
|
+
console.debug(formatLog("debug", message), ...args);
|
|
205
300
|
}
|
|
206
301
|
},
|
|
207
302
|
info: (message, ...args) => {
|
|
208
303
|
if (shouldLog("info")) {
|
|
209
|
-
console.info(
|
|
304
|
+
console.info(formatLog("info", message), ...args);
|
|
210
305
|
}
|
|
211
306
|
},
|
|
212
307
|
warn: (message, ...args) => {
|
|
213
308
|
if (shouldLog("warn")) {
|
|
214
|
-
console.warn(
|
|
309
|
+
console.warn(formatLog("warn", message), ...args);
|
|
215
310
|
}
|
|
216
311
|
},
|
|
217
312
|
error: (message, ...args) => {
|
|
218
313
|
if (shouldLog("error")) {
|
|
219
|
-
console.error(
|
|
314
|
+
console.error(formatLog("error", message), ...args);
|
|
220
315
|
}
|
|
221
316
|
}
|
|
222
317
|
};
|
|
@@ -225,6 +320,7 @@ function createLogger(minLevel = "info", enabled = true) {
|
|
|
225
320
|
// src/client.ts
|
|
226
321
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
227
322
|
var DEFAULT_TIMEOUT = 500;
|
|
323
|
+
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
228
324
|
var currentContext = {};
|
|
229
325
|
function setScrapeContext(ctx) {
|
|
230
326
|
currentContext = ctx;
|
|
@@ -240,79 +336,74 @@ var FetchBrainClient = class {
|
|
|
240
336
|
intelligence: config.intelligence || "high",
|
|
241
337
|
learning: config.learning ?? true,
|
|
242
338
|
alwaysRun: config.alwaysRun ?? false,
|
|
243
|
-
|
|
339
|
+
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
244
340
|
timeout: config.timeout || DEFAULT_TIMEOUT,
|
|
245
341
|
debug: config.debug || false,
|
|
246
342
|
extractForLearning: config.extractForLearning,
|
|
247
|
-
|
|
343
|
+
learnUrlField: config.learnUrlField,
|
|
344
|
+
telemetry: config.telemetry ?? { enabled: true },
|
|
345
|
+
batch: config.batch,
|
|
346
|
+
circuitBreaker: config.circuitBreaker
|
|
248
347
|
};
|
|
249
348
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
250
|
-
this.circuitBreaker = new CircuitBreaker(
|
|
349
|
+
this.circuitBreaker = new CircuitBreaker(
|
|
350
|
+
this.config.circuitBreaker,
|
|
351
|
+
this.logger
|
|
352
|
+
);
|
|
251
353
|
this.batcher = new RequestBatcher(
|
|
252
|
-
(
|
|
253
|
-
|
|
354
|
+
(items) => this.executeBatchQuery(items),
|
|
355
|
+
this.config.batch,
|
|
356
|
+
this.logger
|
|
357
|
+
);
|
|
358
|
+
this.learnBatcher = new LearnBatcher(
|
|
359
|
+
(entries) => this.executeBatchLearn(entries),
|
|
360
|
+
this.config.batch,
|
|
254
361
|
this.logger
|
|
255
362
|
);
|
|
256
363
|
}
|
|
257
364
|
/**
|
|
258
|
-
* Query if FetchBrain "knows" a
|
|
365
|
+
* Query if FetchBrain "knows" a request
|
|
259
366
|
*/
|
|
260
|
-
async query(
|
|
367
|
+
async query(request) {
|
|
261
368
|
if (this.circuitBreaker.isOpen()) {
|
|
262
|
-
this.logger.debug(`Circuit open, skipping query for: ${url}`);
|
|
263
369
|
return { known: false, fallback: true };
|
|
264
370
|
}
|
|
265
371
|
try {
|
|
266
|
-
return await this.batcher.query(
|
|
372
|
+
return await this.batcher.query(request);
|
|
267
373
|
} catch (error) {
|
|
268
|
-
this.logger.debug(
|
|
374
|
+
this.logger.debug("Query failed:", error);
|
|
269
375
|
return { known: false, fallback: true };
|
|
270
376
|
}
|
|
271
377
|
}
|
|
272
378
|
/**
|
|
273
|
-
* Query multiple
|
|
379
|
+
* Query multiple requests at once — returns ordered array matching input order
|
|
274
380
|
*/
|
|
275
|
-
async queryBulk(
|
|
381
|
+
async queryBulk(requests) {
|
|
276
382
|
if (this.circuitBreaker.isOpen()) {
|
|
277
|
-
|
|
278
|
-
return new Map(
|
|
279
|
-
urls.map((url) => [url, { known: false, fallback: true }])
|
|
280
|
-
);
|
|
383
|
+
return requests.map(() => ({ known: false, fallback: true }));
|
|
281
384
|
}
|
|
282
385
|
try {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
);
|
|
386
|
+
const items = requests.map((request, i) => ({ ref: String(i), request }));
|
|
387
|
+
const results = await this.executeBatchQuery(items);
|
|
388
|
+
return items.map((i) => results.get(i.ref) ?? { known: false });
|
|
389
|
+
} catch {
|
|
390
|
+
return requests.map(() => ({ known: false, fallback: true }));
|
|
289
391
|
}
|
|
290
392
|
}
|
|
291
393
|
/**
|
|
292
|
-
* "Teach" FetchBrain new data
|
|
394
|
+
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
293
395
|
*/
|
|
294
|
-
async learn(
|
|
396
|
+
async learn(request, data) {
|
|
295
397
|
if (!this.config.learning) {
|
|
296
398
|
return { status: "rejected", learned: 0 };
|
|
297
399
|
}
|
|
298
400
|
if (this.circuitBreaker.isOpen()) {
|
|
299
|
-
this.logger.debug(`Circuit open, skipping learn for: ${url}`);
|
|
300
401
|
return { status: "rejected", learned: 0 };
|
|
301
402
|
}
|
|
302
403
|
try {
|
|
303
|
-
|
|
304
|
-
const response = await this.makeRequest("/v1/learn", {
|
|
305
|
-
method: "POST",
|
|
306
|
-
body: JSON.stringify({
|
|
307
|
-
entries: [{ url, data: extractedData }]
|
|
308
|
-
})
|
|
309
|
-
});
|
|
310
|
-
this.circuitBreaker.recordSuccess();
|
|
311
|
-
this.logger.debug(`Learned data for: ${url}`);
|
|
312
|
-
return response;
|
|
404
|
+
return await this.learnBatcher.learn(request, data);
|
|
313
405
|
} catch (error) {
|
|
314
|
-
this.
|
|
315
|
-
this.logger.warn(`Learn failed for ${url}:`, error);
|
|
406
|
+
this.logger.warn("Learn failed:", error);
|
|
316
407
|
return { status: "rejected", learned: 0 };
|
|
317
408
|
}
|
|
318
409
|
}
|
|
@@ -338,13 +429,13 @@ var FetchBrainClient = class {
|
|
|
338
429
|
/**
|
|
339
430
|
* Execute a batch query against the API
|
|
340
431
|
*/
|
|
341
|
-
async executeBatchQuery(
|
|
432
|
+
async executeBatchQuery(items) {
|
|
342
433
|
const results = /* @__PURE__ */ new Map();
|
|
343
434
|
const request = {
|
|
344
|
-
|
|
435
|
+
items,
|
|
345
436
|
intelligence: this.config.intelligence
|
|
346
437
|
};
|
|
347
|
-
if (this.config.
|
|
438
|
+
if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
|
|
348
439
|
request.build = process.env.APIFY_ACTOR_BUILD_ID;
|
|
349
440
|
}
|
|
350
441
|
try {
|
|
@@ -354,14 +445,10 @@ var FetchBrainClient = class {
|
|
|
354
445
|
});
|
|
355
446
|
this.circuitBreaker.recordSuccess();
|
|
356
447
|
for (const item of response.known) {
|
|
357
|
-
results.set(item.
|
|
358
|
-
known: true,
|
|
359
|
-
data: item.data,
|
|
360
|
-
confidence: item.confidence
|
|
361
|
-
});
|
|
448
|
+
results.set(item.ref, { known: true, data: item.data, confidence: item.confidence });
|
|
362
449
|
}
|
|
363
|
-
for (const
|
|
364
|
-
results.set(
|
|
450
|
+
for (const ref of response.unknown) {
|
|
451
|
+
results.set(ref, { known: false });
|
|
365
452
|
}
|
|
366
453
|
return results;
|
|
367
454
|
} catch (error) {
|
|
@@ -369,13 +456,40 @@ var FetchBrainClient = class {
|
|
|
369
456
|
throw error;
|
|
370
457
|
}
|
|
371
458
|
}
|
|
459
|
+
/**
|
|
460
|
+
* Execute a batch learn against the API
|
|
461
|
+
*/
|
|
462
|
+
async executeBatchLearn(entries) {
|
|
463
|
+
const processed = entries.map((e) => ({
|
|
464
|
+
request: e.request,
|
|
465
|
+
data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
|
|
466
|
+
}));
|
|
467
|
+
try {
|
|
468
|
+
const response = await this.makeRequest(
|
|
469
|
+
"/v1/learn",
|
|
470
|
+
{
|
|
471
|
+
method: "POST",
|
|
472
|
+
body: JSON.stringify({ entries: processed })
|
|
473
|
+
},
|
|
474
|
+
DEFAULT_LEARN_TIMEOUT
|
|
475
|
+
);
|
|
476
|
+
this.circuitBreaker.recordSuccess();
|
|
477
|
+
return response;
|
|
478
|
+
} catch (error) {
|
|
479
|
+
this.circuitBreaker.recordFailure();
|
|
480
|
+
throw error;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
372
483
|
/**
|
|
373
484
|
* Make an HTTP request to the API
|
|
374
485
|
*/
|
|
375
|
-
async makeRequest(path, options) {
|
|
486
|
+
async makeRequest(path, options, timeout) {
|
|
376
487
|
const url = `${this.config.baseUrl}${path}`;
|
|
377
488
|
const controller = new AbortController();
|
|
378
|
-
const timeoutId = setTimeout(
|
|
489
|
+
const timeoutId = setTimeout(
|
|
490
|
+
() => controller.abort(),
|
|
491
|
+
timeout ?? this.config.timeout
|
|
492
|
+
);
|
|
379
493
|
const contextHeaders = {
|
|
380
494
|
"X-FB-SDK": "js",
|
|
381
495
|
"X-FB-Node": process.version || "unknown",
|
|
@@ -441,6 +555,13 @@ var FetchBrainClient = class {
|
|
|
441
555
|
*/
|
|
442
556
|
clearBatch() {
|
|
443
557
|
this.batcher.clear();
|
|
558
|
+
this.learnBatcher.clear();
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Flush pending learn requests (call before shutdown)
|
|
562
|
+
*/
|
|
563
|
+
async flushLearnBatch() {
|
|
564
|
+
await this.learnBatcher.forceFlush();
|
|
444
565
|
}
|
|
445
566
|
/**
|
|
446
567
|
* Send telemetry data to the API
|
|
@@ -616,6 +737,36 @@ var TelemetryBuffer = class {
|
|
|
616
737
|
};
|
|
617
738
|
|
|
618
739
|
// src/enhance.ts
|
|
740
|
+
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
741
|
+
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainKnown", "fetchBrainData", "__fetchBrainResult"]);
|
|
742
|
+
function buildRawRequest(request) {
|
|
743
|
+
const r = request;
|
|
744
|
+
let headers;
|
|
745
|
+
if (r.headers) {
|
|
746
|
+
headers = {};
|
|
747
|
+
for (const [k, v] of Object.entries(r.headers)) {
|
|
748
|
+
if (!STRIP_HEADERS.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
|
|
749
|
+
}
|
|
750
|
+
if (Object.keys(headers).length === 0) headers = void 0;
|
|
751
|
+
}
|
|
752
|
+
let userData;
|
|
753
|
+
if (r.userData) {
|
|
754
|
+
userData = {};
|
|
755
|
+
for (const [k, v] of Object.entries(r.userData)) if (!SDK_USERDATA_KEYS.has(k)) userData[k] = v;
|
|
756
|
+
if (Object.keys(userData).length === 0) userData = void 0;
|
|
757
|
+
}
|
|
758
|
+
let body;
|
|
759
|
+
if (typeof r.payload === "string") body = r.payload;
|
|
760
|
+
return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
|
|
761
|
+
}
|
|
762
|
+
function warnDefaultUniqueKey(request, logger, warned) {
|
|
763
|
+
const method = (request.method ?? "GET").toUpperCase();
|
|
764
|
+
const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
|
|
765
|
+
if (method !== "GET" && isDefault && !warned.has(request.url)) {
|
|
766
|
+
warned.add(request.url);
|
|
767
|
+
logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't be cached separately.`);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
619
770
|
var asyncContext = new async_hooks.AsyncLocalStorage();
|
|
620
771
|
function getCurrentContext() {
|
|
621
772
|
return asyncContext.getStore();
|
|
@@ -631,7 +782,6 @@ function shouldRunHandler(alwaysRun, label) {
|
|
|
631
782
|
const requestLabel = label || "default";
|
|
632
783
|
return labels.includes(requestLabel);
|
|
633
784
|
}
|
|
634
|
-
var requestContextMap = /* @__PURE__ */ new WeakMap();
|
|
635
785
|
var FetchBrain = class {
|
|
636
786
|
constructor(config) {
|
|
637
787
|
this.client = new FetchBrainClient(config);
|
|
@@ -641,7 +791,7 @@ var FetchBrain = class {
|
|
|
641
791
|
* Query if FetchBrain "knows" a URL
|
|
642
792
|
*/
|
|
643
793
|
async query(options) {
|
|
644
|
-
const result = await this.client.query(options.url);
|
|
794
|
+
const result = await this.client.query({ url: options.url });
|
|
645
795
|
return {
|
|
646
796
|
known: result.known,
|
|
647
797
|
data: result.data,
|
|
@@ -652,7 +802,7 @@ var FetchBrain = class {
|
|
|
652
802
|
* "Teach" FetchBrain new data
|
|
653
803
|
*/
|
|
654
804
|
async learn(options) {
|
|
655
|
-
return this.client.learn(options.url, options.data);
|
|
805
|
+
return this.client.learn({ url: options.url }, options.data);
|
|
656
806
|
}
|
|
657
807
|
/**
|
|
658
808
|
* Get usage statistics
|
|
@@ -684,24 +834,38 @@ var FetchBrain = class {
|
|
|
684
834
|
}
|
|
685
835
|
}
|
|
686
836
|
});
|
|
837
|
+
const runStats = {
|
|
838
|
+
totalRequests: 0,
|
|
839
|
+
aiKnown: 0,
|
|
840
|
+
aiSkipped: 0,
|
|
841
|
+
// AI knew + skipped scraping
|
|
842
|
+
learned: 0,
|
|
843
|
+
scraped: 0,
|
|
844
|
+
// Actually ran handler
|
|
845
|
+
startTime: 0
|
|
846
|
+
};
|
|
687
847
|
const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
|
|
688
848
|
if (!originalHandler) {
|
|
689
849
|
logger.warn("No request handler found on crawler, returning unmodified");
|
|
690
850
|
return Object.assign(crawler, { fetchBrain: client });
|
|
691
851
|
}
|
|
692
852
|
const crawlerType = crawler.constructor?.name || "Unknown";
|
|
853
|
+
const warnedKeys = /* @__PURE__ */ new Set();
|
|
693
854
|
const wrappedHandler = async (context) => {
|
|
694
855
|
const { request } = context;
|
|
695
856
|
const url = request.url;
|
|
696
857
|
const label = request.label;
|
|
697
858
|
const startTime = Date.now();
|
|
859
|
+
runStats.totalRequests++;
|
|
698
860
|
setScrapeContext({
|
|
699
861
|
crawler: crawlerType,
|
|
700
862
|
label,
|
|
701
863
|
url
|
|
702
864
|
});
|
|
865
|
+
const rawRequest = buildRawRequest(request);
|
|
866
|
+
warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
|
|
703
867
|
try {
|
|
704
|
-
const aiResult = await client.query(
|
|
868
|
+
const aiResult = await client.query(rawRequest);
|
|
705
869
|
let usedAIData = false;
|
|
706
870
|
const originalPushData = context.pushData;
|
|
707
871
|
context.ai = {
|
|
@@ -726,34 +890,37 @@ var FetchBrain = class {
|
|
|
726
890
|
const handlerLabel = request.label;
|
|
727
891
|
const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
|
|
728
892
|
if (aiResult.known && aiResult.data && !runHandler) {
|
|
893
|
+
runStats.aiKnown++;
|
|
894
|
+
runStats.aiSkipped++;
|
|
729
895
|
logger.info(
|
|
730
|
-
`
|
|
896
|
+
`AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
731
897
|
);
|
|
732
898
|
if (originalPushData) {
|
|
733
899
|
await originalPushData.call(context, aiResult.data);
|
|
734
900
|
}
|
|
735
901
|
return;
|
|
736
902
|
}
|
|
903
|
+
runStats.scraped++;
|
|
737
904
|
if (aiResult.known) {
|
|
905
|
+
runStats.aiKnown++;
|
|
738
906
|
logger.info(
|
|
739
907
|
`Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
|
|
740
908
|
);
|
|
741
909
|
} else {
|
|
742
910
|
logger.debug(`Learning: ${url}`);
|
|
743
911
|
}
|
|
744
|
-
requestContextMap.set(context, url);
|
|
745
912
|
if (originalPushData && config.learning !== false) {
|
|
746
913
|
context.pushData = async (data) => {
|
|
747
914
|
const shouldLearn = !usedAIData && !aiResult.known;
|
|
748
915
|
if (shouldLearn) {
|
|
749
|
-
|
|
750
|
-
await client.learn(
|
|
916
|
+
runStats.learned++;
|
|
917
|
+
await client.learn(rawRequest, data);
|
|
751
918
|
}
|
|
752
919
|
return originalPushData.call(context, data);
|
|
753
920
|
};
|
|
754
921
|
}
|
|
755
922
|
const requestContext = {
|
|
756
|
-
|
|
923
|
+
request: rawRequest,
|
|
757
924
|
client,
|
|
758
925
|
learning: config.learning !== false,
|
|
759
926
|
aiKnown: aiResult.known
|
|
@@ -761,7 +928,6 @@ var FetchBrain = class {
|
|
|
761
928
|
await asyncContext.run(requestContext, async () => {
|
|
762
929
|
await originalHandler.call(crawler, context);
|
|
763
930
|
});
|
|
764
|
-
requestContextMap.delete(context);
|
|
765
931
|
if (config.telemetry?.enabled) {
|
|
766
932
|
try {
|
|
767
933
|
const telemetry = await collectTelemetry(
|
|
@@ -846,14 +1012,24 @@ var FetchBrain = class {
|
|
|
846
1012
|
if (typeof crawlerAny.run === "function") {
|
|
847
1013
|
const originalRun = crawlerAny.run.bind(crawlerAny);
|
|
848
1014
|
crawlerAny.run = async (...args) => {
|
|
1015
|
+
runStats.startTime = Date.now();
|
|
849
1016
|
try {
|
|
850
1017
|
const result = await originalRun(...args);
|
|
851
1018
|
return result;
|
|
852
1019
|
} finally {
|
|
1020
|
+
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1021
|
+
await client.flushLearnBatch();
|
|
853
1022
|
if (config.telemetry?.enabled) {
|
|
854
1023
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
855
1024
|
await telemetryBuffer.stop();
|
|
856
1025
|
}
|
|
1026
|
+
const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
|
|
1027
|
+
1
|
|
1028
|
+
);
|
|
1029
|
+
const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
|
|
1030
|
+
logger.info(
|
|
1031
|
+
`Finished! AI known: ${runStats.aiKnown}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
|
|
1032
|
+
);
|
|
857
1033
|
}
|
|
858
1034
|
};
|
|
859
1035
|
}
|
|
@@ -868,7 +1044,7 @@ async function pushData(data, dataset, datasetName) {
|
|
|
868
1044
|
if (ctx && ctx.learning && !ctx.aiKnown) {
|
|
869
1045
|
const items = Array.isArray(data) ? data : [data];
|
|
870
1046
|
for (const item of items) {
|
|
871
|
-
await ctx.client.learn(ctx.
|
|
1047
|
+
await ctx.client.learn(ctx.request, item);
|
|
872
1048
|
}
|
|
873
1049
|
}
|
|
874
1050
|
if (datasetName && dataset.open) {
|