@crawlee/cli 4.0.0-beta.321 → 4.0.0-beta.323

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.
@@ -0,0 +1,19 @@
1
+ import type { ArgumentsCamelCase, Argv, CommandModule } from 'yargs';
2
+ interface UpgradeArgs {
3
+ from?: number;
4
+ to?: number;
5
+ export?: string;
6
+ }
7
+ export declare class UpgradeCommand<T> implements CommandModule<T, UpgradeArgs> {
8
+ command: string;
9
+ describe: string;
10
+ builder: (args: Argv<T>) => Argv<T & {
11
+ from: number | undefined;
12
+ } & {
13
+ to: number | undefined;
14
+ } & {
15
+ export: string | undefined;
16
+ }>;
17
+ handler(args: ArgumentsCamelCase<UpgradeArgs>): Promise<void>;
18
+ }
19
+ export {};
@@ -0,0 +1,150 @@
1
+ import { cp, readFile, readdir } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import semver from 'semver';
6
+ const runtimePackages = new Set([
7
+ 'crawlee',
8
+ ...[
9
+ 'basic',
10
+ 'browser',
11
+ 'browser-pool',
12
+ 'cheerio',
13
+ 'core',
14
+ 'fs-storage',
15
+ 'http',
16
+ 'http-client',
17
+ 'impit-client',
18
+ 'got-scraping-client',
19
+ 'playwright',
20
+ 'puppeteer',
21
+ 'stagehand',
22
+ 'types',
23
+ 'utils',
24
+ 'otel',
25
+ ].map((name) => `@crawlee/${name}`),
26
+ ]);
27
+ async function detectProjectMajor() {
28
+ let directory = process.cwd();
29
+ let manifestPath;
30
+ let manifest;
31
+ while (true) {
32
+ manifestPath = join(directory, 'package.json');
33
+ try {
34
+ manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
35
+ break;
36
+ }
37
+ catch (error) {
38
+ if (error.code !== 'ENOENT')
39
+ throw error;
40
+ const parent = dirname(directory);
41
+ if (parent === directory) {
42
+ throw new Error('No project package.json found. Run inside the project or specify --from <major>.');
43
+ }
44
+ directory = parent;
45
+ }
46
+ }
47
+ const require = createRequire(manifestPath);
48
+ const majors = new Set();
49
+ for (const section of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
50
+ for (const [name, specifier] of Object.entries(manifest[section] ?? {})) {
51
+ if (!runtimePackages.has(name))
52
+ continue;
53
+ const range = typeof specifier === 'string' ? semver.validRange(specifier.replace(/^workspace:/, '')) : null;
54
+ let installedVersion = null;
55
+ try {
56
+ const installed = JSON.parse(await readFile(require.resolve(`${name}/package.json`), 'utf8'));
57
+ installedVersion = semver.valid(installed.version);
58
+ }
59
+ catch (error) {
60
+ if (!['MODULE_NOT_FOUND', 'ERR_PACKAGE_PATH_NOT_EXPORTED', 'ENOENT'].includes(error.code ?? '')) {
61
+ throw error;
62
+ }
63
+ }
64
+ if (installedVersion &&
65
+ (!range || semver.satisfies(installedVersion, range, { includePrerelease: true }))) {
66
+ majors.add(semver.major(installedVersion));
67
+ continue;
68
+ }
69
+ const minimum = range ? semver.minVersion(range) : null;
70
+ if (!minimum ||
71
+ !semver.subset(range, `>=${minimum.major}.0.0-0 <${minimum.major + 1}.0.0-0`, {
72
+ includePrerelease: true,
73
+ })) {
74
+ throw new Error(`Cannot determine the Crawlee major from ${name}: ${specifier} in ${manifestPath}. Install project dependencies or specify --from <major>.`);
75
+ }
76
+ majors.add(minimum.major);
77
+ }
78
+ }
79
+ if (majors.size !== 1) {
80
+ const reason = majors.size
81
+ ? `Crawlee dependencies use different majors (${[...majors].sort().join(', ')})`
82
+ : 'No Crawlee runtime dependency found';
83
+ throw new Error(`${reason} in ${manifestPath}. Run in the relevant workspace package or specify --from <major>.`);
84
+ }
85
+ return [...majors][0];
86
+ }
87
+ function body(markdown) {
88
+ return markdown.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n+/, '').trim();
89
+ }
90
+ export class UpgradeCommand {
91
+ command = 'upgrade';
92
+ describe = 'Prints an AI migration prompt, upgrading one Crawlee major at a time';
93
+ builder = (args) => args
94
+ .option('from', { type: 'number', describe: 'Starting major version; defaults to the project version' })
95
+ .option('to', {
96
+ type: 'number',
97
+ describe: 'Target major version; defaults to the newest bundled migration',
98
+ })
99
+ .option('export', {
100
+ type: 'string',
101
+ describe: 'Copy the migration guides into this directory and link the prompt to that copy',
102
+ });
103
+ async handler(args) {
104
+ for (const [name, value] of Object.entries({ from: args.from, to: args.to })) {
105
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
106
+ throw new Error(`--${name} must be a positive major version number.`);
107
+ }
108
+ }
109
+ const skillsUrl = new URL('../skills/', import.meta.url);
110
+ const migrations = new Map();
111
+ for (const entry of await readdir(skillsUrl, { withFileTypes: true })) {
112
+ const match = /^crawlee-upgrade-v(\d+)$/.exec(entry.name);
113
+ if (entry.isDirectory() && match)
114
+ migrations.set(Number(match[1]), new URL(`${entry.name}/`, skillsUrl));
115
+ }
116
+ if (!migrations.size)
117
+ throw new Error('No migration guides are bundled with this CLI.');
118
+ const from = args.from ?? (await detectProjectMajor());
119
+ const to = args.to ?? Math.max(...migrations.keys());
120
+ if (from >= to) {
121
+ throw new Error(`The project is already on Crawlee v${from}; the target must be newer. Use --from to explicitly review an earlier migration.`);
122
+ }
123
+ const steps = [];
124
+ const guides = [];
125
+ for (let major = from + 1; major <= to; major++) {
126
+ const skillUrl = migrations.get(major);
127
+ if (!skillUrl)
128
+ throw new Error(`No bundled migration from v${major - 1} to v${major}. Choose a supported --to version or use a CLI with that guide.`);
129
+ let skillPath = fileURLToPath(skillUrl);
130
+ if (args.export !== undefined) {
131
+ const target = join(resolve(args.export), `crawlee-upgrade-v${major}`);
132
+ await cp(skillPath, target, { recursive: true });
133
+ skillPath = target;
134
+ }
135
+ const skillRoot = skillPath.replace(/\\/g, '/').replace(/\/$/, '');
136
+ const prompt = await readFile(new URL('SKILL.md', skillUrl), 'utf8');
137
+ steps.push(`${steps.length + 1}. Upgrade v${major - 1} to v${major}, then verify before continuing.`);
138
+ guides.push(body(prompt).replaceAll('{SKILL_ROOT}', () => skillRoot));
139
+ }
140
+ const template = await readFile(new URL('crawlee-upgrade/SKILL.md', skillsUrl), 'utf8');
141
+ const replacements = {
142
+ FROM_MAJOR: String(from),
143
+ TO_MAJOR: String(to),
144
+ MIGRATION_PLAN: steps.join('\n'),
145
+ MIGRATION_GUIDES: guides.join('\n\n---\n\n'),
146
+ };
147
+ const prompt = body(template).replace(/\{(FROM_MAJOR|TO_MAJOR|MIGRATION_PLAN|MIGRATION_GUIDES)\}/g, (_, key) => replacements[key]);
148
+ process.stdout.write(`${prompt}\n`);
149
+ }
150
+ }
package/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { CreateProjectCommand } from './commands/create-project-command.js';
4
4
  import { InstallPlaywrightBrowsersCommand } from './commands/install-playwright-browsers-command.js';
