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