@fetchbrain.com/sdk 0.7.0 → 0.8.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,6 +1124,40 @@ 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
1162
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
1065
1163
  var MAX_STASH_ENTRIES = 5e3;
@@ -1073,6 +1171,13 @@ function isIterableInputRejection(err) {
1073
1171
  const message = err instanceof Error ? err.message : String(err);
1074
1172
  return /iterable|\barray\b/i.test(message);
1075
1173
  }
1174
+ function resolveHandlerKey(crawler) {
1175
+ const c = crawler;
1176
+ for (const key of ["userProvidedRequestHandler", "requestHandler", "userDefinedRequestHandler"]) {
1177
+ if (typeof c[key] === "function") return key;
1178
+ }
1179
+ return null;
1180
+ }
1076
1181
  function buildRawRequest(request) {
1077
1182
  const r = request;
1078
1183
  let headers;
@@ -1091,7 +1196,7 @@ function buildRawRequest(request) {
1091
1196
  }
1092
1197
  let body;
1093
1198
  if (typeof r.payload === "string") body = r.payload;
1094
- return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
1199
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
1095
1200
  }
1096
1201
  function warnDefaultUniqueKey(request, logger, warned) {
1097
1202
  const method = (request.method ?? "GET").toUpperCase();
@@ -1182,8 +1287,27 @@ var FetchBrain = class {
1182
1287
  // enqueue-time fetch skipped, but remembered data gone by execution
1183
1288
  startTime: 0
1184
1289
  };
1290
+ const labelStats = /* @__PURE__ */ new Map();
1291
+ const labelCounts = (label) => {
1292
+ const key = reportLabel(label);
1293
+ let counts = labelStats.get(key);
1294
+ if (!counts && labelStats.size < REPORT_MAX_LABELS) {
1295
+ counts = { scraped: 0, empty: 0, failed: 0 };
1296
+ labelStats.set(key, counts);
1297
+ } else if (!counts) {
1298
+ logger.debug(`Run report: more than ${REPORT_MAX_LABELS} labels; not tracking "${key}"`);
1299
+ }
1300
+ return counts;
1301
+ };
1185
1302
  const pendingLearns = /* @__PURE__ */ new Set();
1186
- const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
1303
+ if ("adaptiveRequestHandler" in crawler) {
1304
+ logger.warn(
1305
+ "AdaptivePlaywrightCrawler is not supported yet \u2014 FetchBrain left this crawler unmodified"
1306
+ );
1307
+ return Object.assign(crawler, { fetchBrain: client });
1308
+ }
1309
+ const handlerKey = resolveHandlerKey(crawler);
1310
+ const originalHandler = handlerKey ? crawler[handlerKey] : void 0;
1187
1311
  if (!originalHandler) {
1188
1312
  logger.warn("No request handler found on crawler, returning unmodified");
1189
1313
  return Object.assign(crawler, { fetchBrain: client });
@@ -1273,6 +1397,7 @@ var FetchBrain = class {
1273
1397
  );
1274
1398
  }
1275
1399
  let usedAIData = false;
1400
+ const relearn = aiResult.known && config.changeDetection?.enabled === true;
1276
1401
  const originalPushData = context.pushData;
1277
1402
  const fireOnRecalled = async (data) => {
1278
1403
  if (!config.onRecalled) return;
@@ -1317,6 +1442,8 @@ var FetchBrain = class {
1317
1442
  return;
1318
1443
  }
1319
1444
  runStats.scraped++;
1445
+ const counts = labelCounts(request.label);
1446
+ if (counts) counts.scraped++;
1320
1447
  if (aiResult.known) {
1321
1448
  runStats.recalled++;
1322
1449
  logger.info(
@@ -1328,7 +1455,7 @@ var FetchBrain = class {
1328
1455
  const learnItems = [];
1329
1456
  if (originalPushData && config.learning !== false) {
1330
1457
  context.pushData = async (data) => {
1331
- if (!usedAIData && !aiResult.known) {
1458
+ if (!usedAIData && (!aiResult.known || relearn)) {
1332
1459
  learnItems.push(...Array.isArray(data) ? data : [data]);
1333
1460
  }
1334
1461
  return originalPushData.call(context, data);
@@ -1339,12 +1466,21 @@ var FetchBrain = class {
1339
1466
  client,
1340
1467
  learning: config.learning !== false,
1341
1468
  aiKnown: aiResult.known,
1469
+ relearn,
1342
1470
  items: learnItems
1343
1471
  };
1344
- await asyncContext.run(requestContext, async () => {
1345
- await originalHandler.call(crawler, context);
1346
- });
1347
- if (learnItems.length > 0 && !usedAIData && !aiResult.known) {
1472
+ try {
1473
+ await asyncContext.run(requestContext, async () => {
1474
+ await originalHandler.call(crawler, context);
1475
+ });
1476
+ } catch (handlerErr) {
1477
+ if (counts) counts.failed++;
1478
+ throw handlerErr;
1479
+ }
1480
+ if (counts && learnItems.length === 0 && originalPushData && config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1481
+ counts.empty++;
1482
+ }
1483
+ if (learnItems.length > 0 && !usedAIData && (!aiResult.known || relearn)) {
1348
1484
  await client.waitForLearnRoom(LEARN_ROOM_WAIT_MS);
1349
1485
  const pending = client.learn(rawRequest, learnItems.length === 1 ? learnItems[0] : learnItems).then((res) => {
1350
1486
  if (res.status !== "rejected") runStats.learned += learnItems.length;
@@ -1430,16 +1566,17 @@ var FetchBrain = class {
1430
1566
  }
1431
1567
  };
1432
1568
  const crawlerAny = crawler;
1433
- if ("requestHandler" in crawlerAny) {
1434
- crawlerAny.requestHandler = wrappedHandler;
1435
- }
1436
- if ("userDefinedRequestHandler" in crawlerAny) {
1437
- crawlerAny.userDefinedRequestHandler = wrappedHandler;
1438
- }
1569
+ crawlerAny[handlerKey] = wrappedHandler;
1570
+ logger.debug(`Wrapped ${handlerKey}`);
1439
1571
  if (typeof crawlerAny.run === "function") {
1440
1572
  const originalRun = crawlerAny.run.bind(crawlerAny);
1441
1573
  crawlerAny.run = async (...args) => {
1442
1574
  runStats.startTime = Date.now();
1575
+ const runStartedAt = new Date(runStats.startTime).toISOString();
1576
+ labelStats.clear();
1577
+ const runBase = { scraped: runStats.scraped, learned: runStats.learned, recalled: runStats.recalled };
1578
+ const changeBase = safeChangeStats(client);
1579
+ const runId = nextRunId();
1443
1580
  try {
1444
1581
  const result = await originalRun(...args);
1445
1582
  return result;
@@ -1456,9 +1593,55 @@ var FetchBrain = class {
1456
1593
  );
1457
1594
  const managedRequests = runStats.totalRequests - runStats.bypassed;
1458
1595
  const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1596
+ let changes = { changed: 0, drift: [] };
1597
+ try {
1598
+ const now = safeChangeStats(client);
1599
+ const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
1600
+ const seen = new Set(changeBase.drift.map(key));
1601
+ changes = {
1602
+ changed: Math.max(0, now.changed - changeBase.changed) || 0,
1603
+ drift: now.drift.filter((d) => !seen.has(key(d)))
1604
+ };
1605
+ } catch (diffErr) {
1606
+ logger.debug(`Change summary skipped: ${diffErr}`);
1607
+ }
1608
+ const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1459
1609
  logger.info(
1460
- `\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`
1610
+ `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1461
1611
  );
1612
+ for (const item of changes.drift) {
1613
+ try {
1614
+ logger.warn(describeDrift(item));
1615
+ } catch (warnErr) {
1616
+ logger.debug(`Drift warning skipped: ${warnErr}`);
1617
+ }
1618
+ }
1619
+ if (config.reportRuns !== false) {
1620
+ try {
1621
+ const labels = Object.fromEntries(labelStats);
1622
+ const flags = await client.reportRun({
1623
+ runId,
1624
+ build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1625
+ startedAt: runStartedAt,
1626
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1627
+ scraped: runStats.scraped - runBase.scraped,
1628
+ learned: runStats.learned - runBase.learned,
1629
+ recalled: runStats.recalled - runBase.recalled,
1630
+ labels
1631
+ });
1632
+ for (const flag of Array.isArray(flags) ? flags : []) {
1633
+ if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
1634
+ continue;
1635
+ }
1636
+ const label = clipText(flag.label, 64);
1637
+ logger.warn(
1638
+ flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
1639
+ );
1640
+ }
1641
+ } catch (reportErr) {
1642
+ logger.debug(`Run report skipped: ${reportErr}`);
1643
+ }
1644
+ }
1462
1645
  }
1463
1646
  };
1464
1647
  }
@@ -1581,7 +1764,7 @@ function createFetchBrain(config) {
1581
1764
  }
1582
1765
  async function pushData(data, dataset, datasetName) {
1583
1766
  const ctx = getCurrentContext();
1584
- if (ctx && ctx.learning && !ctx.aiKnown) {
1767
+ if (ctx && ctx.learning && (!ctx.aiKnown || ctx.relearn)) {
1585
1768
  ctx.items.push(...Array.isArray(data) ? data : [data]);
1586
1769
  }
1587
1770
  if (datasetName && dataset.open) {