5
5
  import { RunProjectCommand } from './commands/run-project-command.js';
6
+ import { UpgradeCommand } from './commands/upgrade-command.js';
6
7
  import { createRequire } from 'node:module';
7
8
  import yargs from 'yargs';
8
9
  const require = createRequire(import.meta.url);
@@ -26,8 +27,19 @@ const cli = yargs()
26
27
  .command(new CreateProjectCommand())
27
28
  .command(new RunProjectCommand())
28
29
  .command(new InstallPlaywrightBrowsersCommand())
30
+ .command(new UpgradeCommand())
29
31
  .recommendCommands()
30
- .showHelpOnFail(true)
32
+ .showHelpOnFail(false)
33
+ .fail((message, error, instance) => {
34
+ if (error) {
35
+ console.error(error.message);
36
+ }
37
+ else {
38
+ instance.showHelp();
39
+ console.error(`\n${message}`);
40
+ }
41
+ process.exit(1);
42
+ })
31
43
  .demandCommand(1, '')
32
44
  .strict();
33
45
  void (async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/cli",
3
- "version": "4.0.0-beta.321",
3
+ "version": "4.0.0-beta.323",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"
@@ -39,15 +39,16 @@
39
39
  "build": "pnpm clean && pnpm compile && pnpm copy",
40
40
  "clean": "rimraf ./dist",
41
41
  "compile": "tsc -p tsconfig.build.json",
42
- "copy": "tsx ../../scripts/copy.ts"
42
+ "copy": "node scripts/copy-skills.mjs && tsx ../../scripts/copy.ts"
43
43
  },
44
44
  "publishConfig": {
45
45
  "access": "public"
46
46
  },
47
47
  "dependencies": {
48
- "@crawlee/templates": "4.0.0-beta.321",
48
+ "@crawlee/templates": "4.0.0-beta.323",
49
49
  "@inquirer/prompts": "^8.8.1",
50
50
  "ansi-colors": "^4.1.3",
51
+ "semver": "^7.8.5",
51
52
  "tslib": "^2.9.1",
52
53
  "yargs": "^18.2.0"
53
54
  },
@@ -58,5 +59,5 @@
58
59
  }
59
60
  }
60
61
  },
61
- "gitHead": "56dbe5b65c85128a3f1cc8d0ee7a5aff2e5fde4b"
62
+ "gitHead": "f08b3c8d5e61f1dfe7c55308d64db92390c3352c"
62
63
  }
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: crawlee-upgrade
3
+ description: Plan and perform a Crawlee upgrade using the bundled migration guides, completing one major version at a time.
4
+ ---
5
+
6
+ # Crawlee upgrade plan: v{FROM_MAJOR} to v{TO_MAJOR}
7
+
8
+ Inspect this project and confirm its Crawlee versions before changing files. The guides below link local files; if they are unreadable from here, run `npx crawlee@{TO_MAJOR} upgrade --export <dir>` with a readable directory and use the prompt it prints instead. The CLI selected v{FROM_MAJOR} as the starting major from the project or an explicit `--from` override. If that does not match the code and dependencies, resolve the discrepancy with the user.
9
+
10
+ ## Migration sequence
11
+
12
+ {MIGRATION_PLAN}
13
+
14
+ Apply the guides below in this order. Complete each major upgrade, install compatible dependencies, and run its verification before starting the next. Do not jump directly to the final major or mix changes from different steps. If a step fails verification, fix it or report the blocker before proceeding.
15
+
16
+ Follow the Git permission and incremental-commit instructions in the guides. One approval covers the full sequence; commit each coherent, verified change before continuing. Preserve user edits and data throughout the migration.
17
+
18
+ ## Migration guides
19
+
20
+ {MIGRATION_GUIDES}
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: crawlee-upgrade-v4
3
+ description: Migrate a JavaScript or TypeScript Crawlee project from v3 to v4 while preserving crawl behavior and persistence.
4
+ ---
5
+
6
+ # Upgrade Crawlee from v3 to v4
7
+
8
+ Inspect, plan, migrate and verify this project. The breaking changes are described in the bundled copy of the [v4 upgrade guide](<{SKILL_ROOT}/guide/upgrading-v4.md>), which is the same text as the [published guide](https://crawlee.dev/js/docs/next/upgrading/upgrading-to-v4).
9
+
10
+ ## Read the guide
11
+
12
+ Read the guide's rename cheat sheet and all of "Changes most users will hit" before planning. Each "Only if you…" section applies only when the project uses what its title names; most of them summarize a detail page, so read that page when the section applies:
13
+
14
+ | Project usage or migration error | Detail page |
15
+ | --- | --- |
16
+ | Crawler subclasses, protected overrides, private fields, explicit generics, hook types, `RecoverableState` | [Internals](<{SKILL_ROOT}/guide/internals.md>) |
17
+ | `SessionPool`, `Session`, `createSessionFunction`, proxy tiers, `newUrlFunction` | [Sessions and proxies](<{SKILL_ROOT}/guide/sessions-and-proxies.md>) |
18
+ | `browserPoolOptions`, `browserController`, `launchContext`, rendering type predictor | [Browser management](<{SKILL_ROOT}/guide/browser-management.md>) |
19
+ | `statisticsOptions`, custom `Statistics`, persisted counters | [Statistics](<{SKILL_ROOT}/guide/statistics.md>) |
20
+ | `gotScraping`, `BaseHttpClient`, custom HTTP clients | [HTTP clients](<{SKILL_ROOT}/guide/http-clients.md>) |
21
+ | `RequestList`, sitemap loaders, custom request managers, per-domain throttling | [Request loaders](<{SKILL_ROOT}/guide/request-loaders.md>) |
22
+ | `StorageClient`, custom storage backends, `RequestQueue` or `Dataset` internals | [Storage backends](<{SKILL_ROOT}/guide/storage-backends.md>) |
23
+ | `autoscaledPoolOptions`, `crawler.autoscaledPool`, snapshotting, load signals | [Autoscaling](<{SKILL_ROOT}/guide/autoscaling.md>) |
24
+ | Imports from `@crawlee/utils` or `@crawlee/types` | [Utils and types](<{SKILL_ROOT}/guide/utils-and-types.md>) |
25
+ | An import the compiler no longer finds | [Removed symbols](<{SKILL_ROOT}/guide/removed-symbols.md>) |
26
+
27
+ Skip the guide's "Upgrade with an AI coding tool" section: it describes the command that printed this prompt.
28
+
29
+ ## Inspect and plan
30
+
31
+ Inspect manifests, lockfiles, crawler code, tests, runtime versions, CI and Dockerfiles. Inventory `crawlee`, `@crawlee/*`, `apify`, `apify-*` and `@apify/*` across workspace dependency sections. Update the Crawlee packages together to compatible v4 releases and refresh the lockfile. Actor projects also move to `apify@4`; other Apify packages version independently, so update them only when compatibility requires it.
32
+
33
+ Search the project for what the guide's sections name. Plan the changes around the project's crawler types, custom collaborators, storage persistence and queue reuse. Ask about behavior the code does not establish. If the project is already on v4, address the remaining migration gaps.
34
+
35
+ Apply the Node.js and optional-dependency requirements everywhere the project sets them: every Dockerfile build and runtime stage, base images selected through `ARG`, Compose or CI variables, install and prune scripts, and package-manager configuration. Preserve the image family, browser support, dev-dependency omission and frozen-lockfile behavior.
36
+
37
+ ## Git
38
+
39
+ For a Git project, inspect the branch and working tree. Ask once for permission to create a migration branch and make incremental commits, unless both are already authorized. Wait for approval before those Git actions.
40
+
41
+ If approved, verify and commit each coherent step before continuing. Stage only migration changes; preserve existing edits and ask about overlaps. Do not push unless asked. If branching or commits are declined, continue the migration without them.
42
+
43
+ ## Verify
44
+
45
+ Run the project's type check, relevant tests and build. Use fixtures or a bounded crawl with isolated storage to check affected behavior, including that native HTTP and filesystem binaries load in the target container. Do not purge user storage or run a production crawl as verification. Report changes, failed or unavailable checks, and unresolved decisions.
@@ -0,0 +1,256 @@
1
+ ---
2
+ id: autoscaling
3
+ title: 'Upgrading to v4: autoscaling'
4
+ sidebar_label: Autoscaling
5
+ sidebar_position: 8
6
+ slug: /upgrading/upgrading-to-v4/autoscaling
7
+ ---
8
+
9
+ The `minConcurrency` / `maxConcurrency` / `maxRequestsPerMinute` crawler options work as before. This section matters when you used `autoscaledPoolOptions`, drove an `AutoscaledPool` directly, or configured snapshotting and system status. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## Autoscaling moved to `ConcurrencySystem`
12
+
13
+ Everything that decides whether there is free compute for one more task — snapshotting, the system-status evaluation, the concurrency budget and the scaling logic — moved out of `AutoscaledPool` into a new `ConcurrencySystem`. What is left of the pool is a bare task loop, which is now **internal**: crawlers build and drive one for themselves, and `ConcurrencySystem` is the only part of this you configure.
14
+
15
+ The point is sharing: inject one instance into several crawlers to cap their **combined** concurrency against a single budget, instead of letting each scale independently and oversubscribe the host. The option is typed as `IConcurrencySystem`, a minimal read-only contract, so an alternative governor can be substituted; `ConcurrencySystem` is the canonical implementation and the one crawlers build by default.
16
+
17
+ :::info Who starts and stops it
18
+
19
+ Whoever *builds* a `ConcurrencySystem` owns its lifecycle. Crawlers do that for the default system they build per run. One **you** supply is yours to `start()` and `stop()`, because no crawler can know when the last borrower has finished. Forgetting to start it makes `run()` **throw**; stopping it while a crawler is still running only **warns**. Read `isRunning` to check whether a system handed to you was already started by its owner.
20
+
21
+ :::
22
+
23
+ Every migration below has the same shape — build, start, run, stop:
24
+
25
+ ```typescript
26
+ import { CheerioCrawler, ConcurrencySystem } from 'crawlee';
27
+
28
+ const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 20 });
29
+ await concurrencySystem.start();
30
+
31
+ // One crawler, or several: a shared instance caps their combined concurrency.
32
+ const a = new CheerioCrawler({ concurrencySystem, requestHandler });
33
+ const b = new CheerioCrawler({ concurrencySystem, requestHandler });
34
+
35
+ try {
36
+ await Promise.all([a.run(), b.run()]);
37
+ } finally {
38
+ await concurrencySystem.stop();
39
+ }
40
+ ```
41
+
42
+ On Node.js 24, `await using` replaces the `try`/`finally` — see [collaborators you own are disposable](./upgrading-v4.md#collaborators-you-own-are-disposable).
43
+
44
+ ### `AutoscaledPool` is no longer public API
45
+
46
+ `AutoscaledPool` is `@internal` in v4, along with `AutoscaledPoolOptions`. It is still exported from `@crawlee/basic` (and re-exported by `crawlee`), so nothing breaks at import time — but with all the configuration moved to the `ConcurrencySystem`, what remains is a bare parallel task runner. It can change without a major bump, so avoid depending on it; if you only wanted bounded parallelism, a `p-limit`-style helper is a better fit than an internal Crawlee class.
47
+
48
+ The crawler's `autoscaledPool` property is **removed** as a result. Everything it was reached for has a crawler-level counterpart:
49
+
50
+ | Before | After |
51
+ |---|---|
52
+ | `await crawler.autoscaledPool.pause(secs)` | `await crawler.pause(secs)` |
53
+ | `crawler.autoscaledPool.resume()` | `crawler.resume()` |
54
+ | `await crawler.autoscaledPool.abort()` | `await crawler.teardown()` — or `crawler.stop()`, to let in-flight requests finish |
55
+ | `crawler.autoscaledPool.desiredConcurrency` | `crawler.concurrencySystem?.desiredConcurrency` |
56
+ | `crawler.autoscaledPool.currentConcurrency` | `crawler.concurrencySystem?.currentConcurrency` |
57
+
58
+ ```typescript
59
+ const crawler = new CheerioCrawler({
60
+ async requestHandler({ log }) {
61
+ log.info(`Currently running ${crawler.concurrencySystem?.currentConcurrency} requests in parallel.`);
62
+ },
63
+ });
64
+ ```
65
+
66
+ `crawler.concurrencySystem` is `undefined` until `run()` has resolved it, and a crawler-owned default is rebuilt for every run — so read it during a run rather than caching it across runs. A system *you* injected is simply the instance you passed in.
67
+
68
+ The getter is typed as the read-only `IConcurrencySystem` and has no setters, so retuning concurrency mid-crawl means owning the instance:
69
+
70
+ ```typescript
71
+ const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });
72
+
73
+ const crawler = new CheerioCrawler({
74
+ concurrencySystem,
75
+ requestHandler,
76
+ errorHandler: async ({ response }) => {
77
+ if (response?.status === 429) concurrencySystem.maxConcurrency = 10;
78
+ },
79
+ });
80
+ ```
81
+
82
+ `crawler.pause()` resolves once the requests already in flight have settled, and leaves `run()` pending until you `resume()` — unlike `crawler.stop()`, which ends the run gracefully. One behavioral consequence of the split: pausing no longer suspends autoscaling, because the autoscaling interval belongs to the `ConcurrencySystem`, which knows nothing about its borrowers' pause state — deliberately, since other crawlers sharing it may still need scaling. A paused crawler's system keeps evaluating (and possibly scaling down) the desired concurrency and keeps emitting its periodic state log. Scaling *up* stays effectively blocked, as the current concurrency drains below the ratio required for a scale-up. To silence the system during a long pause, `stop()` it (if you own it) and `start()` it again before resuming; a restart discards the snapshots taken before it, so the pause is not mistaken for load.
83
+
84
+ #### If you were driving an `AutoscaledPool` directly
85
+
86
+ All scaling and load-monitoring options were **removed** from `AutoscaledPoolOptions` and now live on `ConcurrencySystemOptions`: `minConcurrency`, `maxConcurrency`, `desiredConcurrency`, `desiredConcurrencyRatio`, `scaleUpStepRatio`, `scaleDownStepRatio`, `loggingIntervalSecs`, `autoscaleIntervalSecs`, and `maxTasksPerMinute`, plus the load-signal configuration described [below](#load-signal-options-restructured). The `snapshotterOptions` and `systemStatusOptions` bags are both gone, as are the `minConcurrency`/`maxConcurrency` accessors and every setter (`desiredConcurrency` and `currentConcurrency` remain as read-only getters, joined by a new read-only `system` getter). In their place, `AutoscaledPoolOptions` gained a **required** `concurrencySystem`, plus a **required** `consumer` — the pool's identity (`{ id }`), which it presents to the governor on every capacity query and booking so that a shared one can tell several pools' tasks apart.
87
+
88
+ **Before:**
89
+ ```typescript
90
+ const pool = new AutoscaledPool({
91
+ minConcurrency: 5,
92
+ maxConcurrency: 50,
93
+ maxTasksPerMinute: 120,
94
+ runTaskFunction: async () => { /* ... */ },
95
+ isTaskReadyFunction: async () => true,
96
+ isFinishedFunction: async () => false,
97
+ });
98
+ await pool.run();
99
+ ```
100
+
101
+ **After:**
102
+ ```typescript
103
+ import { AutoscaledPool, ConcurrencySystem } from '@crawlee/basic';
104
+
105
+ const concurrencySystem = new ConcurrencySystem({
106
+ minConcurrency: 5,
107
+ maxConcurrency: 50,
108
+ maxTasksPerMinute: 120,
109
+ });
110
+ await concurrencySystem.start();
111
+
112
+ const pool = new AutoscaledPool({
113
+ concurrencySystem,
114
+ consumer: { id: 'my-pool' },
115
+ runTaskFunction: async () => { /* ... */ },
116
+ isTaskReadyFunction: async () => true,
117
+ isFinishedFunction: async () => false,
118
+ });
119
+
120
+ try {
121
+ await pool.run();
122
+ } finally {
123
+ await concurrencySystem.stop();
124
+ }
125
+ ```
126
+
127
+ ### `autoscaledPoolOptions` is now `taskLoopOptions`, and no longer carries concurrency config
128
+
129
+ The crawler option was renamed — it was named after a class that is now internal — and narrowed to **only** the task-loop predicates `isFinishedFunction` and `isTaskReadyFunction`. Its type changed from `AutoscaledPoolOptions` to `TaskLoopPredicates`. Concurrency configuration goes through either the `minConcurrency` / `maxConcurrency` / `initialConcurrency` / `maxRequestsPerMinute` shortcuts (which configure the crawler's default `ConcurrencySystem`), or — for anything finer — a supplied `concurrencySystem`. The new `initialConcurrency` shortcut replaces `autoscaledPoolOptions.desiredConcurrency` and defaults to `minConcurrency` (`HttpCrawler` and its subclasses default to 10 instead, see the preset below).
130
+
131
+ Two options that used to live here — `maybeRunIntervalSecs` and `taskTimeoutSecs` — did *not* move to the `ConcurrencySystem` and have no replacement: the crawler's task-loop cadence is no longer configurable. The third, `log`, is gone from the crawler option too: the crawler passes its own logger to the default system, and a `ConcurrencySystem` you build takes a `log` option.
132
+
133
+ **Before:**
134
+ ```typescript
135
+ const crawler = new CheerioCrawler({
136
+ autoscaledPoolOptions: {
137
+ desiredConcurrency: 10,
138
+ maxTasksPerMinute: 120,
139
+ systemStatusOptions: { currentHistorySecs: 10 },
140
+ },
141
+ requestHandler,
142
+ });
143
+ ```
144
+
145
+ **After:**
146
+ ```typescript
147
+ const concurrencySystem = new ConcurrencySystem({
148
+ desiredConcurrency: 10,
149
+ maxTasksPerMinute: 120,
150
+ currentHistorySecs: 10,
151
+ });
152
+
153
+ const crawler = new CheerioCrawler({ concurrencySystem, requestHandler });
154
+ ```
155
+
156
+ The shortcuts cannot be combined with a supplied `concurrencySystem` — they configure the default system that a supplied one replaces, so the crawler constructor **throws** rather than dropping a limit you asked for. For the common case, the shortcuts are all you need and no `ConcurrencySystem` is involved:
157
+
158
+ ```typescript
159
+ const crawler = new CheerioCrawler({
160
+ minConcurrency: 5,
161
+ maxConcurrency: 50,
162
+ initialConcurrency: 10,
163
+ maxRequestsPerMinute: 120,
164
+ requestHandler,
165
+ });
166
+ ```
167
+
168
+ A supplied system also replaces the default *wholesale*, including any crawler-specific tuning that default carried. `HttpCrawler` and its subclasses (`CheerioCrawler`, `JSDOMCrawler`, …) ship a preset — a higher `desiredConcurrency` and a relaxed event loop signal — exported as `HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS`; spread it in to keep it:
169
+
170
+ ```typescript
171
+ import { ConcurrencySystem, HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS } from 'crawlee';
172
+
173
+ const concurrencySystem = new ConcurrencySystem({
174
+ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS,
175
+ maxConcurrency: 50,
176
+ });
177
+ ```
178
+
179
+ ## Load-signal options restructured
180
+
181
+ The per-resource load-signal configuration was consolidated. It used to be spread across flat `SnapshotterOptions` fields, the `max*OverloadedRatio` options on `SystemStatusOptions`, and a separate `loadSignals` array — three places, two of them named after classes that are now internal. All of it now lives in a single `loadSignals` bag on `ConcurrencySystemOptions`: one options bag per built-in signal (each carrying its own limits *and* its `overloadedRatio`), plus `custom` for your own implementations.
182
+
183
+ **Before:**
184
+ ```typescript
185
+ new AutoscaledPool({
186
+ snapshotterOptions: {
187
+ maxUsedMemoryRatio: 0.8,
188
+ eventLoopSnapshotIntervalSecs: 2,
189
+ maxBlockedMillis: 100,
190
+ clientSnapshotIntervalSecs: 1,
191
+ maxClientErrors: 3,
192
+ snapshotHistorySecs: 60,
193
+ },
194
+ systemStatusOptions: {
195
+ maxMemoryOverloadedRatio: 0.2,
196
+ maxEventLoopOverloadedRatio: 0.7,
197
+ maxCpuOverloadedRatio: 0.4,
198
+ maxClientOverloadedRatio: 0.3,
199
+ currentHistorySecs: 10,
200
+ loadSignals: [myProxyHealthSignal],
201
+ },
202
+ // ...
203
+ });
204
+ ```
205
+
206
+ **After:**
207
+ ```typescript
208
+ new ConcurrencySystem({
209
+ loadSignals: {
210
+ memory: { maxUsedRatio: 0.8, overloadedRatio: 0.2 },
211
+ eventLoop: { snapshotIntervalSecs: 2, maxBlockedMillis: 100, overloadedRatio: 0.7 },
212
+ cpu: { overloadedRatio: 0.4 },
213
+ storageBackend: { snapshotIntervalSecs: 1, maxErrors: 3, overloadedRatio: 0.3 },
214
+ custom: [myProxyHealthSignal],
215
+ },
216
+ // the two evaluation windows are policy, alongside the scaling options
217
+ snapshotHistorySecs: 60,
218
+ currentHistorySecs: 10,
219
+ });
220
+ ```
221
+
222
+ The signal that watches storage rate-limit errors follows the [`StorageClient` → `StorageBackend` rename](./storage-backends.md#storagebackend-interface-simplified): the option is `loadSignals.storageBackend`, the class `StorageBackendLoadSignal`, and its verdict is reported as `SystemInfo.storageBackendInfo`. The type of that verdict, `ClientInfo`, is now `LoadSignalInfo` — it backs every signal's entry, not just this one.
223
+
224
+ In detail: the four `max*OverloadedRatio` options of `SystemStatusOptions` were **removed** (each signal now owns its overload ratio, set in its own bag), custom signals moved from `systemStatusOptions.loadSignals` to `loadSignals.custom`, and the two evaluation windows — `snapshotHistorySecs` (autoscaling) and `currentHistorySecs` (task gating) — are plain options on `ConcurrencySystemOptions`, since they apply to every signal alike rather than to any one of them.
225
+
226
+ If you built the signals yourself, the factory functions `createCpuLoadSignal()`, `createEventLoopLoadSignal()` and `createClientLoadSignal()` are **removed**, together with the `ClientLoadSignal`, `ClientLoadSignalOptions` and `ClientSnapshot` types. Construct the classes instead — `new CpuLoadSignal(options)`, `new EventLoopLoadSignal(options)`, `new StorageBackendLoadSignal(options)` — alongside `MemoryLoadSignal`, which already was one. Their option names lost the per-resource prefixes, as in the example above:
227
+
228
+ | v3 | v4 |
229
+ | --- | --- |
230
+ | `MemoryLoadSignalOptions.maxUsedMemoryRatio` | `maxUsedRatio` |
231
+ | `EventLoopLoadSignalOptions.eventLoopSnapshotIntervalSecs` | `snapshotIntervalSecs` |
232
+ | `ClientLoadSignalOptions.clientSnapshotIntervalSecs` | `StorageBackendLoadSignalOptions.snapshotIntervalSecs` |
233
+ | `ClientLoadSignalOptions.maxClientErrors` | `StorageBackendLoadSignalOptions.maxErrors` |
234
+ | `ClientLoadSignalOptions.client`, `CpuLoadSignalOptions.config`, `MemoryLoadSignalOptions.config` / `log` | *(removed — the signals read the storage backend and event manager from the `serviceLocator`)* |
235
+
236
+ Two related capabilities are new, and covered in the [scaling guide](https://crawlee.dev/js/docs/next/guides/scaling-crawlers#load-signals): a built-in signal can be switched **off** with `false`, and each built-in is also a public class (`MemoryLoadSignal`, `EventLoopLoadSignal`, `CpuLoadSignal`, `StorageBackendLoadSignal`) you can construct to wrap or adapt.
237
+
238
+ A duplicate signal name now **throws**, where naming a custom signal after a built-in (`memInfo`, `eventLoopInfo`, `cpuInfo`, or `clientInfo`, now `storageBackendInfo`) used to look like an override but never was one: the built-in kept running and kept holding concurrency down, while your signal only overwrote its field in the reported `SystemInfo`. To take a built-in's place, switch it off:
239
+
240
+ ```typescript
241
+ new ConcurrencySystem({
242
+ loadSignals: {
243
+ // Without `memory: false`, this throws — the built-in memory signal is still enabled.
244
+ memory: false,
245
+ custom: [myMemorySignal], // free to take over the vacated `memInfo` field
246
+ },
247
+ });
248
+ ```
249
+
250
+ `Snapshotter` and `SystemStatus` are no longer public API, along with `SnapshotterOptions` and `SystemStatusOptions` — they are implementation details of the `ConcurrencySystem`, which is now the only supported entry point to load monitoring; read the resulting `SystemInfo` through `ConcurrencySystem.getCurrentStatus()`. Still public: the configuration types, the four built-in signal classes, and the extension surface (`LoadSignal`, `SnapshotStore`, `LoadSignalStartContext`). The concrete snapshot types the built-ins produce are *not* — `getSample()` returns plain `LoadSnapshot` values.
251
+
252
+ ### Both evaluation windows are now requested from every signal
253
+
254
+ Overload is evaluated over two windows: `currentHistorySecs` (default 5s) gates whether another task may start, and `snapshotHistorySecs` (default 30s) drives autoscaling. The long one used to be implicit — `getHistoricalStatus()` asked each signal for *everything it had retained*, so a custom signal keeping five minutes of snapshots silently made autoscaling reason over five minutes of history for that resource while the built-ins used 30 seconds. Both are now requested explicitly from every signal, and `LoadSignal.start()` receives the wider of the two as `maxSampleWindowMillis` so retention can be sized to match.
255
+
256
+ You are affected if a custom signal retains **more** history than `snapshotHistorySecs` (its stale snapshots no longer influence scaling), or if its `getSample()` ignores the `sampleDurationMillis` argument, in which case it still contributes everything it has. On the API side, `snapshotHistoryMillis` was removed from the per-signal option types and `SnapshotStore` lost both its constructor argument and the `fromInterval`/`fromEvent` factories; call `useSampleWindow(maxSampleWindowMillis)` and `clear()` from your `start()` instead, as a store that is never given a window retains everything. The [scaling guide](https://crawlee.dev/js/docs/next/guides/scaling-crawlers#load-signals) has a worked example.