@fetchbrain.com/sdk 0.7.1 → 0.9.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.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'async_hooks';
2
+ import { randomUUID } from 'crypto';
2
3
 
3
4
  // src/enhance.ts
4
5
 
@@ -427,6 +428,7 @@ function getPlatformBuildId(env = process.env) {
427
428
  // src/client.ts
428
429
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
429
430
  var DEFAULT_TIMEOUT = 1500;
431
+ var REPORT_RUN_TIMEOUT = 3e3;
430
432
  var DEFAULT_LEARN_TIMEOUT = 5e3;
431
433
  var BULK_RECALL_TIMEOUT = 3e3;
432
434
  var MAX_BULK_ITEMS = 90;
@@ -467,6 +469,9 @@ function setScrapeContext(ctx) {
467
469
  function clearScrapeContext() {
468
470
  currentContext = {};
469
471
  }
472
+ var MAX_DRIFT_ITEMS = 100;
473
+ var DRIFT_KINDS = /* @__PURE__ */ new Set(["fill_drop", "missing", "type_changed"]);
474
+ var clipText = (v, max = 128) => String(v).replace(/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g, " ").slice(0, max);
470
475
  var FetchBrainClient = class {
471
476
  constructor(config) {
472
477
  /**
@@ -486,6 +491,8 @@ var FetchBrainClient = class {
486
491
  this.warnedOversizeLearn = false;
487
492
  /** Warn about the learn cap once per pause, independent of the pause state. */
488
493
  this.learnCapWarnedUntil = 0;
494
+ /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
495
+ this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
489
496
  this.config = {
490
497
  apiKey: config.apiKey,
491
498
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
@@ -507,7 +514,9 @@ var FetchBrainClient = class {
507
514
  // enhance-only; stored so getConfig() round-trips
508
515
  onRecalled: config.onRecalled,
509
516
  // enhance-only; stored so getConfig() round-trips
510
- scraper: config.scraper
517
+ scraper: config.scraper,
518
+ changeDetection: config.changeDetection,
519
+ reportRuns: config.reportRuns ?? true
511
520
  };
512
521
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
513
522
  const scraper = resolveScraperName(config.scraper);
@@ -746,6 +755,8 @@ var FetchBrainClient = class {
746
755
  async executeBatchLearn(entries) {
747
756
  if (entries.length === 0) return { status: "rejected", learned: 0 };
748
757
  const request = { entries };
758
+ const ignore = this.config.changeDetection?.ignoreFields;
759
+ if (ignore && ignore.length > 0) request.ignore = ignore;
749
760
  const platformBuildId = getPlatformBuildId();
750
761
  if (this.config.refreshOnRebuild && platformBuildId) {
751
762
  request.build = platformBuildId;
@@ -760,6 +771,11 @@ var FetchBrainClient = class {
760
771
  DEFAULT_LEARN_TIMEOUT
761
772
  );
762
773
  this.circuitBreaker.recordSuccess();
774
+ try {
775
+ this.accumulateChanges(response);
776
+ } catch (statsErr) {
777
+ this.logger.debug("Change stats skipped:", statsErr);
778
+ }
763
779
  return response;
764
780
  } catch (error) {
765
781
  if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
@@ -785,6 +801,54 @@ var FetchBrainClient = class {
785
801
  throw error;
786
802
  }
787
803
  }
804
+ /** Fold one batch response into the change totals (called once per HTTP batch). */
805
+ accumulateChanges(response) {
806
+ const stats = this.changeStats;
807
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : 0;
808
+ stats.changed += num(response.changed);
809
+ stats.unchanged += num(response.unchanged);
810
+ stats.firstSeen += num(response.firstSeen);
811
+ const drift = Array.isArray(response.drift) ? response.drift : [];
812
+ for (const item of drift) {
813
+ if (!item || typeof item !== "object" || typeof item.label !== "string" || typeof item.field !== "string" || !DRIFT_KINDS.has(item.kind)) {
814
+ continue;
815
+ }
816
+ if (stats.drift.length >= MAX_DRIFT_ITEMS) break;
817
+ const clean = {
818
+ ...item,
819
+ label: clipText(item.label),
820
+ field: clipText(item.field)
821
+ };
822
+ const exists = stats.drift.some(
823
+ (d) => d.label === clean.label && d.field === clean.field && d.kind === clean.kind
824
+ );
825
+ if (!exists) stats.drift.push(clean);
826
+ }
827
+ }
828
+ /** Change counts so far (a copy). */
829
+ getChangeStats() {
830
+ return { ...this.changeStats, drift: [...this.changeStats.drift] };
831
+ }
832
+ /**
833
+ * Send the end-of-run report. Counts and labels only. Never throws: on
834
+ * failure or timeout it returns no flags.
835
+ */
836
+ async reportRun(report, timeoutMs = REPORT_RUN_TIMEOUT) {
837
+ if (this.config.reportRuns === false || this.recallBlocked()) return [];
838
+ try {
839
+ const response = await this.makeRequest(
840
+ "/v1/runs",
841
+ { method: "POST", body: JSON.stringify(report) },
842
+ Math.min(timeoutMs, REPORT_RUN_TIMEOUT)
843
+ );
844
+ this.circuitBreaker.recordSuccess();
845
+ return Array.isArray(response?.flags) ? response.flags : [];
846
+ } catch (error) {
847
+ if (isOutage(error)) this.circuitBreaker.recordFailure();
848
+ this.logger.debug("Run report failed:", error);
849
+ return [];
850
+ }
851
+ }
788
852
  /**
789
853
  * Make an HTTP request to the API
790
854
  */
@@ -1060,8 +1124,47 @@ var TelemetryBuffer = class {
1060
1124
  };
1061
1125
 
1062
1126
  // src/enhance.ts
1127
+ var REPORT_MAX_LABELS = 50;
1128
+ var REPORT_LABEL_MAX_CHARS = 64;
1129
+ var RUN_ID_MAX_CHARS = 128;
1130
+ var NO_LABEL = "_nolabel";
1131
+ var platformRunSeq = /* @__PURE__ */ new Map();
1132
+ function nextRunId() {
1133
+ const platform = process.env.APIFY_ACTOR_RUN_ID;
1134
+ if (!platform) return randomUUID();
1135
+ const id = platform.slice(0, RUN_ID_MAX_CHARS - 8);
1136
+ const n = (platformRunSeq.get(id) ?? 0) + 1;
1137
+ platformRunSeq.set(id, n);
1138
+ return n === 1 ? id : `${id}-${n}`;
1139
+ }
1140
+ function labelText(label) {
1141
+ if (typeof label === "string") return label;
1142
+ if (typeof label === "number" || typeof label === "boolean") return String(label);
1143
+ return void 0;
1144
+ }
1145
+ function reportLabel(label) {
1146
+ const trimmed = (labelText(label) ?? "").trim().slice(0, REPORT_LABEL_MAX_CHARS);
1147
+ return trimmed || NO_LABEL;
1148
+ }
1149
+ var pct = (rate) => `${Math.round(rate * 100)}%`;
1150
+ function describeDrift(d) {
1151
+ const detail = d.kind === "type_changed" ? `type ${clipText(d.from, 32)} \u2192 ${clipText(d.to, 32)}` : `filled ${pct(Number(d.from))} \u2192 ${pct(Number(d.to))}`;
1152
+ return `\u26A0\uFE0F drift [${clipText(d.label, 64)}] ${clipText(d.field, 64)}: ${detail}`;
1153
+ }
1154
+ function safeChangeStats(client) {
1155
+ try {
1156
+ return client.getChangeStats();
1157
+ } catch {
1158
+ return { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
1159
+ }
1160
+ }
1063
1161
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
1064
- var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
1162
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set([
1163
+ "fetchBrainRecalled",
1164
+ "fetchBrainData",
1165
+ "__fetchBrainResult",
1166
+ "__fetchBrainCounted"
1167
+ ]);
1065
1168
  var MAX_STASH_ENTRIES = 5e3;
1066
1169
  var MAX_STASH_BYTES = 256 * 1024 * 1024;
1067
1170
  var stashBytesCap = MAX_STASH_BYTES;
@@ -1098,7 +1201,7 @@ function buildRawRequest(request) {
1098
1201
  }
1099
1202
  let body;
1100
1203
  if (typeof r.payload === "string") body = r.payload;
1101
- return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
1204
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
1102
1205
  }
1103
1206
  function warnDefaultUniqueKey(request, logger, warned) {
1104
1207
  const method = (request.method ?? "GET").toUpperCase();
@@ -1180,6 +1283,10 @@ var FetchBrain = class {
1180
1283
  recalled: 0,
1181
1284
  aiSkipped: 0,
1182
1285
  // brain knew + skipped scraping
1286
+ requestsSkipped: 0,
1287
+ // recalled without a fetch (pre-recalled at enqueue + skipNavigation)
1288
+ lateRecalls: 0,
1289
+ // recalled after the page was already fetched
1183
1290
  learned: 0,
1184
1291
  scraped: 0,
1185
1292
  // Actually ran handler
@@ -1189,6 +1296,18 @@ var FetchBrain = class {
1189
1296
  // enqueue-time fetch skipped, but remembered data gone by execution
1190
1297
  startTime: 0
1191
1298
  };
1299
+ const labelStats = /* @__PURE__ */ new Map();
1300
+ const labelCounts = (label) => {
1301
+ const key = reportLabel(label);
1302
+ let counts = labelStats.get(key);
1303
+ if (!counts && labelStats.size < REPORT_MAX_LABELS) {
1304
+ counts = { scraped: 0, empty: 0, failed: 0 };
1305
+ labelStats.set(key, counts);
1306
+ } else if (!counts) {
1307
+ logger.debug(`Run report: more than ${REPORT_MAX_LABELS} labels; not tracking "${key}"`);
1308
+ }
1309
+ return counts;
1310
+ };
1192
1311
  const pendingLearns = /* @__PURE__ */ new Set();
1193
1312
  if ("adaptiveRequestHandler" in crawler) {
1194
1313
  logger.warn(
@@ -1287,6 +1406,7 @@ var FetchBrain = class {
1287
1406
  );
1288
1407
  }
1289
1408
  let usedAIData = false;
1409
+ const relearn = aiResult.known && config.changeDetection?.enabled === true;
1290
1410
  const originalPushData = context.pushData;
1291
1411
  const fireOnRecalled = async (data) => {
1292
1412
  if (!config.onRecalled) return;
@@ -1321,18 +1441,31 @@ var FetchBrain = class {
1321
1441
  const handlerLabel = request.label;
1322
1442
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
1323
1443
  if (aiResult.known && aiResult.data && !runHandler) {
1324
- runStats.recalled++;
1325
- runStats.aiSkipped++;
1326
1444
  logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
1327
1445
  if (originalPushData) {
1328
1446
  await originalPushData.call(context, aiResult.data);
1329
1447
  }
1448
+ try {
1449
+ if (!request.userData?.__fetchBrainCounted) {
1450
+ request.userData = { ...request.userData, __fetchBrainCounted: true };
1451
+ runStats.recalled++;
1452
+ runStats.aiSkipped++;
1453
+ const skippedNav = request.skipNavigation === true;
1454
+ if (preRecalled?.known && skippedNav) {
1455
+ runStats.requestsSkipped++;
1456
+ } else if (!skippedNav) {
1457
+ runStats.lateRecalls++;
1458
+ }
1459
+ }
1460
+ } catch (countErr) {
1461
+ logger.debug(`Run stats skipped: ${countErr}`);
1462
+ }
1330
1463
  await fireOnRecalled(aiResult.data);
1331
1464
  return;
1332
1465
  }
1333
- runStats.scraped++;
1466
+ const counts = labelCounts(request.label);
1467
+ if (counts) counts.scraped++;
1334
1468
  if (aiResult.known) {
1335
- runStats.recalled++;
1336
1469
  logger.info(
1337
1470
  `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
1338
1471
  );
@@ -1342,7 +1475,7 @@ var FetchBrain = class {
1342
1475
  const learnItems = [];
1343
1476
  if (originalPushData && config.learning !== false) {
1344
1477
  context.pushData = async (data) => {
1345
- if (!usedAIData && !aiResult.known) {
1478
+ if (!usedAIData && (!aiResult.known || relearn)) {
1346
1479
  learnItems.push(...Array.isArray(data) ? data : [data]);
1347
1480
  }
1348
1481
  return originalPushData.call(context, data);
@@ -1353,12 +1486,30 @@ var FetchBrain = class {
1353
1486
  client,
1354
1487
  learning: config.learning !== false,
1355
1488
  aiKnown: aiResult.known,
1489
+ relearn,
1356
1490
  items: learnItems
1357
1491
  };
1358
- await asyncContext.run(requestContext, async () => {
1359
- await originalHandler.call(crawler, context);
1360
- });
1361
- if (learnItems.length > 0 && !usedAIData && !aiResult.known) {
1492
+ try {
1493
+ await asyncContext.run(requestContext, async () => {
1494
+ await originalHandler.call(crawler, context);
1495
+ });
1496
+ } catch (handlerErr) {
1497
+ if (counts) counts.failed++;
1498
+ throw handlerErr;
1499
+ }
1500
+ try {
1501
+ if (!request.userData?.__fetchBrainCounted) {
1502
+ request.userData = { ...request.userData, __fetchBrainCounted: true };
1503
+ runStats.scraped++;
1504
+ if (aiResult.known) runStats.recalled++;
1505
+ }
1506
+ } catch (countErr) {
1507
+ logger.debug(`Run stats skipped: ${countErr}`);
1508
+ }
1509
+ if (counts && learnItems.length === 0 && originalPushData && config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1510
+ counts.empty++;
1511
+ }
1512
+ if (learnItems.length > 0 && !usedAIData && (!aiResult.known || relearn)) {
1362
1513
  await client.waitForLearnRoom(LEARN_ROOM_WAIT_MS);
1363
1514
  const pending = client.learn(rawRequest, learnItems.length === 1 ? learnItems[0] : learnItems).then((res) => {
1364
1515
  if (res.status !== "rejected") runStats.learned += learnItems.length;
@@ -1450,6 +1601,21 @@ var FetchBrain = class {
1450
1601
  const originalRun = crawlerAny.run.bind(crawlerAny);
1451
1602
  crawlerAny.run = async (...args) => {
1452
1603
  runStats.startTime = Date.now();
1604
+ const runStartedAt = new Date(runStats.startTime).toISOString();
1605
+ labelStats.clear();
1606
+ const runBase = {
1607
+ totalRequests: runStats.totalRequests,
1608
+ bypassed: runStats.bypassed,
1609
+ dropped: runStats.dropped,
1610
+ scraped: runStats.scraped,
1611
+ learned: runStats.learned,
1612
+ recalled: runStats.recalled,
1613
+ aiSkipped: runStats.aiSkipped,
1614
+ requestsSkipped: runStats.requestsSkipped,
1615
+ lateRecalls: runStats.lateRecalls
1616
+ };
1617
+ const changeBase = safeChangeStats(client);
1618
+ const runId = nextRunId();
1453
1619
  try {
1454
1620
  const result = await originalRun(...args);
1455
1621
  return result;
@@ -1464,11 +1630,76 @@ var FetchBrain = class {
1464
1630
  const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1465
1631
  1
1466
1632
  );
1467
- const managedRequests = runStats.totalRequests - runStats.bypassed;
1468
- const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1633
+ const run = {
1634
+ totalRequests: runStats.totalRequests - runBase.totalRequests,
1635
+ bypassed: runStats.bypassed - runBase.bypassed,
1636
+ dropped: runStats.dropped - runBase.dropped,
1637
+ scraped: runStats.scraped - runBase.scraped,
1638
+ learned: runStats.learned - runBase.learned,
1639
+ recalled: runStats.recalled - runBase.recalled,
1640
+ aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
1641
+ requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
1642
+ lateRecalls: runStats.lateRecalls - runBase.lateRecalls
1643
+ };
1644
+ const managedRequests = run.totalRequests - run.bypassed;
1645
+ const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1646
+ let changes = { changed: 0, drift: [] };
1647
+ try {
1648
+ const now = safeChangeStats(client);
1649
+ const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
1650
+ const seen = new Set(changeBase.drift.map(key));
1651
+ changes = {
1652
+ changed: Math.max(0, now.changed - changeBase.changed) || 0,
1653
+ drift: now.drift.filter((d) => !seen.has(key(d)))
1654
+ };
1655
+ } catch (diffErr) {
1656
+ logger.debug(`Change summary skipped: ${diffErr}`);
1657
+ }
1658
+ const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1469
1659
  logger.info(
1470
- `\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`
1660
+ `\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} (${savingsPercent}%), requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1471
1661
  );
1662
+ if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
1663
+ logger.info(
1664
+ `${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
1665
+ );
1666
+ }
1667
+ for (const item of changes.drift) {
1668
+ try {
1669
+ logger.warn(describeDrift(item));
1670
+ } catch (warnErr) {
1671
+ logger.debug(`Drift warning skipped: ${warnErr}`);
1672
+ }
1673
+ }
1674
+ if (config.reportRuns !== false) {
1675
+ try {
1676
+ const labels = Object.fromEntries(labelStats);
1677
+ const flags = await client.reportRun({
1678
+ runId,
1679
+ build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1680
+ startedAt: runStartedAt,
1681
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1682
+ scraped: run.scraped,
1683
+ learned: run.learned,
1684
+ recalled: run.recalled,
1685
+ requestsSkipped: run.requestsSkipped,
1686
+ lateRecalls: run.lateRecalls,
1687
+ bypassed: run.bypassed,
1688
+ labels
1689
+ });
1690
+ for (const flag of Array.isArray(flags) ? flags : []) {
1691
+ if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
1692
+ continue;
1693
+ }
1694
+ const label = clipText(flag.label, 64);
1695
+ logger.warn(
1696
+ flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
1697
+ );
1698
+ }
1699
+ } catch (reportErr) {
1700
+ logger.debug(`Run report skipped: ${reportErr}`);
1701
+ }
1702
+ }
1472
1703
  }
1473
1704
  };
1474
1705
  }
@@ -1486,10 +1717,11 @@ var FetchBrain = class {
1486
1717
  const r = slice[i];
1487
1718
  if (!r || typeof r.url !== "string") continue;
1488
1719
  const prior = r.userData?.__fetchBrainResult;
1489
- if (prior) {
1490
- if (prior.known && r.skipNavigation) r.skipNavigation = false;
1720
+ if (prior || r.userData?.__fetchBrainCounted) {
1721
+ if (prior?.known && r.skipNavigation) r.skipNavigation = false;
1491
1722
  const rest = { ...r.userData };
1492
1723
  delete rest.__fetchBrainResult;
1724
+ delete rest.__fetchBrainCounted;
1493
1725
  r.userData = rest;
1494
1726
  }
1495
1727
  if (r.skipNavigation) continue;
@@ -1591,7 +1823,7 @@ function createFetchBrain(config) {
1591
1823
  }
1592
1824
  async function pushData(data, dataset, datasetName) {
1593
1825
  const ctx = getCurrentContext();
1594
- if (ctx && ctx.learning && !ctx.aiKnown) {
1826
+ if (ctx && ctx.learning && (!ctx.aiKnown || ctx.relearn)) {
1595
1827
  ctx.items.push(...Array.isArray(data) ? data : [data]);
1596
1828
  }
1597
1829
  if (datasetName && dataset.open) {