cloudflare/cloudflare-typescript

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
ea8255ae5dc48a4f6bf3e53155d54e92ccc48d02

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/client.ts

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