cloudflare/cloudflare-typescript

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v3.3.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/index.ts

581lines · modecode

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