@fetchbrain.com/sdk 0.11.0 → 0.12.1

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
@@ -477,6 +477,14 @@ var ApiError = class extends Error {
477
477
  this.name = "ApiError";
478
478
  }
479
479
  };
480
+ var TERMINAL_ANALYTICS_STATUSES = /* @__PURE__ */ new Set([400, 413, 415, 422]);
481
+ var ANALYTICS_RATE_LIMIT_PAUSE_SEC = 10;
482
+ var BadReplyError = class extends Error {
483
+ constructor(message) {
484
+ super(message);
485
+ this.name = "BadReplyError";
486
+ }
487
+ };
480
488
  function parseRetryAfter(header) {
481
489
  if (!header) return void 0;
482
490
  const secs = Number(header);
@@ -515,13 +523,20 @@ var FetchBrainClient = class {
515
523
  this.warnedOversizeLearn = false;
516
524
  /** Warn about the learn cap once per pause, independent of the pause state. */
517
525
  this.learnCapWarnedUntil = 0;
526
+ /**
527
+ * The monthly recall limit answered HARD_CAP_EXCEEDED. Recall (handler-time and
528
+ * enqueue-time bulk) stops for the rest of the run. Per client instance; reset by
529
+ * beginRun() so each new run() tries once more (a plan can reset between runs).
530
+ */
531
+ this.recallCapped = false;
518
532
  /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
519
- this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
533
+ this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [], known: 0 };
520
534
  this.logger = createLogger(config.debug ? "debug" : "info", true);
521
535
  this.config = {
522
536
  apiKey: config.apiKey,
523
537
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
524
538
  memory: config.memory || "recent",
539
+ recall: config.recall ?? true,
525
540
  learning: config.learning ?? true,
526
541
  alwaysRun: config.alwaysRun ?? false,
527
542
  refreshOnRebuild: config.refreshOnRebuild ?? false,
@@ -530,8 +545,6 @@ var FetchBrainClient = class {
530
545
  debug: config.debug || false,
531
546
  extractForLearning: config.extractForLearning,
532
547
  learnUrlField: config.learnUrlField,
533
- telemetry: config.telemetry ?? { enabled: false },
534
- // opt-in
535
548
  batch: config.batch,
536
549
  circuitBreaker: config.circuitBreaker,
537
550
  skipLabels: config.skipLabels,
@@ -544,6 +557,8 @@ var FetchBrainClient = class {
544
557
  // enhance-only; stored so getConfig() round-trips
545
558
  scraper: config.scraper,
546
559
  changeDetection: config.changeDetection,
560
+ analytics: config.analytics,
561
+ // enhance-only; stored so getConfig() round-trips
547
562
  reportRuns: config.reportRuns ?? true
548
563
  };
549
564
  const scraper = resolveScraperName(config.scraper);
@@ -562,6 +577,11 @@ var FetchBrainClient = class {
562
577
  this.logger,
563
578
  "Ask"
564
579
  );
580
+ this.analyticsCircuitBreaker = new CircuitBreaker(
581
+ this.config.circuitBreaker,
582
+ this.logger,
583
+ "Analytics"
584
+ );
565
585
  this.batcher = new RequestBatcher(
566
586
  (items) => this.executeBatchQuery(items),
567
587
  clampBatch(this.config.batch, MAX_BULK_ITEMS),
@@ -575,11 +595,45 @@ var FetchBrainClient = class {
575
595
  }
576
596
  /** True when recalls must not reach the API right now (crawl continues without). */
577
597
  recallBlocked() {
578
- return this.isKeyRejected() || this.circuitBreaker.isOpen();
598
+ return this.recallCapped || this.isKeyRejected() || this.circuitBreaker.isOpen();
599
+ }
600
+ /** Where the account stands against its limits: recall cap wins over learn cap. */
601
+ quotaState() {
602
+ if (this.recallCapped) return "recall_cap";
603
+ if (Date.now() < this.learnCapWarnedUntil) return "learn_cap";
604
+ return "ok";
605
+ }
606
+ /**
607
+ * Start of a run(): the recall limit is retried once (plans can reset between
608
+ * runs); if the API still answers HARD_CAP_EXCEEDED, recall stops again for
609
+ * that run. The learn cap is month-bound and keeps its own pause.
610
+ */
611
+ beginRun() {
612
+ this.recallCapped = false;
613
+ }
614
+ /** Called (never throws into the caller) when a limit is first seen. Pass undefined to clear. */
615
+ onQuotaReached(listener) {
616
+ this.quotaListener = listener;
617
+ }
618
+ notifyQuota(cap) {
619
+ try {
620
+ this.quotaListener?.(cap);
621
+ } catch (err) {
622
+ this.logger.debug("Quota listener failed:", err);
623
+ }
579
624
  }
580
625
  isKeyRejected() {
581
626
  return Date.now() < this.keyRejectedUntil;
582
627
  }
628
+ /** A 403 HARD_CAP_EXCEEDED on recall: warn once, pause recall for the run, tell the listener. */
629
+ noteRecallCap(error) {
630
+ if (!(error instanceof ApiError) || error.status !== 403 || error.code !== "HARD_CAP_EXCEEDED" && error.serverError !== "HARD_CAP_EXCEEDED" || this.recallCapped) {
631
+ return;
632
+ }
633
+ this.recallCapped = true;
634
+ this.logger.warn("Monthly recall limit reached \u2014 recall is paused until your plan resets; pages are fetched normally.");
635
+ this.notifyQuota("recall");
636
+ }
583
637
  /**
584
638
  * React to a 4xx the API returned. These are not outages (they don't open the
585
639
  * shared breaker). A 401 means the next calls would fail the same way, so all
@@ -714,10 +768,14 @@ var FetchBrainClient = class {
714
768
  query: question,
715
769
  answer: opts?.answer,
716
770
  limit: opts?.limit,
717
- model: opts?.model
771
+ model: opts?.model,
772
+ memory: opts?.memory,
773
+ versions: opts?.versions
718
774
  };
719
775
  const platformBuildId = getPlatformBuildId();
720
- if (this.config.refreshOnRebuild && platformBuildId) {
776
+ if (opts?.build !== void 0) {
777
+ askBody.build = opts.build;
778
+ } else if (this.config.refreshOnRebuild && platformBuildId) {
721
779
  askBody.build = platformBuildId;
722
780
  }
723
781
  try {
@@ -777,8 +835,10 @@ var FetchBrainClient = class {
777
835
  }
778
836
  return results;
779
837
  } catch (error) {
780
- if (!isOutage(error)) this.noteRefusal(error);
781
- else if (outcome) outcome.outage = true;
838
+ if (!isOutage(error)) {
839
+ this.noteRefusal(error);
840
+ this.noteRecallCap(error);
841
+ } else if (outcome) outcome.outage = true;
782
842
  else this.circuitBreaker.recordFailure();
783
843
  throw error;
784
844
  }
@@ -797,6 +857,10 @@ var FetchBrainClient = class {
797
857
  const request = { entries };
798
858
  const ignore = this.config.changeDetection?.ignoreFields;
799
859
  if (ignore && ignore.length > 0) request.ignore = ignore;
860
+ if (this.config.recall === false) {
861
+ request.observe = true;
862
+ request.memory = this.config.memory;
863
+ }
800
864
  const platformBuildId = getPlatformBuildId();
801
865
  if (this.config.refreshOnRebuild && platformBuildId) {
802
866
  request.build = platformBuildId;
@@ -817,6 +881,7 @@ var FetchBrainClient = class {
817
881
  const now = /* @__PURE__ */ new Date();
818
882
  const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
819
883
  this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
884
+ this.notifyQuota("learn");
820
885
  if (this.learnCapWarnedUntil < monthStart) {
821
886
  this.learnCapWarnedUntil = monthStart;
822
887
  this.logger.warn(
@@ -863,6 +928,7 @@ var FetchBrainClient = class {
863
928
  stats.changed += num(response.changed);
864
929
  stats.unchanged += num(response.unchanged);
865
930
  stats.firstSeen += num(response.firstSeen);
931
+ stats.known = (stats.known ?? 0) + num(response.known);
866
932
  const drift = Array.isArray(response.drift) ? response.drift : [];
867
933
  for (const item of drift) {
868
934
  if (!item || typeof item !== "object" || typeof item.label !== "string" || typeof item.field !== "string" || !DRIFT_KINDS.has(item.kind)) {
@@ -889,7 +955,7 @@ var FetchBrainClient = class {
889
955
  * failure or timeout it returns no flags.
890
956
  */
891
957
  async reportRun(report, timeoutMs = REPORT_RUN_TIMEOUT) {
892
- if (this.config.reportRuns === false || this.recallBlocked()) return [];
958
+ if (this.config.reportRuns === false || this.isKeyRejected() || this.circuitBreaker.isOpen()) return [];
893
959
  try {
894
960
  const response = await this.makeRequest(
895
961
  "/v1/runs",
@@ -904,12 +970,95 @@ var FetchBrainClient = class {
904
970
  return [];
905
971
  }
906
972
  }
973
+ /**
974
+ * Ship one gzipped analytics batch. Never throws. null = retry later (outage,
975
+ * breaker open, key rejected, other 4xx, 429 without Retry-After, bad 2xx body);
976
+ * `{ drop: true }` = the server permanently refused this batch (400/413/415/422),
977
+ * so discard it.
978
+ */
979
+ async postAnalyticsEvents(body, _runId, signal) {
980
+ if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
981
+ try {
982
+ const response = await this.makeRequest(
983
+ "/v1/analytics/events",
984
+ {
985
+ method: "POST",
986
+ body,
987
+ headers: {
988
+ "Content-Type": "application/json",
989
+ "Content-Encoding": "gzip"
990
+ }
991
+ },
992
+ DEFAULT_LEARN_TIMEOUT,
993
+ { signal, lenientBody: true }
994
+ );
995
+ this.analyticsCircuitBreaker.recordSuccess();
996
+ const out = {};
997
+ if (response && typeof response.sampleRate === "number") out.sampleRate = response.sampleRate;
998
+ if (response && typeof response.pauseUntil === "number") out.pauseUntil = response.pauseUntil;
999
+ return out;
1000
+ } catch (error) {
1001
+ this.noteRefusal(error);
1002
+ if (signal?.aborted) {
1003
+ return null;
1004
+ } else if (error instanceof BadReplyError) {
1005
+ this.analyticsCircuitBreaker.recordFailure();
1006
+ this.logger.debug("Analytics reply was not JSON:", error);
1007
+ return null;
1008
+ } else if (isOutage(error)) {
1009
+ this.analyticsCircuitBreaker.recordFailure();
1010
+ } else if (error instanceof ApiError) {
1011
+ if (error.status === 429) {
1012
+ const hinted = error.retryAfterSec;
1013
+ const waitSec = typeof hinted === "number" && Number.isFinite(hinted) && hinted > 0 ? Math.min(Math.max(hinted, 1), 3600) : ANALYTICS_RATE_LIMIT_PAUSE_SEC;
1014
+ return { pauseUntil: Date.now() + waitSec * 1e3, retry: true };
1015
+ } else if (TERMINAL_ANALYTICS_STATUSES.has(error.status)) {
1016
+ this.logger.debug("Analytics batch refused:", error);
1017
+ return { drop: true };
1018
+ }
1019
+ }
1020
+ this.logger.debug("Analytics events post failed:", error);
1021
+ return null;
1022
+ }
1023
+ }
1024
+ /** The resolved scraper name (valid option, else env var); undefined = default memory. */
1025
+ getScraperName() {
1026
+ return this.scraperName;
1027
+ }
1028
+ /** Fetch the analytics config for this key. Never throws: failure returns null. */
1029
+ async getAnalyticsConfig() {
1030
+ if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
1031
+ try {
1032
+ const r = await this.makeRequest("/v1/analytics/config", { method: "GET" });
1033
+ this.analyticsCircuitBreaker.recordSuccess();
1034
+ if (!r || typeof r.enabled !== "boolean") return null;
1035
+ const salt = typeof r.salt === "string" ? r.salt : "";
1036
+ if (!r.enabled) return { enabled: false, salt, sampleRate: 1 };
1037
+ return {
1038
+ salt,
1039
+ sampleRate: typeof r.sampleRate === "number" ? r.sampleRate : 1,
1040
+ ...typeof r.pauseUntil === "number" ? { pauseUntil: r.pauseUntil } : {},
1041
+ enabled: true
1042
+ };
1043
+ } catch (error) {
1044
+ this.noteRefusal(error);
1045
+ if (isOutage(error)) this.analyticsCircuitBreaker.recordFailure();
1046
+ this.logger.debug("Analytics config fetch failed:", error);
1047
+ return null;
1048
+ }
1049
+ }
907
1050
  /**
908
1051
  * Make an HTTP request to the API
909
1052
  */
910
- async makeRequest(path, options, timeout) {
1053
+ async makeRequest(path, options, timeout, extra) {
911
1054
  const url = `${this.config.baseUrl}${path}`;
912
1055
  const controller = new AbortController();
1056
+ const external = extra?.signal;
1057
+ const onExternalAbort = () => controller.abort();
1058
+ if (external) {
1059
+ if (external.aborted) controller.abort();
1060
+ else external.addEventListener("abort", onExternalAbort, { once: true });
1061
+ }
913
1062
  const timeoutId = setTimeout(
914
1063
  () => controller.abort(),
915
1064
  timeout ?? this.config.timeout
@@ -973,9 +1122,24 @@ var FetchBrainClient = class {
973
1122
  parseRetryAfter(response.headers.get("Retry-After"))
974
1123
  );
975
1124
  }
1125
+ if (extra?.lenientBody) {
1126
+ const text = await readBody(response, (r) => r.text());
1127
+ if (response.status === 204 || text.length === 0) return {};
1128
+ let parsed;
1129
+ try {
1130
+ parsed = JSON.parse(text);
1131
+ } catch {
1132
+ throw new BadReplyError("Unexpected non-JSON reply");
1133
+ }
1134
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1135
+ throw new BadReplyError("Unexpected reply shape");
1136
+ }
1137
+ return parsed;
1138
+ }
976
1139
  return await readBody(response, (r) => r.json());
977
1140
  } finally {
978
1141
  clearTimeout(timeoutId);
1142
+ external?.removeEventListener("abort", onExternalAbort);
979
1143
  }
980
1144
  }
981
1145
  /**
@@ -1017,181 +1181,42 @@ var FetchBrainClient = class {
1017
1181
  async flushLearnBatch() {
1018
1182
  await this.learnBatcher.forceFlush();
1019
1183
  }
1020
- /**
1021
- * Send telemetry data to the API
1022
- * This is fire-and-forget - failures are silently ignored
1023
- */
1024
- async sendTelemetry(entries) {
1025
- if (!this.config.telemetry?.enabled || entries.length === 0) {
1026
- return;
1027
- }
1028
- try {
1029
- await this.makeRequest("/v1/telemetry", {
1030
- method: "POST",
1031
- body: JSON.stringify({ entries })
1032
- });
1033
- } catch {
1034
- }
1035
- }
1036
- /**
1037
- * Check if telemetry is enabled
1038
- */
1039
- isTelemetryEnabled() {
1040
- return this.config.telemetry?.enabled ?? false;
1041
- }
1042
- /**
1043
- * Get telemetry config
1044
- */
1045
- getTelemetryConfig() {
1046
- return this.config.telemetry;
1047
- }
1048
1184
  };
1049
1185
 
1050
- // src/telemetry.ts
1051
- async function hashString(str) {
1052
- const encoder = new TextEncoder();
1053
- const data = encoder.encode(str);
1054
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1055
- const hashArray = Array.from(new Uint8Array(hashBuffer));
1056
- return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
1057
- }
1058
- function extractDomain(url) {
1059
- try {
1060
- return new URL(url).hostname;
1061
- } catch {
1062
- return "unknown";
1063
- }
1186
+ // src/enhance.ts
1187
+ var collectorModule;
1188
+ function loadCollector() {
1189
+ return collectorModule ?? (collectorModule = import('./collector-KEC7N6EY.mjs').catch(() => {
1190
+ collectorModule = void 0;
1191
+ return void 0;
1192
+ }));
1064
1193
  }
1065
- function generalizeUrlPath(url) {
1066
- try {
1067
- const parsed = new URL(url);
1068
- const path = parsed.pathname;
1069
- return path.replace(/\/\d+/g, "/*").replace(/\/[a-f0-9-]{36}/gi, "/*").replace(/\/[a-zA-Z0-9]{20,}/g, "/*").replace(/\?.*$/, "");
1070
- } catch {
1071
- return "/*";
1194
+ var MAX_TALLY_LABELS = 50;
1195
+ var DEFAULT_CHILD_LABEL = "_nolabel";
1196
+ var ANALYTICS_CONFIG_TIMEOUT_MS = 500;
1197
+ var MAX_BLOCKED_TRACKED = 1e4;
1198
+ var msSince = (t0) => Math.round(performance.now() - t0);
1199
+ function statusFrom(response) {
1200
+ const r = response;
1201
+ if (!r) return void 0;
1202
+ if (typeof r.statusCode === "number") return r.statusCode;
1203
+ if (typeof r.status === "function") {
1204
+ const s = r.status.call(r);
1205
+ return typeof s === "number" ? s : void 0;
1072
1206
  }
1207
+ return void 0;
1073
1208
  }
1074
- function detectBlockType(statusCode, errorMessage) {
1075
- if (!statusCode && !errorMessage) return void 0;
1076
- if (statusCode === 403) return "403";
1077
- if (statusCode === 429) return "429";
1078
- if (statusCode === 503) return "503";
1079
- if (statusCode && statusCode >= 400) return `${statusCode}`;
1080
- const msg = errorMessage?.toLowerCase() || "";
1081
- if (msg.includes("captcha")) return "captcha";
1082
- if (msg.includes("timeout")) return "timeout";
1083
- if (msg.includes("blocked")) return "blocked";
1084
- if (msg.includes("rate limit")) return "429";
1209
+ function bodyBytes(context) {
1210
+ const body = context.body;
1211
+ if (Buffer.isBuffer(body)) return body.length;
1212
+ if (typeof body === "string") return Buffer.byteLength(body);
1085
1213
  return void 0;
1086
1214
  }
1087
- function extractProxyType(proxyUrl) {
1088
- if (!proxyUrl) return void 0;
1089
- const url = proxyUrl.toLowerCase();
1090
- if (url.includes("residential")) return "residential";
1091
- if (url.includes("mobile")) return "mobile";
1092
- if (url.includes("datacenter") || url.includes("dc")) return "datacenter";
1093
- if (url.includes("bright") || url.includes("oxylabs") || url.includes("smartproxy")) {
1094
- return "residential";
1095
- }
1096
- return "datacenter";
1215
+ function headerBytes(response) {
1216
+ const headers = response?.headers;
1217
+ const len = headers && typeof headers === "object" ? Number(headers["content-length"]) : NaN;
1218
+ return Number.isFinite(len) && len >= 0 ? len : void 0;
1097
1219
  }
1098
- async function collectTelemetry(context, timing, config, error) {
1099
- if (!config?.enabled) {
1100
- return null;
1101
- }
1102
- const url = context.request.url;
1103
- const statusCode = context.response?.status || context.response?.statusCode;
1104
- const telemetry = {
1105
- domain: extractDomain(url),
1106
- urlHash: await hashString(url),
1107
- urlPattern: generalizeUrlPath(url),
1108
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1109
- };
1110
- if (config.sharePerformance !== false) {
1111
- telemetry.statusCode = statusCode;
1112
- telemetry.retryCount = context.request.retryCount;
1113
- if (timing) {
1114
- telemetry.responseTimeMs = timing.responseTime;
1115
- telemetry.totalTimeMs = timing.endTime && timing.startTime ? timing.endTime - timing.startTime : void 0;
1116
- telemetry.contentSize = timing.contentSize;
1117
- }
1118
- }
1119
- if (config.shareProxyInfo !== false && context.proxyInfo) {
1120
- telemetry.proxyCountry = context.proxyInfo.countryCode;
1121
- telemetry.proxyType = extractProxyType(context.proxyInfo.url);
1122
- telemetry.proxySuccess = statusCode ? statusCode < 400 : void 0;
1123
- }
1124
- if (config.shareSitePatterns !== false) {
1125
- const isBlocked = statusCode && (statusCode === 403 || statusCode === 429 || statusCode >= 500);
1126
- telemetry.blocked = isBlocked || !!error;
1127
- telemetry.blockType = detectBlockType(statusCode, error?.message);
1128
- }
1129
- if (context.session) {
1130
- telemetry.sessionAge = context.session.usageCount;
1131
- telemetry.sessionErrorScore = context.session.errorScore;
1132
- }
1133
- telemetry.crawlerType = context.crawler?.constructor?.name?.replace("Crawler", "").toLowerCase();
1134
- telemetry.requestLabel = context.request.label;
1135
- return telemetry;
1136
- }
1137
- var TelemetryBuffer = class {
1138
- constructor(options = {}) {
1139
- this.buffer = [];
1140
- this.maxSize = options.maxSize ?? 50;
1141
- this.flushInterval = options.flushInterval ?? 3e4;
1142
- this.flushCallback = options.onFlush;
1143
- this.startFlushTimer();
1144
- }
1145
- /**
1146
- * Add telemetry entry to buffer
1147
- */
1148
- add(entry) {
1149
- if (!entry) return;
1150
- this.buffer.push(entry);
1151
- if (this.buffer.length >= this.maxSize) {
1152
- this.flush();
1153
- }
1154
- }
1155
- /**
1156
- * Flush buffer and send telemetry
1157
- */
1158
- async flush() {
1159
- if (this.buffer.length === 0) return [];
1160
- const entries = [...this.buffer];
1161
- this.buffer = [];
1162
- if (this.flushCallback) {
1163
- try {
1164
- await this.flushCallback(entries);
1165
- } catch (err) {
1166
- console.debug("Telemetry flush failed:", err);
1167
- }
1168
- }
1169
- return entries;
1170
- }
1171
- /**
1172
- * Get current buffer size
1173
- */
1174
- get size() {
1175
- return this.buffer.length;
1176
- }
1177
- startFlushTimer() {
1178
- this.flushTimer = setInterval(() => {
1179
- this.flush();
1180
- }, this.flushInterval);
1181
- this.flushTimer.unref?.();
1182
- }
1183
- /**
1184
- * Stop the flush timer and flush remaining entries
1185
- */
1186
- async stop() {
1187
- if (this.flushTimer) {
1188
- clearInterval(this.flushTimer);
1189
- }
1190
- await this.flush();
1191
- }
1192
- };
1193
-
1194
- // src/enhance.ts
1195
1220
  var REPORT_MAX_LABELS = 50;
1196
1221
  var REPORT_LABEL_MAX_CHARS = 64;
1197
1222
  var RUN_ID_MAX_CHARS = 128;
@@ -1214,11 +1239,36 @@ function reportLabel(label) {
1214
1239
  const trimmed = (labelText(label) ?? "").trim().slice(0, REPORT_LABEL_MAX_CHARS);
1215
1240
  return trimmed || NO_LABEL;
1216
1241
  }
1242
+ function analyticsLabelText(label) {
1243
+ return (labelText(label) ?? "").replace(/^[\s~]+/, "").trim().slice(0, REPORT_LABEL_MAX_CHARS);
1244
+ }
1245
+ function analyticsLabel(label) {
1246
+ return analyticsLabelText(label) || NO_LABEL;
1247
+ }
1217
1248
  var pct = (rate) => `${Math.round(rate * 100)}%`;
1218
1249
  function describeDrift(d) {
1219
1250
  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))}`;
1220
1251
  return `\u26A0\uFE0F drift [${clipText(d.label, 64)}] ${clipText(d.field, 64)}: ${detail}`;
1221
1252
  }
1253
+ function safeBeginRun(client) {
1254
+ try {
1255
+ client.beginRun();
1256
+ } catch {
1257
+ }
1258
+ }
1259
+ function safeQuotaState(client) {
1260
+ try {
1261
+ return client.quotaState();
1262
+ } catch {
1263
+ return "ok";
1264
+ }
1265
+ }
1266
+ function safeOnQuotaReached(client, listener) {
1267
+ try {
1268
+ client.onQuotaReached(listener);
1269
+ } catch {
1270
+ }
1271
+ }
1222
1272
  function safeChangeStats(client) {
1223
1273
  try {
1224
1274
  return client.getChangeStats();
@@ -1300,9 +1350,52 @@ function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
1300
1350
  }
1301
1351
  }
1302
1352
  var asyncContext = new AsyncLocalStorage();
1353
+ var noopCapture = () => {
1354
+ };
1355
+ var recordCount = (data) => Array.isArray(data) ? data.length : 1;
1356
+ function childLabelOf(r) {
1357
+ if (!r || typeof r !== "object") return DEFAULT_CHILD_LABEL;
1358
+ try {
1359
+ const o = r;
1360
+ return analyticsLabelText(o.label ?? o.userData?.label) || DEFAULT_CHILD_LABEL;
1361
+ } catch {
1362
+ return DEFAULT_CHILD_LABEL;
1363
+ }
1364
+ }
1365
+ function tallyAdd(t, label, added, already) {
1366
+ const key = t.has(label) || t.size < MAX_TALLY_LABELS ? label : "~other";
1367
+ const cur = t.get(key);
1368
+ if (cur) {
1369
+ cur[0] += added;
1370
+ cur[1] += already;
1371
+ } else {
1372
+ t.set(key, [added, already]);
1373
+ }
1374
+ }
1375
+ function userDataForCallback(userData) {
1376
+ if (!userData) return {};
1377
+ let hasSdkKey = false;
1378
+ for (const k of SDK_USERDATA_KEYS) if (k in userData) hasSdkKey = true;
1379
+ if (!hasSdkKey) return userData;
1380
+ const out = {};
1381
+ for (const [k, v] of Object.entries(userData)) if (!SDK_USERDATA_KEYS.has(k)) out[k] = v;
1382
+ return out;
1383
+ }
1303
1384
  function getCurrentContext() {
1304
1385
  return asyncContext.getStore();
1305
1386
  }
1387
+ async function fetchAnalyticsConfig(client) {
1388
+ let timer;
1389
+ const timeout = new Promise((resolve) => {
1390
+ timer = setTimeout(() => resolve(null), ANALYTICS_CONFIG_TIMEOUT_MS);
1391
+ timer.unref?.();
1392
+ });
1393
+ try {
1394
+ return await Promise.race([client.getAnalyticsConfig().catch(() => null), timeout]);
1395
+ } finally {
1396
+ if (timer) clearTimeout(timer);
1397
+ }
1398
+ }
1306
1399
  function shouldRunHandler(alwaysRun, label) {
1307
1400
  if (alwaysRun === void 0 || alwaysRun === false) {
1308
1401
  return false;
@@ -1353,19 +1446,9 @@ var FetchBrain = class {
1353
1446
  * @returns Enhanced crawler with same interface
1354
1447
  */
1355
1448
  static enhance(crawler, config) {
1356
- const client = new FetchBrainClient(config);
1449
+ const client = Object.assign(new FetchBrainClient(config), { capture: noopCapture });
1357
1450
  const logger = createLogger(config.debug ? "debug" : "info", true);
1358
- const telemetryConfig = config.telemetry ?? { enabled: false };
1359
- const telemetryBuffer = new TelemetryBuffer({
1360
- maxSize: 50,
1361
- flushInterval: 3e4,
1362
- onFlush: async (entries) => {
1363
- if (telemetryConfig.enabled) {
1364
- await client.sendTelemetry(entries);
1365
- logger.debug(`Telemetry: sent ${entries.length} entries`);
1366
- }
1367
- }
1368
- });
1451
+ const observe = config.recall === false;
1369
1452
  const runStats = {
1370
1453
  totalRequests: 0,
1371
1454
  recalled: 0,
@@ -1444,19 +1527,302 @@ var FetchBrain = class {
1444
1527
  return void 0;
1445
1528
  };
1446
1529
  const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
1530
+ const analyticsOn = config.analytics?.enabled === true;
1531
+ if (analyticsOn) void loadCollector();
1532
+ let collector;
1533
+ const attempts = /* @__PURE__ */ new WeakMap();
1534
+ const blockedByRequest = /* @__PURE__ */ new Map();
1535
+ const emittedThenFailed = /* @__PURE__ */ new Set();
1536
+ const attemptOf = (ctx) => {
1537
+ let a = attempts.get(ctx);
1538
+ if (!a) {
1539
+ a = {};
1540
+ attempts.set(ctx, a);
1541
+ }
1542
+ return a;
1543
+ };
1544
+ const requestKey = (r) => String(r.id ?? r.uniqueKey ?? r.url);
1545
+ const emitRequest = (c, ctx, a, outcome, blockType) => {
1546
+ if (a.emitted) return;
1547
+ a.emitted = true;
1548
+ const request = ctx.request;
1549
+ const key = requestKey(request);
1550
+ if (emittedThenFailed.size > 0 && emittedThenFailed.has(key)) return;
1551
+ const blockedAttempts = blockedByRequest.get(key) ?? 0;
1552
+ if (blockedAttempts) blockedByRequest.delete(key);
1553
+ c.request({
1554
+ label: analyticsLabel(request.label),
1555
+ outcome,
1556
+ retries: typeof request.retryCount === "number" ? request.retryCount : 0,
1557
+ url: request.url,
1558
+ statusCode: a.statusCode,
1559
+ navMs: a.navMs,
1560
+ handlerMs: a.handlerMs,
1561
+ recallMs: a.recallMs,
1562
+ bytes: a.bytes,
1563
+ blockType,
1564
+ blockedAttempts,
1565
+ // Evaluated only if the event survives sampling.
1566
+ context: () => contextFor(c, a, request)
1567
+ });
1568
+ };
1569
+ const recordSuccess = (context, outcome, handlerMs, recallMs) => {
1570
+ const c = collector;
1571
+ if (!c) return;
1572
+ try {
1573
+ const a = attemptOf(context);
1574
+ if (a.failed) return;
1575
+ a.handlerMs = handlerMs;
1576
+ a.recallMs = recallMs;
1577
+ a.bytes = bodyBytes(context) ?? a.bytes;
1578
+ emitRequest(c, context, a, outcome);
1579
+ } catch (analyticsErr) {
1580
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1581
+ }
1582
+ };
1583
+ const noteFailure = (c, ctx, err) => {
1584
+ const a = attemptOf(ctx);
1585
+ a.failed = true;
1586
+ if (a.emitted && emittedThenFailed.size < MAX_BLOCKED_TRACKED) {
1587
+ emittedThenFailed.add(requestKey(ctx.request));
1588
+ }
1589
+ a.statusCode ?? (a.statusCode = statusFrom(ctx.response));
1590
+ const message = err instanceof Error ? err.message : typeof err === "string" ? err : void 0;
1591
+ const blockType = c.blockType(a.statusCode, message);
1592
+ if (blockType && !a.blockCounted) {
1593
+ a.blockCounted = true;
1594
+ const key = requestKey(ctx.request);
1595
+ const n = blockedByRequest.get(key);
1596
+ if (n !== void 0 || blockedByRequest.size < MAX_BLOCKED_TRACKED) blockedByRequest.set(key, (n ?? 0) + 1);
1597
+ }
1598
+ return { a, blockType };
1599
+ };
1600
+ const contextFn = config.analytics?.context;
1601
+ const contextFor = (c, a, request) => {
1602
+ if (!contextFn) return void 0;
1603
+ if (a.ctxDone) return a.ctx;
1604
+ a.ctxDone = true;
1605
+ try {
1606
+ const raw = contextFn({
1607
+ url: request.url,
1608
+ label: labelText(request.label),
1609
+ userData: userDataForCallback(request.userData)
1610
+ });
1611
+ if (raw && typeof raw.then === "function") {
1612
+ Promise.resolve(raw).catch(() => {
1613
+ });
1614
+ return void 0;
1615
+ }
1616
+ a.ctx = c.sanitizeContext(raw);
1617
+ } catch {
1618
+ a.ctx = void 0;
1619
+ }
1620
+ return a.ctx;
1621
+ };
1622
+ const noteRecords = (label, n) => {
1623
+ const c = collector;
1624
+ if (!c) return;
1625
+ try {
1626
+ c.records(label, n);
1627
+ } catch (analyticsErr) {
1628
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1629
+ }
1630
+ };
1631
+ const captureFor = (context, request, label) => (name, props) => {
1632
+ const c = collector;
1633
+ if (!c) return;
1634
+ try {
1635
+ c.capture(name, props, label, contextFor(c, attemptOf(context), request));
1636
+ } catch (analyticsErr) {
1637
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1638
+ }
1639
+ };
1640
+ const emitTally = (parentLabel, t) => {
1641
+ const c = collector;
1642
+ if (!c) return;
1643
+ for (const [child, [added, already]] of t) c.enqueued(parentLabel, child, added, already);
1644
+ };
1645
+ const wrapFanOut = (context, parentLabel) => {
1646
+ const handlerTally = /* @__PURE__ */ new Map();
1647
+ let late;
1648
+ let flushed = false;
1649
+ const merge = (t) => {
1650
+ const into = flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally;
1651
+ for (const [label, [added, already]] of t) tallyAdd(into, label, added, already);
1652
+ };
1653
+ const settle = () => {
1654
+ if (flushed && late && late.size > 0) {
1655
+ const t = late;
1656
+ late = void 0;
1657
+ emitTally(parentLabel, t);
1658
+ }
1659
+ };
1660
+ const flush = () => {
1661
+ if (flushed) return;
1662
+ flushed = true;
1663
+ try {
1664
+ emitTally(parentLabel, handlerTally);
1665
+ } catch (analyticsErr) {
1666
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1667
+ }
1668
+ };
1669
+ const origLinks = context.enqueueLinks;
1670
+ if (typeof origLinks === "function") {
1671
+ context.enqueueLinks = async function(options) {
1672
+ const tally = /* @__PURE__ */ new Map();
1673
+ let viewUsed = false;
1674
+ let opts = options;
1675
+ if (collector) {
1676
+ try {
1677
+ const crawlerRef = context.crawler;
1678
+ const rq = options?.requestQueue ?? (typeof crawlerRef?.getRequestQueue === "function" ? await crawlerRef.getRequestQueue() : void 0);
1679
+ const addBatched = rq?.addRequestsBatched;
1680
+ if (rq && typeof addBatched === "function") {
1681
+ const view = Object.create(rq);
1682
+ view.addRequestsBatched = async (reqs, o) => {
1683
+ const res2 = await addBatched.call(rq, reqs, o);
1684
+ try {
1685
+ viewUsed = true;
1686
+ if (Array.isArray(reqs)) {
1687
+ const present = /* @__PURE__ */ new Set();
1688
+ const added = res2?.addedRequests;
1689
+ if (Array.isArray(added)) {
1690
+ for (const pr of added) {
1691
+ if (pr && pr.wasAlreadyPresent === true) present.add(pr.uniqueKey);
1692
+ }
1693
+ }
1694
+ for (const r of reqs) {
1695
+ const already = present.has(r?.uniqueKey);
1696
+ tallyAdd(tally, childLabelOf(r), already ? 0 : 1, already ? 1 : 0);
1697
+ }
1698
+ }
1699
+ } catch {
1700
+ }
1701
+ return res2;
1702
+ };
1703
+ opts = { ...options ?? {}, requestQueue: view };
1704
+ }
1705
+ } catch {
1706
+ opts = options;
1707
+ }
1708
+ }
1709
+ const res = await origLinks.call(this, opts);
1710
+ try {
1711
+ if (collector) {
1712
+ if (!viewUsed) {
1713
+ const label = childLabelOf(options);
1714
+ const processed = res?.processedRequests;
1715
+ if (Array.isArray(processed)) {
1716
+ for (const pr of processed) {
1717
+ const already = pr?.wasAlreadyPresent === true;
1718
+ tallyAdd(tally, label, already ? 0 : 1, already ? 1 : 0);
1719
+ }
1720
+ }
1721
+ }
1722
+ merge(tally);
1723
+ settle();
1724
+ }
1725
+ } catch (analyticsErr) {
1726
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1727
+ }
1728
+ return res;
1729
+ };
1730
+ }
1731
+ const origAdd = context.addRequests;
1732
+ if (typeof origAdd === "function") {
1733
+ context.addRequests = async function(requests, options) {
1734
+ if (!collector) return origAdd.call(this, requests, options);
1735
+ if (Array.isArray(requests)) {
1736
+ const res = await origAdd.call(this, requests, options);
1737
+ try {
1738
+ const tally = /* @__PURE__ */ new Map();
1739
+ for (const r of requests) tallyAdd(tally, childLabelOf(r), 1, 0);
1740
+ merge(tally);
1741
+ settle();
1742
+ } catch (analyticsErr) {
1743
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1744
+ }
1745
+ return res;
1746
+ }
1747
+ const iterable = requests;
1748
+ if (!iterable || typeof iterable !== "object" || typeof iterable[Symbol.iterator] !== "function" && typeof iterable[Symbol.asyncIterator] !== "function") {
1749
+ return origAdd.call(this, requests, options);
1750
+ }
1751
+ async function* counted() {
1752
+ try {
1753
+ for await (const r of requests) {
1754
+ try {
1755
+ tallyAdd(flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally, childLabelOf(r), 1, 0);
1756
+ } catch {
1757
+ }
1758
+ yield r;
1759
+ }
1760
+ } finally {
1761
+ try {
1762
+ settle();
1763
+ } catch {
1764
+ }
1765
+ }
1766
+ }
1767
+ return origAdd.call(this, counted(), options);
1768
+ };
1769
+ }
1770
+ return flush;
1771
+ };
1772
+ const clientCapture = (name, props) => {
1773
+ try {
1774
+ const store = asyncContext.getStore();
1775
+ if (store?.capture && store.client === client) return store.capture(name, props);
1776
+ collector?.capture(name, props, NO_LABEL);
1777
+ } catch (analyticsErr) {
1778
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
1779
+ }
1780
+ };
1781
+ client.capture = clientCapture;
1447
1782
  const wrappedHandler = async (context) => {
1448
1783
  crawlStarted = true;
1449
1784
  const { request } = context;
1450
1785
  const url = request.url;
1451
1786
  const label = request.label;
1452
- const startTime = Date.now();
1453
1787
  runStats.totalRequests++;
1788
+ const aLabel = collector ? analyticsLabel(label) : NO_LABEL;
1454
1789
  if (skipLabels && skipLabels.has(label || "default")) {
1455
1790
  runStats.bypassed++;
1456
1791
  if (config.debug) {
1457
1792
  logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
1458
1793
  }
1459
- await originalHandler.call(crawler, context);
1794
+ const b0 = analyticsOn ? performance.now() : 0;
1795
+ if (collector) {
1796
+ const bypassPush = context.pushData;
1797
+ if (bypassPush) {
1798
+ context.pushData = async (data) => {
1799
+ const res = await bypassPush.call(context, data);
1800
+ noteRecords(aLabel, recordCount(data));
1801
+ return res;
1802
+ };
1803
+ }
1804
+ const flushFanOut = wrapFanOut(context, aLabel);
1805
+ const bypassContext = {
1806
+ request: buildRawRequest(request),
1807
+ client,
1808
+ learning: false,
1809
+ aiKnown: false,
1810
+ relearn: false,
1811
+ items: [],
1812
+ capture: captureFor(context, request, aLabel),
1813
+ records: (n) => noteRecords(aLabel, n)
1814
+ };
1815
+ try {
1816
+ await asyncContext.run(bypassContext, async () => {
1817
+ await originalHandler.call(crawler, context);
1818
+ });
1819
+ } finally {
1820
+ flushFanOut();
1821
+ }
1822
+ } else {
1823
+ await originalHandler.call(crawler, context);
1824
+ }
1825
+ if (analyticsOn) recordSuccess(context, "bypassed", msSince(b0), void 0);
1460
1826
  return;
1461
1827
  }
1462
1828
  setScrapeContext({
@@ -1469,6 +1835,8 @@ var FetchBrain = class {
1469
1835
  const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
1470
1836
  warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
1471
1837
  let consumedStash;
1838
+ let recallMs;
1839
+ let handlerMs;
1472
1840
  try {
1473
1841
  const preRecalled = request.userData?.__fetchBrainResult;
1474
1842
  let aiResult;
@@ -1478,12 +1846,18 @@ var FetchBrain = class {
1478
1846
  consumedStash = stashedData;
1479
1847
  aiResult = { known: true, data: stashedData };
1480
1848
  } else {
1849
+ const r0 = analyticsOn ? performance.now() : 0;
1481
1850
  aiResult = await client.recall(rawRequest);
1851
+ if (analyticsOn) recallMs = msSince(r0);
1482
1852
  }
1483
1853
  } else if (preRecalled) {
1484
1854
  aiResult = preRecalled;
1855
+ } else if (observe) {
1856
+ aiResult = { known: false };
1485
1857
  } else {
1858
+ const r0 = analyticsOn ? performance.now() : 0;
1486
1859
  aiResult = await client.recall(rawRequest);
1860
+ if (analyticsOn) recallMs = msSince(r0);
1487
1861
  }
1488
1862
  if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1489
1863
  if (aiResult.fallback) {
@@ -1520,10 +1894,13 @@ var FetchBrain = class {
1520
1894
  if (aiResult.known && aiResult.data && originalPushData) {
1521
1895
  usedAIData = true;
1522
1896
  await originalPushData.call(context, aiResult.data);
1897
+ noteRecords(aLabel, recordCount(aiResult.data));
1523
1898
  if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
1524
1899
  await fireOnRecalled(aiResult.data);
1525
1900
  }
1526
- }
1901
+ },
1902
+ // Custom analytics event for this request; a no-op when analytics is off. Never throws.
1903
+ capture: clientCapture
1527
1904
  };
1528
1905
  request.userData = {
1529
1906
  ...request.userData,
@@ -1536,6 +1913,7 @@ var FetchBrain = class {
1536
1913
  if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
1537
1914
  if (originalPushData) {
1538
1915
  await originalPushData.call(context, aiResult.data);
1916
+ noteRecords(aLabel, recordCount(aiResult.data));
1539
1917
  }
1540
1918
  try {
1541
1919
  if (!request.userData?.__fetchBrainCounted) {
@@ -1553,6 +1931,10 @@ var FetchBrain = class {
1553
1931
  logger.debug(`Run stats skipped: ${countErr}`);
1554
1932
  }
1555
1933
  await fireOnRecalled(aiResult.data);
1934
+ if (analyticsOn) {
1935
+ const fetchSkipped = request.skipNavigation === true;
1936
+ recordSuccess(context, fetchSkipped ? "skipped" : "recalled", void 0, recallMs);
1937
+ }
1556
1938
  return;
1557
1939
  }
1558
1940
  const counts = labelCounts(request.label);
@@ -1565,22 +1947,27 @@ var FetchBrain = class {
1565
1947
  logger.debug(`Learning${urlSuffix(shownUrl())}`);
1566
1948
  }
1567
1949
  const learnItems = [];
1568
- if (originalPushData && config.learning !== false) {
1950
+ if (originalPushData && (config.learning !== false || collector)) {
1569
1951
  context.pushData = async (data) => {
1570
- if (!usedAIData && (!aiResult.known || relearn)) {
1952
+ if (config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1571
1953
  learnItems.push(...Array.isArray(data) ? data : [data]);
1572
1954
  }
1573
- return originalPushData.call(context, data);
1955
+ const res = await originalPushData.call(context, data);
1956
+ noteRecords(aLabel, recordCount(data));
1957
+ return res;
1574
1958
  };
1575
1959
  }
1960
+ const flushFanOut = collector ? wrapFanOut(context, aLabel) : void 0;
1576
1961
  const requestContext = {
1577
1962
  request: rawRequest,
1578
1963
  client,
1579
1964
  learning: config.learning !== false,
1580
1965
  aiKnown: aiResult.known,
1581
1966
  relearn,
1582
- items: learnItems
1967
+ items: learnItems,
1968
+ ...collector ? { capture: captureFor(context, request, aLabel), records: (n) => noteRecords(aLabel, n) } : {}
1583
1969
  };
1970
+ const h0 = analyticsOn ? performance.now() : 0;
1584
1971
  try {
1585
1972
  await asyncContext.run(requestContext, async () => {
1586
1973
  await originalHandler.call(crawler, context);
@@ -1588,6 +1975,9 @@ var FetchBrain = class {
1588
1975
  } catch (handlerErr) {
1589
1976
  if (counts) counts.failed++;
1590
1977
  throw handlerErr;
1978
+ } finally {
1979
+ if (analyticsOn) handlerMs = msSince(h0);
1980
+ flushFanOut?.();
1591
1981
  }
1592
1982
  try {
1593
1983
  if (!request.userData?.__fetchBrainCounted) {
@@ -1609,75 +1999,16 @@ var FetchBrain = class {
1609
1999
  pendingLearns.add(pending);
1610
2000
  void pending.finally(() => pendingLearns.delete(pending));
1611
2001
  }
1612
- if (telemetryConfig.enabled) {
1613
- try {
1614
- const telemetry = await collectTelemetry(
1615
- {
1616
- request: {
1617
- url,
1618
- retryCount: request.retryCount,
1619
- label,
1620
- userData: request.userData
1621
- },
1622
- response: {
1623
- statusCode: context.response?.statusCode || context.response?.status
1624
- },
1625
- proxyInfo: context.proxyInfo ? {
1626
- url: context.proxyInfo.url,
1627
- hostname: context.proxyInfo.hostname,
1628
- countryCode: context.proxyInfo.countryCode
1629
- } : void 0,
1630
- session: context.session ? {
1631
- errorScore: context.session.errorScore,
1632
- usageCount: context.session.usageCount
1633
- } : void 0,
1634
- crawler: {
1635
- constructor: { name: crawlerType }
1636
- }
1637
- },
1638
- {
1639
- startTime,
1640
- endTime: Date.now(),
1641
- responseTime: Date.now() - startTime,
1642
- contentSize: context.response?.body?.length
1643
- },
1644
- telemetryConfig
1645
- );
1646
- if (telemetry) {
1647
- telemetryBuffer.add(telemetry);
1648
- }
1649
- } catch (err) {
1650
- logger.debug(`Telemetry collection error: ${err}`);
1651
- }
1652
- }
2002
+ if (analyticsOn) recordSuccess(context, "scraped", handlerMs, recallMs);
1653
2003
  } catch (err) {
1654
2004
  if (consumedStash) {
1655
2005
  stashSet(stashKey(rawRequest), consumedStash);
1656
2006
  }
1657
- if (telemetryConfig.enabled) {
2007
+ if (analyticsOn && collector) {
1658
2008
  try {
1659
- const telemetry = await collectTelemetry(
1660
- {
1661
- request: {
1662
- url,
1663
- retryCount: request.retryCount,
1664
- label
1665
- },
1666
- crawler: {
1667
- constructor: { name: crawlerType }
1668
- }
1669
- },
1670
- {
1671
- startTime,
1672
- endTime: Date.now(),
1673
- responseTime: Date.now() - startTime
1674
- },
1675
- telemetryConfig,
1676
- err instanceof Error ? err : new Error(String(err))
1677
- );
1678
- if (telemetry) {
1679
- telemetryBuffer.add(telemetry);
1680
- }
2009
+ const a = attemptOf(context);
2010
+ a.handlerMs = handlerMs;
2011
+ a.recallMs = recallMs;
1681
2012
  } catch {
1682
2013
  }
1683
2014
  }
@@ -1689,10 +2020,64 @@ var FetchBrain = class {
1689
2020
  const crawlerAny = crawler;
1690
2021
  crawlerAny[handlerKey] = wrappedHandler;
1691
2022
  logger.debug(`Wrapped ${handlerKey}`);
2023
+ if (analyticsOn) {
2024
+ const preNav = (ctx) => {
2025
+ if (!collector) return;
2026
+ try {
2027
+ attemptOf(ctx).navStart = performance.now();
2028
+ } catch {
2029
+ }
2030
+ };
2031
+ const postNav = (ctx) => {
2032
+ if (!collector) return;
2033
+ try {
2034
+ const a = attemptOf(ctx);
2035
+ if (a.navStart !== void 0) a.navMs = msSince(a.navStart);
2036
+ a.statusCode = statusFrom(ctx.response);
2037
+ a.bytes = headerBytes(ctx.response);
2038
+ } catch {
2039
+ }
2040
+ };
2041
+ if (Array.isArray(crawlerAny.preNavigationHooks)) {
2042
+ crawlerAny.preNavigationHooks = [...crawlerAny.preNavigationHooks, preNav];
2043
+ }
2044
+ if (Array.isArray(crawlerAny.postNavigationHooks)) {
2045
+ crawlerAny.postNavigationHooks = [postNav, ...crawlerAny.postNavigationHooks];
2046
+ }
2047
+ const userErrorHandler = crawlerAny.errorHandler;
2048
+ crawlerAny.errorHandler = function(...args) {
2049
+ const c = collector;
2050
+ if (c) {
2051
+ try {
2052
+ noteFailure(c, args[0], args[1]);
2053
+ } catch (analyticsErr) {
2054
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2055
+ }
2056
+ }
2057
+ return typeof userErrorHandler === "function" ? userErrorHandler.apply(this, args) : void 0;
2058
+ };
2059
+ const userFailedHandler = crawlerAny.failedRequestHandler;
2060
+ crawlerAny.failedRequestHandler = function(...args) {
2061
+ const c = collector;
2062
+ if (c) {
2063
+ try {
2064
+ const ctx = args[0];
2065
+ const { a, blockType } = noteFailure(c, ctx, args[1]);
2066
+ const req = ctx.request;
2067
+ c.error(analyticsLabel(req.label), args[1], contextFor(c, a, req));
2068
+ emitRequest(c, ctx, a, blockType ? "blocked" : "failed", blockType);
2069
+ } catch (analyticsErr) {
2070
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2071
+ }
2072
+ }
2073
+ return typeof userFailedHandler === "function" ? userFailedHandler.apply(this, args) : void 0;
2074
+ };
2075
+ }
1692
2076
  if (typeof crawlerAny.run === "function") {
1693
2077
  const originalRun = crawlerAny.run.bind(crawlerAny);
1694
2078
  crawlerAny.run = async (...args) => {
1695
2079
  runStats.startTime = Date.now();
2080
+ safeBeginRun(client);
1696
2081
  const runStartedAt = new Date(runStats.startTime).toISOString();
1697
2082
  labelStats.clear();
1698
2083
  const runBase = {
@@ -1708,94 +2093,190 @@ var FetchBrain = class {
1708
2093
  };
1709
2094
  const changeBase = safeChangeStats(client);
1710
2095
  const runId = nextRunId();
2096
+ let analyticsQueue;
2097
+ let reportClient;
2098
+ let reportAnalytics;
2099
+ if (analyticsOn) {
2100
+ try {
2101
+ const [mod, cfg] = await Promise.all([loadCollector(), fetchAnalyticsConfig(client)]);
2102
+ if (mod && cfg?.enabled !== false) {
2103
+ const analyticsRunId = runId;
2104
+ const scraper = client.getScraperName();
2105
+ const batchStartSeq = mod.startSeqFromEnv();
2106
+ analyticsQueue = new mod.AnalyticsQueue(
2107
+ (gz, signal) => client.postAnalyticsEvents(gz, analyticsRunId, signal),
2108
+ {
2109
+ wrap: (events, seq) => ({ runId: analyticsRunId, scraper, seq, events }),
2110
+ // Unique across Apify migrations: a restarted process must not reuse the earlier seqs.
2111
+ startSeq: batchStartSeq
2112
+ }
2113
+ );
2114
+ if (cfg) {
2115
+ if (Number.isFinite(cfg.sampleRate) && cfg.sampleRate > 0 && cfg.sampleRate <= 1) {
2116
+ analyticsQueue.sampleRate = cfg.sampleRate;
2117
+ }
2118
+ if (typeof cfg.pauseUntil === "number") analyticsQueue.pause(cfg.pauseUntil);
2119
+ }
2120
+ const apifyUserId = process.env.APIFY_USER_ID;
2121
+ const clientHash = apifyUserId && cfg?.salt ? mod.Collector.hashClient(apifyUserId, cfg.salt) : void 0;
2122
+ collector = new mod.Collector(
2123
+ analyticsQueue,
2124
+ {
2125
+ runId: analyticsRunId,
2126
+ scraper,
2127
+ ...clientHash ? { client: clientHash } : {},
2128
+ crawlerType,
2129
+ sdkVersion: mod.SDK_VERSION,
2130
+ platform: process.env.APIFY_IS_AT_HOME || process.env.APIFY_ACTOR_ID ? "apify" : "other"
2131
+ },
2132
+ {
2133
+ debug: (msg) => logger.debug(msg),
2134
+ // Event seqs after a migration start above the earlier process's (batch seq
2135
+ // is whole seconds x 1000, so x 1000 again leaves 1e6 events per second of run).
2136
+ startSeq: batchStartSeq * 1e3
2137
+ }
2138
+ );
2139
+ reportClient = clientHash;
2140
+ const quotaSeen = /* @__PURE__ */ new Set();
2141
+ safeOnQuotaReached(client, (cap) => {
2142
+ if (quotaSeen.has(cap)) return;
2143
+ quotaSeen.add(cap);
2144
+ collector?.quotaReached(cap);
2145
+ });
2146
+ blockedByRequest.clear();
2147
+ emittedThenFailed.clear();
2148
+ const memoryMb = Number(process.env.APIFY_MEMORY_MBYTES);
2149
+ const maxConcurrency = crawlerAny.autoscaledPoolOptions?.maxConcurrency;
2150
+ collector.runStarted({
2151
+ memoryMb: Number.isFinite(memoryMb) && memoryMb > 0 ? memoryMb : void 0,
2152
+ maxConcurrency: typeof maxConcurrency === "number" ? maxConcurrency : void 0
2153
+ });
2154
+ analyticsQueue.start();
2155
+ }
2156
+ } catch (analyticsErr) {
2157
+ collector = void 0;
2158
+ analyticsQueue = void 0;
2159
+ reportClient = void 0;
2160
+ safeOnQuotaReached(client, void 0);
2161
+ logger.debug(`Analytics off for this run: ${analyticsErr}`);
2162
+ }
2163
+ }
1711
2164
  try {
1712
2165
  const result = await originalRun(...args);
1713
2166
  return result;
1714
2167
  } finally {
1715
- logger.debug("Flushing pending learn requests on crawl complete");
1716
- await client.flushLearnBatch();
1717
- await Promise.allSettled([...pendingLearns]);
1718
- if (telemetryConfig.enabled) {
1719
- logger.debug("Telemetry: flushing on crawl complete");
1720
- await telemetryBuffer.stop();
2168
+ let analyticsStop;
2169
+ if (analyticsQueue) {
2170
+ try {
2171
+ collector?.runFinished({ durationMs: Date.now() - runStats.startTime });
2172
+ if (collector) reportAnalytics = { labels: collector.labelStats(), ...collector.aggregateReport() };
2173
+ } catch (analyticsErr) {
2174
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2175
+ }
2176
+ analyticsStop = analyticsQueue.stop().catch((analyticsErr) => {
2177
+ logger.debug(`Analytics flush skipped: ${analyticsErr}`);
2178
+ });
2179
+ collector = void 0;
1721
2180
  }
1722
- const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1723
- 1
1724
- );
1725
- const run = {
1726
- totalRequests: runStats.totalRequests - runBase.totalRequests,
1727
- bypassed: runStats.bypassed - runBase.bypassed,
1728
- dropped: runStats.dropped - runBase.dropped,
1729
- scraped: runStats.scraped - runBase.scraped,
1730
- learned: runStats.learned - runBase.learned,
1731
- recalled: runStats.recalled - runBase.recalled,
1732
- aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
1733
- requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
1734
- lateRecalls: runStats.lateRecalls - runBase.lateRecalls
1735
- };
1736
- const managedRequests = run.totalRequests - run.bypassed;
1737
- const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1738
- let changes = { changed: 0, drift: [] };
1739
2181
  try {
1740
- const now = safeChangeStats(client);
1741
- const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
1742
- const seen = new Set(changeBase.drift.map(key));
1743
- changes = {
1744
- changed: Math.max(0, now.changed - changeBase.changed) || 0,
1745
- drift: now.drift.filter((d) => !seen.has(key(d)))
1746
- };
1747
- } catch (diffErr) {
1748
- logger.debug(`Change summary skipped: ${diffErr}`);
1749
- }
1750
- const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1751
- logger.info(
1752
- `\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`
1753
- );
1754
- if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
1755
- logger.info(
1756
- `${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).`
2182
+ safeOnQuotaReached(client, void 0);
2183
+ logger.debug("Flushing pending learn requests on crawl complete");
2184
+ await client.flushLearnBatch();
2185
+ await Promise.allSettled([...pendingLearns]);
2186
+ const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
2187
+ 1
1757
2188
  );
1758
- }
1759
- for (const item of changes.drift) {
2189
+ const run = {
2190
+ totalRequests: runStats.totalRequests - runBase.totalRequests,
2191
+ bypassed: runStats.bypassed - runBase.bypassed,
2192
+ dropped: runStats.dropped - runBase.dropped,
2193
+ scraped: runStats.scraped - runBase.scraped,
2194
+ learned: runStats.learned - runBase.learned,
2195
+ recalled: runStats.recalled - runBase.recalled,
2196
+ aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
2197
+ requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
2198
+ lateRecalls: runStats.lateRecalls - runBase.lateRecalls
2199
+ };
2200
+ const managedRequests = run.totalRequests - run.bypassed;
2201
+ const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
2202
+ let changes = { changed: 0, drift: [], known: 0 };
1760
2203
  try {
1761
- logger.warn(describeDrift(item));
1762
- } catch (warnErr) {
1763
- logger.debug(`Drift warning skipped: ${warnErr}`);
2204
+ const now = safeChangeStats(client);
2205
+ const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
2206
+ const seen = new Set(changeBase.drift.map(key));
2207
+ changes = {
2208
+ changed: Math.max(0, now.changed - changeBase.changed) || 0,
2209
+ drift: now.drift.filter((d) => !seen.has(key(d))),
2210
+ known: Math.max(0, (now.known ?? 0) - (changeBase.known ?? 0)) || 0
2211
+ };
2212
+ } catch (diffErr) {
2213
+ logger.debug(`Change summary skipped: ${diffErr}`);
1764
2214
  }
1765
- }
1766
- if (config.reportRuns !== false) {
1767
- try {
1768
- const labels = Object.fromEntries(labelStats);
1769
- const flags = await client.reportRun({
1770
- runId,
1771
- build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1772
- startedAt: runStartedAt,
1773
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1774
- scraped: run.scraped,
1775
- learned: run.learned,
1776
- recalled: run.recalled,
1777
- requestsSkipped: run.requestsSkipped,
1778
- lateRecalls: run.lateRecalls,
1779
- bypassed: run.bypassed,
1780
- labels
1781
- });
1782
- for (const flag of Array.isArray(flags) ? flags : []) {
1783
- if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
1784
- continue;
1785
- }
1786
- const label = clipText(flag.label, 64);
1787
- logger.warn(
1788
- flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
2215
+ const showChanged = observe || config.changeDetection?.enabled === true || changes.changed > 0;
2216
+ if (observe) {
2217
+ logger.info(
2218
+ `\u{1F440} Observe run finished: learned: ${run.learned}, scraped: ${run.scraped}, changed: ${changes.changed}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + `, duration: ${duration}s`
2219
+ );
2220
+ if (changes.known > 0) {
2221
+ logger.info(
2222
+ `${changes.known} ${changes.known === 1 ? "page was" : "pages were"} already known \u2014 recall (the default) would have skipped ${changes.known === 1 ? "that fetch" : "those fetches"}.`
1789
2223
  );
1790
2224
  }
1791
- } catch (reportErr) {
1792
- logger.debug(`Run report skipped: ${reportErr}`);
2225
+ } else logger.info(
2226
+ `\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} ` + (safeQuotaState(client) === "recall_cap" ? "(monthly recall limit reached)" : `(${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`
2227
+ );
2228
+ if (!observe && run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
2229
+ logger.info(
2230
+ `${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).`
2231
+ );
2232
+ }
2233
+ for (const item of changes.drift) {
2234
+ try {
2235
+ logger.warn(describeDrift(item));
2236
+ } catch (warnErr) {
2237
+ logger.debug(`Drift warning skipped: ${warnErr}`);
2238
+ }
2239
+ }
2240
+ if (config.reportRuns !== false) {
2241
+ try {
2242
+ const labels = Object.fromEntries(labelStats);
2243
+ const flags = await client.reportRun({
2244
+ runId,
2245
+ build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
2246
+ startedAt: runStartedAt,
2247
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2248
+ scraped: run.scraped,
2249
+ learned: run.learned,
2250
+ recalled: run.recalled,
2251
+ requestsSkipped: run.requestsSkipped,
2252
+ // recall:false: pages memory already knew were fetched anyway —
2253
+ // the same untapped savings late recalls report.
2254
+ lateRecalls: observe ? changes.known : run.lateRecalls,
2255
+ bypassed: run.bypassed,
2256
+ labels,
2257
+ ...reportClient ? { client: reportClient } : {},
2258
+ ...reportAnalytics ? { analytics: reportAnalytics } : {}
2259
+ });
2260
+ for (const flag of Array.isArray(flags) ? flags : []) {
2261
+ if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
2262
+ continue;
2263
+ }
2264
+ const label = clipText(flag.label, 64);
2265
+ logger.warn(
2266
+ flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
2267
+ );
2268
+ }
2269
+ } catch (reportErr) {
2270
+ logger.debug(`Run report skipped: ${reportErr}`);
2271
+ }
1793
2272
  }
2273
+ } finally {
2274
+ await analyticsStop;
1794
2275
  }
1795
2276
  }
1796
2277
  };
1797
2278
  }
1798
- if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
2279
+ if (!observe && config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
1799
2280
  const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
1800
2281
  if (crawlerAny.retryOnBlocked) {
1801
2282
  logger.info(
@@ -1924,8 +2405,18 @@ async function pushData(data, dataset, datasetName) {
1924
2405
  } else {
1925
2406
  await dataset.pushData(data);
1926
2407
  }
2408
+ try {
2409
+ ctx?.records?.(Array.isArray(data) ? data.length : 1);
2410
+ } catch {
2411
+ }
2412
+ }
2413
+ function capture(name, props) {
2414
+ try {
2415
+ asyncContext.getStore()?.capture?.(name, props);
2416
+ } catch {
2417
+ }
1927
2418
  }
1928
2419
 
1929
- export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
2420
+ export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, capture, createFetchBrain, createLogger, getCurrentContext, pushData };
1930
2421
  //# sourceMappingURL=index.mjs.map
1931
2422
  //# sourceMappingURL=index.mjs.map