apify-client 3.0.0-beta.1 → 3.0.0-beta.11

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 (94) hide show
  1. package/README.md +5 -3
  2. package/dist/apify_api_error.d.ts +59 -3
  3. package/dist/apify_api_error.js +71 -11
  4. package/dist/apify_client.d.ts +27 -27
  5. package/dist/apify_client.js +86 -91
  6. package/dist/base/api_client.d.ts +3 -3
  7. package/dist/base/api_client.js +6 -10
  8. package/dist/base/resource_client.d.ts +13 -4
  9. package/dist/base/resource_client.js +25 -21
  10. package/dist/base/resource_collection_client.d.ts +7 -6
  11. package/dist/base/resource_collection_client.js +11 -15
  12. package/dist/body_parser.js +6 -11
  13. package/dist/bundle.js +38 -48
  14. package/dist/bundle.js.map +1 -1
  15. package/dist/generated/api.d.ts +287 -214
  16. package/dist/generated/api.js +1 -2
  17. package/dist/generated/schemas.d.ts +6699 -0
  18. package/dist/generated/schemas.js +1521 -0
  19. package/dist/http_client.d.ts +2 -2
  20. package/dist/http_client.js +23 -28
  21. package/dist/index.d.ts +33 -32
  22. package/dist/index.js +32 -36
  23. package/dist/interceptors.d.ts +1 -1
  24. package/dist/interceptors.js +14 -19
  25. package/dist/lazy_schema.d.ts +8 -0
  26. package/dist/lazy_schema.js +11 -0
  27. package/dist/models.d.ts +33 -52
  28. package/dist/models.js +8 -11
  29. package/dist/resource_clients/actor.d.ts +13 -13
  30. package/dist/resource_clients/actor.js +70 -73
  31. package/dist/resource_clients/actor_collection.d.ts +10 -10
  32. package/dist/resource_clients/actor_collection.js +19 -20
  33. package/dist/resource_clients/actor_env_var.d.ts +3 -3
  34. package/dist/resource_clients/actor_env_var.js +7 -10
  35. package/dist/resource_clients/actor_env_var_collection.d.ts +11 -20
  36. package/dist/resource_clients/actor_env_var_collection.js +15 -19
  37. package/dist/resource_clients/actor_version.d.ts +16 -8
  38. package/dist/resource_clients/actor_version.js +15 -19
  39. package/dist/resource_clients/actor_version_collection.d.ts +13 -19
  40. package/dist/resource_clients/actor_version_collection.js +17 -19
  41. package/dist/resource_clients/build.d.ts +7 -5
  42. package/dist/resource_clients/build.js +16 -17
  43. package/dist/resource_clients/build_collection.d.ts +5 -5
  44. package/dist/resource_clients/build_collection.js +10 -13
  45. package/dist/resource_clients/dataset.d.ts +8 -8
  46. package/dist/resource_clients/dataset.js +75 -85
  47. package/dist/resource_clients/dataset_collection.d.ts +4 -4
  48. package/dist/resource_clients/dataset_collection.js +18 -21
  49. package/dist/resource_clients/key_value_store.d.ts +16 -8
  50. package/dist/resource_clients/key_value_store.js +61 -65
  51. package/dist/resource_clients/key_value_store_collection.d.ts +4 -4
  52. package/dist/resource_clients/key_value_store_collection.js +18 -21
  53. package/dist/resource_clients/log.d.ts +6 -4
  54. package/dist/resource_clients/log.js +23 -28
  55. package/dist/resource_clients/request_queue.d.ts +4 -11
  56. package/dist/resource_clients/request_queue.js +100 -106
  57. package/dist/resource_clients/request_queue_collection.d.ts +4 -4
  58. package/dist/resource_clients/request_queue_collection.js +16 -19
  59. package/dist/resource_clients/run.d.ts +18 -8
  60. package/dist/resource_clients/run.js +62 -54
  61. package/dist/resource_clients/run_collection.d.ts +4 -4
  62. package/dist/resource_clients/run_collection.js +15 -18
  63. package/dist/resource_clients/schedule.d.ts +8 -8
  64. package/dist/resource_clients/schedule.js +14 -23
  65. package/dist/resource_clients/schedule_collection.d.ts +4 -4
  66. package/dist/resource_clients/schedule_collection.js +13 -16
  67. package/dist/resource_clients/store_collection.d.ts +5 -5
  68. package/dist/resource_clients/store_collection.js +15 -18
  69. package/dist/resource_clients/task.d.ts +11 -11
  70. package/dist/resource_clients/task.js +49 -59
  71. package/dist/resource_clients/task_collection.d.ts +6 -6
  72. package/dist/resource_clients/task_collection.js +12 -15
  73. package/dist/resource_clients/user.d.ts +11 -11
  74. package/dist/resource_clients/user.js +16 -35
  75. package/dist/resource_clients/webhook.d.ts +8 -8
  76. package/dist/resource_clients/webhook.js +13 -23
  77. package/dist/resource_clients/webhook_collection.d.ts +4 -4
  78. package/dist/resource_clients/webhook_collection.js +13 -16
  79. package/dist/resource_clients/webhook_dispatch.d.ts +5 -5
  80. package/dist/resource_clients/webhook_dispatch.js +5 -9
  81. package/dist/resource_clients/webhook_dispatch_collection.d.ts +4 -4
  82. package/dist/resource_clients/webhook_dispatch_collection.js +10 -13
  83. package/dist/response_validation_error.d.ts +26 -0
  84. package/dist/response_validation_error.js +37 -0
  85. package/dist/schemas.d.ts +15 -0
  86. package/dist/schemas.js +15 -0
  87. package/dist/statistics.js +5 -9
  88. package/dist/timezones.js +1 -2
  89. package/dist/utils.d.ts +27 -24
  90. package/dist/utils.js +69 -93
  91. package/package.json +38 -40
  92. package/dist/argument_validation_error.d.ts +0 -17
  93. package/dist/argument_validation_error.js +0 -157
  94. package/dist/index.mjs +0 -42
