apify-client 3.0.0-beta.13 → 3.0.0-beta.15

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.
@@ -1,7 +1,7 @@
1
1
  import axios, { AxiosHeaders } from 'axios';
2
2
  import contentTypeParser from 'content-type';
3
3
  import { maybeParseBody } from './body_parser.js';
4
- import { isNode, maybeCompressValue } from './utils.js';
4
+ import { isCompressibleContentType, isNode, maybeCompressValue } from './utils.js';
5
5
  /**
6
6
  * This error exists for the quite common situation, where only a partial JSON response is received and
7
7
  * an attempt to parse the JSON throws an error. In most cases this can be resolved by retrying the
@@ -20,6 +20,16 @@ export class InvalidResponseBodyError extends Error {
20
20
  this.cause = cause;
21
21
  }
22
22
  }
23
+ /**
24
+ * Reads a request header regardless of the casing it was set with, since HTTP header names are case-insensitive
25
+ * while the config keeps whatever casing the caller used.
26
+ */
27
+ function getHeader(config, name) {
28
+ const wanted = name.toLowerCase();
29
+ const key = Object.keys(config.headers ?? {}).find((candidate) => candidate.toLowerCase() === wanted);
30
+ const value = key === undefined ? undefined : config.headers?.[key];
31
+ return typeof value === 'string' ? value : undefined;
32
+ }
23
33
  function serializeRequest(config) {
24
34
  const [defaultTransform] = axios.defaults.transformRequest;
25
35
  // The function not only serializes data, but it also adds correct headers.
@@ -30,9 +40,9 @@ function serializeRequest(config) {
30
40
  // it's a small price to pay. The axios default transform does a lot
31
41
  // of body type checks and we would have to copy all of them to the resource clients.
32
42
  if (config.stringifyFunctions) {
33
- const contentTypeHeader = config.headers?.['Content-Type'] || config.headers?.['content-type'];
43
+ const contentTypeHeader = getHeader(config, 'content-type');
34
44
  try {
35
- const { type } = contentTypeParser.parse(contentTypeHeader);
45
+ const type = contentTypeHeader ? contentTypeParser.parse(contentTypeHeader).type : undefined;
36
46
  if (type === 'application/json' && typeof config.data === 'object') {
37
47
  config.data = stringifyWithFunctions(config.data);
38
48
  }
@@ -65,7 +75,10 @@ function stringifyWithFunctions(obj) {
65
75
  });
66
76
  }
67
77
  async function maybeCompressRequest(config) {
68
- if (config.headers?.['content-encoding'])
78
+ // A caller-supplied encoding means the body is already encoded and the header describes it, so leave both alone.
79
+ if (getHeader(config, 'content-encoding'))
80
+ return config;
81
+ if (!isCompressibleContentType(getHeader(config, 'content-type')))
69
82
  return config;
70
83
  const maybeCompressed = await maybeCompressValue(config.data);
71
84
  if (maybeCompressed) {
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { createStorageContentSignatureAsync } from '@apify/utilities';
3
3
  import { DEFAULT_TIMEOUT_MILLIS, MEDIUM_TIMEOUT_MILLIS, ResourceClient, SMALL_TIMEOUT_MILLIS, } from '../base/resource_client.js';
4
4
  import * as schemas from '../schemas.js';
5
- import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, } from '../utils.js';
5
+ import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, SCANNED_COUNT, } from '../utils.js';
6
6
  // A predicate, not a `z.object()` arm, which would walk and copy every key of every pushed item.
7
7
  const itemSchema = z.custom(isNonArrayObject, 'Expected an object');
8
8
  const listItemsOptionsSchema = z.strictObject({
@@ -350,15 +350,21 @@ export class DatasetClient extends ResourceClient {
350
350
  return createdItemsPublicUrl.toString();
351
351
  }
352
352
  _createPaginationList(response, userProvidedDesc) {
353
- return {
353
+ const page = {
354
354
  items: response.data,
355
355
  total: Number(response.headers['x-apify-pagination-total']),
356
356
  offset: Number(response.headers['x-apify-pagination-offset']),
357
- count: response.data.length, // because x-apify-pagination-count returns invalid values when hidden/empty items are skipped
357
+ // `x-apify-pagination-count` reports the rows scanned, which filters and `unwind` can leave above or below
358
+ // the items returned.
359
+ count: response.data.length,
358
360
  limit: Number(response.headers['x-apify-pagination-limit']), // API returns 999999999999 when no limit is used
359
361
  // TODO: Replace this once https://github.com/apify/apify-core/issues/3503 is solved
360
362
  desc: JSON.parse(response.headers['x-apify-pagination-desc'] ?? userProvidedDesc),
361
363
  };
364
+ // The offset iterator paginates by the scanned number, so it travels with the page outside its public shape.
365
+ return Object.defineProperty(page, SCANNED_COUNT, {
366
+ value: Number(response.headers['x-apify-pagination-count']) || 0,
367
+ });
362
368
  }
363
369
  }
364
370
  /**
@@ -190,6 +190,11 @@ export declare class KeyValueStoreClient extends ResourceClient {
190
190
  * - Objects: `'application/json; charset=utf-8'`
191
191
  * - Strings: `'text/plain; charset=utf-8'`
192
192
  * - Binary values and streams: `'application/octet-stream'`
193
+ *
194
+ * Worth setting for media and archives: the client skips compressing a body
195
+ * whose content type already carries its own compression. The
196
+ * `'application/octet-stream'` fallback is treated as compressible, because
197
+ * it could hold any binary data.
193
198
  * @param options - Storage options
194
199
  * @param options.timeoutSecs - Timeout for the upload in seconds. Default varies by value size.
195
200
  * @param options.doNotRetryTimeouts - If `true`, don't retry on timeout errors. Default is `false`.
@@ -340,6 +340,11 @@ export class KeyValueStoreClient extends ResourceClient {
340
340
  * - Objects: `'application/json; charset=utf-8'`
341
341
  * - Strings: `'text/plain; charset=utf-8'`
342
342
  * - Binary values and streams: `'application/octet-stream'`
343
+ *
344
+ * Worth setting for media and archives: the client skips compressing a body
345
+ * whose content type already carries its own compression. The
346
+ * `'application/octet-stream'` fallback is treated as compressible, because
347
+ * it could hold any binary data.
343
348
  * @param options - Storage options
344
349
  * @param options.timeoutSecs - Timeout for the upload in seconds. Default varies by value size.
345
350
  * @param options.doNotRetryTimeouts - If `true`, don't retry on timeout errors. Default is `false`.
package/dist/utils.d.ts CHANGED
@@ -79,6 +79,16 @@ export interface CompressedValue {
79
79
  data: Buffer;
80
80
  encoding: 'br' | 'gzip';
81
81
  }
82
+ /**
83
+ * Decides whether a request body with the given content type is worth compressing.
84
+ *
85
+ * Images, audio, video and archives already carry their own compression. Running them through brotli or gzip
86
+ * burns CPU, holds a second full copy of the body in memory, and usually produces output slightly larger than
87
+ * the input. Formats that are raw despite such a media type, for example `image/bmp` or `audio/wav`, are still
88
+ * compressed. A body with no content type is assumed to be compressible.
89
+ * @internal
90
+ */
91
+ export declare function isCompressibleContentType(contentType?: string): boolean;
82
92
  /**
83
93
  * Compress the passed value using brotli, falling back to gzip. Returns undefined if the data is
84
94
  * too small / wrong type, or if neither algorithm is available.
@@ -174,6 +184,16 @@ export interface PaginatedList<Data> extends PaginatedResponse<Data> {
174
184
  /** Should the results be in descending order. */
175
185
  desc: boolean;
176
186
  }
187
+ /**
188
+ * Key under which a page of dataset items carries the number of rows the API scanned to produce it, as a
189
+ * non-enumerable property that stays out of the page's public shape. The API applies `offset` and `limit` to the
190
+ * dataset's rows first and shapes the result afterwards: filters (`clean`, `skipEmpty`, `skipHidden`) drop items and
191
+ * `unwind` splits or drops them, so `items.length` can land on either side of the rows scanned. The
192
+ * `x-apify-pagination-count` header reports the scanned number, and the offset iterator advances and terminates by it
193
+ * alone. A page without the property falls back to `items.length`.
194
+ * @internal
195
+ */
196
+ export declare const SCANNED_COUNT: unique symbol;
177
197
  /**
178
198
  * Type representing both a Promise of a paginated list and an async iterable.
179
199
  *
package/dist/utils.js CHANGED
@@ -5,6 +5,51 @@ import { ResponseValidationError } from './response_validation_error.js';
5
5
  // @ts-ignore if we enable `resolveJsonModule`, we end up with a `src` folder in `dist`
6
6
  import packageJson from '../package.json' with { type: 'json' };
7
7
  const MIN_COMPRESS_BYTES = 1024;
8
+ /** Media type prefixes whose payloads carry their own compression, so compressing the request body is wasted work. */
9
+ const ALREADY_COMPRESSED_MEDIA_TYPE_PREFIXES = ['audio/', 'image/', 'video/'];
10
+ /** Exact media types whose payloads carry their own compression. */
11
+ const ALREADY_COMPRESSED_MEDIA_TYPES = new Set([
12
+ 'application/epub+zip',
13
+ 'application/gzip',
14
+ 'application/java-archive',
15
+ 'application/vnd.android.package-archive',
16
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
17
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
18
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
19
+ 'application/vnd.rar',
20
+ 'application/x-7z-compressed',
21
+ 'application/x-bzip',
22
+ 'application/x-bzip2',
23
+ 'application/x-gzip',
24
+ 'application/x-rar-compressed',
25
+ 'application/x-xz',
26
+ 'application/x-zip-compressed',
27
+ 'application/zip',
28
+ 'application/zstd',
29
+ 'font/woff',
30
+ 'font/woff2',
31
+ ]);
32
+ /** Uncompressed media types that sit under an already-compressed prefix, so compressing them still pays off. */
33
+ const COMPRESSIBLE_MEDIA_TYPES = new Set([
34
+ 'audio/aiff',
35
+ 'audio/basic',
36
+ 'audio/l16',
37
+ 'audio/l24',
38
+ 'audio/midi',
39
+ 'audio/vnd.wave',
40
+ 'audio/wav',
41
+ 'audio/wave',
42
+ 'audio/x-aiff',
43
+ 'audio/x-wav',
44
+ 'image/bmp',
45
+ 'image/tiff',
46
+ 'image/vnd.adobe.photoshop',
47
+ 'image/vnd.microsoft.icon',
48
+ 'image/x-icon',
49
+ 'image/x-ms-bmp',
50
+ ]);
51
+ /** Structured syntax suffixes marking a media type as text even under an already-compressed prefix (`image/svg+xml`). */
52
+ const COMPRESSIBLE_MEDIA_TYPE_SUFFIXES = ['+json', '+xml'];
8
53
  export { parseArgument };
9
54
  /**
10
55
  * Accepts any non-null, non-array object as a predicate for `z.custom()`.
@@ -162,6 +207,28 @@ async function gzipValue(value) {
162
207
  }
163
208
  return gzipPromisified(value);
164
209
  }
210
+ /**
211
+ * Decides whether a request body with the given content type is worth compressing.
212
+ *
213
+ * Images, audio, video and archives already carry their own compression. Running them through brotli or gzip
214
+ * burns CPU, holds a second full copy of the body in memory, and usually produces output slightly larger than
215
+ * the input. Formats that are raw despite such a media type, for example `image/bmp` or `audio/wav`, are still
216
+ * compressed. A body with no content type is assumed to be compressible.
217
+ * @internal
218
+ */
219
+ export function isCompressibleContentType(contentType) {
220
+ if (!contentType)
221
+ return true;
222
+ // `Content-Type` is case-insensitive and may carry parameters, for example `text/plain; charset=utf-8`.
223
+ const mediaType = contentType.split(';', 1)[0].trim().toLowerCase();
224
+ if (COMPRESSIBLE_MEDIA_TYPES.has(mediaType))
225
+ return true;
226
+ if (COMPRESSIBLE_MEDIA_TYPE_SUFFIXES.some((suffix) => mediaType.endsWith(suffix)))
227
+ return true;
228
+ if (ALREADY_COMPRESSED_MEDIA_TYPES.has(mediaType))
229
+ return false;
230
+ return !ALREADY_COMPRESSED_MEDIA_TYPE_PREFIXES.some((prefix) => mediaType.startsWith(prefix));
231
+ }
165
232
  /**
166
233
  * Compress the passed value using brotli, falling back to gzip. Returns undefined if the data is
167
234
  * too small / wrong type, or if neither algorithm is available.
@@ -290,6 +357,16 @@ export const paginationOptionsShape = {
290
357
  offset: z.number().min(0).optional(),
291
358
  chunkSize: z.number().positive().optional(),
292
359
  };
360
+ /**
361
+ * Key under which a page of dataset items carries the number of rows the API scanned to produce it, as a
362
+ * non-enumerable property that stays out of the page's public shape. The API applies `offset` and `limit` to the
363
+ * dataset's rows first and shapes the result afterwards: filters (`clean`, `skipEmpty`, `skipHidden`) drop items and
364
+ * `unwind` splits or drops them, so `items.length` can land on either side of the rows scanned. The
365
+ * `x-apify-pagination-count` header reports the scanned number, and the offset iterator advances and terminates by it
366
+ * alone. A page without the property falls back to `items.length`.
367
+ * @internal
368
+ */
369
+ export const SCANNED_COUNT = Symbol('scannedCount');
293
370
  export function cast(input) {
294
371
  return input;
295
372
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify-client",
3
- "version": "3.0.0-beta.13",
3
+ "version": "3.0.0-beta.15",
4
4
  "description": "Apify API client for JavaScript",
5
5
  "engines": {
6
6
  "node": ">=22.0.0"