cloudflare/cloudflare-typescript

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0f711a6ec6dfa3a06bb7b4f9dcb2223ac65707d9

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/client.ts

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