apify 3.7.3-beta.97 → 4.0.0-beta.101

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.
Files changed (51) hide show
  1. package/README.md +1 -1
  2. package/dist/actor.d.ts +379 -139
  3. package/dist/actor.js +764 -500
  4. package/dist/apify_dataset_backend.d.ts +19 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +23 -0
  9. package/dist/apify_key_value_store_backend.js +56 -0
  10. package/dist/apify_request_queue_backend.d.ts +78 -0
  11. package/dist/apify_request_queue_backend.js +114 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +193 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +256 -0
  16. package/dist/apify_storage_backend.d.ts +90 -0
  17. package/dist/apify_storage_backend.js +210 -0
  18. package/dist/charging.d.ts +39 -44
  19. package/dist/charging.js +237 -293
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +105 -0
  22. package/dist/child_run_tracker.d.ts +88 -0
  23. package/dist/child_run_tracker.js +239 -0
  24. package/dist/configuration.d.ts +85 -144
  25. package/dist/configuration.js +138 -174
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +10 -4
  33. package/dist/index.js +12 -22
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/input-schemas.js +12 -18
  36. package/dist/platform_event_manager.d.ts +15 -10
  37. package/dist/platform_event_manager.js +193 -63
  38. package/dist/proxy_configuration.d.ts +52 -72
  39. package/dist/proxy_configuration.js +176 -221
  40. package/dist/smart_apify_storage_backend.d.ts +52 -0
  41. package/dist/smart_apify_storage_backend.js +73 -0
  42. package/dist/storage.d.ts +6 -24
  43. package/dist/storage.js +1 -79
  44. package/dist/utils.d.ts +30 -0
  45. package/dist/utils.js +81 -23
  46. package/package.json +38 -43
  47. package/dist/index.mjs +0 -19
  48. package/dist/key_value_store.d.ts +0 -16
  49. package/dist/key_value_store.js +0 -40
  50. package/dist/patched_apify_client.d.ts +0 -25
  51. package/dist/patched_apify_client.js +0 -75
@@ -1,21 +1,24 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ProxyConfiguration = void 0;
4
- const tslib_1 = require("tslib");
5
- const core_1 = require("@crawlee/core");
6
- const utils_1 = require("@crawlee/utils");
7
- const ow_1 = tslib_1.__importDefault(require("ow"));
8
- const consts_1 = require("@apify/consts");
9
- const utilities_1 = require("@apify/utilities");
10
- const actor_js_1 = require("./actor.js");
11
- const configuration_js_1 = require("./configuration.js");
12
- // https://docs.apify.com/proxy/datacenter-proxy#username-parameters
13
- const MAX_SESSION_ID_LENGTH = 50;
14
- const CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS = 4000;
1
+ import { once } from 'node:events';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { json } from 'node:stream/consumers';
4
+ import { ProxyConfiguration as CoreProxyConfiguration } from '@crawlee/core';
5
+ import { z } from 'zod';
6
+ import { APIFY_ENV_VARS, APIFY_PROXY_VALUE_REGEX } from '@apify/consts';
7
+ import defaultLog from '@apify/log';
8
+ import { cryptoRandomObjectId } from '@apify/utilities';
9
+ import { parseArgument } from '@apify/validations';
10
+ import { Actor } from './actor.js';
11
+ import { Configuration } from './configuration.js';
12
+ const CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS = 4_000;
15
13
  const CHECK_ACCESS_MAX_ATTEMPTS = 2;
16
14
  const COUNTRY_CODE_REGEX = /^[A-Z]{2}$/;
17
15
  // ISO 3166-2 subdivision codes are 1–3 uppercase alphanumeric characters, e.g. 'CA' (California), 'NSW' (New South Wales), '9' (Wien, AT-9)
18
16
  const SUBDIVISION_CODE_REGEX = /^[A-Z0-9]{1,3}$/;
17
+ // Apify Proxy session identifier embedded in the proxy username — opaque to
18
+ // users; a fresh one is minted for every URL the SDK hands out so that the
19
+ // returned proxy URLs are independent.
20
+ const SESSION_ID_LENGTH = 12;
21
+ const SESSION_USERNAME_REGEX = /(?:^|,)session-[^,]+/;
19
22
  /**
20
23
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
21
24
  * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -49,109 +52,63 @@ const SUBDIVISION_CODE_REGEX = /^[A-Z0-9]{1,3}$/;
49
52
  * ```
50
53
  * @category Scaling
51
54
  */
