@fetchbrain.com/sdk 0.5.1 → 0.6.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
@@ -171,8 +171,8 @@ Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES
171
171
 
172
172
  Memory is always private to your account. Within it, scoping depends on
173
173
  where the scraper runs ([details](#do-my-scrapers-share-memory)): on Apify
174
- each actor has its own memory; everywhere else, all scrapers under one API
175
- key share one memory.
174
+ each actor has its own memory; everywhere else, scrapers share one default
175
+ memory unless you [name them](#name-your-scraper-scraper).
176
176
 
177
177
  ### Memory depth
178
178
 
@@ -243,6 +243,7 @@ interface FetchBrainConfig {
243
243
  apiKey: string;
244
244
 
245
245
  // Optional
246
+ scraper?: string; // Name this scraper so it gets its own memory (or set FETCHBRAIN_SCRAPER_ID)
246
247
  baseUrl?: string; // API URL (default: https://api.fetchbrain.com)
247
248
  memory?: MemoryDepth; // How far back the brain recalls (default: "recent")
248
249
  learning?: boolean; // Teach the brain from scraped data (default: true)
@@ -265,6 +266,33 @@ interface FetchBrainConfig {
265
266
  }
266
267
  ```
267
268
 
269
+ ### Name your scraper (`scraper`)
270
+
271
+ Memory is private to your account. Outside Apify, every scraper on the
272
+ account shares one default memory unless you name it:
273
+
274
+ ```typescript
275
+ FetchBrain.enhance(crawler, { apiKey, scraper: "shop-a" });
276
+ // or, with no code change: FETCHBRAIN_SCRAPER_ID=shop-a node crawl.js
277
+ ```
278
+
279
+ - A named scraper learns and recalls only its own memory, so `shop-a` and
280
+ `shop-b` never see each other's pages.
281
+ - Names use lowercase letters, digits, `.`, `_` and `-`, up to 64 characters,
282
+ and must start with a letter or digit. Uppercase is lowercased. An invalid
283
+ name is ignored with a warning: an invalid `scraper` option falls back to
284
+ `FETCHBRAIN_SCRAPER_ID` if that is valid, otherwise the scraper keeps using
285
+ the default memory.
286
+ - A new name starts empty. What you learned before naming stays in the default
287
+ memory, which unnamed scrapers keep using.
288
+ - On Apify, memory is already per actor. Setting a name there replaces the
289
+ actor id, so that actor's existing memory goes cold.
290
+ - A valid `scraper` option wins over the environment variable; an empty one
291
+ doesn't hide it. SDK 0.3.0 and later
292
+ also forward `FETCHBRAIN_SCRAPER_ID`, but before this release only on a
293
+ best-effort basis: many other `*_ID` variables can push it out of the
294
+ header. Upgrade to guarantee delivery.
295
+
268
296
  ### Recall at enqueue time (`preRecall`)
269
297
 
270
298
  In `HttpCrawler`/`CheerioCrawler`, Crawlee performs the HTTP request *before*
@@ -493,7 +521,8 @@ Every API call (recall, learn, ask, stats, telemetry) sends these headers:
493
521
  | `X-FB-Label` | the request's Crawlee label, while a request is being handled |
494
522
 
495
523
  `X-FB-Context` carries your platform identifiers; the API uses
496
- `APIFY_ACTOR_ID` from it to scope memory per Apify actor (other `*_ID`
524
+ `FETCHBRAIN_SCRAPER_ID` (your scraper name, sent first) and otherwise
525
+ `APIFY_ACTOR_ID` from it to scope memory per scraper (other `*_ID`
497
526
  variables do not affect scoping) and `*BUILD_ID` for `refreshOnRebuild`. It includes
498
527
  every environment variable whose name ends in `_ID`, plus `NODE_ENV`,
499
528
  `REGION` and `CI`, except names containing `TOKEN`, `SECRET`, `PASSWORD`,
@@ -632,8 +661,10 @@ simulate the learning limit). It isn't included in the npm package.
632
661
  It depends on where they run. Memory is always private to your account.
633
662
  - **On Apify**, each actor (`APIFY_ACTOR_ID`) has its own memory: recall and
634
663
  SDK `ask()` calls from inside an actor only see what that actor learned.
635
- - **Everywhere else**, all scrapers using the same API key share one memory —
636
- scraper A can recall what scraper B learned.
664
+ - **Everywhere else**, scrapers share one default memory, so scraper A can
665
+ recall what scraper B learned, unless you name them with `scraper` /
666
+ `FETCHBRAIN_SCRAPER_ID` (see [Name your scraper](#name-your-scraper-scraper)).
667
+ - **A named scraper** (anywhere, including Apify) only sees its own memory.
637
668
  - **Ask Your Brain in the dashboard** (and `ask()` calls with no platform
638
669
  context) answers across everything your account has indexed.
639
670
 
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BMwfPE5J.mjs';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BMwfPE5J.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-B1MFygnZ.mjs';
2
+ export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-B1MFygnZ.mjs';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -22,6 +22,8 @@ declare class FetchBrainClient {
22
22
  private learnPausedUntil;
23
23
  /** Warn about the learn cap once per pause, independent of the pause state. */
24
24
  private learnCapWarnedUntil;
25
+ /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
26
+ private scraperName;
25
27
  constructor(config: FetchBrainConfig);
26
28
  /**
27
29
  * Recall if FetchBrain "knows" a request
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-BMwfPE5J.js';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-BMwfPE5J.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-B1MFygnZ.js';
2
+ export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-B1MFygnZ.js';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -22,6 +22,8 @@ declare class FetchBrainClient {
22
22
  private learnPausedUntil;
23
23
  /** Warn about the learn cap once per pause, independent of the pause state. */
24
24
  private learnCapWarnedUntil;
25
+ /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
26
+ private scraperName;
25
27
  constructor(config: FetchBrainConfig);
26
28
  /**
27
29
  * Recall if FetchBrain "knows" a request
package/dist/index.js CHANGED
@@ -323,16 +323,38 @@ var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
323
323
  var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
324
324
  var MAX_VALUE_LENGTH = 256;
325
325
  var MAX_HEADER_LENGTH = 2048;
326
- function buildNativeContext(env = process.env) {
326
+ var SCRAPER_NAME_VAR = "FETCHBRAIN_SCRAPER_ID";
327
+ var SCRAPER_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
328
+ function normalizeScraperName(raw) {
329
+ const name = raw?.trim().toLowerCase();
330
+ return name && SCRAPER_NAME.test(name) ? name : void 0;
331
+ }
332
+ function resolveScraperName(option, env = process.env) {
333
+ const rejected = [];
334
+ const candidates = [
335
+ ["option", option],
336
+ [SCRAPER_NAME_VAR, env[SCRAPER_NAME_VAR]]
337
+ ];
338
+ for (const [source, raw] of candidates) {
339
+ if (raw === void 0 || raw.trim() === "") continue;
340
+ const name = normalizeScraperName(raw);
341
+ if (name) return { name, rejected };
342
+ rejected.push(source);
343
+ }
344
+ return { rejected };
345
+ }
346
+ function buildNativeContext(env = process.env, scraper) {
327
347
  const context = {};
328
- const names = Object.keys(env).filter((name) => ALLOWED_NAME.test(name) && !DENYLIST.test(name)).sort();
329
- for (const name of names) {
330
- const value = env[name];
348
+ const name = normalizeScraperName(scraper);
349
+ if (name) context[SCRAPER_NAME_VAR] = name;
350
+ const names = Object.keys(env).filter((n) => n !== SCRAPER_NAME_VAR && ALLOWED_NAME.test(n) && !DENYLIST.test(n)).sort();
351
+ for (const varName of names) {
352
+ const value = env[varName];
331
353
  if (!value || value.length > MAX_VALUE_LENGTH) continue;
332
354
  if (CREDENTIAL_VALUE.test(value)) continue;
333
- const candidate = { ...context, [name]: value };
355
+ const candidate = { ...context, [varName]: value };
334
356
  if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
335
- context[name] = value;
357
+ context[varName] = value;
336
358
  }
337
359
  if (Object.keys(context).length === 0) return void 0;
338
360
  return JSON.stringify(context);
@@ -408,10 +430,18 @@ var FetchBrainClient = class {
408
430
  // enhance-only; stored so getConfig() round-trips
409
431
  preRecall: config.preRecall,
410
432
  // enhance-only; stored so getConfig() round-trips
411
- onRecalled: config.onRecalled
433
+ onRecalled: config.onRecalled,
412
434
  // enhance-only; stored so getConfig() round-trips
435
+ scraper: config.scraper
413
436
  };
414
437
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
438
+ const scraper = resolveScraperName(config.scraper);
439
+ this.scraperName = scraper.name;
440
+ for (const source of scraper.rejected) {
441
+ this.logger.warn(
442
+ `ignoring invalid scraper name from ${source === "option" ? "the scraper option" : source}; use 1-64 lowercase letters, digits, '.', '_' or '-', starting with a letter or digit. ` + (scraper.name ? `Using "${scraper.name}" instead.` : "This scraper uses the shared default memory.")
443
+ );
444
+ }
415
445
  this.circuitBreaker = new CircuitBreaker(
416
446
  this.config.circuitBreaker,
417
447
  this.logger
@@ -661,7 +691,7 @@ var FetchBrainClient = class {
661
691
  if (process.env.NODE_ENV) {
662
692
  contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
663
693
  }
664
- const nativeContext = buildNativeContext();
694
+ const nativeContext = buildNativeContext(process.env, this.scraperName);
665
695
  if (nativeContext) {
666
696
  contextHeaders["X-FB-Context"] = nativeContext;
667
697
  }