cloudflare/cloudflare-typescript

Public

mirrored fromhttps://github.com/cloudflare/cloudflare-typescriptAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v3.5.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/index.ts

587lines · modecode

1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3import * as Errors from './error';
4import * as Uploads from './uploads';
5import { type Agent } from './_shims/index';
6import * as qs from 'qs';
7import * as Core from './core';
8import * as Pagination from './pagination';
9import * as API from './resources/index';
10
11export interface ClientOptions {
12 /**
13 * Defaults to process.env['CLOUDFLARE_API_TOKEN'].
14 */
15 apiToken?: string | null | undefined;
16
17 /**
18 * Defaults to process.env['CLOUDFLARE_API_KEY'].
19 */
20 apiKey?: string | null | undefined;
21
22 /**
23 * Defaults to process.env['CLOUDFLARE_EMAIL'].
24 */
25 apiEmail?: string | null | undefined;
26
27 /**
28 * Defaults to process.env['CLOUDFLARE_API_USER_SERVICE_KEY'].
29 */
30 userServiceKey?: string | null | undefined;
31
32 /**
33 * Override the default base URL for the API, e.g., "https://api.example.com/v2/"
34 *
35 * Defaults to process.env['CLOUDFLARE_BASE_URL'].
36 */
37 baseURL?: string | null | undefined;
38
39 /**
40 * The maximum amount of time (in milliseconds) that the client should wait for a response
41 * from the server before timing out a single request.
42 *
43 * Note that request timeouts are retried by default, so in a worst-case scenario you may wait
44 * much longer than this timeout before the promise succeeds or fails.
45 */
46 timeout?: number;
47
48 /**
49 * An HTTP agent used to manage HTTP(S) connections.
50 *
51 * If not provided, an agent will be constructed by default in the Node.js environment,
52 * otherwise no agent is used.
53 */
54 httpAgent?: Agent;
55
56 /**
57 * Specify a custom `fetch` function implementation.
58 *
59 * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
60 * defined globally.
61 */
62 fetch?: Core.Fetch | undefined;
63
64 /**
65 * The maximum number of times that the client will retry a request in case of a
66 * temporary failure, like a network error or a 5XX error from the server.
67 *
68 * @default 2
69 */
70 maxRetries?: number;
71
72 /**
73 * Default headers to include with every request to the API.
74 *
75 * These can be removed in individual requests by explicitly setting the
76 * header to `undefined` or `null` in request options.
77 */
78 defaultHeaders?: Core.Headers;
79
80 /**
81 * Default query parameters to include with every request to the API.
82 *
83 * These can be removed in individual requests by explicitly setting the
84 * param to `undefined` in request options.
85 */
86 defaultQuery?: Core.DefaultQuery;
87}
88
89/**
90 * API Client for interfacing with the Cloudflare API.
91 */
92export class Cloudflare extends Core.APIClient {
93 apiToken: string | null;
94 apiKey: string | null;
95 apiEmail: string | null;
96 userServiceKey: string | null;
97
98 private _options: ClientOptions;
99
100 /**
101 * API Client for interfacing with the Cloudflare API.
102 *
103 * @param {string | null | undefined} [opts.apiToken=process.env['CLOUDFLARE_API_TOKEN'] ?? null]
104 * @param {string | null | undefined} [opts.apiKey=process.env['CLOUDFLARE_API_KEY'] ?? null]
105 * @param {string | null | undefined} [opts.apiEmail=process.env['CLOUDFLARE_EMAIL'] ?? null]
106 * @param {string | null | undefined} [opts.userServiceKey=process.env['CLOUDFLARE_API_USER_SERVICE_KEY'] ?? null]
107 * @param {string} [opts.baseURL=process.env['CLOUDFLARE_BASE_URL'] ?? https://api.cloudflare.com/client/v4] - Override the default base URL for the API.
108 * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
109 * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
110 * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
111 * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
112 * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
113 * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
114 */
115 constructor({
116 baseURL = Core.readEnv('CLOUDFLARE_BASE_URL'),
117 apiToken = Core.readEnv('CLOUDFLARE_API_TOKEN') ?? null,
118 apiKey = Core.readEnv('CLOUDFLARE_API_KEY') ?? null,
119 apiEmail = Core.readEnv('CLOUDFLARE_EMAIL') ?? null,
120 userServiceKey = Core.readEnv('CLOUDFLARE_API_USER_SERVICE_KEY') ?? null,
121 ...opts
122 }: ClientOptions = {}) {
123 const options: ClientOptions = {
124 apiToken,
125 apiKey,
126 apiEmail,
127 userServiceKey,
128 ...opts,
129 baseURL: baseURL || `https://api.cloudflare.com/client/v4`,
130 };
131
132 super({
133 baseURL: options.baseURL!,
134 timeout: options.timeout ?? 60000 /* 1 minute */,
135 httpAgent: options.httpAgent,
136 maxRetries: options.maxRetries,
137 fetch: options.fetch,
138 });
139
140 this._options = options;
141
142 this.apiToken = apiToken;
143 this.apiKey = apiKey;
144 this.apiEmail = apiEmail;
145 this.userServiceKey = userServiceKey;
146 }
147
148 accounts: API.Accounts = new API.Accounts(this);
149 originCACertificates: API.OriginCACertificates = new API.OriginCACertificates(this);
150 ips: API.IPs = new API.IPs(this);
151 memberships: API.Memberships = new API.Memberships(this);
152 user: API.User = new API.User(this);
153 zones: API.Zones = new API.Zones(this);
154 loadBalancers: API.LoadBalancers = new API.LoadBalancers(this);
155 cache: API.Cache = new API.Cache(this);
156 ssl: API.SSL = new API.SSL(this);
157 subscriptions: API.Subscriptions = new API.Subscriptions(this);
158 acm: API.ACM = new API.ACM(this);
159 argo: API.Argo = new API.Argo(this);
160 plans: API.Plans = new API.Plans(this);
161 ratePlans: API.RatePlans = new API.RatePlans(this);
162 certificateAuthorities: API.CertificateAuthorities = new API.CertificateAuthorities(this);
163 clientCertificates: API.ClientCertificates = new API.ClientCertificates(this);
164 customCertificates: API.CustomCertificates = new API.CustomCertificates(this);
165 customHostnames: API.CustomHostnames = new API.CustomHostnames(this);
166 customNameservers: API.CustomNameservers = new API.CustomNameservers(this);
167 dns: API.DNS = new API.DNS(this);
168 dnssec: API.DNSSECResource = new API.DNSSECResource(this);
169 emailRouting: API.EmailRouting = new API.EmailRouting(this);
170 filters: API.Filters = new API.Filters(this);
171 firewall: API.Firewall = new API.Firewall(this);
172 healthchecks: API.Healthchecks = new API.Healthchecks(this);
173 keylessCertificates: API.KeylessCertificates = new API.KeylessCertificates(this);
174 logpush: API.Logpush = new API.Logpush(this);
175 logs: API.Logs = new API.Logs(this);
176 originTLSClientAuth: API.OriginTLSClientAuth = new API.OriginTLSClientAuth(this);
177 pagerules: API.Pagerules = new API.Pagerules(this);
178 rateLimits: API.RateLimits = new API.RateLimits(this);
179 secondaryDNS: API.SecondaryDNS = new API.SecondaryDNS(this);
180 waitingRooms: API.WaitingRooms = new API.WaitingRooms(this);
181 web3: API.Web3 = new API.Web3(this);
182 workers: API.Workers = new API.Workers(this);
183 kv: API.KV = new API.KV(this);
184 durableObjects: API.DurableObjects = new API.DurableObjects(this);
185 queues: API.Queues = new API.Queues(this);
186 apiGateway: API.APIGateway = new API.APIGateway(this);
187 managedHeaders: API.ManagedHeaders = new API.ManagedHeaders(this);
188 pageShield: API.PageShield = new API.PageShield(this);
189 rulesets: API.Rulesets = new API.Rulesets(this);
190 urlNormalization: API.URLNormalization = new API.URLNormalization(this);
191 spectrum: API.Spectrum = new API.Spectrum(this);
192 addressing: API.Addressing = new API.Addressing(this);
193 auditLogs: API.AuditLogs = new API.AuditLogs(this);
194 billing: API.Billing = new API.Billing(this);
195 brandProtection: API.BrandProtection = new API.BrandProtection(this);
196 diagnostics: API.Diagnostics = new API.Diagnostics(this);
197 images: API.Images = new API.Images(this);
198 intel: API.Intel = new API.Intel(this);
199 magicTransit: API.MagicTransit = new API.MagicTransit(this);
200 magicNetworkMonitoring: API.MagicNetworkMonitoring = new API.MagicNetworkMonitoring(this);
201 mtlsCertificates: API.MTLSCertificates = new API.MTLSCertificates(this);
202 pages: API.Pages = new API.Pages(this);
203 pcaps: API.PCAPs = new API.PCAPs(this);
204 registrar: API.Registrar = new API.Registrar(this);
205 requestTracers: API.RequestTracers = new API.RequestTracers(this);
206 rules: API.Rules = new API.Rules(this);
207 storage: API.Storage = new API.Storage(this);
208 stream: API.Stream = new API.Stream(this);
209 alerting: API.Alerting = new API.Alerting(this);
210 d1: API.D1Resource = new API.D1Resource(this);
211 r2: API.R2 = new API.R2(this);
212 warpConnector: API.WARPConnector = new API.WARPConnector(this);
213 workersForPlatforms: API.WorkersForPlatforms = new API.WorkersForPlatforms(this);
214 zeroTrust: API.ZeroTrust = new API.ZeroTrust(this);
215 challenges: API.Challenges = new API.Challenges(this);
216 hyperdrive: API.HyperdriveResource = new API.HyperdriveResource(this);
217 rum: API.RUM = new API.RUM(this);
218 vectorize: API.Vectorize = new API.Vectorize(this);
219 urlScanner: API.URLScanner = new API.URLScanner(this);
220 radar: API.Radar = new API.Radar(this);
221 botManagement: API.BotManagement = new API.BotManagement(this);
222 originPostQuantumEncryption: API.OriginPostQuantumEncryption = new API.OriginPostQuantumEncryption(this);
223 speed: API.Speed = new API.Speed(this);
224 dcvDelegation: API.DCVDelegation = new API.DCVDelegation(this);
225 hostnames: API.Hostnames = new API.Hostnames(this);
226 snippets: API.Snippets = new API.Snippets(this);
227 calls: API.Calls = new API.Calls(this);
228 cloudforceOne: API.CloudforceOne = new API.CloudforceOne(this);
229 eventNotifications: API.EventNotifications = new API.EventNotifications(this);
230 aiGateway: API.AIGateway = new API.AIGateway(this);
231 iam: API.IAM = new API.IAM(this);
232 cloudConnector: API.CloudConnector = new API.CloudConnector(this);
233
234 protected override defaultQuery(): Core.DefaultQuery | undefined {
235 return this._options.defaultQuery;
236 }
237
238 protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
239 return {
240 ...super.defaultHeaders(opts),
241 'X-Auth-Key': this.apiKey,
242 'X-Auth-Email': this.apiEmail,
243 ...this._options.defaultHeaders,
244 };
245 }
246
247 protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {
248 if (this.apiEmail && headers['x-auth-email']) {
249 return;
250 }
251 if (customHeaders['x-auth-email'] === null) {
252 return;
253 }
254
255 if (this.apiKey && headers['x-auth-key']) {
256 return;
257 }
258 if (customHeaders['x-auth-key'] === null) {
259 return;
260 }
261
262 if (this.apiToken && headers['authorization']) {
263 return;
264 }
265 if (customHeaders['authorization'] === null) {
266 return;
267 }
268
269 if (this.userServiceKey && headers['x-auth-user-service-key']) {
270 return;
271 }
272 if (customHeaders['x-auth-user-service-key'] === null) {
273 return;
274 }
275
276 throw new Error(
277 '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',
278 );
279 }
280
281 protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
282 const apiEmailAuth = this.apiEmailAuth(opts);
283 const apiKeyAuth = this.apiKeyAuth(opts);
284 const apiTokenAuth = this.apiTokenAuth(opts);
285 const userServiceKeyAuth = this.userServiceKeyAuth(opts);
286
287 if (
288 apiEmailAuth != null &&
289 !Core.isEmptyObj(apiEmailAuth) &&
290 apiKeyAuth != null &&
291 !Core.isEmptyObj(apiKeyAuth)
292 ) {
293 return { ...apiEmailAuth, ...apiKeyAuth };
294 }
295
296 if (apiTokenAuth != null && !Core.isEmptyObj(apiTokenAuth)) {
297 return apiTokenAuth;
298 }
299
300 if (userServiceKeyAuth != null && !Core.isEmptyObj(userServiceKeyAuth)) {
301 return userServiceKeyAuth;
302 }
303 return {};
304 }
305
306 protected apiEmailAuth(opts: Core.FinalRequestOptions): Core.Headers {
307 if (this.apiEmail == null) {
308 return {};
309 }
310 return { 'X-Auth-Email': this.apiEmail };
311 }
312
313 protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
314 if (this.apiKey == null) {
315 return {};
316 }
317 return { 'X-Auth-Key': this.apiKey };
318 }
319
320 protected apiTokenAuth(opts: Core.FinalRequestOptions): Core.Headers {
321 if (this.apiToken == null) {
322 return {};
323 }
324 return { Authorization: `Bearer ${this.apiToken}` };
325 }
326
327 protected userServiceKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
328 if (this.userServiceKey == null) {
329 return {};
330 }
331 return { 'X-Auth-User-Service-Key': this.userServiceKey };
332 }
333
334 protected override stringifyQuery(query: Record<string, unknown>): string {
335 return qs.stringify(query, { allowDots: true, arrayFormat: 'repeat' });
336 }
337
338 static Cloudflare = this;
339
340 static CloudflareError = Errors.CloudflareError;
341 static APIError = Errors.APIError;
342 static APIConnectionError = Errors.APIConnectionError;
343 static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
344 static APIUserAbortError = Errors.APIUserAbortError;
345 static NotFoundError = Errors.NotFoundError;
346 static ConflictError = Errors.ConflictError;
347 static RateLimitError = Errors.RateLimitError;
348 static BadRequestError = Errors.BadRequestError;
349 static AuthenticationError = Errors.AuthenticationError;
350 static InternalServerError = Errors.InternalServerError;
351 static PermissionDeniedError = Errors.PermissionDeniedError;
352 static UnprocessableEntityError = Errors.UnprocessableEntityError;
353
354 static toFile = Uploads.toFile;
355 static fileFromPath = Uploads.fileFromPath;
356}
357
358export const {
359 CloudflareError,
360 APIError,
361 APIConnectionError,
362 APIConnectionTimeoutError,
363 APIUserAbortError,
364 NotFoundError,
365 ConflictError,
366 RateLimitError,
367 BadRequestError,
368 AuthenticationError,
369 InternalServerError,
370 PermissionDeniedError,
371 UnprocessableEntityError,
372} = Errors;
373
374export import toFile = Uploads.toFile;
375export import fileFromPath = Uploads.fileFromPath;
376
377export namespace Cloudflare {
378 export import RequestOptions = Core.RequestOptions;
379
380 export import V4PagePagination = Pagination.V4PagePagination;
381 export import V4PagePaginationParams = Pagination.V4PagePaginationParams;
382 export import V4PagePaginationResponse = Pagination.V4PagePaginationResponse;
383
384 export import V4PagePaginationArray = Pagination.V4PagePaginationArray;
385 export import V4PagePaginationArrayParams = Pagination.V4PagePaginationArrayParams;
386 export import V4PagePaginationArrayResponse = Pagination.V4PagePaginationArrayResponse;
387
388 export import CursorPagination = Pagination.CursorPagination;
389 export import CursorPaginationParams = Pagination.CursorPaginationParams;
390 export import CursorPaginationResponse = Pagination.CursorPaginationResponse;
391
392 export import CursorLimitPagination = Pagination.CursorLimitPagination;
393 export import CursorLimitPaginationParams = Pagination.CursorLimitPaginationParams;
394 export import CursorLimitPaginationResponse = Pagination.CursorLimitPaginationResponse;
395
396 export import SinglePage = Pagination.SinglePage;
397 export import SinglePageResponse = Pagination.SinglePageResponse;
398
399 export import Accounts = API.Accounts;
400
401 export import OriginCACertificates = API.OriginCACertificates;
402
403 export import IPs = API.IPs;
404
405 export import Memberships = API.Memberships;
406
407 export import User = API.User;
408
409 export import Zones = API.Zones;
410
411 export import LoadBalancers = API.LoadBalancers;
412
413 export import Cache = API.Cache;
414
415 export import SSL = API.SSL;
416
417 export import Subscriptions = API.Subscriptions;
418
419 export import ACM = API.ACM;
420
421 export import Argo = API.Argo;
422
423 export import Plans = API.Plans;
424
425 export import RatePlans = API.RatePlans;
426
427 export import CertificateAuthorities = API.CertificateAuthorities;
428
429 export import ClientCertificates = API.ClientCertificates;
430
431 export import CustomCertificates = API.CustomCertificates;
432
433 export import CustomHostnames = API.CustomHostnames;
434
435 export import CustomNameservers = API.CustomNameservers;
436
437 export import DNS = API.DNS;
438
439 export import DNSSECResource = API.DNSSECResource;
440
441 export import EmailRouting = API.EmailRouting;
442
443 export import Filters = API.Filters;
444
445 export import Firewall = API.Firewall;
446
447 export import Healthchecks = API.Healthchecks;
448
449 export import KeylessCertificates = API.KeylessCertificates;
450
451 export import Logpush = API.Logpush;
452
453 export import Logs = API.Logs;
454
455 export import OriginTLSClientAuth = API.OriginTLSClientAuth;
456
457 export import Pagerules = API.Pagerules;
458
459 export import RateLimits = API.RateLimits;
460
461 export import SecondaryDNS = API.SecondaryDNS;
462
463 export import WaitingRooms = API.WaitingRooms;
464
465 export import Web3 = API.Web3;
466
467 export import Workers = API.Workers;
468
469 export import KV = API.KV;
470
471 export import DurableObjects = API.DurableObjects;
472
473 export import Queues = API.Queues;
474
475 export import APIGateway = API.APIGateway;
476
477 export import ManagedHeaders = API.ManagedHeaders;
478
479 export import PageShield = API.PageShield;
480
481 export import Rulesets = API.Rulesets;
482
483 export import URLNormalization = API.URLNormalization;
484
485 export import Spectrum = API.Spectrum;
486
487 export import Addressing = API.Addressing;
488
489 export import AuditLogs = API.AuditLogs;
490
491 export import Billing = API.Billing;
492
493 export import BrandProtection = API.BrandProtection;
494
495 export import Diagnostics = API.Diagnostics;
496
497 export import Images = API.Images;
498
499 export import Intel = API.Intel;
500
501 export import MagicTransit = API.MagicTransit;
502
503 export import MagicNetworkMonitoring = API.MagicNetworkMonitoring;
504
505 export import MTLSCertificates = API.MTLSCertificates;
506
507 export import Pages = API.Pages;
508
509 export import PCAPs = API.PCAPs;
510
511 export import Registrar = API.Registrar;
512
513 export import RequestTracers = API.RequestTracers;
514
515 export import Rules = API.Rules;
516
517 export import Storage = API.Storage;
518
519 export import Stream = API.Stream;
520
521 export import Alerting = API.Alerting;
522
523 export import D1Resource = API.D1Resource;
524
525 export import R2 = API.R2;
526
527 export import WARPConnector = API.WARPConnector;
528
529 export import WorkersForPlatforms = API.WorkersForPlatforms;
530
531 export import ZeroTrust = API.ZeroTrust;
532
533 export import Challenges = API.Challenges;
534
535 export import HyperdriveResource = API.HyperdriveResource;
536
537 export import RUM = API.RUM;
538
539 export import Vectorize = API.Vectorize;
540
541 export import URLScanner = API.URLScanner;
542
543 export import Radar = API.Radar;
544
545 export import BotManagement = API.BotManagement;
546
547 export import OriginPostQuantumEncryption = API.OriginPostQuantumEncryption;
548
549 export import Speed = API.Speed;
550
551 export import DCVDelegation = API.DCVDelegation;
552
553 export import Hostnames = API.Hostnames;
554
555 export import Snippets = API.Snippets;
556
557 export import Calls = API.Calls;
558
559 export import CloudforceOne = API.CloudforceOne;
560
561 export import EventNotifications = API.EventNotifications;
562
563 export import AIGateway = API.AIGateway;
564
565 export import IAM = API.IAM;
566
567 export import CloudConnector = API.CloudConnector;
568
569 export import ASN = API.ASN;
570 export import AuditLog = API.AuditLog;
571 export import CertificateCA = API.CertificateCA;
572 export import CertificateRequestType = API.CertificateRequestType;
573 export import CloudflareTunnel = API.CloudflareTunnel;
574 export import ErrorData = API.ErrorData;
575 export import Identifier = API.Identifier;
576 export import LoadBalancerPreview = API.LoadBalancerPreview;
577 export import Member = API.Member;
578 export import PaginationInfo = API.PaginationInfo;
579 export import Permission = API.Permission;
580 export import PermissionGrant = API.PermissionGrant;
581 export import ResponseInfo = API.ResponseInfo;
582 export import Result = API.Result;
583 export import Role = API.Role;
584 export import SortDirection = API.SortDirection;
585}
586
587export default Cloudflare;
588