cloudflare/cloudflare-typescript

Public

mirrored from https://github.com/cloudflare/cloudflare-typescriptAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v7

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/client.ts

1527lines · modecode

1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3import type { RequestInit, RequestInfo, BodyInit } from './internal/builtin-types';
4import type { HTTPMethod, PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from './internal/types';
5import { uuid4 } from './internal/utils/uuid';
6import { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values';
7import { sleep } from './internal/utils/sleep';
8export type { Logger, LogLevel } from './internal/utils/log';
9import { castToError, isAbortError } from './internal/errors';
10import type { APIResponseProps } from './internal/parse';
11import { getPlatformHeaders } from './internal/detect-platform';
12import * as Shims from './internal/shims';
13import * as Opts from './internal/request-options';
14import { stringifyQuery } from './internal/utils/query';
15import { VERSION } from './version';
16import * as Errors from './core/error';
17import * as Pagination from './core/pagination';
18import {
19 AbstractPage,
20 type CursorLimitPaginationParams,
21 CursorLimitPaginationResponse,
22 type CursorPaginationAfterParams,
23 CursorPaginationAfterResponse,
24 type CursorPaginationParams,
25 CursorPaginationResponse,
26 SinglePageResponse,
27 type V4PagePaginationArrayParams,
28 V4PagePaginationArrayResponse,
29 type V4PagePaginationParams,
30 V4PagePaginationResponse,
31} from './core/pagination';
32import * as Uploads from './core/uploads';
33import * as API from './resources/index';
34import { APIPromise } from './core/api-promise';
35import { AbuseReports } from './resources/abuse-reports/abuse-reports';
36import { Accounts } from './resources/accounts/accounts';
37import { ACM } from './resources/acm/acm';
38import { Addressing } from './resources/addressing/addressing';
39import { AIAudit } from './resources/ai-audit/ai-audit';
40import { AIGateway } from './resources/ai-gateway/ai-gateway';
41import { AISecurity } from './resources/ai-security/ai-security';
42import { AI } from './resources/ai/ai';
43import { AISearch } from './resources/aisearch/aisearch';
44import { Alerting } from './resources/alerting/alerting';
45import { APIGateway } from './resources/api-gateway/api-gateway';
46import { Argo } from './resources/argo/argo';
47import { AuditLogs } from './resources/audit-logs/audit-logs';
48import { Billing } from './resources/billing/billing';
49import { BotManagement } from './resources/bot-management/bot-management';
50import { BotnetFeed } from './resources/botnet-feed/botnet-feed';
51import { BrandProtection } from './resources/brand-protection/brand-protection';
52import { BrowserRendering } from './resources/browser-rendering/browser-rendering';
53import { Cache } from './resources/cache/cache';
54import { Calls } from './resources/calls/calls';
55import { CertificateAuthorities } from './resources/certificate-authorities/certificate-authorities';
56import { ClientCertificates } from './resources/client-certificates/client-certificates';
57import { CloudConnector } from './resources/cloud-connector/cloud-connector';
58import { CloudforceOne } from './resources/cloudforce-one/cloudforce-one';
59import { Connectivity } from './resources/connectivity/connectivity';
60import { ContentScanning } from './resources/content-scanning/content-scanning';
61import { CsamScanner } from './resources/csam-scanner/csam-scanner';
62import { CustomCertificates } from './resources/custom-certificates/custom-certificates';
63import { CustomCsrs } from './resources/custom-csrs/custom-csrs';
64import { CustomHostnames } from './resources/custom-hostnames/custom-hostnames';
65import { CustomNameservers } from './resources/custom-nameservers/custom-nameservers';
66import { CustomPages } from './resources/custom-pages/custom-pages';
67import { D1Resource } from './resources/d1/d1';
68import { DCVDelegation } from './resources/dcv-delegation/dcv-delegation';
69import { DDoSProtection } from './resources/ddos-protection/ddos-protection';
70import { Diagnostics } from './resources/diagnostics/diagnostics';
71import { DLS } from './resources/dls/dls';
72import { DNSFirewall } from './resources/dns-firewall/dns-firewall';
73import { DNS } from './resources/dns/dns';
74import { DurableObjects } from './resources/durable-objects/durable-objects';
75import { EmailAuth } from './resources/email-auth/email-auth';
76import { EmailRouting } from './resources/email-routing/email-routing';
77import { EmailSecurity } from './resources/email-security/email-security';
78import { EmailSending } from './resources/email-sending/email-sending';
79import { Filters } from './resources/filters/filters';
80import { Firewall } from './resources/firewall/firewall';
81import { Flagship } from './resources/flagship/flagship';
82import { Fraud } from './resources/fraud/fraud';
83import { GoogleTagGateway } from './resources/google-tag-gateway/google-tag-gateway';
84import { Healthchecks } from './resources/healthchecks/healthchecks';
85import { Hostnames } from './resources/hostnames/hostnames';
86import { HyperdriveResource } from './resources/hyperdrive/hyperdrive';
87import { IAM } from './resources/iam/iam';
88import { Images } from './resources/images/images';
89import { Intel } from './resources/intel/intel';
90import { IPs } from './resources/ips/ips';
91import { KeylessCertificates } from './resources/keyless-certificates/keyless-certificates';
92import { KV } from './resources/kv/kv';
93import { LeakedCredentialChecks } from './resources/leaked-credential-checks/leaked-credential-checks';
94import { LoadBalancers } from './resources/load-balancers/load-balancers';
95import { Logpush } from './resources/logpush/logpush';
96import { Logs } from './resources/logs/logs';
97import { MagicCloudNetworking } from './resources/magic-cloud-networking/magic-cloud-networking';
98import { MagicNetworkMonitoring } from './resources/magic-network-monitoring/magic-network-monitoring';
99import { MagicTransit } from './resources/magic-transit/magic-transit';
100import { ManagedTransforms } from './resources/managed-transforms/managed-transforms';
101import { Memberships } from './resources/memberships/memberships';
102import { MoQ } from './resources/moq/moq';
103import { MTLSCertificates } from './resources/mtls-certificates/mtls-certificates';
104import { NetworkInterconnects } from './resources/network-interconnects/network-interconnects';
105import { Organizations } from './resources/organizations/organizations';
106import { OriginCACertificates } from './resources/origin-ca-certificates/origin-ca-certificates';
107import { OriginPostQuantumEncryption } from './resources/origin-post-quantum-encryption/origin-post-quantum-encryption';
108import { OriginTLSClientAuth } from './resources/origin-tls-client-auth/origin-tls-client-auth';
109import { OriginTLSComplianceModes } from './resources/origin-tls-compliance-modes/origin-tls-compliance-modes';
110import { PageRules } from './resources/page-rules/page-rules';
111import { PageShield } from './resources/page-shield/page-shield';
112import { Pages } from './resources/pages/pages';
113import { Pipelines } from './resources/pipelines/pipelines';
114import { Queues } from './resources/queues/queues';
115import { R2DataCatalog } from './resources/r2-data-catalog/r2-data-catalog';
116import { R2 } from './resources/r2/r2';
117import { Radar } from './resources/radar/radar';
118import { RateLimits } from './resources/rate-limits/rate-limits';
119import { RealtimeKit } from './resources/realtime-kit/realtime-kit';
120import { Registrar } from './resources/registrar/registrar';
121import { RequestTracers } from './resources/request-tracers/request-tracers';
122import { ResourceSharing } from './resources/resource-sharing/resource-sharing';
123import { ResourceTagging } from './resources/resource-tagging/resource-tagging';
124import { Rules } from './resources/rules/rules';
125import { Rulesets } from './resources/rulesets/rulesets';
126import { RUM } from './resources/rum/rum';
127import { SchemaValidation } from './resources/schema-validation/schema-validation';
128import { SecretsStore } from './resources/secrets-store/secrets-store';
129import { SecurityCenter } from './resources/security-center/security-center';
130import { SecurityTXT } from './resources/security-txt/security-txt';
131import { Snippets } from './resources/snippets/snippets';
132import { Spectrum } from './resources/spectrum/spectrum';
133import { Speed } from './resources/speed/speed';
134import { SSL } from './resources/ssl/ssl';
135import { Stream } from './resources/stream/stream';
136import { TenantCustomNameservers } from './resources/tenant-custom-nameservers/tenant-custom-nameservers';
137import { Tenants } from './resources/tenants/tenants';
138import { TokenValidation } from './resources/token-validation/token-validation';
139import { Turnstile } from './resources/turnstile/turnstile';
140import { URLNormalization } from './resources/url-normalization/url-normalization';
141import { URLScanner } from './resources/url-scanner/url-scanner';
142import { User } from './resources/user/user';
143import { Vectorize } from './resources/vectorize/vectorize';
144import { VulnerabilityScanner } from './resources/vulnerability-scanner/vulnerability-scanner';
145import { WaitingRooms } from './resources/waiting-rooms/waiting-rooms';
146import { Web3 } from './resources/web3/web3';
147import { WorkersForPlatforms } from './resources/workers-for-platforms/workers-for-platforms';
148import { Workers } from './resources/workers/workers';
149import { Workflows } from './resources/workflows/workflows';
150import { Zaraz } from './resources/zaraz/zaraz';
151import { ZeroTrust } from './resources/zero-trust/zero-trust';
152import { Zones } from './resources/zones/zones';
153import { type Fetch } from './internal/builtin-types';
154import { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers';
155import { FinalRequestOptions, RequestOptions } from './internal/request-options';
156import { readEnv } from './internal/utils/env';
157import {
158 type LogLevel,
159 type Logger,
160 formatRequestDetails,
161 loggerFor,
162 parseLogLevel,
163} from './internal/utils/log';
164import { isEmptyObj } from './internal/utils/values';
165
166export interface ClientOptions {
167 /**
168 * The preferred authorization scheme for interacting with the Cloudflare API. [Create a token](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/).
169 */
170 apiToken?: string | null | undefined;
171
172 /**
173 * The previous authorization scheme for interacting with the Cloudflare API. When possible, use API tokens instead of Global API keys.
174 */
175 apiKey?: string | null | undefined;
176
177 /**
178 * The previous authorization scheme for interacting with the Cloudflare API, used in conjunction with a Global API key.
179 */
180 apiEmail?: string | null | undefined;
181
182 /**
183 * Used when interacting with the Origin CA certificates API. [View/change your key](https://developers.cloudflare.com/fundamentals/api/get-started/ca-keys/#viewchange-your-origin-ca-keys).
184 */
185 userServiceKey?: string | null | undefined;
186
187 /**
188 * Override the default base URL for the API, e.g., "https://api.example.com/v2/"
189 *
190 * Defaults to process.env['CLOUDFLARE_BASE_URL'].
191 */
192 baseURL?: string | null | undefined;
193
194 /**
195 * The maximum amount of time (in milliseconds) that the client should wait for a response
196 * from the server before timing out a single request.
197 *
198 * Note that request timeouts are retried by default, so in a worst-case scenario you may wait
199 * much longer than this timeout before the promise succeeds or fails.
200 *
201 * @unit milliseconds
202 */
203 timeout?: number | undefined;
204 /**
205 * Additional `RequestInit` options to be passed to `fetch` calls.
206 * Properties will be overridden by per-request `fetchOptions`.
207 */
208 fetchOptions?: MergedRequestInit | undefined;
209
210 /**
211 * Specify a custom `fetch` function implementation.
212 *
213 * If not provided, we expect that `fetch` is defined globally.
214 */
215 fetch?: Fetch | undefined;
216
217 /**
218 * The maximum number of times that the client will retry a request in case of a
219 * temporary failure, like a network error or a 5XX error from the server.
220 *
221 * @default 2
222 */
223 maxRetries?: number | undefined;
224
225 /**
226 * Default headers to include with every request to the API.
227 *
228 * These can be removed in individual requests by explicitly setting the
229 * header to `null` in request options.
230 */
231 defaultHeaders?: HeadersLike | undefined;
232
233 /**
234 * Default query parameters to include with every request to the API.
235 *
236 * These can be removed in individual requests by explicitly setting the
237 * param to `undefined` in request options.
238 */
239 defaultQuery?: Record<string, string | undefined> | undefined;
240
241 /**
242 * Set the log level.
243 *
244 * Defaults to process.env['CLOUDFLARE_LOG'] or 'warn' if it isn't set.
245 */
246 logLevel?: LogLevel | undefined;
247
248 /**
249 * Set the logger.
250 *
251 * Defaults to globalThis.console.
252 */
253 logger?: Logger | undefined;
254}
255
256/**
257 * Base class for Cloudflare API clients.
258 */
259export class BaseCloudflare {
260 apiToken: string | null;
261 apiKey: string | null;
262 apiEmail: string | null;
263 userServiceKey: string | null;
264
265 baseURL: string;
266 maxRetries: number;
267 timeout: number;
268 logger: Logger;
269 logLevel: LogLevel | undefined;
270 fetchOptions: MergedRequestInit | undefined;
271
272 private fetch: Fetch;
273 #encoder: Opts.RequestEncoder;
274 protected idempotencyHeader?: string;
275 private _options: ClientOptions;
276
277 /**
278 * API Client for interfacing with the Cloudflare API.
279 *
280 * @param {string | null | undefined} [opts.apiToken=process.env['CLOUDFLARE_API_TOKEN'] ?? null]
281 * @param {string | null | undefined} [opts.apiKey=process.env['CLOUDFLARE_API_KEY'] ?? null]
282 * @param {string | null | undefined} [opts.apiEmail=process.env['CLOUDFLARE_EMAIL'] ?? null]
283 * @param {string | null | undefined} [opts.userServiceKey=process.env['CLOUDFLARE_API_USER_SERVICE_KEY'] ?? null]
284 * @param {string} [opts.baseURL=process.env['CLOUDFLARE_BASE_URL'] ?? https://api.cloudflare.com/client/v4] - Override the default base URL for the API.
285 * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
286 * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
287 * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
288 * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
289 * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
290 * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
291 */
292 constructor({
293 baseURL = readEnv('CLOUDFLARE_BASE_URL'),
294 apiToken = readEnv('CLOUDFLARE_API_TOKEN') ?? null,
295 apiKey = readEnv('CLOUDFLARE_API_KEY') ?? null,
296 apiEmail = readEnv('CLOUDFLARE_EMAIL') ?? null,
297 userServiceKey = readEnv('CLOUDFLARE_API_USER_SERVICE_KEY') ?? null,
298 ...opts
299 }: ClientOptions = {}) {
300 const options: ClientOptions = {
301 apiToken,
302 apiKey,
303 apiEmail,
304 userServiceKey,
305 ...opts,
306 baseURL: baseURL || `https://api.cloudflare.com/client/v4`,
307 };
308
309 this.baseURL = options.baseURL!;
310 this.timeout = options.timeout ?? BaseCloudflare.DEFAULT_TIMEOUT /* 1 minute */;
311 this.logger = options.logger ?? console;
312 const defaultLogLevel = 'warn';
313 // Set default logLevel early so that we can log a warning in parseLogLevel.
314 this.logLevel = defaultLogLevel;
315 this.logLevel =
316 parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
317 parseLogLevel(readEnv('CLOUDFLARE_LOG'), "process.env['CLOUDFLARE_LOG']", this) ??
318 defaultLogLevel;
319 this.fetchOptions = options.fetchOptions;
320 this.maxRetries = options.maxRetries ?? 2;
321 this.fetch = options.fetch ?? Shims.getDefaultFetch();
322 this.#encoder = Opts.FallbackEncoder;
323
324 const customHeadersEnv = readEnv('CLOUDFLARE_CUSTOM_HEADERS');
325 if (customHeadersEnv) {
326 const parsed: Record<string, string> = {};
327 for (const line of customHeadersEnv.split('\n')) {
328 const colon = line.indexOf(':');
329 if (colon >= 0) {
330 parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
331 }
332 }
333 options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
334 }
335
336 this._options = options;
337
338 this.apiToken = apiToken;
339 this.apiKey = apiKey;
340 this.apiEmail = apiEmail;
341 this.userServiceKey = userServiceKey;
342 }
343
344 /**
345 * Create a new client instance re-using the same options given to the current client with optional overriding.
346 */
347 withOptions(options: Partial<ClientOptions>): this {
348 const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
349 ...this._options,
350 baseURL: this.baseURL,
351 maxRetries: this.maxRetries,
352 timeout: this.timeout,
353 logger: this.logger,
354 logLevel: this.logLevel,
355 fetch: this.fetch,
356 fetchOptions: this.fetchOptions,
357 apiToken: this.apiToken,
358 apiKey: this.apiKey,
359 apiEmail: this.apiEmail,
360 userServiceKey: this.userServiceKey,
361 ...options,
362 });
363 return client;
364 }
365
366 /**
367 * Check whether the base URL is set to its default.
368 */
369 #baseURLOverridden(): boolean {
370 return this.baseURL !== 'https://api.cloudflare.com/client/v4';
371 }
372
373 protected defaultQuery(): Record<string, string | undefined> | undefined {
374 return this._options.defaultQuery;
375 }
376
377 protected validateHeaders({ values, nulls }: NullableHeaders) {
378 if (this.apiEmail && values.get('x-auth-email')) {
379 return;
380 }
381 if (nulls.has('x-auth-email')) {
382 return;
383 }
384
385 if (this.apiKey && values.get('x-auth-key')) {
386 return;
387 }
388 if (nulls.has('x-auth-key')) {
389 return;
390 }
391
392 if (this.apiToken && values.get('authorization')) {
393 return;
394 }
395 if (nulls.has('authorization')) {
396 return;
397 }
398
399 if (this.userServiceKey && values.get('x-auth-user-service-key')) {
400 return;
401 }
402 if (nulls.has('x-auth-user-service-key')) {
403 return;
404 }
405
406 throw new Error(
407 'Could not resolve authentication method. Expected one of apiEmail, apiKey, apiToken or userServiceKey to be set. Or for one of the "X-Auth-Email", "X-Auth-Key", "Authorization" or "X-Auth-User-Service-Key" headers to be explicitly omitted',
408 );
409 }
410
411 protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
412 return buildHeaders([
413 await this.apiEmailAuth(opts),
414 await this.apiKeyAuth(opts),
415 await this.apiTokenAuth(opts),
416 await this.userServiceKeyAuth(opts),
417 ]);
418 }
419
420 protected async apiEmailAuth(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
421 if (this.apiEmail == null) {
422 return undefined;
423 }
424 return buildHeaders([{ 'X-Auth-Email': this.apiEmail }]);
425 }
426
427 protected async apiKeyAuth(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
428 if (this.apiKey == null) {
429 return undefined;
430 }
431 return buildHeaders([{ 'X-Auth-Key': this.apiKey }]);
432 }
433
434 protected async apiTokenAuth(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
435 if (this.apiToken == null) {
436 return undefined;
437 }
438 return buildHeaders([{ Authorization: `Bearer ${this.apiToken}` }]);
439 }
440
441 protected async userServiceKeyAuth(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
442 if (this.userServiceKey == null) {
443 return undefined;
444 }
445 return buildHeaders([{ 'X-Auth-User-Service-Key': this.userServiceKey }]);
446 }
447
448 protected stringifyQuery(query: object | Record<string, unknown>): string {
449 return stringifyQuery(query);
450 }
451
452 private getUserAgent(): string {
453 return `${this.constructor.name}/JS ${VERSION}`;
454 }
455
456 protected defaultIdempotencyKey(): string {
457 return `stainless-node-retry-${uuid4()}`;
458 }
459
460 protected makeStatusError(
461 status: number,
462 error: Object,
463 message: string | undefined,
464 headers: Headers,
465 ): Errors.APIError {
466 return Errors.APIError.generate(status, error, message, headers);
467 }
468
469 buildURL(
470 path: string,
471 query: Record<string, unknown> | null | undefined,
472 defaultBaseURL?: string | undefined,
473 ): string {
474 const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL;
475 const url =
476 isAbsoluteURL(path) ?
477 new URL(path)
478 : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
479
480 const defaultQuery = this.defaultQuery();
481 const pathQuery = Object.fromEntries(url.searchParams);
482 if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
483 query = { ...pathQuery, ...defaultQuery, ...query };
484 }
485
486 if (typeof query === 'object' && query && !Array.isArray(query)) {
487 url.search = this.stringifyQuery(query);
488 }
489
490 return url.toString();
491 }
492
493 /**
494 * Used as a callback for mutating the given `FinalRequestOptions` object.
495 */
496 protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}
497
498 /**
499 * Used as a callback for mutating the given `RequestInit` object.
500 *
501 * This is useful for cases where you want to add certain headers based off of
502 * the request properties, e.g. `method` or `url`.
503 */
504 protected async prepareRequest(
505 request: RequestInit,
506 { url, options }: { url: string; options: FinalRequestOptions },
507 ): Promise<void> {}
508
509 get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
510 return this.methodRequest('get', path, opts);
511 }
512
513 post<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
514 return this.methodRequest('post', path, opts);
515 }
516
517 patch<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
518 return this.methodRequest('patch', path, opts);
519 }
520
521 put<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
522 return this.methodRequest('put', path, opts);
523 }
524
525 delete<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
526 return this.methodRequest('delete', path, opts);
527 }
528
529 private methodRequest<Rsp>(
530 method: HTTPMethod,
531 path: string,
532 opts?: PromiseOrValue<RequestOptions>,
533 ): APIPromise<Rsp> {
534 return this.request(
535 Promise.resolve(opts).then((opts) => {
536 return { method, path, ...opts };
537 }),
538 );
539 }
540
541 request<Rsp>(
542 options: PromiseOrValue<FinalRequestOptions>,
543 remainingRetries: number | null = null,
544 ): APIPromise<Rsp> {
545 return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
546 }
547
548 private async makeRequest(
549 optionsInput: PromiseOrValue<FinalRequestOptions>,
550 retriesRemaining: number | null,
551 retryOfRequestLogID: string | undefined,
552 ): Promise<APIResponseProps> {
553 const options = await optionsInput;
554 const maxRetries = options.maxRetries ?? this.maxRetries;
555 if (retriesRemaining == null) {
556 retriesRemaining = maxRetries;
557 }
558
559 await this.prepareOptions(options);
560
561 const { req, url, timeout } = await this.buildRequest(options, {
562 retryCount: maxRetries - retriesRemaining,
563 });
564
565 await this.prepareRequest(req, { url, options });
566
567 /** Not an API request ID, just for correlating local log entries. */
568 const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
569 const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
570 const startTime = Date.now();
571
572 loggerFor(this).debug(
573 `[${requestLogID}] sending request`,
574 formatRequestDetails({
575 retryOfRequestLogID,
576 method: options.method,
577 url,
578 options,
579 headers: req.headers,
580 }),
581 );
582
583 if (options.signal?.aborted) {
584 throw new Errors.APIUserAbortError();
585 }
586
587 const controller = new AbortController();
588 const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
589 const headersTime = Date.now();
590
591 if (response instanceof globalThis.Error) {
592 const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
593 if (options.signal?.aborted) {
594 throw new Errors.APIUserAbortError();
595 }
596 // detect native connection timeout errors
597 // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
598 // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
599 // others do not provide enough information to distinguish timeouts from other connection errors
600 const isTimeout =
601 isAbortError(response) ||
602 /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
603 if (retriesRemaining) {
604 loggerFor(this).info(
605 `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`,
606 );
607 loggerFor(this).debug(
608 `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`,
609 formatRequestDetails({
610 retryOfRequestLogID,
611 url,
612 durationMs: headersTime - startTime,
613 message: response.message,
614 }),
615 );
616 return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
617 }
618 loggerFor(this).info(
619 `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`,
620 );
621 loggerFor(this).debug(
622 `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`,
623 formatRequestDetails({
624 retryOfRequestLogID,
625 url,
626 durationMs: headersTime - startTime,
627 message: response.message,
628 }),
629 );
630 if (isTimeout) {
631 throw new Errors.APIConnectionTimeoutError();
632 }
633 throw new Errors.APIConnectionError({ cause: response });
634 }
635
636 const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${
637 response.ok ? 'succeeded' : 'failed'
638 } with status ${response.status} in ${headersTime - startTime}ms`;
639
640 if (!response.ok) {
641 const shouldRetry = await this.shouldRetry(response);
642 if (retriesRemaining && shouldRetry) {
643 const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
644
645 // We don't need the body of this response.
646 await Shims.CancelReadableStream(response.body);
647 loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
648 loggerFor(this).debug(
649 `[${requestLogID}] response error (${retryMessage})`,
650 formatRequestDetails({
651 retryOfRequestLogID,
652 url: response.url,
653 status: response.status,
654 headers: response.headers,
655 durationMs: headersTime - startTime,
656 }),
657 );
658 return this.retryRequest(
659 options,
660 retriesRemaining,
661 retryOfRequestLogID ?? requestLogID,
662 response.headers,
663 );
664 }
665
666 const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
667
668 loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
669
670 const errText = await response.text().catch((err: any) => castToError(err).message);
671 const errJSON = safeJSON(errText) as any;
672 const errMessage = errJSON ? undefined : errText;
673
674 loggerFor(this).debug(
675 `[${requestLogID}] response error (${retryMessage})`,
676 formatRequestDetails({
677 retryOfRequestLogID,
678 url: response.url,
679 status: response.status,
680 headers: response.headers,
681 message: errMessage,
682 durationMs: Date.now() - startTime,
683 }),
684 );
685
686 const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
687 throw err;
688 }
689
690 loggerFor(this).info(responseInfo);
691 loggerFor(this).debug(
692 `[${requestLogID}] response start`,
693 formatRequestDetails({
694 retryOfRequestLogID,
695 url: response.url,
696 status: response.status,
697 headers: response.headers,
698 durationMs: headersTime - startTime,
699 }),
700 );
701
702 return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
703 }
704
705 getAPIList<Item, PageClass extends Pagination.AbstractPage<Item> = Pagination.AbstractPage<Item>>(
706 path: string,
707 Page: new (...args: any[]) => PageClass,
708 opts?: PromiseOrValue<RequestOptions>,
709 ): Pagination.PagePromise<PageClass, Item> {
710 return this.requestAPIList(
711 Page,
712 opts && 'then' in opts ?
713 opts.then((opts) => ({ method: 'get', path, ...opts }))
714 : { method: 'get', path, ...opts },
715 );
716 }
717
718 requestAPIList<
719 Item = unknown,
720 PageClass extends Pagination.AbstractPage<Item> = Pagination.AbstractPage<Item>,
721 >(
722 Page: new (...args: ConstructorParameters<typeof Pagination.AbstractPage>) => PageClass,
723 options: PromiseOrValue<FinalRequestOptions>,
724 ): Pagination.PagePromise<PageClass, Item> {
725 const request = this.makeRequest(options, null, undefined);
726 return new Pagination.PagePromise<PageClass, Item>(this as any as Cloudflare, request, Page);
727 }
728
729 async fetchWithTimeout(
730 url: RequestInfo,
731 init: RequestInit | undefined,
732 ms: number,
733 controller: AbortController,
734 ): Promise<Response> {
735 const { signal, method, ...options } = init || {};
736 const abort = this._makeAbort(controller);
737 if (signal) signal.addEventListener('abort', abort, { once: true });
738
739 const timeout = setTimeout(abort, ms);
740
741 const isReadableBody =
742 ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) ||
743 (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
744
745 const fetchOptions: RequestInit = {
746 signal: controller.signal as any,
747 ...(isReadableBody ? { duplex: 'half' } : {}),
748 method: 'GET',
749 ...options,
750 };
751 if (method) {
752 // Custom methods like 'patch' need to be uppercased
753 // See https://github.com/nodejs/undici/issues/2294
754 fetchOptions.method = method.toUpperCase();
755 }
756
757 try {
758 // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
759 return await this.fetch.call(undefined, url, fetchOptions);
760 } finally {
761 clearTimeout(timeout);
762 }
763 }
764
765 private async shouldRetry(response: Response): Promise<boolean> {
766 // Note this is not a standard header.
767 const shouldRetryHeader = response.headers.get('x-should-retry');
768
769 // If the server explicitly says whether or not to retry, obey.
770 if (shouldRetryHeader === 'true') return true;
771 if (shouldRetryHeader === 'false') return false;
772
773 // Retry on request timeouts.
774 if (response.status === 408) return true;
775
776 // Retry on lock timeouts.
777 if (response.status === 409) return true;
778
779 // Retry on rate limits.
780 if (response.status === 429) return true;
781
782 // Retry internal errors.
783 if (response.status >= 500) return true;
784
785 return false;
786 }
787
788 private async retryRequest(
789 options: FinalRequestOptions,
790 retriesRemaining: number,
791 requestLogID: string,
792 responseHeaders?: Headers | undefined,
793 ): Promise<APIResponseProps> {
794 let timeoutMillis: number | undefined;
795
796 // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
797 const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
798 if (retryAfterMillisHeader) {
799 const timeoutMs = parseFloat(retryAfterMillisHeader);
800 if (!Number.isNaN(timeoutMs)) {
801 timeoutMillis = timeoutMs;
802 }
803 }
804
805 // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
806 const retryAfterHeader = responseHeaders?.get('retry-after');
807 if (retryAfterHeader && !timeoutMillis) {
808 const timeoutSeconds = parseFloat(retryAfterHeader);
809 if (!Number.isNaN(timeoutSeconds)) {
810 timeoutMillis = timeoutSeconds * 1000;
811 } else {
812 timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
813 }
814 }
815
816 // If the API asks us to wait a certain amount of time, just do what it
817 // says, but otherwise calculate a default
818 if (timeoutMillis === undefined) {
819 const maxRetries = options.maxRetries ?? this.maxRetries;
820 timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
821 }
822 await sleep(timeoutMillis);
823
824 return this.makeRequest(options, retriesRemaining - 1, requestLogID);
825 }
826
827 private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
828 const initialRetryDelay = 0.5;
829 const maxRetryDelay = 8.0;
830
831 const numRetries = maxRetries - retriesRemaining;
832
833 // Apply exponential backoff, but not more than the max.
834 const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
835
836 // Apply some jitter, take up to at most 25 percent of the retry time.
837 const jitter = 1 - Math.random() * 0.25;
838
839 return sleepSeconds * jitter * 1000;
840 }
841
842 async buildRequest(
843 inputOptions: FinalRequestOptions,
844 { retryCount = 0 }: { retryCount?: number } = {},
845 ): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
846 const options = { ...inputOptions };
847 const { method, path, query, defaultBaseURL } = options;
848
849 const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
850 if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
851 options.timeout = options.timeout ?? this.timeout;
852 const { bodyHeaders, body } = this.buildBody({ options });
853 const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
854
855 const req: FinalizedRequestInit = {
856 method,
857 headers: reqHeaders,
858 ...(options.signal && { signal: options.signal }),
859 ...((globalThis as any).ReadableStream &&
860 body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }),
861 ...(body && { body }),
862 ...((this.fetchOptions as any) ?? {}),
863 ...((options.fetchOptions as any) ?? {}),
864 };
865
866 return { req, url, timeout: options.timeout };
867 }
868
869 private async buildHeaders({
870 options,
871 method,
872 bodyHeaders,
873 retryCount,
874 }: {
875 options: FinalRequestOptions;
876 method: HTTPMethod;
877 bodyHeaders: HeadersLike;
878 retryCount: number;
879 }): Promise<Headers> {
880 let idempotencyHeaders: HeadersLike = {};
881 if (this.idempotencyHeader && method !== 'get') {
882 if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
883 idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
884 }
885
886 const headers = buildHeaders([
887 idempotencyHeaders,
888 {
889 Accept: 'application/json',
890 'User-Agent': this.getUserAgent(),
891 'X-Stainless-Retry-Count': String(retryCount),
892 ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
893 ...getPlatformHeaders(),
894 'X-Auth-Key': this.apiKey,
895 'X-Auth-Email': this.apiEmail,
896 },
897 await this.authHeaders(options),
898 this._options.defaultHeaders,
899 bodyHeaders,
900 options.headers,
901 ]);
902
903 this.validateHeaders(headers);
904
905 return headers.values;
906 }
907
908 private _makeAbort(controller: AbortController) {
909 // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
910 // would capture all request options, and cause a memory leak.
911 return () => controller.abort();
912 }
913
914 private buildBody({ options }: { options: FinalRequestOptions }): {
915 bodyHeaders: HeadersLike;
916 body: BodyInit | undefined;
917 } {
918 const { body, headers: rawHeaders } = options;
919 if (!body) {
920 // A resource method always passes a `body` key when its operation defines a
921 // request body, even if the caller omitted an optional body param. Keep the
922 // content-type for those, and only elide it for operations with no body at
923 // all (e.g. GET/DELETE).
924 if (body == null && 'body' in options) {
925 return this.#encoder({ body, headers: buildHeaders([rawHeaders]) });
926 }
927 return { bodyHeaders: undefined, body: undefined };
928 }
929 const headers = buildHeaders([rawHeaders]);
930 if (
931 // Pass raw type verbatim
932 ArrayBuffer.isView(body) ||
933 body instanceof ArrayBuffer ||
934 body instanceof DataView ||
935 (typeof body === 'string' &&
936 // Preserve legacy string encoding behavior for now
937 headers.values.has('content-type')) ||
938 // `Blob` is superset of `File`
939 ((globalThis as any).Blob && body instanceof (globalThis as any).Blob) ||
940 // `FormData` -> `multipart/form-data`
941 body instanceof FormData ||
942 // `URLSearchParams` -> `application/x-www-form-urlencoded`
943 body instanceof URLSearchParams ||
944 // Send chunked stream (each chunk has own `length`)
945 ((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream)
946 ) {
947 return { bodyHeaders: undefined, body: body as BodyInit };
948 } else if (
949 typeof body === 'object' &&
950 (Symbol.asyncIterator in body ||
951 (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))
952 ) {
953 return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable<Uint8Array>) };
954 } else if (
955 typeof body === 'object' &&
956 headers.values.get('content-type') === 'application/x-www-form-urlencoded'
957 ) {
958 return {
959 bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
960 body: this.stringifyQuery(body),
961 };
962 } else {
963 return this.#encoder({ body, headers });
964 }
965 }
966
967 static DEFAULT_TIMEOUT = 60000; // 1 minute
968}
969
970/**
971 * API Client for interfacing with the Cloudflare API.
972 */
973export class Cloudflare extends BaseCloudflare {
974 static Cloudflare = this;
975
976 static CloudflareError = Errors.CloudflareError;
977 static APIError = Errors.APIError;
978 static APIConnectionError = Errors.APIConnectionError;
979 static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
980 static APIUserAbortError = Errors.APIUserAbortError;
981 static NotFoundError = Errors.NotFoundError;
982 static ConflictError = Errors.ConflictError;
983 static RateLimitError = Errors.RateLimitError;
984 static BadRequestError = Errors.BadRequestError;
985 static AuthenticationError = Errors.AuthenticationError;
986 static InternalServerError = Errors.InternalServerError;
987 static PermissionDeniedError = Errors.PermissionDeniedError;
988 static UnprocessableEntityError = Errors.UnprocessableEntityError;
989
990 static toFile = Uploads.toFile;
991
992 accounts: API.Accounts = new API.Accounts(this);
993 organizations: API.Organizations = new API.Organizations(this);
994 tenants: API.Tenants = new API.Tenants(this);
995 originCACertificates: API.OriginCACertificates = new API.OriginCACertificates(this);
996 ips: API.IPs = new API.IPs(this);
997 memberships: API.Memberships = new API.Memberships(this);
998 user: API.User = new API.User(this);
999 zones: API.Zones = new API.Zones(this);
1000 loadBalancers: API.LoadBalancers = new API.LoadBalancers(this);
1001 cache: API.Cache = new API.Cache(this);
1002 ssl: API.SSL = new API.SSL(this);
1003 acm: API.ACM = new API.ACM(this);
1004 argo: API.Argo = new API.Argo(this);
1005 certificateAuthorities: API.CertificateAuthorities = new API.CertificateAuthorities(this);
1006 clientCertificates: API.ClientCertificates = new API.ClientCertificates(this);
1007 customCertificates: API.CustomCertificates = new API.CustomCertificates(this);
1008 customCsrs: API.CustomCsrs = new API.CustomCsrs(this);
1009 customHostnames: API.CustomHostnames = new API.CustomHostnames(this);
1010 customNameservers: API.CustomNameservers = new API.CustomNameservers(this);
1011 tenantCustomNameservers: API.TenantCustomNameservers = new API.TenantCustomNameservers(this);
1012 dnsFirewall: API.DNSFirewall = new API.DNSFirewall(this);
1013 dns: API.DNS = new API.DNS(this);
1014 emailSecurity: API.EmailSecurity = new API.EmailSecurity(this);
1015 emailAuth: API.EmailAuth = new API.EmailAuth(this);
1016 emailRouting: API.EmailRouting = new API.EmailRouting(this);
1017 emailSending: API.EmailSending = new API.EmailSending(this);
1018 filters: API.Filters = new API.Filters(this);
1019 firewall: API.Firewall = new API.Firewall(this);
1020 healthchecks: API.Healthchecks = new API.Healthchecks(this);
1021 keylessCertificates: API.KeylessCertificates = new API.KeylessCertificates(this);
1022 logpush: API.Logpush = new API.Logpush(this);
1023 logs: API.Logs = new API.Logs(this);
1024 originTLSClientAuth: API.OriginTLSClientAuth = new API.OriginTLSClientAuth(this);
1025 pageRules: API.PageRules = new API.PageRules(this);
1026 rateLimits: API.RateLimits = new API.RateLimits(this);
1027 waitingRooms: API.WaitingRooms = new API.WaitingRooms(this);
1028 web3: API.Web3 = new API.Web3(this);
1029 workers: API.Workers = new API.Workers(this);
1030 kv: API.KV = new API.KV(this);
1031 durableObjects: API.DurableObjects = new API.DurableObjects(this);
1032 queues: API.Queues = new API.Queues(this);
1033 apiGateway: API.APIGateway = new API.APIGateway(this);
1034 managedTransforms: API.ManagedTransforms = new API.ManagedTransforms(this);
1035 pageShield: API.PageShield = new API.PageShield(this);
1036 rulesets: API.Rulesets = new API.Rulesets(this);
1037 urlNormalization: API.URLNormalization = new API.URLNormalization(this);
1038 spectrum: API.Spectrum = new API.Spectrum(this);
1039 addressing: API.Addressing = new API.Addressing(this);
1040 dls: API.DLS = new API.DLS(this);
1041 auditLogs: API.AuditLogs = new API.AuditLogs(this);
1042 billing: API.Billing = new API.Billing(this);
1043 brandProtection: API.BrandProtection = new API.BrandProtection(this);
1044 diagnostics: API.Diagnostics = new API.Diagnostics(this);
1045 images: API.Images = new API.Images(this);
1046 intel: API.Intel = new API.Intel(this);
1047 magicTransit: API.MagicTransit = new API.MagicTransit(this);
1048 DDoSProtection: API.DDoSProtection = new API.DDoSProtection(this);
1049 magicNetworkMonitoring: API.MagicNetworkMonitoring = new API.MagicNetworkMonitoring(this);
1050 magicCloudNetworking: API.MagicCloudNetworking = new API.MagicCloudNetworking(this);
1051 networkInterconnects: API.NetworkInterconnects = new API.NetworkInterconnects(this);
1052 mtlsCertificates: API.MTLSCertificates = new API.MTLSCertificates(this);
1053 pages: API.Pages = new API.Pages(this);
1054 registrar: API.Registrar = new API.Registrar(this);
1055 requestTracers: API.RequestTracers = new API.RequestTracers(this);
1056 rules: API.Rules = new API.Rules(this);
1057 stream: API.Stream = new API.Stream(this);
1058 alerting: API.Alerting = new API.Alerting(this);
1059 d1: API.D1Resource = new API.D1Resource(this);
1060 r2: API.R2 = new API.R2(this);
1061 r2DataCatalog: API.R2DataCatalog = new API.R2DataCatalog(this);
1062 workersForPlatforms: API.WorkersForPlatforms = new API.WorkersForPlatforms(this);
1063 zeroTrust: API.ZeroTrust = new API.ZeroTrust(this);
1064 turnstile: API.Turnstile = new API.Turnstile(this);
1065 connectivity: API.Connectivity = new API.Connectivity(this);
1066 hyperdrive: API.HyperdriveResource = new API.HyperdriveResource(this);
1067 rum: API.RUM = new API.RUM(this);
1068 vectorize: API.Vectorize = new API.Vectorize(this);
1069 urlScanner: API.URLScanner = new API.URLScanner(this);
1070 vulnerabilityScanner: API.VulnerabilityScanner = new API.VulnerabilityScanner(this);
1071 radar: API.Radar = new API.Radar(this);
1072 botManagement: API.BotManagement = new API.BotManagement(this);
1073 fraud: API.Fraud = new API.Fraud(this);
1074 originPostQuantumEncryption: API.OriginPostQuantumEncryption = new API.OriginPostQuantumEncryption(this);
1075 originTLSComplianceModes: API.OriginTLSComplianceModes = new API.OriginTLSComplianceModes(this);
1076 googleTagGateway: API.GoogleTagGateway = new API.GoogleTagGateway(this);
1077 zaraz: API.Zaraz = new API.Zaraz(this);
1078 speed: API.Speed = new API.Speed(this);
1079 dcvDelegation: API.DCVDelegation = new API.DCVDelegation(this);
1080 hostnames: API.Hostnames = new API.Hostnames(this);
1081 snippets: API.Snippets = new API.Snippets(this);
1082 realtimeKit: API.RealtimeKit = new API.RealtimeKit(this);
1083 calls: API.Calls = new API.Calls(this);
1084 moq: API.MoQ = new API.MoQ(this);
1085 cloudforceOne: API.CloudforceOne = new API.CloudforceOne(this);
1086 aiGateway: API.AIGateway = new API.AIGateway(this);
1087 flagship: API.Flagship = new API.Flagship(this);
1088 iam: API.IAM = new API.IAM(this);
1089 cloudConnector: API.CloudConnector = new API.CloudConnector(this);
1090 botnetFeed: API.BotnetFeed = new API.BotnetFeed(this);
1091 securityTXT: API.SecurityTXT = new API.SecurityTXT(this);
1092 workflows: API.Workflows = new API.Workflows(this);
1093 resourceSharing: API.ResourceSharing = new API.ResourceSharing(this);
1094 resourceTagging: API.ResourceTagging = new API.ResourceTagging(this);
1095 leakedCredentialChecks: API.LeakedCredentialChecks = new API.LeakedCredentialChecks(this);
1096 contentScanning: API.ContentScanning = new API.ContentScanning(this);
1097 aiSecurity: API.AISecurity = new API.AISecurity(this);
1098 csamScanner: API.CsamScanner = new API.CsamScanner(this);
1099 abuseReports: API.AbuseReports = new API.AbuseReports(this);
1100 ai: API.AI = new API.AI(this);
1101 aiAudit: API.AIAudit = new API.AIAudit(this);
1102 aiSearch: API.AISearch = new API.AISearch(this);
1103 securityCenter: API.SecurityCenter = new API.SecurityCenter(this);
1104 browserRendering: API.BrowserRendering = new API.BrowserRendering(this);
1105 customPages: API.CustomPages = new API.CustomPages(this);
1106 secretsStore: API.SecretsStore = new API.SecretsStore(this);
1107 pipelines: API.Pipelines = new API.Pipelines(this);
1108 schemaValidation: API.SchemaValidation = new API.SchemaValidation(this);
1109 tokenValidation: API.TokenValidation = new API.TokenValidation(this);
1110}
1111
1112Cloudflare.Accounts = Accounts;
1113Cloudflare.Organizations = Organizations;
1114Cloudflare.Tenants = Tenants;
1115Cloudflare.OriginCACertificates = OriginCACertificates;
1116Cloudflare.IPs = IPs;
1117Cloudflare.Memberships = Memberships;
1118Cloudflare.User = User;
1119Cloudflare.Zones = Zones;
1120Cloudflare.LoadBalancers = LoadBalancers;
1121Cloudflare.Cache = Cache;
1122Cloudflare.SSL = SSL;
1123Cloudflare.ACM = ACM;
1124Cloudflare.Argo = Argo;
1125Cloudflare.CertificateAuthorities = CertificateAuthorities;
1126Cloudflare.ClientCertificates = ClientCertificates;
1127Cloudflare.CustomCertificates = CustomCertificates;
1128Cloudflare.CustomCsrs = CustomCsrs;
1129Cloudflare.CustomHostnames = CustomHostnames;
1130Cloudflare.CustomNameservers = CustomNameservers;
1131Cloudflare.TenantCustomNameservers = TenantCustomNameservers;
1132Cloudflare.DNSFirewall = DNSFirewall;
1133Cloudflare.DNS = DNS;
1134Cloudflare.EmailSecurity = EmailSecurity;
1135Cloudflare.EmailAuth = EmailAuth;
1136Cloudflare.EmailRouting = EmailRouting;
1137Cloudflare.EmailSending = EmailSending;
1138Cloudflare.Filters = Filters;
1139Cloudflare.Firewall = Firewall;
1140Cloudflare.Healthchecks = Healthchecks;
1141Cloudflare.KeylessCertificates = KeylessCertificates;
1142Cloudflare.Logpush = Logpush;
1143Cloudflare.Logs = Logs;
1144Cloudflare.OriginTLSClientAuth = OriginTLSClientAuth;
1145Cloudflare.PageRules = PageRules;
1146Cloudflare.RateLimits = RateLimits;
1147Cloudflare.WaitingRooms = WaitingRooms;
1148Cloudflare.Web3 = Web3;
1149Cloudflare.Workers = Workers;
1150Cloudflare.KV = KV;
1151Cloudflare.DurableObjects = DurableObjects;
1152Cloudflare.Queues = Queues;
1153Cloudflare.APIGateway = APIGateway;
1154Cloudflare.ManagedTransforms = ManagedTransforms;
1155Cloudflare.PageShield = PageShield;
1156Cloudflare.Rulesets = Rulesets;
1157Cloudflare.URLNormalization = URLNormalization;
1158Cloudflare.Spectrum = Spectrum;
1159Cloudflare.Addressing = Addressing;
1160Cloudflare.DLS = DLS;
1161Cloudflare.AuditLogs = AuditLogs;
1162Cloudflare.Billing = Billing;
1163Cloudflare.BrandProtection = BrandProtection;
1164Cloudflare.Diagnostics = Diagnostics;
1165Cloudflare.Images = Images;
1166Cloudflare.Intel = Intel;
1167Cloudflare.MagicTransit = MagicTransit;
1168Cloudflare.DDoSProtection = DDoSProtection;
1169Cloudflare.MagicNetworkMonitoring = MagicNetworkMonitoring;
1170Cloudflare.MagicCloudNetworking = MagicCloudNetworking;
1171Cloudflare.NetworkInterconnects = NetworkInterconnects;
1172Cloudflare.MTLSCertificates = MTLSCertificates;
1173Cloudflare.Pages = Pages;
1174Cloudflare.Registrar = Registrar;
1175Cloudflare.RequestTracers = RequestTracers;
1176Cloudflare.Rules = Rules;
1177Cloudflare.Stream = Stream;
1178Cloudflare.Alerting = Alerting;
1179Cloudflare.D1Resource = D1Resource;
1180Cloudflare.R2 = R2;
1181Cloudflare.R2DataCatalog = R2DataCatalog;
1182Cloudflare.WorkersForPlatforms = WorkersForPlatforms;
1183Cloudflare.ZeroTrust = ZeroTrust;
1184Cloudflare.Turnstile = Turnstile;
1185Cloudflare.Connectivity = Connectivity;
1186Cloudflare.HyperdriveResource = HyperdriveResource;
1187Cloudflare.RUM = RUM;
1188Cloudflare.Vectorize = Vectorize;
1189Cloudflare.URLScanner = URLScanner;
1190Cloudflare.VulnerabilityScanner = VulnerabilityScanner;
1191Cloudflare.Radar = Radar;
1192Cloudflare.BotManagement = BotManagement;
1193Cloudflare.Fraud = Fraud;
1194Cloudflare.OriginPostQuantumEncryption = OriginPostQuantumEncryption;
1195Cloudflare.OriginTLSComplianceModes = OriginTLSComplianceModes;
1196Cloudflare.GoogleTagGateway = GoogleTagGateway;
1197Cloudflare.Zaraz = Zaraz;
1198Cloudflare.Speed = Speed;
1199Cloudflare.DCVDelegation = DCVDelegation;
1200Cloudflare.Hostnames = Hostnames;
1201Cloudflare.Snippets = Snippets;
1202Cloudflare.RealtimeKit = RealtimeKit;
1203Cloudflare.Calls = Calls;
1204Cloudflare.MoQ = MoQ;
1205Cloudflare.CloudforceOne = CloudforceOne;
1206Cloudflare.AIGateway = AIGateway;
1207Cloudflare.Flagship = Flagship;
1208Cloudflare.IAM = IAM;
1209Cloudflare.CloudConnector = CloudConnector;
1210Cloudflare.BotnetFeed = BotnetFeed;
1211Cloudflare.SecurityTXT = SecurityTXT;
1212Cloudflare.Workflows = Workflows;
1213Cloudflare.ResourceSharing = ResourceSharing;
1214Cloudflare.ResourceTagging = ResourceTagging;
1215Cloudflare.LeakedCredentialChecks = LeakedCredentialChecks;
1216Cloudflare.ContentScanning = ContentScanning;
1217Cloudflare.AISecurity = AISecurity;
1218Cloudflare.CsamScanner = CsamScanner;
1219Cloudflare.AbuseReports = AbuseReports;
1220Cloudflare.AI = AI;
1221Cloudflare.AIAudit = AIAudit;
1222Cloudflare.AISearch = AISearch;
1223Cloudflare.SecurityCenter = SecurityCenter;
1224Cloudflare.BrowserRendering = BrowserRendering;
1225Cloudflare.CustomPages = CustomPages;
1226Cloudflare.SecretsStore = SecretsStore;
1227Cloudflare.Pipelines = Pipelines;
1228Cloudflare.SchemaValidation = SchemaValidation;
1229Cloudflare.TokenValidation = TokenValidation;
1230
1231export declare namespace Cloudflare {
1232 export type RequestOptions = Opts.RequestOptions;
1233
1234 export import V4PagePagination = Pagination.V4PagePagination;
1235 export {
1236 type V4PagePaginationParams as V4PagePaginationParams,
1237 type V4PagePaginationResponse as V4PagePaginationResponse,
1238 };
1239
1240 export import V4PagePaginationArray = Pagination.V4PagePaginationArray;
1241 export {
1242 type V4PagePaginationArrayParams as V4PagePaginationArrayParams,
1243 type V4PagePaginationArrayResponse as V4PagePaginationArrayResponse,
1244 };
1245
1246 export import CursorPagination = Pagination.CursorPagination;
1247 export {
1248 type CursorPaginationParams as CursorPaginationParams,
1249 type CursorPaginationResponse as CursorPaginationResponse,
1250 };
1251
1252 export import CursorPaginationAfter = Pagination.CursorPaginationAfter;
1253 export {
1254 type CursorPaginationAfterParams as CursorPaginationAfterParams,
1255 type CursorPaginationAfterResponse as CursorPaginationAfterResponse,
1256 };
1257
1258 export import CursorLimitPagination = Pagination.CursorLimitPagination;
1259 export {
1260 type CursorLimitPaginationParams as CursorLimitPaginationParams,
1261 type CursorLimitPaginationResponse as CursorLimitPaginationResponse,
1262 };
1263
1264 export import SinglePage = Pagination.SinglePage;
1265 export { type SinglePageResponse as SinglePageResponse };
1266
1267 export { Accounts as Accounts };
1268
1269 export { Organizations as Organizations };
1270
1271 export { Tenants as Tenants };
1272
1273 export { OriginCACertificates as OriginCACertificates };
1274
1275 export { IPs as IPs };
1276
1277 export { Memberships as Memberships };
1278
1279 export { User as User };
1280
1281 export { Zones as Zones };
1282
1283 export { LoadBalancers as LoadBalancers };
1284
1285 export { Cache as Cache };
1286
1287 export { SSL as SSL };
1288
1289 export { ACM as ACM };
1290
1291 export { Argo as Argo };
1292
1293 export { CertificateAuthorities as CertificateAuthorities };
1294
1295 export { ClientCertificates as ClientCertificates };
1296
1297 export { CustomCertificates as CustomCertificates };
1298
1299 export { CustomCsrs as CustomCsrs };
1300
1301 export { CustomHostnames as CustomHostnames };
1302
1303 export { CustomNameservers as CustomNameservers };
1304
1305 export { TenantCustomNameservers as TenantCustomNameservers };
1306
1307 export { DNSFirewall as DNSFirewall };
1308
1309 export { DNS as DNS };
1310
1311 export { EmailSecurity as EmailSecurity };
1312
1313 export { EmailAuth as EmailAuth };
1314
1315 export { EmailRouting as EmailRouting };
1316
1317 export { EmailSending as EmailSending };
1318
1319 export { Filters as Filters };
1320
1321 export { Firewall as Firewall };
1322
1323 export { Healthchecks as Healthchecks };
1324
1325 export { KeylessCertificates as KeylessCertificates };
1326
1327 export { Logpush as Logpush };
1328
1329 export { Logs as Logs };
1330
1331 export { OriginTLSClientAuth as OriginTLSClientAuth };
1332
1333 export { PageRules as PageRules };
1334
1335 export { RateLimits as RateLimits };
1336
1337 export { WaitingRooms as WaitingRooms };
1338
1339 export { Web3 as Web3 };
1340
1341 export { Workers as Workers };
1342
1343 export { KV as KV };
1344
1345 export { DurableObjects as DurableObjects };
1346
1347 export { Queues as Queues };
1348
1349 export { APIGateway as APIGateway };
1350
1351 export { ManagedTransforms as ManagedTransforms };
1352
1353 export { PageShield as PageShield };
1354
1355 export { Rulesets as Rulesets };
1356
1357 export { URLNormalization as URLNormalization };
1358
1359 export { Spectrum as Spectrum };
1360
1361 export { Addressing as Addressing };
1362
1363 export { DLS as DLS };
1364
1365 export { AuditLogs as AuditLogs };
1366
1367 export { Billing as Billing };
1368
1369 export { BrandProtection as BrandProtection };
1370
1371 export { Diagnostics as Diagnostics };
1372
1373 export { Images as Images };
1374
1375 export { Intel as Intel };
1376
1377 export { MagicTransit as MagicTransit };
1378
1379 export { DDoSProtection as DDoSProtection };
1380
1381 export { MagicNetworkMonitoring as MagicNetworkMonitoring };
1382
1383 export { MagicCloudNetworking as MagicCloudNetworking };
1384
1385 export { NetworkInterconnects as NetworkInterconnects };
1386
1387 export { MTLSCertificates as MTLSCertificates };
1388
1389 export { Pages as Pages };
1390
1391 export { Registrar as Registrar };
1392
1393 export { RequestTracers as RequestTracers };
1394
1395 export { Rules as Rules };
1396
1397 export { Stream as Stream };
1398
1399 export { Alerting as Alerting };
1400
1401 export { D1Resource as D1Resource };
1402
1403 export { R2 as R2 };
1404
1405 export { R2DataCatalog as R2DataCatalog };
1406
1407 export { WorkersForPlatforms as WorkersForPlatforms };
1408
1409 export { ZeroTrust as ZeroTrust };
1410
1411 export { Turnstile as Turnstile };
1412
1413 export { Connectivity as Connectivity };
1414
1415 export { HyperdriveResource as HyperdriveResource };
1416
1417 export { RUM as RUM };
1418
1419 export { Vectorize as Vectorize };
1420
1421 export { URLScanner as URLScanner };
1422
1423 export { VulnerabilityScanner as VulnerabilityScanner };
1424
1425 export { Radar as Radar };
1426
1427 export { BotManagement as BotManagement };
1428
1429 export { Fraud as Fraud };
1430
1431 export { OriginPostQuantumEncryption as OriginPostQuantumEncryption };
1432
1433 export { OriginTLSComplianceModes as OriginTLSComplianceModes };
1434
1435 export { GoogleTagGateway as GoogleTagGateway };
1436
1437 export { Zaraz as Zaraz };
1438
1439 export { Speed as Speed };
1440
1441 export { DCVDelegation as DCVDelegation };
1442
1443 export { Hostnames as Hostnames };
1444
1445 export { Snippets as Snippets };
1446
1447 export { RealtimeKit as RealtimeKit };
1448
1449 export { Calls as Calls };
1450
1451 export { MoQ as MoQ };
1452
1453 export { CloudforceOne as CloudforceOne };
1454
1455 export { AIGateway as AIGateway };
1456
1457 export { Flagship as Flagship };
1458
1459 export { IAM as IAM };
1460
1461 export { CloudConnector as CloudConnector };
1462
1463 export { BotnetFeed as BotnetFeed };
1464
1465 export { SecurityTXT as SecurityTXT };
1466
1467 export { Workflows as Workflows };
1468
1469 export { ResourceSharing as ResourceSharing };
1470
1471 export { ResourceTagging as ResourceTagging };
1472
1473 export { LeakedCredentialChecks as LeakedCredentialChecks };
1474
1475 export { ContentScanning as ContentScanning };
1476
1477 export { AISecurity as AISecurity };
1478
1479 export { CsamScanner as CsamScanner };
1480
1481 export { AbuseReports as AbuseReports };
1482
1483 export { AI as AI };
1484
1485 export { AIAudit as AIAudit };
1486
1487 export { AISearch as AISearch };
1488
1489 export { SecurityCenter as SecurityCenter };
1490
1491 export { BrowserRendering as BrowserRendering };
1492
1493 export { CustomPages as CustomPages };
1494
1495 export { SecretsStore as SecretsStore };
1496
1497 export { Pipelines as Pipelines };
1498
1499 export { SchemaValidation as SchemaValidation };
1500
1501 export { TokenValidation as TokenValidation };
1502
1503 export type ASN = API.ASN;
1504 export type AuditLog = API.AuditLog;
1505 export type CertificateCA = API.CertificateCA;
1506 export type CertificateRequestType = API.CertificateRequestType;
1507 export type CloudflareTunnel = API.CloudflareTunnel;
1508 export type ErrorData = API.ErrorData;
1509 export type Identifier = API.Identifier;
1510 export type LoadBalancerPreview = API.LoadBalancerPreview;
1511 export type Member = API.Member;
1512 export type PaginationInfo = API.PaginationInfo;
1513 export type Permission = API.Permission;
1514 export type PermissionGrant = API.PermissionGrant;
1515 export type RatePlan = API.RatePlan;
1516 export type ResponseInfo = API.ResponseInfo;
1517 export type Result = API.Result;
1518 export type Role = API.Role;
1519 export type SortDirection = API.SortDirection;
1520 export type Subscription = API.Subscription;
1521 export type SubscriptionComponent = API.SubscriptionComponent;
1522 export type SubscriptionZone = API.SubscriptionZone;
1523 export type Token = API.Token;
1524 export type TokenConditionCIDRList = API.TokenConditionCIDRList;
1525 export type TokenPolicy = API.TokenPolicy;
1526 export type TokenValue = API.TokenValue;
1527}