@@ -1,12 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebhookDispatchCollectionClient = void 0;
4
- const zod_1 = require("zod");
5
- const resource_collection_client_1 = require("../base/resource_collection_client");
6
- const utils_1 = require("../utils");
7
- const listOptionsSchema = zod_1.z.strictObject({
8
- ...utils_1.paginationOptionsShape,
9
- desc: zod_1.z.boolean().optional(),
1
+ import { z } from 'zod';
2
+ import { ResourceCollectionClient } from '../base/resource_collection_client.js';
3
+ import * as schemas from '../schemas.js';
4
+ import { paginationOptionsShape, parseArgument } from '../utils.js';
5
+ const listOptionsSchema = z.strictObject({
6
+ ...paginationOptionsShape,
7
+ desc: z.boolean().optional(),
10
8
  });
11
9
  /**
12
10
  * Client for managing the collection of webhook dispatches.
@@ -26,7 +24,7 @@ const listOptionsSchema = zod_1.z.strictObject({
26
24
  *
27
25
  * @see https://docs.apify.com/platform/integrations/webhooks
28
26
  */
29
- class WebhookDispatchCollectionClient extends resource_collection_client_1.ResourceCollectionClient {
27
+ export class WebhookDispatchCollectionClient extends ResourceCollectionClient {
30
28
  /**
31
29
  * @hidden
32
30
  */
@@ -57,8 +55,7 @@ class WebhookDispatchCollectionClient extends resource_collection_client_1.Resou
57
55
  * @see https://docs.apify.com/api/v2/webhook-dispatches-get
58
56
  */
59
57
  list(options = {}) {
60
- const parsed = (0, utils_1.parseArgument)(options, listOptionsSchema, 'WebhookDispatchCollectionListOptions');
61
- return this._listPaginated(parsed);
58
+ const parsed = parseArgument(options, listOptionsSchema, 'WebhookDispatchCollectionListOptions');
59
+ return this._listPaginated(schemas.ListOfWebhookDispatches(), parsed);
62
60
  }
63
61
  }
64
- exports.WebhookDispatchCollectionClient = WebhookDispatchCollectionClient;
@@ -0,0 +1,26 @@
1
+ import type { z } from 'zod';
2
+ /**
3
+ * Thrown when an API response does not match the schema the client expects for it.
4
+ *
5
+ * The schemas are generated from the Apify OpenAPI specification, so this error means the API returned
6
+ * something the specification does not describe -- a missing required field, a different type, a value
7
+ * outside the documented range. Unknown fields and unknown enum values are not errors: the schemas let
8
+ * both through, so the client keeps working when the API grows.
9
+ *
10
+ * The `message` names the request and every offending field with the value it received, and ends by asking for
11
+ * a bug report: the mismatch is in the API or its specification, not in the caller's code. The structured
12
+ * {@link https://zod.dev | zod} issues are available on `issues`, and the original `ZodError` on `cause`,
13
+ * for programmatic inspection.
14
+ */
15
+ export declare class ResponseValidationError extends Error {
16
+ /** Structured issues from the underlying schema check. */
17
+ readonly issues: z.ZodError['issues'];
18
+ /** HTTP method of the request whose response failed validation, upper-cased. */
19
+ readonly method: string;
20
+ /** URL of the request whose response failed validation, without its query string. */
21
+ readonly url: string;
22
+ constructor(error: z.ZodError, value: unknown, request: {
23
+ method: string;
24
+ url: string;
25
+ });
26
+ }
@@ -0,0 +1,37 @@
1
+ import { ArgumentValidationError } from '@apify/validations';
2
+ const REPORT_HINT = 'The API returned something its OpenAPI specification does not describe. ' +
3
+ 'Please report this at https://github.com/apify/apify-client-js/issues.';
4
+ /**
5
+ * Thrown when an API response does not match the schema the client expects for it.
6
+ *
7
+ * The schemas are generated from the Apify OpenAPI specification, so this error means the API returned
8
+ * something the specification does not describe -- a missing required field, a different type, a value
9
+ * outside the documented range. Unknown fields and unknown enum values are not errors: the schemas let
10
+ * both through, so the client keeps working when the API grows.
11
+ *
12
+ * The `message` names the request and every offending field with the value it received, and ends by asking for
13
+ * a bug report: the mismatch is in the API or its specification, not in the caller's code. The structured
14
+ * {@link https://zod.dev | zod} issues are available on `issues`, and the original `ZodError` on `cause`,
15
+ * for programmatic inspection.
16
+ */
17
+ export class ResponseValidationError extends Error {
18
+ /** Structured issues from the underlying schema check. */
19
+ issues;
20
+ /** HTTP method of the request whose response failed validation, upper-cased. */
21
+ method;
22
+ /** URL of the request whose response failed validation, without its query string. */
23
+ url;
24
+ constructor(error, value, request) {
25
+ const method = request.method.toUpperCase();
26
+ // `@apify/validations` keeps its zod error formatter private, so the issue lines come from the
27
+ // message of the error class it does export.
28
+ const details = new ArgumentValidationError(error, value).message;
29
+ super(`Response from ${method} ${request.url} does not match the API schema:\n${details}\n${REPORT_HINT}`, {
30
+ cause: error,
31
+ });
32
+ this.name = 'ResponseValidationError';
33
+ this.issues = error.issues;
34
+ this.method = method;
35
+ this.url = request.url;
36
+ }
37
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The schemas the resource clients validate API responses with.
3
+ *
4
+ * Today these are exactly the generated ones. The module still exists as the one place where a generated
5
+ * schema is widened when the API is known to return something the specification does not describe, so a
6
+ * documented deviation never sends a resource client reaching into `./generated` directly. An override
7
+ * declared here shadows the generated export of the same name and takes the same form, a `lazySchema()` thunk
8
+ * built on the generated schema it replaces. Every schema that embeds an overridden one has to be rebuilt on
9
+ * top of it, and `spec_guards.ts` checks that each override still accepts what the specification describes,
10
+ * so one cannot narrow by accident.
11
+ *
12
+ * Spec gaps need no override: the generated objects are loose, so a field the specification omits passes
13
+ * through. Neither do client narrowings: a schema only ever accepts more than the published type.
14
+ */
15
+ export * from './generated/schemas.js';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The schemas the resource clients validate API responses with.
3
+ *
4
+ * Today these are exactly the generated ones. The module still exists as the one place where a generated
5
+ * schema is widened when the API is known to return something the specification does not describe, so a
6
+ * documented deviation never sends a resource client reaching into `./generated` directly. An override
7
+ * declared here shadows the generated export of the same name and takes the same form, a `lazySchema()` thunk
8
+ * built on the generated schema it replaces. Every schema that embeds an overridden one has to be rebuilt on
9
+ * top of it, and `spec_guards.ts` checks that each override still accepts what the specification describes,
10
+ * so one cannot narrow by accident.
11
+ *
12
+ * Spec gaps need no override: the generated objects are loose, so a field the specification omits passes
13
+ * through. Neither do client narrowings: a schema only ever accepts more than the published type.
14
+ */
15
+ export * from './generated/schemas.js';
@@ -1,10 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Statistics = void 0;
4
- const zod_1 = require("zod");
5
- const utils_1 = require("./utils");
6
- const attemptSchema = zod_1.z.number().gt(0);
7
- class Statistics {
1
+ import { z } from 'zod';
2
+ import { parseArgument } from './utils.js';
3
+ const attemptSchema = z.number().gt(0);
4
+ export class Statistics {
8
5
  /**
9
6
  * Number of Apify client function calls
10
7
  */
@@ -19,7 +16,7 @@ class Statistics {
19
16
  */
20
17
  rateLimitErrors = [];
21
18
  addRateLimitError(attempt) {
22
- (0, utils_1.parseArgument)(attempt, attemptSchema);
19
+ parseArgument(attempt, attemptSchema);
23
20
  // attempt is never 0,
24
21
  // but we don't want index 0 empty
25
22
  const index = attempt - 1;
@@ -41,4 +38,3 @@ class Statistics {
41
38
  }
42
39
  }
43
40
  }
44
- exports.Statistics = Statistics;
package/dist/timezones.js CHANGED
@@ -1,8 +1,6 @@
1
- "use strict";
2
1
  // This contains exactly the list of timezones supported by 'moment-timezone' package, you can fetch it using:
3
2
  // require('moment-timzone').tz.names()
4
3
  // This should be kept in sync with timezones.js in storage
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
4
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
7
5
  const timezones = [
8
6
  'Africa/Abidjan',
@@ -599,3 +597,4 @@ const timezones = [
599
597
  'WET',
600
598
  'Zulu',
601
599
  ];
600
+ export {};
package/dist/utils.d.ts CHANGED
@@ -1,18 +1,12 @@
1
1
  import type { Readable } from 'node:stream';
2
2
  import type { JsonValue, TypedArray } from 'type-fest';
3
3
  import { z } from 'zod';
4
- import type { ApifyApiError } from './apify_api_error';
5
- import type { RequestQueueClientListRequestsOptions, RequestQueueClientListRequestsResult } from './resource_clients/request_queue';
6
- import type { WebhookUpdateData } from './resource_clients/webhook';
7
- /**
8
- * Parses `value` with `schema`, returning the typed result (with schema defaults applied).
9
- * Throws {@link ArgumentValidationError} on failure.
10
- *
11
- * The optional `label` names the interface being validated and is appended to every error line
12
- * (e.g. ``... at `memory` in `ActorStartOptions` ``).
13
- * @internal
14
- */
15
- export declare function parseArgument<TValue, TSchema extends z.ZodType>(value: TValue, schema: TSchema, label?: string): TValue & z.output<TSchema>;
4
+ import type { ApifyApiError } from './apify_api_error.js';
5
+ import { parseArgument } from '@apify/validations';
6
+ import type { ApifyResponse } from './http_client.js';
7
+ import type { RequestQueueClientListRequestsOptions, RequestQueueClientListRequestsResult } from './resource_clients/request_queue.js';
8
+ import type { WebhookUpdateData } from './resource_clients/webhook.js';
9
+ export { parseArgument };
16
10
  /**
17
11
  * Accepts any non-null, non-array object as a predicate for `z.custom()`.
18
12
  * @internal
@@ -33,16 +27,34 @@ export declare const anyObjectSchema: z.ZodCustom<Record<string, unknown>, Recor
33
27
  export interface MaybeData<R> {
34
28
  data?: R;
35
29
  }
30
+ /**
31
+ * Turns a JSON API response into the value a resource method returns: unwraps the `data` envelope, converts the
32
+ * date fields and validates the result against `schema`, one of the schemas generated from the OpenAPI
33
+ * specification. The validated copy is what callers get, so it is the schema's output -- unknown fields and unknown
34
+ * enum values included, since the schemas let both through, and URL fields normalized, since `z.url()` hands back
35
+ * the parsed URL's serialization.
36
+ *
37
+ * Throws {@link ResponseValidationError} when the response does not match the specification.
38
+ * @internal
39
+ */
40
+ export declare function parseResponse<R>(response: ApifyResponse, schema: z.ZodType, shouldParseField?: ((key: string) => boolean) | null): R;
36
41
  /**
37
42
  * Returns object's 'data' property or throws if parameter is not an object,
38
43
  * or an object without a 'data' property.
39
44
  */
40
45
  export declare function pluckData<R>(obj: MaybeData<R>): R;
41
46
  /**
42
- * If given HTTP error has NOT_FOUND_STATUS_CODE status code then returns undefined.
43
- * Otherwise rethrows error.
47
+ * Swallows a 404 Not Found API error and rethrows anything else.
44
48
  */
45
49
  export declare function catchNotFoundOrThrow(err: ApifyApiError): void;
50
+ /**
51
+ * Like `catchNotFoundOrThrow()`, but swallows the 404 only when the client names its resource by ID.
52
+ *
53
+ * A chained client without an ID, such as `run.dataset()` or `run.log()`, requests a path where a 404 can mean either
54
+ * the parent or the default sub-resource is missing. The response cannot tell the two apart, so the error propagates.
55
+ * @internal
56
+ */
57
+ export declare function catchNotFoundForResourceOrThrow(err: ApifyApiError, resourceId: string | undefined): void;
46
58
  type ReturnJsonValue = string | number | boolean | null | Date | ReturnJsonObject | ReturnJsonArray;
47
59
  type ReturnJsonObject = {
48
60
  [Key in string]?: ReturnJsonValue;
@@ -83,13 +95,12 @@ export declare function getVersionData(): {
83
95
  version: string;
84
96
  };
85
97
  /**
86
- * Helper class to create async iterators from paginated list endpoints with exclusive start key.
98
+ * Helper class to create async iterators from paginated list endpoints.
87
99
  */
88
100
  export declare class RequestQueuePaginationIterator {
89
101
  private readonly maxPageLimit;
90
102
  private readonly getPage;
91
103
  private readonly limit?;
92
- private readonly exclusiveStartId?;
93
104
  private readonly cursor?;
94
105
  constructor(options: RequestQueuePaginationIteratorOptions);
95
106
  [Symbol.asyncIterator](): AsyncIterator<RequestQueueClientListRequestsResult>;
@@ -105,7 +116,6 @@ export interface RequestQueuePaginationIteratorOptions {
105
116
  maxPageLimit: number;
106
117
  getPage: (opts: RequestQueueClientListRequestsOptions) => Promise<RequestQueueClientListRequestsResult>;
107
118
  limit?: number;
108
- exclusiveStartId?: string;
109
119
  cursor?: string;
110
120
  }
111
121
  /**
@@ -192,12 +202,6 @@ export type DistributiveOptional<T, K extends keyof T> = T extends any ? Omit<T,
192
202
  * Adds query parameters to a given URL based on the provided options object.
193
203
  */
194
204
  export declare function applyQueryParamsToUrl(url: URL, options?: Record<string, string | number | boolean | string[] | undefined>): URL;
195
- /**
196
- * Builds a `[check, message]` pair to spread into `.refine()`, asserting that at most one of `keys`
197
- * is present. Pass the options interface as `T`, so that a misspelled key is a type error.
198
- * @internal
199
- */
200
- export declare const mutuallyExclusive: <T extends object>(...keys: (keyof T & string)[]) => [(value: T) => boolean, string];
201
205
  /**
202
206
  * Percent-encodes a caller-supplied URL path segment so it cannot restructure the request path.
203
207
  *
@@ -210,4 +214,3 @@ export declare function toPathSegment(value: string): string;
210
214
  * `requests/batch` keep their separators; an array has each of its segments encoded individually.
211
215
  */
212
216
  export declare function toPath(path: string | string[]): string;
213
- export {};
package/dist/utils.js CHANGED
@@ -1,53 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mutuallyExclusive = exports.paginationOptionsShape = exports.RequestQueuePaginationIterator = exports.anyObjectSchema = void 0;
4
- exports.parseArgument = parseArgument;
5
- exports.isNonArrayObject = isNonArrayObject;
6
- exports.pluckData = pluckData;
7
- exports.catchNotFoundOrThrow = catchNotFoundOrThrow;
8
- exports.parseDateFields = parseDateFields;
9
- exports.stringifyWebhooksToBase64 = stringifyWebhooksToBase64;
10
- exports.maybeCompressValue = maybeCompressValue;
11
- exports.sliceArrayByByteLength = sliceArrayByByteLength;
12
- exports.isNode = isNode;
13
- exports.isBuffer = isBuffer;
14
- exports.isStream = isStream;
15
- exports.getVersionData = getVersionData;
16
- exports.cast = cast;
17
- exports.asArray = asArray;
18
- exports.applyQueryParamsToUrl = applyQueryParamsToUrl;
19
- exports.toPathSegment = toPathSegment;
20
- exports.toPath = toPath;
21
- const zod_1 = require("zod");
22
- const argument_validation_error_1 = require("./argument_validation_error");
23
- const NOT_FOUND_STATUS_CODE = 404;
24
- const RECORD_NOT_FOUND_TYPE = 'record-not-found';
25
- const RECORD_OR_TOKEN_NOT_FOUND_TYPE = 'record-or-token-not-found';
1
+ import { z } from 'zod';
2
+ import { NotFoundError } from './apify_api_error.js';
3
+ import { parseArgument } from '@apify/validations';
4
+ import { ResponseValidationError } from './response_validation_error.js';
5
+ // @ts-ignore if we enable `resolveJsonModule`, we end up with a `src` folder in `dist`
6
+ import packageJson from '../package.json' with { type: 'json' };
26
7
  const MIN_COMPRESS_BYTES = 1024;
27
- // Zod installs its English locale as a module-level side effect but ships `"sideEffects": false`, so
28
- // any tree-shaking bundler drops it and every message degrades to a bare "Invalid input". Passing it
29
- // in per parse keeps them intact without reaching into the zod config the whole process shares.
30
- const { localeError } = zod_1.z.locales.en();
31
- /**
32
- * Parses `value` with `schema`, returning the typed result (with schema defaults applied).
33
- * Throws {@link ArgumentValidationError} on failure.
34
- *
35
- * The optional `label` names the interface being validated and is appended to every error line
36
- * (e.g. ``... at `memory` in `ActorStartOptions` ``).
37
- * @internal
38
- */
39
- function parseArgument(value, schema, label) {
40
- const result = schema.safeParse(value, { error: localeError });
41
- if (!result.success) {
42
- throw new argument_validation_error_1.ArgumentValidationError(result.error, value, label);
43
- }
44
- return result.data;
45
- }
8
+ export { parseArgument };
46
9
  /**
47
10
  * Accepts any non-null, non-array object as a predicate for `z.custom()`.
48
11
  * @internal
49
12
  */
50
- function isNonArrayObject(value) {
13
+ export function isNonArrayObject(value) {
51
14
  return typeof value === 'object' && value !== null && !Array.isArray(value);
52
15
  }
53
16
  /**
@@ -56,14 +19,37 @@ function isNonArrayObject(value) {
56
19
  * the value itself instead of a copy.
57
20
  * @internal
58
21
  */
59
- exports.anyObjectSchema = zod_1.z.custom(isNonArrayObject, {
22
+ export const anyObjectSchema = z.custom(isNonArrayObject, {
60
23
  error: 'Invalid input: expected an object',
61
24
  });
25
+ // Zod installs its English locale as a module-level side effect but ships `"sideEffects": false`, so
26
+ // any tree-shaking bundler drops it and every message degrades to a bare "Invalid input". Passing it
27
+ // in per parse keeps them intact without reaching into the zod config the whole process shares.
28
+ const { localeError } = z.locales.en();
29
+ /**
30
+ * Turns a JSON API response into the value a resource method returns: unwraps the `data` envelope, converts the
31
+ * date fields and validates the result against `schema`, one of the schemas generated from the OpenAPI
32
+ * specification. The validated copy is what callers get, so it is the schema's output -- unknown fields and unknown
33
+ * enum values included, since the schemas let both through, and URL fields normalized, since `z.url()` hands back
34
+ * the parsed URL's serialization.
35
+ *
36
+ * Throws {@link ResponseValidationError} when the response does not match the specification.
37
+ * @internal
38
+ */
39
+ export function parseResponse(response, schema, shouldParseField = null) {
40
+ const data = parseDateFields(pluckData(response.data), shouldParseField);
41
+ const result = schema.safeParse(data, { error: localeError });
42
+ if (!result.success) {
43
+ const { method = 'GET', url = '' } = response.config;
44
+ throw new ResponseValidationError(result.error, data, { method, url });
45
+ }
46
+ return result.data;
47
+ }
62
48
  /**
63
49
  * Returns object's 'data' property or throws if parameter is not an object,
64
50
  * or an object without a 'data' property.
65
51
  */
66
- function pluckData(obj) {
52
+ export function pluckData(obj) {
67
53
  if (typeof obj === 'object' && obj) {
68
54
  if (typeof obj.data !== 'undefined')
69
55
  return obj.data;
@@ -71,16 +57,24 @@ function pluckData(obj) {
71
57
  throw new Error(`Expected response object with a "data" property, but received: ${obj}`);
72
58
  }
73
59
  /**
74
- * If given HTTP error has NOT_FOUND_STATUS_CODE status code then returns undefined.
75
- * Otherwise rethrows error.
60
+ * Swallows a 404 Not Found API error and rethrows anything else.
76
61
  */
77
- function catchNotFoundOrThrow(err) {
78
- const isNotFoundStatus = err.statusCode === NOT_FOUND_STATUS_CODE;
79
- const isNotFoundMessage = err.type === RECORD_NOT_FOUND_TYPE || err.type === RECORD_OR_TOKEN_NOT_FOUND_TYPE || err.httpMethod === 'head';
80
- const isNotFoundError = isNotFoundStatus && isNotFoundMessage;
81
- if (!isNotFoundError)
62
+ export function catchNotFoundOrThrow(err) {
63
+ if (!(err instanceof NotFoundError))
82
64
  throw err;
83
65
  }
66
+ /**
67
+ * Like `catchNotFoundOrThrow()`, but swallows the 404 only when the client names its resource by ID.
68
+ *
69
+ * A chained client without an ID, such as `run.dataset()` or `run.log()`, requests a path where a 404 can mean either
70
+ * the parent or the default sub-resource is missing. The response cannot tell the two apart, so the error propagates.
71
+ * @internal
72
+ */
73
+ export function catchNotFoundForResourceOrThrow(err, resourceId) {
74
+ if (!resourceId)
75
+ throw err;
76
+ catchNotFoundOrThrow(err);
77
+ }
84
78
  /**
85
79
  * Traverses JSON structure and converts fields that end with "At" to a Date object (fields such as "modifiedAt" or
86
80
  * "createdAt").
@@ -91,7 +85,7 @@ function catchNotFoundOrThrow(err) {
91
85
  *
92
86
  * If the field cannot be converted to Date, it is left as is.
93
87
  */
94
- function parseDateFields(input, shouldParseField = null, depth = 0) {
88
+ export function parseDateFields(input, shouldParseField = null, depth = 0) {
95
89
  // Don't go too deep to avoid stack overflows (especially if there is a circular reference). The depth of 4
96
90
  // corresponds to obj.items.[x].someArrayField.[y].field, which is what a list response looks like: it
97
91
  // nests one level deeper than the single resource it wraps, because both the item array and the nested
@@ -131,7 +125,7 @@ function parseDateFields(input, shouldParseField = null, depth = 0) {
131
125
  /**
132
126
  * Helper function that converts array of webhooks to base64 string
133
127
  */
134
- function stringifyWebhooksToBase64(webhooks) {
128
+ export function stringifyWebhooksToBase64(webhooks) {
135
129
  if (!webhooks)
136
130
  return;
137
131
  const webhooksJson = JSON.stringify(webhooks);
@@ -172,7 +166,7 @@ async function gzipValue(value) {
172
166
  * Compress the passed value using brotli, falling back to gzip. Returns undefined if the data is
173
167
  * too small / wrong type, or if neither algorithm is available.
174
168
  */
175
- async function maybeCompressValue(value) {
169
+ export async function maybeCompressValue(value) {
176
170
  if (!isNode())
177
171
  return undefined;
178
172
  // Request compression is not that important so let's
@@ -201,7 +195,7 @@ async function maybeCompressValue(value) {
201
195
  /**
202
196
  * Helper function slice the items from array to fit the max byte length.
203
197
  */
204
- function sliceArrayByByteLength(array, maxByteLength, startIndex) {
198
+ export function sliceArrayByByteLength(array, maxByteLength, startIndex) {
205
199
  const stringByteLength = (str) => (isNode() ? Buffer.byteLength(str) : new Blob([str]).size);
206
200
  const arrayByteLength = stringByteLength(JSON.stringify(array));
207
201
  if (arrayByteLength < maxByteLength)
@@ -222,12 +216,12 @@ function sliceArrayByByteLength(array, maxByteLength, startIndex) {
222
216
  }
223
217
  return slicedArray;
224
218
  }
225
- function isNode() {
219
+ export function isNode() {
226
220
  if (typeof BROWSER_BUILD !== 'undefined')
227
221
  return false;
228
222
  return !!(typeof process !== 'undefined' && process.versions && process.versions.node);
229
223
  }
230
- function isBuffer(value) {
224
+ export function isBuffer(value) {
231
225
  // Tag checks rather than `instanceof`, to also match buffers from another realm. `isView()`
232
226
  // additionally covers `DataView`, which is not raw binary content.
233
227
  if (ArrayBuffer.isView(value))
@@ -237,39 +231,34 @@ function isBuffer(value) {
237
231
  function isTagged(value, tag) {
238
232
  return Object.prototype.toString.call(value) === `[object ${tag}]`;
239
233
  }
240
- function isStream(value) {
234
+ export function isStream(value) {
241
235
  if (value === null || typeof value !== 'object')
242
236
  return false;
243
237
  const { on, pipe } = value;
244
238
  return typeof on === 'function' && typeof pipe === 'function';
245
239
  }
246
- function getVersionData() {
240
+ export function getVersionData() {
247
241
  if (typeof BROWSER_BUILD !== 'undefined') {
248
242
  return { version: VERSION };
249
243
  }
250
- // eslint-disable-next-line
251
- return require('../package.json');
244
+ return packageJson;
252
245
  }
253
246
  /**
254
- * Helper class to create async iterators from paginated list endpoints with exclusive start key.
247
+ * Helper class to create async iterators from paginated list endpoints.
255
248
  */
256
- class RequestQueuePaginationIterator {
249
+ export class RequestQueuePaginationIterator {
257
250
  maxPageLimit;
258
251
  getPage;
259
252
  limit;
260
- exclusiveStartId;
261
253
  cursor;
262
254
  constructor(options) {
263
255
  this.maxPageLimit = options.maxPageLimit;
264
256
  this.limit = options.limit;
265
- this.exclusiveStartId = options.exclusiveStartId;
266
257
  this.cursor = options.cursor;
267
258
  this.getPage = options.getPage;
268
259
  }
269
260
  async *[Symbol.asyncIterator]() {
270
261
  let nextCursor = this.cursor;
271
- // allow using exclusiveStartId for the first page, but then we'll delete it to avoid using it for any later page
272
- let nextExclusiveStartId = this.exclusiveStartId;
273
262
  let iterateItemCount = 0;
274
263
  while (true) {
275
264
  const pageLimit = this.limit
@@ -278,7 +267,6 @@ class RequestQueuePaginationIterator {
278
267
  const page = await this.getPage({
279
268
  limit: pageLimit,
280
269
  cursor: nextCursor,
281
- exclusiveStartId: nextExclusiveStartId,
282
270
  });
283
271
  // There are no more pages to iterate
284
272
  if (page.items.length === 0)
@@ -289,25 +277,23 @@ class RequestQueuePaginationIterator {
289
277
  if ((this.limit && iterateItemCount >= this.limit) || !page.nextCursor)
290
278
  return;
291
279
  nextCursor = page.nextCursor;
292
- nextExclusiveStartId = undefined; // see comment above - delete it for any page after the first one, and paginate with cursor
293
280
  }
294
281
  }
295
282
  }
296
- exports.RequestQueuePaginationIterator = RequestQueuePaginationIterator;
297
283
  /**
298
284
  * Schema shape of {@link PaginationOptions}, to spread into every paginating client's list schema. One
299
285
  * copy stops it drifting from the interface.
300
286
  * @internal
301
287
  */
302
- exports.paginationOptionsShape = {
303
- limit: zod_1.z.number().min(0).optional(),
304
- offset: zod_1.z.number().min(0).optional(),
305
- chunkSize: zod_1.z.number().positive().optional(),
288
+ export const paginationOptionsShape = {
289
+ limit: z.number().min(0).optional(),
290
+ offset: z.number().min(0).optional(),
291
+ chunkSize: z.number().positive().optional(),
306
292
  };
307
- function cast(input) {
293
+ export function cast(input) {
308
294
  return input;
309
295
  }
310
- function asArray(value) {
296
+ export function asArray(value) {
311
297
  if (Array.isArray(value)) {
312
298
  return value;
313
299
  }
@@ -316,7 +302,7 @@ function asArray(value) {
316
302
  /**
317
303
  * Adds query parameters to a given URL based on the provided options object.
318
304
  */
319
- function applyQueryParamsToUrl(url, options) {
305
+ export function applyQueryParamsToUrl(url, options) {
320
306
  for (const [key, value] of Object.entries(options ?? {})) {
321
307
  // skip undefined values
322
308
  if (value === undefined)
@@ -330,17 +316,7 @@ function applyQueryParamsToUrl(url, options) {
330
316
  }
331
317
  return url;
332
318
  }
333
- /**
334
- * Builds a `[check, message]` pair to spread into `.refine()`, asserting that at most one of `keys`
335
- * is present. Pass the options interface as `T`, so that a misspelled key is a type error.
336
- * @internal
337
- */
338
- const mutuallyExclusive = (...keys) => [
339
- (value) => keys.filter((key) => typeof value[key] !== 'undefined').length <= 1,
340
- `At most one of the following fields is allowed: ${keys.join(', ')}`,
341
- ];
342
- exports.mutuallyExclusive = mutuallyExclusive;
343
- const pathSegmentSchema = zod_1.z
319
+ const pathSegmentSchema = z
344
320
  .string()
345
321
  .nonempty()
346
322
  .refine((v) => v !== '.' && v !== '..', { error: 'URL path must not contain dot segments' });
@@ -350,7 +326,7 @@ const pathSegmentSchema = zod_1.z
350
326
  * Empty strings and dot segments are rejected instead of encoded, because URL parsers resolve
351
327
  * dot segments after decoding - `records/%2E%2E` collapses to the parent endpoint just like `records/..`.
352
328
  */
353
- function toPathSegment(value) {
329
+ export function toPathSegment(value) {
354
330
  const valueParsed = parseArgument(value, pathSegmentSchema);
355
331
  return encodeURIComponent(valueParsed);
356
332
  }
@@ -358,6 +334,6 @@ function toPathSegment(value) {
358
334
  * Builds a URL path from segments. A plain string is used as-is, so literal paths such as
359
335
  * `requests/batch` keep their separators; an array has each of its segments encoded individually.
360
336
  */
361
- function toPath(path) {
337
+ export function toPath(path) {
362
338
  return Array.isArray(path) ? path.map(toPathSegment).join('/') : path;
363
339
  }