@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/README.md CHANGED
@@ -261,6 +261,8 @@ interface FetchBrainConfig {
261
261
  successThreshold?: number; // Successes to close it again (default: 1)
262
262
  };
263
263
  telemetry?: TelemetryConfig; // Opt-in telemetry (default: { enabled: false })
264
+ changeDetection?: { enabled?: boolean; ignoreFields?: string[] }; // Relearn known alwaysRun pages and report changes (default: off)
265
+ reportRuns?: boolean; // Send the end-of-run report: run id, timestamps, counts per label (default: true)
264
266
  learnUrlField?: string; // Accepted but not currently applied
265
267
  debug?: boolean; // Enable debug logging (default: false)
266
268
  }
@@ -524,9 +526,105 @@ exception is [expired memory](#recall-at-enqueue-time-prerecall): a request
524
526
  that skipped its fetch at enqueue and whose remembered data is gone fails
525
527
  into your `failedRequestHandler` rather than disappearing silently.
526
528
 
529
+ ## Change detection & drift
530
+
531
+ FetchBrain can tell you when the pages you scrape change, and when your own
532
+ scraper quietly stops extracting something.
533
+
534
+ **What is detected**
535
+
536
+ - **Changed pages**: a page you re-scrape whose data differs from what the
537
+ brain last learned. Each run summary shows a `changed: N` count.
538
+ - **Drift**: a field that used to be filled on most pages of a label and now
539
+ isn't (for example `price` going from 95% filled to 0%), a field that went
540
+ missing, or a field whose type changed. Each finding prints a warning at the
541
+ end of the run, such as `drift [DETAIL] price: filled 95% → 0%`. The same warning (label, field and kind) is shown once per process even if it recurs in a later `run()`; the email and dashboard still reflect it.
542
+ - **Unhealthy runs**: a large share of a label's pages pushed no data or
543
+ failed, such as `40% of DETAIL pages pushed no data`.
544
+
545
+ **Turn on change detection**
546
+
547
+ Pages the brain already knows are normally recalled, not re-scraped. Change
548
+ detection applies to known pages you choose to re-scrape with
549
+ [`alwaysRun`](#choosing-which-handlers-run): with it on, their fresh data is
550
+ learned again and compared with the previous version.
551
+
552
+ ```ts
553
+ FetchBrain.enhance(crawler, {
554
+ apiKey: process.env.FETCHBRAIN_API_KEY,
555
+ alwaysRun: ["DETAIL"],
556
+ changeDetection: {
557
+ enabled: true,
558
+ ignoreFields: ["scrapedAt", "sessionId"], // fields that always differ; not compared
559
+ },
560
+ });
561
+ ```
562
+
563
+ | Option | Default | Meaning |
564
+ | --- | --- | --- |
565
+ | `changeDetection.enabled` | `false` | Relearn known `alwaysRun` pages so changes can be detected |
566
+ | `changeDetection.ignoreFields` | none | Field names to leave out of the comparison |
567
+
568
+ **Cost note:** relearning a known `alwaysRun` page counts toward your learn
569
+ usage, like any other learn. Pages recalled without running your handler are
570
+ never relearned.
571
+
572
+ **Run report**
573
+
574
+ <a id="run-report"></a>
575
+
576
+ When a run finishes, the SDK sends a small report containing exactly: the run
577
+ id, start and end timestamps, totals for scraped, learned and recalled pages,
578
+ requests skipped, late recalls and bypassed pages, per request label how many
579
+ pages were scraped, came back empty or failed, and your build id only when
580
+ `refreshOnRebuild` is on. It contains no URLs and no scraped data.
581
+
582
+ | Field | Meaning |
583
+ | --- | --- |
584
+ | `scraped` | pages whose handler ran to completion (unknown pages, and known pages matched by `alwaysRun`) |
585
+ | `learned` | records the brain accepted from this run |
586
+ | `recalled` | known pages served from memory, whether or not their handler also ran |
587
+ | `requestsSkipped` | known pages served from memory **without a fetch**: pre-recalled when they were enqueued, so Crawlee never requested them |
588
+ | `lateRecalls` | known pages served from memory **after** they were fetched: the recall happened in your handler, so the request was already spent |
589
+ | `bypassed` | pages handled outside FetchBrain because of `skipLabels` |
590
+
591
+ Every count covers one `run()` call. A request is counted once, after it
592
+ succeeded (its handler finished, or its recalled data was pushed), so a retry
593
+ never counts it twice and a request that finally fails is not counted. The
594
+ per-label counts are the exception: they count every attempt, so failure and
595
+ empty rates see each retry. Each `run()` call gets its own run id: on a platform that sets
596
+ a run id, the first call uses it as-is and later calls in the same process
597
+ (another `run()`, or a second crawler) add `-2`, `-3` and so on.
598
+
599
+ Requests skipped is what saves you requests. Late recalls are pages that came
600
+ from the queue without a [pre-recall](#recall-at-enqueue-time-prerecall):
601
+ links from `enqueueLinks()` or the context `addRequests()`, and every known page
602
+ on a `retryOnBlocked` crawler, plus non-GET requests without an explicit
603
+ `uniqueKey` (pre-recall can't identify them at enqueue time; set one to let it).
604
+ Known requests you marked `skipNavigation` yourself count only as `recalled`,
605
+ never as late recalls: they were never fetched.
606
+ When a run has late recalls, the summary line is followed by a tip such as:
607
+
608
+ ```
609
+ 3 pages were recalled after they were fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).
610
+ ```
611
+
612
+ The tip is not shown on `retryOnBlocked` crawlers (their blocked-check needs
613
+ the fetch, so those pages can't skip it) or when `preRecall` is `false`. A page counts as "pushed no data" when your handler pushed nothing
614
+ through `context.pushData` or the SDK's `pushData` export (pages written
615
+ straight to Crawlee's static `Dataset.pushData` are counted that way too), and
616
+ retries count once per attempt. The report is sent with the same standard
617
+ headers as every other call (see [What leaves your process](#what-leaves-your-process)). It is what powers the unhealthy-run warnings above. It is not
618
+ [telemetry](#telemetry-opt-in) and is on by default; set `reportRuns: false` to
619
+ turn it off. It is bounded to a few seconds at the end of a run and can never
620
+ fail your crawl.
621
+
622
+ You can browse what changed in the FetchBrain dashboard, or fetch it from
623
+ `GET /v1/changes`.
624
+
527
625
  ## What leaves your process
528
626
 
529
- Every API call (recall, learn, ask, stats, telemetry) sends these headers:
627
+ Every API call (recall, learn, ask, stats, telemetry, run report) sends these headers:
530
628
 
531
629
  | Header | Value |
532
630
  | --- | --- |
@@ -556,7 +654,7 @@ query string), method, `uniqueKey`, label, string POST body, your
556
654
  `Authorization`, `Cookie` and `Set-Cookie`. Recall also sends your `memory`
557
655
  depth; learn also sends the record you pushed (after `extractForLearning`).
558
656
 
559
- With `refreshOnRebuild`, recall, learn and `ask()` also send a build ID: the
657
+ With `refreshOnRebuild`, recall, learn, the run report and `ask()` also send a build ID: the
560
658
  value of the first environment variable whose name ends in `BUILD_ID`. This
561
659
  value is sent as-is — it does **not** go through the name, credential or
562
660
  length filters `X-FB-Context` uses.
@@ -567,7 +665,10 @@ forwarded as-is — keep secrets out of them on requests FetchBrain handles,
567
665
  or route those requests through `skipLabels`, which sends nothing for them.
568
666
 
569
667
  `ask()` sends your question and options. Telemetry sends nothing unless you
570
- [opt in](#telemetry-opt-in).
668
+ [opt in](#telemetry-opt-in). At the end of a run the SDK also sends a small
669
+ [run report](#run-report): run id, start/end timestamps, scraped/learned/recalled
670
+ counts, requests skipped, late recalls and bypassed counts, per-label page counts, and a build id only with `refreshOnRebuild`
671
+ (`reportRuns: false` turns it off).
571
672
 
572
673
  ## Telemetry (opt-in)
573
674
 
@@ -587,6 +688,16 @@ so they're linked to your account. They're used to improve FetchBrain's
587
688
  recommendations (proxy recommendations, block detection, configuration
588
689
  tuning); aggregated statistics may inform recommendations for other users.
589
690
 
691
+ **How long it's kept:** raw entries are deleted about 30 days after they're
692
+ received (a daily cleanup), and all of your entries are deleted when you
693
+ delete your account (a very large history may take the daily cleanup a few
694
+ days to finish, never longer than the 30 days above).
695
+ Per-domain aggregate counts (requests, successes, blocks and block rate for a
696
+ hostname, with no URLs and no account link) are kept. Per-domain statistics
697
+ are aggregated per domain, not per account: entries from every account that
698
+ scraped a hostname add to the same counts, and they are not deleted with your
699
+ account.
700
+
590
701
  **When it's collected:** one entry per request FetchBrain handles
591
702
  (`skipLabels` requests are excluded), after your handler finishes — or
592
703
  whenever the request fails inside the SDK's wrapper, including failures
package/dist/index.d.mts CHANGED
@@ -1,14 +1,6 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, c as TelemetryConfig, d as CircuitBreakerConfig, e as Logger, B as BatchConfig, f as LogLevel } from './types-CSG4BekA.mjs';
2
- export { j as LearnRequest, M as MemoryDepth, g as RecallRequest, h as RecallResponse, i as RecallResultItem, k as RecalledEvent, l as TelemetryRequest, m as TelemetryResponse } from './types-CSG4BekA.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-CPyPUGeb.mjs';
2
+ export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-CPyPUGeb.mjs';
3
3
 
4
- /**
5
- * FetchBrain API Client
6
- *
7
- * Handles all communication with the FetchBrain API including:
8
- * - Request batching for high concurrency
9
- * - Circuit breaker for graceful degradation
10
- * - Automatic retries and timeouts
11
- */
12
4
  declare class FetchBrainClient {
13
5
  private config;
14
6
  private circuitBreaker;
@@ -34,6 +26,8 @@ declare class FetchBrainClient {
34
26
  private learnCapWarnedUntil;
35
27
  /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
36
28
  private scraperName;
29
+ /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
30
+ private changeStats;
37
31
  constructor(config: FetchBrainConfig);
38
32
  /** True when recalls must not reach the API right now (crawl continues without). */
39
33
  private recallBlocked;
@@ -87,6 +81,15 @@ declare class FetchBrainClient {
87
81
  * Execute a batch learn against the API
88
82
  */
89
83
  private executeBatchLearn;
84
+ /** Fold one batch response into the change totals (called once per HTTP batch). */
85
+ private accumulateChanges;
86
+ /** Change counts so far (a copy). */
87
+ getChangeStats(): ChangeStats;
88
+ /**
89
+ * Send the end-of-run report. Counts and labels only. Never throws: on
90
+ * failure or timeout it returns no flags.
91
+ */
92
+ reportRun(report: RunReport, timeoutMs?: number): Promise<RunFlag[]>;
90
93
  /**
91
94
  * Make an HTTP request to the API
92
95
  */
@@ -144,6 +147,8 @@ interface RequestContext {
144
147
  client: FetchBrainClient;
145
148
  learning: boolean;
146
149
  aiKnown: boolean;
150
+ /** Known page re-scraped with change detection on: its items are relearned. */
151
+ relearn: boolean;
147
152
  /** Items this request pushed; learned together once the handler succeeds. */
148
153
  items: Record<string, unknown>[];
149
154
  }
@@ -417,4 +422,4 @@ declare class TelemetryBuffer {
417
422
  stop(): Promise<void>;
418
423
  }
419
424
 
420
- export { AskResponse, BatchConfig, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
425
+ export { AskResponse, BatchConfig, ChangeStats, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, RunFlag, RunReport, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
package/dist/index.d.ts CHANGED
@@ -1,14 +1,6 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, c as TelemetryConfig, d as CircuitBreakerConfig, e as Logger, B as BatchConfig, f as LogLevel } from './types-CSG4BekA.js';
2
- export { j as LearnRequest, M as MemoryDepth, g as RecallRequest, h as RecallResponse, i as RecallResultItem, k as RecalledEvent, l as TelemetryRequest, m as TelemetryResponse } from './types-CSG4BekA.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-CPyPUGeb.js';
2
+ export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-CPyPUGeb.js';
3
3
 
4
- /**
5
- * FetchBrain API Client
6
- *
7
- * Handles all communication with the FetchBrain API including:
8
- * - Request batching for high concurrency
9
- * - Circuit breaker for graceful degradation
10
- * - Automatic retries and timeouts
11
- */
12
4
  declare class FetchBrainClient {
13
5
  private config;
14
6
  private circuitBreaker;
@@ -34,6 +26,8 @@ declare class FetchBrainClient {
34
26
  private learnCapWarnedUntil;
35
27
  /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
36
28
  private scraperName;
29
+ /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
30
+ private changeStats;
37
31
  constructor(config: FetchBrainConfig);
38
32
  /** True when recalls must not reach the API right now (crawl continues without). */
39
33
  private recallBlocked;
@@ -87,6 +81,15 @@ declare class FetchBrainClient {
87
81
  * Execute a batch learn against the API
88
82
  */
89
83
  private executeBatchLearn;
84
+ /** Fold one batch response into the change totals (called once per HTTP batch). */
85
+ private accumulateChanges;
86
+ /** Change counts so far (a copy). */
87
+ getChangeStats(): ChangeStats;
88
+ /**
89
+ * Send the end-of-run report. Counts and labels only. Never throws: on
90
+ * failure or timeout it returns no flags.
91
+ */
92
+ reportRun(report: RunReport, timeoutMs?: number): Promise<RunFlag[]>;
90
93
  /**
91
94
  * Make an HTTP request to the API
92
95
  */
@@ -144,6 +147,8 @@ interface RequestContext {
144
147
  client: FetchBrainClient;
145
148
  learning: boolean;
146
149
  aiKnown: boolean;
150
+ /** Known page re-scraped with change detection on: its items are relearned. */
151
+ relearn: boolean;
147
152
  /** Items this request pushed; learned together once the handler succeeds. */
148
153
  items: Record<string, unknown>[];
149
154
  }
@@ -417,4 +422,4 @@ declare class TelemetryBuffer {
417
422
  stop(): Promise<void>;
418
423
  }
419
424
 
420
- export { AskResponse, BatchConfig, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
425
+ export { AskResponse, BatchConfig, ChangeStats, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, RunFlag, RunReport, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };