@crawlee/stagehand 4.0.0-beta.33 → 4.0.0-beta.330

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
@@ -1,23 +1,23 @@
1
1
  <h1 align="center">
2
2
  <a href="https://crawlee.dev">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true">
5
- <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500">
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
6
  </picture>
7
7
  </a>
8
- <br>
8
+ <br />
9
9
  <small>A web scraping and browser automation library</small>
10
10
  </h1>
11
11
 
12
- <p align=center>
13
- <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
14
  </p>
15
15
 
16
- <p align=center>
17
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" style="max-width: 100%;"></a>
18
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" style="max-width: 100%;"></a>
19
- <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" style="max-width: 100%;"></a>
20
- <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" style="max-width: 100%;"></a>
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
21
21
  </p>
22
22
 
23
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -34,7 +34,7 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
34
34
 
35
35
  We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
36
36
 
37
- > Crawlee requires **Node.js 16 or higher**.
37
+ > Crawlee requires **Node.js 22.13 or higher**.
38
38
 
39
39
  ### With Crawlee CLI
40
40
 
@@ -144,6 +144,10 @@ Crawlee is open-source and runs anywhere, but since it's developed by [Apify](ht
144
144
 
145
145
  If you find any bug or issue with Crawlee, please [submit an issue on GitHub](https://github.com/apify/crawlee/issues). For questions, you can ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/apify), in GitHub Discussions or you can join our [Discord server](https://discord.com/invite/jyEM2PRvMU).
146
146
 
147
+ ## Supported versions
148
+
149
+ New features and bug fixes land in the latest major version. The previous major version keeps receiving fixes for high and critical severity vulnerabilities for 12 months after the next major is released, and reaches end of life after that. See the [security policy](https://github.com/apify/crawlee/security/policy) for the current status of each version and for how to report a vulnerability.
150
+
147
151
  ## Contributing
148
152
 
149
153
  Your code contributions are welcome, and you'll be praised to eternity! If you have any ideas for improvements, either submit an issue or create a pull request. For contribution guidelines and the code of conduct, see [CONTRIBUTING.md](https://github.com/apify/crawlee/blob/master/CONTRIBUTING.md).
package/index.d.ts CHANGED
@@ -50,9 +50,9 @@
50
50
  * @module @crawlee/stagehand
51
51
  */
52
52
  export * from '@crawlee/browser';
53
- export { StagehandCrawler, createStagehandRouter, } from './internals/stagehand-crawler';
54
- export type { StagehandOptions, StagehandPage, StagehandCrawlingContext, StagehandHook, StagehandRequestHandler, StagehandGotoOptions, StagehandCrawlerOptions, } from './internals/stagehand-crawler';
55
- export type { StagehandLaunchContext } from './internals/stagehand-launcher';
56
- export * as stagehandUtils from './internals/utils/stagehand-utils';
57
- export type { ActOptions, ActResult, Action, AgentConfig, AgentResult, ExtractOptions, ModelConfiguration, ObserveOptions, Stagehand, } from '@browserbasehq/stagehand';
58
- //# sourceMappingURL=index.d.ts.map
53
+ export { StagehandCrawler, createStagehandRouter } from './internals/stagehand-crawler.js';
54
+ export { stagehandBrowserPool } from './internals/stagehand-browser-pool.js';
55
+ export type { StagehandBrowserPool, StagehandBrowserPoolOptions } from './internals/stagehand-browser-pool.js';
56
+ export type { StagehandOptions, StagehandPage, StagehandCrawlingContext, StagehandHook, StagehandGotoOptions, StagehandCrawlerOptions, } from './internals/stagehand-crawler.js';
57
+ export type { StagehandLaunchContext } from './internals/stagehand-launcher.js';
58
+ export type { ActOptions, ActResult, Action, AgentConfig, ExtractOptions, ModelConfiguration, ObserveOptions, Stagehand, } from '@browserbasehq/stagehand';
package/index.js CHANGED
@@ -51,14 +51,14 @@
51
51
  * @module @crawlee/stagehand
52
52
  */
53
53
  Object.defineProperty(exports, "__esModule", { value: true });
54
- exports.stagehandUtils = exports.createStagehandRouter = exports.StagehandCrawler = void 0;
54
+ exports.stagehandBrowserPool = exports.createStagehandRouter = exports.StagehandCrawler = void 0;
55
55
  const tslib_1 = require("tslib");
56
56
  // Re-export everything from @crawlee/browser for convenience
57
57
  tslib_1.__exportStar(require("@crawlee/browser"), exports);
58
58
  // Export main crawler class
59
- var stagehand_crawler_1 = require("./internals/stagehand-crawler");
60
- Object.defineProperty(exports, "StagehandCrawler", { enumerable: true, get: function () { return stagehand_crawler_1.StagehandCrawler; } });
61
- Object.defineProperty(exports, "createStagehandRouter", { enumerable: true, get: function () { return stagehand_crawler_1.createStagehandRouter; } });
62
- // Export utilities as namespace
63
- exports.stagehandUtils = tslib_1.__importStar(require("./internals/utils/stagehand-utils"));
64
- //# sourceMappingURL=index.js.map
59
+ var stagehand_crawler_js_1 = require("./internals/stagehand-crawler.js");
60
+ Object.defineProperty(exports, "StagehandCrawler", { enumerable: true, get: function () { return stagehand_crawler_js_1.StagehandCrawler; } });
61
+ Object.defineProperty(exports, "createStagehandRouter", { enumerable: true, get: function () { return stagehand_crawler_js_1.createStagehandRouter; } });
62
+ // Export the browser pool factories, which are how a pool with non-default options reaches the crawler
63
+ var stagehand_browser_pool_js_1 = require("./internals/stagehand-browser-pool.js");
64
+ Object.defineProperty(exports, "stagehandBrowserPool", { enumerable: true, get: function () { return stagehand_browser_pool_js_1.stagehandBrowserPool; } });
package/index.mjs CHANGED
@@ -2,26 +2,33 @@ import mod from "./index.js";
2
2
 
3
3
  export default mod;
4
4
  export const API_PROCESSED_REQUESTS_DELAY_MILLIS = mod.API_PROCESSED_REQUESTS_DELAY_MILLIS;
5
+ export const AfterCommitError = mod.AfterCommitError;
5
6
  export const ApifyLogAdapter = mod.ApifyLogAdapter;
7
+ export const ArgumentValidationError = mod.ArgumentValidationError;
6
8
  export const AutoscaledPool = mod.AutoscaledPool;
7
9
  export const BLOCKED_STATUS_CODES = mod.BLOCKED_STATUS_CODES;
8
10
  export const BaseCrawleeLogger = mod.BaseCrawleeLogger;
9
11
  export const BasicCrawler = mod.BasicCrawler;
10
12
  export const BrowserCrawler = mod.BrowserCrawler;
11
13
  export const BrowserLauncher = mod.BrowserLauncher;
14
+ export const ConcurrencySystem = mod.ConcurrencySystem;
12
15
  export const Configuration = mod.Configuration;
13
16
  export const ContextPipeline = mod.ContextPipeline;
14
17
  export const ContextPipelineCleanupError = mod.ContextPipelineCleanupError;
15
18
  export const ContextPipelineInitializationError = mod.ContextPipelineInitializationError;
16
19
  export const ContextPipelineInterruptedError = mod.ContextPipelineInterruptedError;
17
20
  export const CookieParseError = mod.CookieParseError;
21
+ export const CpuLoadSignal = mod.CpuLoadSignal;
22
+ export const CrawlingRequest = mod.CrawlingRequest;
18
23
  export const CriticalError = mod.CriticalError;
19
24
  export const DATASET_ITERATORS_DEFAULT_LIMIT = mod.DATASET_ITERATORS_DEFAULT_LIMIT;
25
+ export const DEFAULT_CURRENT_HISTORY_SECS = mod.DEFAULT_CURRENT_HISTORY_SECS;
26
+ export const DEFAULT_SNAPSHOT_HISTORY_SECS = mod.DEFAULT_SNAPSHOT_HISTORY_SECS;
20
27
  export const Dataset = mod.Dataset;
21
- export const EVENT_SESSION_RETIRED = mod.EVENT_SESSION_RETIRED;
28
+ export const DownloadStartedError = mod.DownloadStartedError;
22
29
  export const EnqueueStrategy = mod.EnqueueStrategy;
23
- export const ErrorSnapshotter = mod.ErrorSnapshotter;
24
30
  export const ErrorTracker = mod.ErrorTracker;
31
+ export const EventLoopLoadSignal = mod.EventLoopLoadSignal;
25
32
  export const EventManager = mod.EventManager;
26
33
  export const EventType = mod.EventType;
27
34
  export const KeyValueStore = mod.KeyValueStore;
@@ -31,28 +38,28 @@ export const LogLevel = mod.LogLevel;
31
38
  export const Logger = mod.Logger;
32
39
  export const LoggerJson = mod.LoggerJson;
33
40
  export const LoggerText = mod.LoggerText;
34
- export const MAX_POOL_SIZE = mod.MAX_POOL_SIZE;
35
41
  export const MAX_QUERIES_FOR_CONSISTENCY = mod.MAX_QUERIES_FOR_CONSISTENCY;
42
+ export const MemoryLoadSignal = mod.MemoryLoadSignal;
43
+ export const MemoryStorageBackend = mod.MemoryStorageBackend;
36
44
  export const MissingRouteError = mod.MissingRouteError;
45
+ export const MissingSessionError = mod.MissingSessionError;
46
+ export const NavigationSkippedError = mod.NavigationSkippedError;
37
47
  export const NonRetryableError = mod.NonRetryableError;
38
- export const PERSIST_STATE_KEY = mod.PERSIST_STATE_KEY;
48
+ export const OwnedOrInjected = mod.OwnedOrInjected;
49
+ export const PersistentRateLimitError = mod.PersistentRateLimitError;
39
50
  export const ProxyConfiguration = mod.ProxyConfiguration;
40
- export const PseudoUrl = mod.PseudoUrl;
41
51
  export const QUERY_HEAD_BUFFER = mod.QUERY_HEAD_BUFFER;
42
52
  export const QUERY_HEAD_MIN_LENGTH = mod.QUERY_HEAD_MIN_LENGTH;
43
53
  export const REQUESTS_PERSISTENCE_KEY = mod.REQUESTS_PERSISTENCE_KEY;
44
54
  export const RecoverableState = mod.RecoverableState;
45
55
  export const Request = mod.Request;
46
56
  export const RequestHandlerError = mod.RequestHandlerError;
47
- export const RequestHandlerResult = mod.RequestHandlerResult;
48
57
  export const RequestList = mod.RequestList;
49
- export const RequestListAdapter = mod.RequestListAdapter;
50
58
  export const RequestManagerTandem = mod.RequestManagerTandem;
51
- export const RequestProvider = mod.RequestProvider;
52
59
  export const RequestQueue = mod.RequestQueue;
53
- export const RequestQueueV1 = mod.RequestQueueV1;
54
- export const RequestQueueV2 = mod.RequestQueueV2;
55
60
  export const RequestState = mod.RequestState;
61
+ export const RequestThrottledError = mod.RequestThrottledError;
62
+ export const RequestValidationError = mod.RequestValidationError;
56
63
  export const RetryRequestError = mod.RetryRequestError;
57
64
  export const Router = mod.Router;
58
65
  export const STATE_PERSISTENCE_KEY = mod.STATE_PERSISTENCE_KEY;
@@ -62,47 +69,73 @@ export const ServiceLocator = mod.ServiceLocator;
62
69
  export const Session = mod.Session;
63
70
  export const SessionError = mod.SessionError;
64
71
  export const SessionPool = mod.SessionPool;
65
- export const SitemapRequestList = mod.SitemapRequestList;
72
+ export const SessionRetiredError = mod.SessionRetiredError;
73
+ export const SitemapRequestLoader = mod.SitemapRequestLoader;
74
+ export const SnapshotStore = mod.SnapshotStore;
66
75
  export const Snapshotter = mod.Snapshotter;
67
76
  export const StagehandCrawler = mod.StagehandCrawler;
77
+ export const StateValidationError = mod.StateValidationError;
68
78
  export const Statistics = mod.Statistics;
69
- export const StorageManager = mod.StorageManager;
79
+ export const StorageBackendLoadSignal = mod.StorageBackendLoadSignal;
80
+ export const StorageInstanceManager = mod.StorageInstanceManager;
81
+ export const StorageTransaction = mod.StorageTransaction;
70
82
  export const SystemStatus = mod.SystemStatus;
83
+ export const ThrottlingRequestManager = mod.ThrottlingRequestManager;
84
+ export const activeStorageTransaction = mod.activeStorageTransaction;
71
85
  export const applyRequestTransform = mod.applyRequestTransform;
86
+ export const assertJsonSerializable = mod.assertJsonSerializable;
72
87
  export const bindMethodsToServiceLocator = mod.bindMethodsToServiceLocator;
73
- export const browserCrawlerEnqueueLinks = mod.browserCrawlerEnqueueLinks;
74
88
  export const browserPoolCookieToToughCookie = mod.browserPoolCookieToToughCookie;
75
- export const checkAndSerialize = mod.checkAndSerialize;
76
- export const checkStorageAccess = mod.checkStorageAccess;
77
- export const chunkBySize = mod.chunkBySize;
89
+ export const coerceBoolean = mod.coerceBoolean;
90
+ export const coerceNumber = mod.coerceNumber;
78
91
  export const constructGlobObjectsFromGlobs = mod.constructGlobObjectsFromGlobs;
79
- export const constructRegExpObjectsFromPseudoUrls = mod.constructRegExpObjectsFromPseudoUrls;
80
92
  export const constructRegExpObjectsFromRegExps = mod.constructRegExpObjectsFromRegExps;
93
+ export const constructUrlPatternObjects = mod.constructUrlPatternObjects;
94
+ export const convertStateSync = mod.convertStateSync;
81
95
  export const cookieStringToToughCookie = mod.cookieStringToToughCookie;
96
+ export const crawleeConfigFields = mod.crawleeConfigFields;
82
97
  export const createBasicRouter = mod.createBasicRouter;
83
98
  export const createDeserialize = mod.createDeserialize;
99
+ export const createDualIterable = mod.createDualIterable;
100
+ export const createRequestDebugInfo = mod.createRequestDebugInfo;
84
101
  export const createRequestOptions = mod.createRequestOptions;
102
+ export const createSkippedRequestArgs = mod.createSkippedRequestArgs;
85
103
  export const createStagehandRouter = mod.createStagehandRouter;
104
+ export const createStorageTransaction = mod.createStorageTransaction;
105
+ export const currentStorageTransaction = mod.currentStorageTransaction;
106
+ export const defaultRoute = mod.defaultRoute;
86
107
  export const deserializeArray = mod.deserializeArray;
87
- export const enqueueLinks = mod.enqueueLinks;
108
+ export const evaluateLoadSignalSample = mod.evaluateLoadSignalSample;
88
109
  export const extractUrlsFromPage = mod.extractUrlsFromPage;
110
+ export const field = mod.field;
89
111
  export const filterRequestOptionsByPatterns = mod.filterRequestOptionsByPatterns;
90
112
  export const getCookiesFromResponse = mod.getCookiesFromResponse;
91
113
  export const getDefaultCookieExpirationDate = mod.getDefaultCookieExpirationDate;
114
+ export const getObjectType = mod.getObjectType;
92
115
  export const getRequestId = mod.getRequestId;
93
- export const handleRequestTimeout = mod.handleRequestTimeout;
116
+ export const inspectValue = mod.inspectValue;
94
117
  export const log = mod.log;
95
- export const maybeStringify = mod.maybeStringify;
96
118
  export const mergeCookies = mod.mergeCookies;
119
+ export const navigationDeadlineKey = mod.navigationDeadlineKey;
120
+ export const operationRejectedInTransaction = mod.operationRejectedInTransaction;
121
+ export const parseRetryAfterHeader = mod.parseRetryAfterHeader;
122
+ export const parseValue = mod.parseValue;
97
123
  export const purgeDefaultStorages = mod.purgeDefaultStorages;
124
+ export const rejectOperationInTransaction = mod.rejectOperationInTransaction;
125
+ export const remainingNavigationWindowMillis = mod.remainingNavigationWindowMillis;
98
126
  export const resolveBaseUrlForEnqueueLinksFiltering = mod.resolveBaseUrlForEnqueueLinksFiltering;
99
127
  export const serializeArray = mod.serializeArray;
128
+ export const serializeValue = mod.serializeValue;
100
129
  export const serviceLocator = mod.serviceLocator;
101
- export const stagehandUtils = mod.stagehandUtils;
130
+ export const skippedNavigationRequest = mod.skippedNavigationRequest;
131
+ export const snapshotValue = mod.snapshotValue;
132
+ export const stagehandBrowserPool = mod.stagehandBrowserPool;
102
133
  export const toughCookieToBrowserPoolCookie = mod.toughCookieToBrowserPoolCookie;
103
- export const tryAbsoluteURL = mod.tryAbsoluteURL;
104
134
  export const updateEnqueueLinksPatternCache = mod.updateEnqueueLinksPatternCache;
135
+ export const urlPatternSchema = mod.urlPatternSchema;
105
136
  export const useState = mod.useState;
106
137
  export const validateGlobPattern = mod.validateGlobPattern;
138
+ export const validateUserData = mod.validateUserData;
107
139
  export const validators = mod.validators;
108
- export const withCheckedStorageAccess = mod.withCheckedStorageAccess;
140
+ export const withDirectStorageAccess = mod.withDirectStorageAccess;
141
+ export const withStorageTransaction = mod.withStorageTransaction;
@@ -0,0 +1,50 @@
1
+ import type { Configuration } from '@crawlee/browser';
2
+ import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions } from '@crawlee/browser-pool';
3
+ // @ts-ignore optional peer dependency or compatibility with es2022
4
+ import type { Page } from 'playwright';
5
+ import type { StagehandOptions } from './stagehand-crawler.js';
6
+ import type { StagehandLaunchContext } from './stagehand-launcher.js';
7
+ import type { StagehandPlugin } from './stagehand-plugin.js';
8
+ /** A {@link BrowserPool} of Stagehand browsers, as built by {@link stagehandBrowserPool}. */
9
+ export type StagehandBrowserPool = BrowserPool<{
10
+ browserPlugins: [StagehandPlugin];
11
+ }, [StagehandPlugin]>;
12
+ export interface StagehandBrowserPoolOptions extends Omit<BrowserPoolOptions, 'browserPlugins'>, BrowserPoolHooks<ReturnType<StagehandPlugin['createController']>, ReturnType<StagehandPlugin['createLaunchContext']>, Page> {
13
+ /** How to launch the browser: which Playwright browser type, proxy, user data dir, ... */
14
+ launchContext?: StagehandLaunchContext;
15
+ /** Stagehand configuration for the AI behavior and Browserbase integration. */
16
+ stagehandOptions?: StagehandOptions;
17
+ /**
18
+ * Whether to run the browser in headless mode. Shorthand for `launchContext.launchOptions.headless`.
19
+ * Defaults to `true`, and can also be set via {@link Configuration}.
20
+ */
21
+ headless?: boolean;
22
+ /** Configuration to read the browser defaults from. Defaults to the global configuration. */
23
+ configuration?: Configuration;
24
+ }
25
+ /**
26
+ * Builds a {@link BrowserPool} of Stagehand browsers to pass to a {@link StagehandCrawler} as its
27
+ * {@link BrowserCrawlerOptions.browserPool|`browserPool`}.
28
+ *
29
+ * It accepts every {@link BrowserPoolOptions|`BrowserPool` option} plus the crawler's own `launchContext`,
30
+ * `stagehandOptions` and `headless`, and derives the browser plugin from them - so a pool built here always
31
+ * matches the crawler it is given to, and configuring one never means assembling a {@link StagehandPlugin}
32
+ * by hand.
33
+ *
34
+ * **Example usage:**
35
+ *
36
+ * ```javascript
37
+ * const crawler = new StagehandCrawler({
38
+ * browserPool: stagehandBrowserPool({
39
+ * maxOpenPagesPerBrowser: 1,
40
+ * stagehandOptions: { env: 'LOCAL', model: 'openai/gpt-4.1-mini' },
41
+ * }),
42
+ * requestHandler: async ({ page }) => { ... },
43
+ * });
44
+ * ```
45
+ *
46
+ * The returned pool is *not* torn down by the crawler, which is what makes it shareable between crawlers.
47
+ *
48
+ * @category Browser management
49
+ */
50
+ export declare function stagehandBrowserPool(options?: StagehandBrowserPoolOptions): StagehandBrowserPool;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stagehandBrowserPool = stagehandBrowserPool;
4
+ const stagehand_launcher_js_1 = require("./stagehand-launcher.js");
5
+ /**
6
+ * Builds a {@link BrowserPool} of Stagehand browsers to pass to a {@link StagehandCrawler} as its
7
+ * {@link BrowserCrawlerOptions.browserPool|`browserPool`}.
8
+ *
9
+ * It accepts every {@link BrowserPoolOptions|`BrowserPool` option} plus the crawler's own `launchContext`,
10
+ * `stagehandOptions` and `headless`, and derives the browser plugin from them - so a pool built here always
11
+ * matches the crawler it is given to, and configuring one never means assembling a {@link StagehandPlugin}
12
+ * by hand.
13
+ *
14
+ * **Example usage:**
15
+ *
16
+ * ```javascript
17
+ * const crawler = new StagehandCrawler({
18
+ * browserPool: stagehandBrowserPool({
19
+ * maxOpenPagesPerBrowser: 1,
20
+ * stagehandOptions: { env: 'LOCAL', model: 'openai/gpt-4.1-mini' },
21
+ * }),
22
+ * requestHandler: async ({ page }) => { ... },
23
+ * });
24
+ * ```
25
+ *
26
+ * The returned pool is *not* torn down by the crawler, which is what makes it shareable between crawlers.
27
+ *
28
+ * @category Browser management
29
+ */
30
+ function stagehandBrowserPool(options = {}) {
31
+ const { launchContext, stagehandOptions, headless, configuration, ...poolOptions } = options;
32
+ return stagehandLauncher(launchContext, stagehandOptions, headless, configuration).createBrowserPool(poolOptions);
33
+ }
34
+ function stagehandLauncher(launchContext = {}, stagehandOptions = {}, headless, configuration) {
35
+ return new stagehand_launcher_js_1.StagehandLauncher({
36
+ ...launchContext,
37
+ stagehandOptions,
38
+ ...(headless == null ? {} : { launchOptions: { ...launchContext.launchOptions, headless } }),
39
+ }, configuration);
40
+ }
@@ -3,7 +3,7 @@ import { BrowserController } from '@crawlee/browser-pool';
3
3
  import type { Cookie } from '@crawlee/types';
4
4
  // @ts-ignore optional peer dependency or compatibility with es2022
5
5
  import type { Browser as PlaywrightBrowser, BrowserType, LaunchOptions, Page } from 'playwright';
6
- import type { StagehandPlugin } from './stagehand-plugin';
6
+ import type { StagehandPlugin } from './stagehand-plugin.js';
7
7
  /**
8
8
  * StagehandController manages the lifecycle of a Stagehand-controlled browser for Crawlee's BrowserPool.
9
9
  *
@@ -18,8 +18,7 @@ import type { StagehandPlugin } from './stagehand-plugin';
18
18
  * @ignore
19
19
  */
20
20
  export declare class StagehandController extends BrowserController<BrowserType, LaunchOptions, PlaywrightBrowser> {
21
- private stagehand;
22
- private readonly stagehandInstances;
21
+ #private;
23
22
  constructor(browserPlugin: StagehandPlugin, stagehandInstances: WeakMap<PlaywrightBrowser, Stagehand>);
24
23
  /**
25
24
  * Gets the Stagehand instance associated with this controller's browser.
@@ -53,4 +52,3 @@ export declare class StagehandController extends BrowserController<BrowserType,
53
52
  */
54
53
  protected _kill(): Promise<void>;
55
54
  }
56
- //# sourceMappingURL=stagehand-controller.d.ts.map
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StagehandController = void 0;
4
- const tslib_1 = require("tslib");
5
4
  const browser_pool_1 = require("@crawlee/browser-pool");
6
- const log_1 = tslib_1.__importDefault(require("@apify/log"));
5
+ const core_1 = require("@crawlee/core");
6
+ const utils_1 = require("@crawlee/utils");
7
7
  /**
8
8
  * StagehandController manages the lifecycle of a Stagehand-controlled browser for Crawlee's BrowserPool.
9
9
  *
@@ -18,23 +18,23 @@ const log_1 = tslib_1.__importDefault(require("@apify/log"));
18
18
  * @ignore
19
19
  */
20
20
  class StagehandController extends browser_pool_1.BrowserController {
21
- stagehand = null;
22
- stagehandInstances;
21
+ #stagehand = null;
22
+ #stagehandInstances;
23
23
  constructor(browserPlugin, stagehandInstances) {
24
24
  super(browserPlugin);
25
- this.stagehandInstances = stagehandInstances;
25
+ this.#stagehandInstances = stagehandInstances;
26
26
  }
27
27
  /**
28
28
  * Gets the Stagehand instance associated with this controller's browser.
29
29
  */
30
30
  getStagehand() {
31
- if (!this.stagehand) {
32
- this.stagehand = this.stagehandInstances.get(this.browser);
33
- if (!this.stagehand) {
31
+ if (!this.#stagehand) {
32
+ this.#stagehand = this.#stagehandInstances.get(this.browser);
33
+ if (!this.#stagehand) {
34
34
  throw new Error('Stagehand instance not found for browser');
35
35
  }
36
36
  }
37
- return this.stagehand;
37
+ return this.#stagehand;
38
38
  }
39
39
  /**
40
40
  * Creates a new page using the browser's default context.
@@ -51,8 +51,15 @@ class StagehandController extends browser_pool_1.BrowserController {
51
51
  const page = await context.newPage();
52
52
  // Track active pages
53
53
  page.once('close', () => {
54
- this.activePages--;
54
+ this.registerPageClosed(page);
55
55
  });
56
+ try {
57
+ await this.#waitForStagehandToRegisterPage(page);
58
+ }
59
+ catch (error) {
60
+ await page.close().catch(() => { });
61
+ throw error;
62
+ }
56
63
  return page;
57
64
  }
58
65
  catch (error) {
@@ -61,6 +68,42 @@ class StagehandController extends browser_pool_1.BrowserController {
61
68
  });
62
69
  }
63
70
  }
71
+ /**
72
+ * Waits until Stagehand knows about the page, so that `act()`/`extract()`/`observe()` can resolve it.
73
+ *
74
+ * Stagehand only learns about pages from CDP `Target.attachedToTarget` events on its own connection,
75
+ * and it maps them by main frame id. We create pages through a separate `connectOverCDP()` handle, so
76
+ * `context.newPage()` resolves before Stagehand has processed that event — the page is unresolvable for
77
+ * a short window, and the AI methods fail with 'Failed to resolve V3 Page from Playwright page'.
78
+ * Stagehand's own `newPage()` polls for the same reason.
79
+ */
80
+ async #waitForStagehandToRegisterPage(page, timeoutMs = 10_000) {
81
+ const stagehand = this.getStagehand();
82
+ const mainFrameId = await this.#getMainFrameId(page);
83
+ const deadline = Date.now() + timeoutMs;
84
+ while (Date.now() < deadline) {
85
+ if (stagehand.context.resolvePageByMainFrameId(mainFrameId)) {
86
+ return;
87
+ }
88
+ await (0, utils_1.sleep)(25);
89
+ }
90
+ // Stagehand skips registration entirely when it cannot install its helper script into the page's CDP
91
+ // session, so this is not always just a slow attach - it can never resolve.
92
+ throw new Error(`Stagehand did not register the page within ${timeoutMs}ms`);
93
+ }
94
+ /**
95
+ * Reads the page's main frame id, which is the key Stagehand resolves pages by.
96
+ */
97
+ async #getMainFrameId(page) {
98
+ const cdpSession = await page.context().newCDPSession(page);
99
+ try {
100
+ const { frameTree } = await cdpSession.send('Page.getFrameTree');
101
+ return frameTree.frame.id;
102
+ }
103
+ finally {
104
+ await cdpSession.detach().catch(() => { });
105
+ }
106
+ }
64
107
  /**
65
108
  * Normalizes proxy options for Playwright.
66
109
  */
@@ -116,7 +159,7 @@ class StagehandController extends browser_pool_1.BrowserController {
116
159
  await stagehand.close();
117
160
  }
118
161
  catch (error) {
119
- log_1.default.error('Error closing Stagehand', { error });
162
+ core_1.serviceLocator.getLogger().error('Error closing Stagehand', { error });
120
163
  }
121
164
  }
122
165
  /**
@@ -133,4 +176,3 @@ class StagehandController extends browser_pool_1.BrowserController {
133
176
  }
134
177
  }
135
178
  exports.StagehandController = StagehandController;
136
- //# sourceMappingURL=stagehand-controller.js.map