52
- class ProxyConfiguration extends core_1.ProxyConfiguration {
55
+ export class ProxyConfiguration extends CoreProxyConfiguration {
56
+ configuration;
57
+ #groups;
58
+ #countryCode;
59
+ #subdivisionCode;
60
+ #password;
61
+ #hostname;
62
+ #port;
63
+ #usesApifyProxy;
64
+ #checkAccess;
65
+ log = defaultLog.child({ prefix: 'ProxyConfiguration' });
53
66
  /**
54
67
  * @internal
55
68
  */
56
- constructor(options = {}, config = configuration_js_1.Configuration.getGlobalConfig()) {
69
+ constructor(options = {}, configuration = Configuration.getGlobalConfiguration()) {
57
70
  const { proxyUrls, newUrlFunction, ...rest } = options;
58
71
  super({
59
72
  proxyUrls,
60
73
  newUrlFunction,
61
74
  ['validateRequired']: false,
62
75
  });
63
- Object.defineProperty(this, "config", {
64
- enumerable: true,
65
- configurable: true,
66
- writable: true,
67
- value: config
68
- });
69
- Object.defineProperty(this, "groups", {
70
- enumerable: true,
71
- configurable: true,
72
- writable: true,
73
- value: void 0
74
- });
75
- Object.defineProperty(this, "countryCode", {
76
- enumerable: true,
77
- configurable: true,
78
- writable: true,
79
- value: void 0
80
- });
81
- Object.defineProperty(this, "subdivisionCode", {
82
- enumerable: true,
83
- configurable: true,
84
- writable: true,
85
- value: void 0
86
- });
87
- Object.defineProperty(this, "password", {
88
- enumerable: true,
89
- configurable: true,
90
- writable: true,
91
- value: void 0
92
- });
93
- Object.defineProperty(this, "hostname", {
94
- enumerable: true,
95
- configurable: true,
96
- writable: true,
97
- value: void 0
98
- });
99
- Object.defineProperty(this, "port", {
100
- enumerable: true,
101
- configurable: true,
102
- writable: true,
103
- value: void 0
104
- });
105
- Object.defineProperty(this, "usesApifyProxy", {
106
- enumerable: true,
107
- configurable: true,
108
- writable: true,
109
- value: void 0
110
- });
111
- Object.defineProperty(this, "checkAccess", {
112
- enumerable: true,
113
- configurable: true,
114
- writable: true,
115
- value: void 0
116
- });
117
- (0, ow_1.default)(rest, ow_1.default.object.partialShape({
118
- groups: ow_1.default.optional.array.ofType(ow_1.default.string.matches(consts_1.APIFY_PROXY_VALUE_REGEX)),
119
- apifyProxyGroups: ow_1.default.optional.array.ofType(ow_1.default.string.matches(consts_1.APIFY_PROXY_VALUE_REGEX)),
120
- countryCode: ow_1.default.optional.string.matches(COUNTRY_CODE_REGEX),
121
- apifyProxyCountry: ow_1.default.optional.string.matches(COUNTRY_CODE_REGEX),
122
- subdivisionCode: ow_1.default.optional.string.matches(SUBDIVISION_CODE_REGEX),
123
- apifyProxySubdivision: ow_1.default.optional.string.matches(SUBDIVISION_CODE_REGEX),
124
- password: ow_1.default.optional.string,
125
- tieredProxyUrls: ow_1.default.optional.array.ofType(ow_1.default.array.ofType(ow_1.default.string)),
126
- tieredProxyConfig: ow_1.default.optional.array.ofType(ow_1.default.object),
127
- }));
128
- const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, subdivisionCode, apifyProxySubdivision, password = config.get('proxyPassword'), tieredProxyConfig, tieredProxyUrls, } = options;
129
- this.tieredProxyUrls ?? (this.tieredProxyUrls = tieredProxyUrls);
130
- if (tieredProxyConfig) {
131
- this.tieredProxyUrls = this._generateTieredProxyUrls(tieredProxyConfig, options);
132
- }
76
+ this.configuration = configuration;
77
+ parseArgument(rest, z
78
+ .object({
79
+ groups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
80
+ apifyProxyGroups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
81
+ countryCode: z.string().regex(COUNTRY_CODE_REGEX).optional(),
82
+ apifyProxyCountry: z.string().regex(COUNTRY_CODE_REGEX).optional(),
83
+ subdivisionCode: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
84
+ apifyProxySubdivision: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
85
+ password: z.string().optional(),
86
+ checkAccess: z.boolean().optional(),
87
+ })
88
+ .strict());
89
+ const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, subdivisionCode, apifyProxySubdivision, password = configuration.proxyPassword, } = options;
133
90
  const groupsToUse = groups.length ? groups : apifyProxyGroups;
134
91
  const countryCodeToUse = countryCode || apifyProxyCountry;
135
92
  const subdivisionCodeToUse = subdivisionCode || apifyProxySubdivision;
136
- const hostname = config.get('proxyHostname');
137
- const port = config.get('proxyPort');
93
+ const hostname = configuration.proxyHostname;
94
+ const port = configuration.proxyPort;
95
+ // The Apify Proxy subdivision is expressed as part of the country
96
+ // username parameter (`country-US_CA`), so a country is required.
138
97
  if (subdivisionCodeToUse && !countryCodeToUse) {
139
98
  throw new Error('ProxyConfiguration: "subdivisionCode" requires "countryCode" to be set.');
140
99
  }
141
100
  // Validation
142
101
  if ((proxyUrls || newUrlFunction) && (groupsToUse.length || countryCodeToUse || subdivisionCodeToUse)) {
143
- this._throwCannotCombineCustomWithApify();
102
+ this.throwCannotCombineCustomWithApify();
144
103
  }
145
- if (proxyUrls && newUrlFunction)
146
- this._throwCannotCombineCustomMethods();
147
- this.groups = groupsToUse;
148
- this.countryCode = countryCodeToUse;
149
- this.subdivisionCode = subdivisionCodeToUse;
150
- this.password = password;
151
- this.hostname = hostname;
152
- this.port = port;
153
- this.usesApifyProxy = !this.proxyUrls && !this.newUrlFunction;
154
- this.checkAccess = options.checkAccess;
104
+ this.#groups = groupsToUse;
105
+ this.#countryCode = countryCodeToUse;
106
+ this.#subdivisionCode = subdivisionCodeToUse;
107
+ this.#password = password;
108
+ this.#hostname = hostname;
109
+ this.#port = port;
110
+ this.#usesApifyProxy = !proxyUrls && !newUrlFunction;
111
+ this.#checkAccess = options.checkAccess;
155
112
  if (proxyUrls && proxyUrls.some((url) => url?.includes('apify.com'))) {
156
113
  this.log.warning('Some Apify proxy features may work incorrectly. Please consider setting up Apify properties instead of `proxyUrls`.\n' +
157
114
  'See https://docs.apify.com/sdk/js/docs/concepts/proxy-management#apify-proxy-configuration');
@@ -164,156 +121,120 @@ class ProxyConfiguration extends core_1.ProxyConfiguration {
164
121
  *
165
122
  * You should use the {@link createProxyConfiguration} function to create a pre-initialized
166
123
  * `ProxyConfiguration` instance instead of calling this manually.
167
- *
168
- * As part of the init process, we verify the configuration by checking the proxy status endpoint.
169
- * This can make the init slower, to opt-out of this, use `checkAccess: false`.
170
124
  */
171
125
  async initialize(options) {
172
- if (this.usesApifyProxy) {
173
- if (!this.password) {
174
- await this._setPasswordIfToken();
126
+ if (this.#usesApifyProxy) {
127
+ if (!this.#password) {
128
+ await this.setPasswordIfToken();
175
129
  }
176
- if (!this.password) {
177
- if (actor_js_1.Actor.isAtHome()) {
178
- throw new Error(`Apify Proxy password must be provided using options.password or the "${consts_1.APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
179
- `You can also provide your Apify token via the "${consts_1.APIFY_ENV_VARS.TOKEN}" environment variable, ` +
180
- `so that the SDK can fetch the proxy password from Apify API, when ${consts_1.APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
130
+ if (!this.#password) {
131
+ if (Actor.isAtHome()) {
132
+ throw new Error(`Apify Proxy password must be provided using options.password or the "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
133
+ `You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
134
+ `so that the SDK can fetch the proxy password from Apify API, when ${APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
181
135
  }
182
136
  else {
183
137
  this.log.warning(`No proxy password or token detected, running without proxy. To use Apify Proxy locally, ` +
184
- `provide options.password or "${consts_1.APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
185
- `You can also provide your Apify token via the "${consts_1.APIFY_ENV_VARS.TOKEN}" environment variable, ` +
186
- `so that the SDK can fetch the proxy password from Apify API, when ${consts_1.APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
138
+ `provide options.password or "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
139
+ `You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
140
+ `so that the SDK can fetch the proxy password from Apify API, when ${APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
187
141
  }
188
142
  }
189
- if ((options?.checkAccess ?? this.checkAccess) !== false) {
190
- return this._checkAccess();
143
+ if ((options?.checkAccess ?? this.#checkAccess) !== false) {
144
+ return this.checkAccess();
191
145
  }
192
146
  }
193
147
  return true;
194
148
  }
195
149
  /**
196
- * This function creates a new {@link ProxyInfo} info object.
197
- * It is used by CheerioCrawler and PuppeteerCrawler to generate proxy URLs and also to allow the user to inspect
198
- * the currently used proxy via the requestHandler parameter `proxyInfo`.
199
- * Use it if you want to work with a rich representation of a proxy URL.
200
- * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
201
- * @param [sessionId]
202
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
203
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
204
- * When the provided sessionId is a number, it's converted to a string. Property sessionId of
205
- * {@link ProxyInfo} is always returned as a type string.
150
+ * Returns a new {@link ProxyInfo} object with a fresh proxy URL. Each call mints an
151
+ * independent URL; for Apify Proxy a random session id is embedded so consecutive
152
+ * calls resolve to different IPs.
206
153
  *
207
- * All the HTTP requests going through the proxy with the same session identifier
208
- * will use the same target proxy server (i.e. the same IP address).
209
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
210
- * @return Represents information about used proxy and its configuration.
154
+ * A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
155
+ * Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
156
+ * username and with it the proxy session.
211
157
  */
212
- async newProxyInfo(sessionId, options) {
213
- if (typeof sessionId === 'number')
214
- sessionId = `${sessionId}`;
215
- (0, ow_1.default)(sessionId, ow_1.default.optional.string.maxLength(MAX_SESSION_ID_LENGTH).matches(consts_1.APIFY_PROXY_VALUE_REGEX));
216
- const proxyInfo = await super.newProxyInfo(sessionId, options);
217
- if (!proxyInfo)
158
+ async newProxyInfo(proxyInfo) {
159
+ // Only Apify Proxy infos carry `groups` and a proxy session in the username.
160
+ if (proxyInfo &&
161
+ !(this.#usesApifyProxy && 'groups' in proxyInfo && SESSION_USERNAME_REGEX.test(proxyInfo.username ?? ''))) {
218
162
  return proxyInfo;
219
- const { groups, countryCode, subdivisionCode, password, port, hostname } = (this.usesApifyProxy ? this : new URL(proxyInfo.url));
220
- return {
221
- ...proxyInfo,
222
- sessionId,
223
- groups,
224
- countryCode,
225
- subdivisionCode,
226
- // this.password is not encoded, but the password from the URL will be, we need to normalize
227
- password: this.usesApifyProxy ? (password ?? '') : decodeURIComponent(password),
228
- hostname,
229
- port: port,
163
+ }
164
+ const url = proxyInfo?.username ? this.composeUrl(proxyInfo.username) : await this.newUrl();
165
+ if (!url)
166
+ return undefined;
167
+ const parsed = new URL(url);
168
+ const result = {
169
+ url,
170
+ username: decodeURIComponent(parsed.username),
171
+ password: decodeURIComponent(parsed.password),
172
+ hostname: parsed.hostname,
173
+ port: parsed.port,
230
174
  };
175
+ // A refreshed info keeps its own groups/country, which match its username rather than this config.
176
+ if (proxyInfo)
177
+ return { ...proxyInfo, ...result };
178
+ if (this.#usesApifyProxy) {
179
+ result.groups = this.#groups;
180
+ if (this.#countryCode !== undefined)
181
+ result.countryCode = this.#countryCode;
182
+ if (this.#subdivisionCode !== undefined)
183
+ result.subdivisionCode = this.#subdivisionCode;
184
+ }
185
+ return result;
231
186
  }
232
187
  /**
233
- * Returns a new proxy URL based on provided configuration options and the `sessionId` parameter.
234
- * @param [sessionId]
235
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
236
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
237
- * When the provided sessionId is a number, it's converted to a string.
238
- *
239
- * All the HTTP requests going through the proxy with the same session identifier
240
- * will use the same target proxy server (i.e. the same IP address).
241
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
242
- * @return A string with a proxy URL, including authentication credentials and port number.
243
- * For example, `http://bob:password123@proxy.example.com:8000`
188
+ * Returns a new proxy URL. For Apify Proxy, each call generates a URL with a fresh
189
+ * random session id, so consecutive calls return independent URLs. For custom
190
+ * `proxyUrls`, the URLs are rotated round-robin.
244
191
  */
245
- async newUrl(sessionId, options) {
246
- if (typeof sessionId === 'number')
247
- sessionId = `${sessionId}`;
248
- (0, ow_1.default)(sessionId, ow_1.default.optional.string.maxLength(MAX_SESSION_ID_LENGTH).matches(consts_1.APIFY_PROXY_VALUE_REGEX));
249
- if (this.newUrlFunction) {
250
- return ((await this._callNewUrlFunction(sessionId, {
251
- request: options?.request,
252
- })) ?? undefined);
192
+ async newUrl() {
193
+ if (!this.#usesApifyProxy) {
194
+ return super.newUrl();
253
195
  }
254
- if (this.proxyUrls) {
255
- return this._handleCustomUrl(sessionId) ?? undefined;
256
- }
257
- if (this.tieredProxyUrls) {
258
- return this._handleTieredUrl(sessionId ?? (0, utilities_1.cryptoRandomObjectId)(6), options).proxyUrl ?? undefined;
259
- }
260
- return this.composeDefaultUrl(sessionId);
261
- }
262
- _generateTieredProxyUrls(tieredProxyConfig, globalOptions) {
263
- return tieredProxyConfig.map((config) => [
264
- new ProxyConfiguration({
265
- ...globalOptions,
266
- ...config,
267
- tieredProxyConfig: undefined,
268
- }).composeDefaultUrl(),
269
- ]);
196
+ return this.composeDefaultUrl(cryptoRandomObjectId(SESSION_ID_LENGTH));
270
197
  }
271
198
  /**
272
199
  * Returns proxy username.
273
200
  */
274
- _getUsername(sessionId) {
275
- let username;
276
- const { groups, countryCode, subdivisionCode } = this;
201
+ getUsername(sessionId) {
277
202
  const parts = [];
278
- if (groups && groups.length) {
279
- parts.push(`groups-${groups.join('+')}`);
280
- }
281
- if (sessionId) {
282
- parts.push(`session-${sessionId}`);
203
+ if (this.#groups && this.#groups.length) {
204
+ parts.push(`groups-${this.#groups.join('+')}`);
283
205
  }
284
- if (subdivisionCode) {
285
- parts.push(`country-${countryCode}_${subdivisionCode}`);
206
+ parts.push(`session-${sessionId}`);
207
+ if (this.#subdivisionCode) {
208
+ parts.push(`country-${this.#countryCode}_${this.#subdivisionCode}`);
286
209
  }
287
- else if (countryCode) {
288
- parts.push(`country-${countryCode}`);
210
+ else if (this.#countryCode) {
211
+ parts.push(`country-${this.#countryCode}`);
289
212
  }
290
- username = parts.join(',');
291
- if (parts.length === 0)
292
- username = 'auto';
293
- return username;
213
+ return parts.join(',');
294
214
  }
295
215
  composeDefaultUrl(sessionId) {
296
- const username = this._getUsername(sessionId);
297
- const url = new URL(`http://${this.hostname}:${this.port}`);
216
+ return this.composeUrl(this.getUsername(sessionId));
217
+ }
218
+ composeUrl(username) {
219
+ const url = new URL(`http://${this.#hostname}:${this.#port}`);
298
220
  url.username = `${username}`;
299
- url.password = `${this.password}`;
221
+ url.password = `${this.#password}`;
300
222
  const urlString = url.toString();
301
223
  return urlString.substring(0, urlString.length - 1);
302
224
  }
303
225
  /**
304
226
  * Fetch & set the proxy password from Apify API if an Apify token is provided.
305
227
  */
306
- // TODO: Make this private
307
- async _setPasswordIfToken() {
308
- const token = this.config.get('token');
228
+ async setPasswordIfToken() {
229
+ const { token } = this.configuration;
309
230
  if (!token)
310
231
  return;
311
232
  try {
312
- const user = await actor_js_1.Actor.apifyClient.user().get();
313
- this.password = user.proxy?.password;
233
+ const user = await Actor.apifyClient.user().get();
234
+ this.#password = user?.proxy?.password;
314
235
  }
315
236
  catch (error) {
316
- if (actor_js_1.Actor.isAtHome()) {
237
+ if (Actor.isAtHome()) {
317
238
  throw error;
318
239
  }
319
240
  else {
@@ -328,14 +249,16 @@ class ProxyConfiguration extends core_1.ProxyConfiguration {
328
249
  * If the check can not be made, it only prints a warning and allows the program to continue. This is to
329
250
  * prevent program crashes caused by short downtimes of Proxy.
330
251
  */
331
- async _checkAccess() {
332
- const status = await this._fetchStatus();
252
+ async checkAccess() {
253
+ const status = await this.fetchStatus();
333
254
  if (!status) {
334
255
  this.log.warning('Apify Proxy access check timed out. Watch out for errors with status code 407. ' +
335
256
  "If you see some, it most likely means you don't have access to either all or some of the proxies you're trying to use.");
336
257
  return true;
337
258
  }
338
259
  const { connected, connectionError, isManInTheMiddle } = status;
260
+ // Declared `readonly false` on the base class; the status check is the one place that
261
+ // learns the actual value, so bypass the readonly marker.
339
262
  this.isManInTheMiddle = isManInTheMiddle;
340
263
  if (connected) {
341
264
  return true;
@@ -343,7 +266,7 @@ class ProxyConfiguration extends core_1.ProxyConfiguration {
343
266
  // Throw only on the platform, locally we just print a warning and run requests without the proxy.
344
267
  // This is because the user might not have set up things correctly yet.
345
268
  // It still fails on the platform, where we don't want to allow this behavior.
346
- if (actor_js_1.Actor.isAtHome()) {
269
+ if (Actor.isAtHome()) {
347
270
  throw new Error(connectionError);
348
271
  }
349
272
  this.log.warning(connectionError);
@@ -352,18 +275,16 @@ class ProxyConfiguration extends core_1.ProxyConfiguration {
352
275
  /**
353
276
  * Apify Proxy can be down for a second or a minute, but this should not crash processes.
354
277
  */
355
- async _fetchStatus() {
356
- const proxyStatusUrl = this.config.get('proxyStatusUrl', 'http://proxy.apify.com');
357
- const requestOpts = {
358
- url: `${proxyStatusUrl}/?format=json`,
359
- proxyUrl: await this.newUrl(),
360
- timeout: { request: CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS },
361
- responseType: 'json',
362
- };
278
+ async fetchStatus() {
279
+ const { proxyStatusUrl } = this.configuration;
280
+ const statusUrl = `${proxyStatusUrl}/?format=json`;
281
+ const proxyUrl = await this.newUrl();
282
+ // Without a proxy URL we can't perform the (proxied) status check.
283
+ if (!proxyUrl)
284
+ return undefined;
363
285
  for (let attempt = 1; attempt <= CHECK_ACCESS_MAX_ATTEMPTS; attempt++) {
364
286
  try {
365
- const response = await (0, utils_1.gotScraping)(requestOpts);
366
- return response.body;
287
+ return await this.requestStatus(statusUrl, proxyUrl);
367
288
  }
368
289
  catch {
369
290
  // retry connection errors
@@ -371,15 +292,49 @@ class ProxyConfiguration extends core_1.ProxyConfiguration {
371
292
  }
372
293
  return undefined;
373
294
  }
295
+ /**
296
+ * Fetches the Apify Proxy status endpoint once, *through* the proxy, so the
297
+ * response reports on this exact connection (auth + man-in-the-middle).
298
+ *
299
+ * Uses a native `node:http` forward-proxy request — an absolute request URL
300
+ * plus a `Proxy-Authorization` header — so no proxy-agent dependency is
301
+ * needed. The status endpoint (`http://proxy.apify.com`) is plain HTTP.
302
+ */
303
+ async requestStatus(statusUrl, proxyUrl) {
304
+ const target = new URL(statusUrl);
305
+ const proxy = new URL(proxyUrl);
306
+ const headers = { host: target.host };
307
+ if (proxy.username) {
308
+ const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
309
+ headers['proxy-authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`;
310
+ }
311
+ const request = httpRequest({
312
+ host: proxy.hostname,
313
+ port: proxy.port,
314
+ // Absolute-form request URI tells the proxy to forward the request.
315
+ path: target.href,
316
+ headers,
317
+ signal: AbortSignal.timeout(CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS),
318
+ });
319
+ request.end();
320
+ // `once` rejects if the request emits `error` first (connection refused,
321
+ // timeout/abort), so failures propagate to the retry loop in `fetchStatus`.
322
+ const [response] = (await once(request, 'response'));
323
+ const statusCode = response.statusCode ?? 0;
324
+ if (statusCode < 200 || statusCode >= 300) {
325
+ response.resume(); // drain so the socket can be freed
326
+ throw new Error(`Apify Proxy status check responded with status code ${statusCode}.`);
327
+ }
328
+ return (await json(response));
329
+ }
374
330
  /**
375
331
  * Throws cannot combine custom proxies with Apify Proxy
376
332
  * @internal
377
333
  */
378
- _throwCannotCombineCustomWithApify() {
334
+ throwCannotCombineCustomWithApify() {
379
335
  throw new Error('Cannot combine custom proxies with Apify Proxy! ' +
380
336
  'It is not allowed to set "options.proxyUrls" or "options.newUrlFunction" combined with ' +
381
337
  '"options.groups", "options.apifyProxyGroups", "options.countryCode", "options.apifyProxyCountry", ' +
382
338
  '"options.subdivisionCode" or "options.apifyProxySubdivision".');
383
339
  }
384
340
  }
385
- exports.ProxyConfiguration = ProxyConfiguration;
@@ -0,0 +1,52 @@
1
+ import type { DatasetBackend, KeyValueStoreBackend, RequestQueueBackend, StorageBackend, StorageIdentifier } from '@crawlee/types';
2
+ import type { StorageType } from './apify_storage_backend.js';
3
+ import type { Configuration } from './configuration.js';
4
+ import type { OpenStorageOptions } from './storage.js';
5
+ export interface SmartApifyStorageBackendOptions {
6
+ /** Used on the Apify platform, and locally for `forceCloud` storages. */
7
+ cloudStorageBackend: StorageBackend;
8
+ /** Used outside of the Apify platform, except for `forceCloud` storages. */
9
+ localStorageBackend: StorageBackend;
10
+ /** Supplies `isAtHome` and the token that cloud storage needs. */
11
+ configuration: Configuration;
12
+ }
13
+ /**
14
+ * Routes storages to Apify cloud storage or to a local one, depending on where the Actor runs.
15
+ *
16
+ * On the Apify platform (detected through the `APIFY_IS_AT_HOME` environment variable) storages are
17
+ * opened in the cloud; locally they are opened through `localStorageBackend`, unless `forceCloud`
18
+ * asks for the cloud one. `Actor` installs it; callers who want storages of their own pass a
19
+ * backend to `Actor.init({ storage })` instead.
20
+ *
21
+ * @internal
22
+ */
23
+ export declare class SmartApifyStorageBackend implements StorageBackend {
24
+ #private;
25
+ constructor(options: SmartApifyStorageBackendOptions);
26
+ /**
27
+ * The backend a storage is opened through: the cloud one on the platform or with `forceCloud`,
28
+ * the local one otherwise.
29
+ *
30
+ * Exposed so that `forceCloud` storages can be opened through the very same cloud backend
31
+ * instance this one delegates to — two instances would resolve run-scoped aliases to two
32
+ * separate storages.
33
+ */
34
+ getSuitableStorageBackend(options?: OpenStorageOptions): StorageBackend;
35
+ get stats(): {
36
+ rateLimitErrors: number[];
37
+ } | undefined;
38
+ /** Repeats crawlee's own fallback, so that routing a backend does not change how storages are cached. */
39
+ getStorageBackendCacheKey(): string;
40
+ createDatasetBackend(options?: StorageIdentifier): Promise<DatasetBackend>;
41
+ createKeyValueStoreBackend(options?: StorageIdentifier): Promise<KeyValueStoreBackend>;
42
+ createRequestQueueBackend(options?: StorageIdentifier): Promise<RequestQueueBackend>;
43
+ /**
44
+ * Declared unconditionally, unlike on the backends this one delegates to: crawlee branches on
45
+ * the presence of the three methods below, and delegating to a backend that lacks one is
46
+ * indistinguishable from not having it — a `false` from `storageExists` means the same as its
47
+ * absence (crawlee falls through to a name lookup), and the other two have no return value.
48
+ */
49
+ storageExists(id: string, type: StorageType): Promise<boolean>;
50
+ purge(): Promise<void>;
51
+ teardown(): Promise<void>;
52
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Routes storages to Apify cloud storage or to a local one, depending on where the Actor runs.
3
+ *
4
+ * On the Apify platform (detected through the `APIFY_IS_AT_HOME` environment variable) storages are
5
+ * opened in the cloud; locally they are opened through `localStorageBackend`, unless `forceCloud`
6
+ * asks for the cloud one. `Actor` installs it; callers who want storages of their own pass a
7
+ * backend to `Actor.init({ storage })` instead.
8
+ *
9
+ * @internal
10
+ */
11
+ export class SmartApifyStorageBackend {
12
+ #cloudStorageBackend;
13
+ #localStorageBackend;
14
+ #configuration;
15
+ constructor(options) {
16
+ this.#cloudStorageBackend = options.cloudStorageBackend;
17
+ this.#localStorageBackend = options.localStorageBackend;
18
+ this.#configuration = options.configuration;
19
+ }
20
+ /**
21
+ * The backend a storage is opened through: the cloud one on the platform or with `forceCloud`,
22
+ * the local one otherwise.
23
+ *
24
+ * Exposed so that `forceCloud` storages can be opened through the very same cloud backend
25
+ * instance this one delegates to — two instances would resolve run-scoped aliases to two
26
+ * separate storages.
27
+ */
28
+ getSuitableStorageBackend(options = {}) {
29
+ if (this.#configuration.isAtHome) {
30
+ return this.#cloudStorageBackend;
31
+ }
32
+ if (!options.forceCloud) {
33
+ return this.#localStorageBackend;
34
+ }
35
+ if (!this.#configuration.token) {
36
+ throw new Error('In order to use the Apify cloud storage from your computer, you need to provide an Apify token ' +
37
+ 'using the APIFY_TOKEN environment variable.');
38
+ }
39
+ return this.#cloudStorageBackend;
40
+ }
41
+ get stats() {
42
+ return this.getSuitableStorageBackend().stats;
43
+ }
44
+ /** Repeats crawlee's own fallback, so that routing a backend does not change how storages are cached. */
45
+ getStorageBackendCacheKey() {
46
+ const backend = this.getSuitableStorageBackend();
47
+ return backend.getStorageBackendCacheKey?.() ?? backend.constructor.name;
48
+ }
49
+ async createDatasetBackend(options) {
50
+ return await this.getSuitableStorageBackend().createDatasetBackend(options);
51
+ }
52
+ async createKeyValueStoreBackend(options) {
53
+ return await this.getSuitableStorageBackend().createKeyValueStoreBackend(options);
54
+ }
55
+ async createRequestQueueBackend(options) {
56
+ return await this.getSuitableStorageBackend().createRequestQueueBackend(options);
57
+ }
58
+ /**
59
+ * Declared unconditionally, unlike on the backends this one delegates to: crawlee branches on
60
+ * the presence of the three methods below, and delegating to a backend that lacks one is
61
+ * indistinguishable from not having it — a `false` from `storageExists` means the same as its
62
+ * absence (crawlee falls through to a name lookup), and the other two have no return value.
63
+ */
64
+ async storageExists(id, type) {
65
+ return (await this.getSuitableStorageBackend().storageExists?.(id, type)) ?? false;
66
+ }
67
+ async purge() {
68
+ await this.getSuitableStorageBackend().purge?.();
69
+ }
70
+ async teardown() {
71
+ await this.getSuitableStorageBackend().teardown?.();
72
+ }
73
+ }