cloudflare/cloudflare-typescript

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
b9426aec57563b81815d82008272622d2754adf5

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/index.ts

583lines · 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 acm: API.ACM = new API.ACM(this);
158 argo: API.Argo = new API.Argo(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 emailSecurity: API.EmailSecurity = new API.EmailSecurity(this);
167 emailRouting: API.EmailRouting = new API.EmailRouting(this);
168 filters: API.Filters = new API.Filters(this);
169 firewall: API.Firewall = new API.Firewall(this);
170 healthchecks: API.Healthchecks = new API.Healthchecks(this);
171 keylessCertificates: API.KeylessCertificates = new API.KeylessCertificates(this);
172 logpush: API.Logpush = new API.Logpush(this);
173 logs: API.Logs = new API.Logs(this);
174 originTLSClientAuth: API.OriginTLSClientAuth = new API.OriginTLSClientAuth(this);
175 pagerules: API.Pagerules = new API.Pagerules(this);
176 rateLimits: API.RateLimits = new API.RateLimits(this);
177 secondaryDNS: API.SecondaryDNS = new API.SecondaryDNS(this);
178 waitingRooms: API.WaitingRooms = new API.WaitingRooms(this);
179 web3: API.Web3 = new API.Web3(this);
180 workers: API.Workers = new API.Workers(this);
181 kv: API.KV = new API.KV(this);
182 durableObjects: API.DurableObjects = new API.DurableObjects(this);
183 queues: API.Queues = new API.Queues(this);
184 apiGateway: API.APIGateway = new API.APIGateway(this);
185 managedTransforms: API.ManagedTransforms = new API.ManagedTransforms(this);
186 pageShield: API.PageShield = new API.PageShield(this);
187 rulesets: API.Rulesets = new API.Rulesets(this);
188 urlNormalization: API.URLNormalization = new API.URLNormalization(this);
189 spectrum: API.Spectrum = new API.Spectrum(this);
190 addressing: API.Addressing = new API.Addressing(this);
191 auditLogs: API.AuditLogs = new API.AuditLogs(this);
192 billing: API.Billing = new API.Billing(this);
193 brandProtection: API.BrandProtection = new API.BrandProtection(this);
194 diagnostics: API.Diagnostics = new API.Diagnostics(this);
195 images: API.Images = new API.Images(this);
196 intel: API.Intel = new API.Intel(this);
197 magicTransit: API.MagicTransit = new API.MagicTransit(this);
198 magicNetworkMonitoring: API.MagicNetworkMonitoring = new API.MagicNetworkMonitoring(this);
199 mtlsCertificates: API.MTLSCertificates = new API.MTLSCertificates(this);
200 pages: API.Pages = new API.Pages(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 turnstile: API.Turnstile = new API.Turnstile(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 cloudConnector: API.CloudConnector = new API.CloudConnector(this);
230
231 protected override defaultQuery(): Core.DefaultQuery | undefined {
232 return this._options.defaultQuery;
233 }
234
235 protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
236 return {
237 ...super.defaultHeaders(opts),
238 'X-Auth-Key': this.apiKey,
239 'X-Auth-Email': this.apiEmail,
240 ...this._options.defaultHeaders,
241 };
242 }
243
244 protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {
245 if (this.apiEmail && headers['x-auth-email']) {
246 return;
247 }
248 if (customHeaders['x-auth-email'] === null) {
249 return;
250 }
251
252 if (this.apiKey && headers['x-auth-key']) {
253 return;
254 }
255 if (customHeaders['x-auth-key'] === null) {
256 return;
257 }
258
259 if (this.apiToken && headers['authorization']) {
260 return;
261 }
262 if (customHeaders['authorization'] === null) {
263 return;
264 }
265
266 if (this.userServiceKey && headers['x-auth-user-service-key']) {
267 return;
268 }
269 if (customHeaders['x-auth-user-service-key'] === null) {
270 return;
271 }
272
273 throw new Error(
274 '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',
275 );
276 }
277
278 protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
279 const apiEmailAuth = this.apiEmailAuth(opts);
280 const apiKeyAuth = this.apiKeyAuth(opts);
281 const apiTokenAuth = this.apiTokenAuth(opts);
282 const userServiceKeyAuth = this.userServiceKeyAuth(opts);
283
284 if (
285 apiEmailAuth != null &&
286 !Core.isEmptyObj(apiEmailAuth) &&
287 apiKeyAuth != null &&
288 !Core.isEmptyObj(apiKeyAuth)
289 ) {
290 return { ...apiEmailAuth, ...apiKeyAuth };
291 }
292
293 if (apiTokenAuth != null && !Core.isEmptyObj(apiTokenAuth)) {
294 return apiTokenAuth;
295 }
296
297 if (userServiceKeyAuth != null && !Core.isEmptyObj(userServiceKeyAuth)) {
298 return userServiceKeyAuth;
299 }
300 return {};
301 }
302
303 protected apiEmailAuth(opts: Core.FinalRequestOptions): Core.Headers {
304 if (this.apiEmail == null) {
305 return {};
306 }
307 return { 'X-Auth-Email': this.apiEmail };
308 }
309
310 protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
311 if (this.apiKey == null) {
312 return {};
313 }
314 return { 'X-Auth-Key': this.apiKey };
315 }
316
317 protected apiTokenAuth(opts: Core.FinalRequestOptions): Core.Headers {
318 if (this.apiToken == null) {
319 return {};
320 }
321 return { Authorization: `Bearer ${this.apiToken}` };
322 }
323
324 protected userServiceKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
325 if (this.userServiceKey == null) {
326 return {};
327 }
328 return { 'X-Auth-User-Service-Key': this.userServiceKey };
329 }
330
331 protected override stringifyQuery(query: Record<string, unknown>): string {
332 return qs.stringify(query, { allowDots: true, arrayFormat: 'repeat' });
333 }
334
335 static Cloudflare = this;
336 static DEFAULT_TIMEOUT = 60000; // 1 minute
337
338 static CloudflareError = Errors.CloudflareError;
339 static APIError = Errors.APIError;
340 static APIConnectionError = Errors.APIConnectionError;
341 static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
342 static APIUserAbortError = Errors.APIUserAbortError;
343 static NotFoundError = Errors.NotFoundError;
344 static ConflictError = Errors.ConflictError;
345 static RateLimitError = Errors.RateLimitError;
346 static BadRequestError = Errors.BadRequestError;
347 static AuthenticationError = Errors.AuthenticationError;
348 static InternalServerError = Errors.InternalServerError;
349 static PermissionDeniedError = Errors.PermissionDeniedError;
350 static UnprocessableEntityError = Errors.UnprocessableEntityError;
351
352 static toFile = Uploads.toFile;
353 static fileFromPath = Uploads.fileFromPath;
354}
355
356export const {
357 CloudflareError,
358 APIError,
359 APIConnectionError,
360 APIConnectionTimeoutError,
361 APIUserAbortError,
362 NotFoundError,
363 ConflictError,
364 RateLimitError,
365 BadRequestError,
366 AuthenticationError,
367 InternalServerError,
368 PermissionDeniedError,
369 UnprocessableEntityError,
370} = Errors;
371
372export import toFile = Uploads.toFile;
373export import fileFromPath = Uploads.fileFromPath;
374
375export namespace Cloudflare {
376 export import RequestOptions = Core.RequestOptions;
377
378 export import V4PagePagination = Pagination.V4PagePagination;
379 export import V4PagePaginationParams = Pagination.V4PagePaginationParams;
380 export import V4PagePaginationResponse = Pagination.V4PagePaginationResponse;
381
382 export import V4PagePaginationArray = Pagination.V4PagePaginationArray;
383 export import V4PagePaginationArrayParams = Pagination.V4PagePaginationArrayParams;
384 export import V4PagePaginationArrayResponse = Pagination.V4PagePaginationArrayResponse;
385
386 export import CursorPagination = Pagination.CursorPagination;
387 export import CursorPaginationParams = Pagination.CursorPaginationParams;
388 export import CursorPaginationResponse = Pagination.CursorPaginationResponse;
389
390 export import CursorLimitPagination = Pagination.CursorLimitPagination;
391 export import CursorLimitPaginationParams = Pagination.CursorLimitPaginationParams;
392 export import CursorLimitPaginationResponse = Pagination.CursorLimitPaginationResponse;
393
394 export import SinglePage = Pagination.SinglePage;
395 export import SinglePageResponse = Pagination.SinglePageResponse;
396
397 export import Accounts = API.Accounts;
398
399 export import OriginCACertificates = API.OriginCACertificates;
400
401 export import IPs = API.IPs;
402
403 export import Memberships = API.Memberships;
404
405 export import User = API.User;
406
407 export import Zones = API.Zones;
408
409 export import LoadBalancers = API.LoadBalancers;
410
411 export import Cache = API.Cache;
412
413 export import SSL = API.SSL;
414
415 export import ACM = API.ACM;
416
417 export import Argo = API.Argo;
418
419 export import CertificateAuthorities = API.CertificateAuthorities;
420
421 export import ClientCertificates = API.ClientCertificates;
422
423 export import CustomCertificates = API.CustomCertificates;
424
425 export import CustomHostnames = API.CustomHostnames;
426
427 export import CustomNameservers = API.CustomNameservers;
428
429 export import DNS = API.DNS;
430
431 export import DNSSECResource = API.DNSSECResource;
432
433 export import EmailSecurity = API.EmailSecurity;
434
435 export import EmailRouting = API.EmailRouting;
436
437 export import Filters = API.Filters;
438
439 export import Firewall = API.Firewall;
440
441 export import Healthchecks = API.Healthchecks;
442
443 export import KeylessCertificates = API.KeylessCertificates;
444
445 export import Logpush = API.Logpush;
446
447 export import Logs = API.Logs;
448
449 export import OriginTLSClientAuth = API.OriginTLSClientAuth;
450
451 export import Pagerules = API.Pagerules;
452
453 export import RateLimits = API.RateLimits;
454
455 export import SecondaryDNS = API.SecondaryDNS;
456
457 export import WaitingRooms = API.WaitingRooms;
458
459 export import Web3 = API.Web3;
460
461 export import Workers = API.Workers;
462
463 export import KV = API.KV;
464
465 export import DurableObjects = API.DurableObjects;
466
467 export import Queues = API.Queues;
468
469 export import APIGateway = API.APIGateway;
470
471 export import ManagedTransforms = API.ManagedTransforms;
472
473 export import PageShield = API.PageShield;
474
475 export import Rulesets = API.Rulesets;
476
477 export import URLNormalization = API.URLNormalization;
478
479 export import Spectrum = API.Spectrum;
480
481 export import Addressing = API.Addressing;
482
483 export import AuditLogs = API.AuditLogs;
484
485 export import Billing = API.Billing;
486
487 export import BrandProtection = API.BrandProtection;
488
489 export import Diagnostics = API.Diagnostics;
490
491 export import Images = API.Images;
492
493 export import Intel = API.Intel;
494
495 export import MagicTransit = API.MagicTransit;
496
497 export import MagicNetworkMonitoring = API.MagicNetworkMonitoring;
498
499 export import MTLSCertificates = API.MTLSCertificates;
500
501 export import Pages = API.Pages;
502
503 export import Registrar = API.Registrar;
504
505 export import RequestTracers = API.RequestTracers;
506
507 export import Rules = API.Rules;
508
509 export import Storage = API.Storage;
510
511 export import Stream = API.Stream;
512
513 export import Alerting = API.Alerting;
514
515 export import D1Resource = API.D1Resource;
516
517 export import R2 = API.R2;
518
519 export import WARPConnector = API.WARPConnector;
520
521 export import WorkersForPlatforms = API.WorkersForPlatforms;
522
523 export import ZeroTrust = API.ZeroTrust;
524
525 export import Turnstile = API.Turnstile;
526
527 export import HyperdriveResource = API.HyperdriveResource;
528
529 export import RUM = API.RUM;
530
531 export import Vectorize = API.Vectorize;
532
533 export import URLScanner = API.URLScanner;
534
535 export import Radar = API.Radar;
536
537 export import BotManagement = API.BotManagement;
538
539 export import OriginPostQuantumEncryption = API.OriginPostQuantumEncryption;
540
541 export import Speed = API.Speed;
542
543 export import DCVDelegation = API.DCVDelegation;
544
545 export import Hostnames = API.Hostnames;
546
547 export import Snippets = API.Snippets;
548
549 export import Calls = API.Calls;
550
551 export import CloudforceOne = API.CloudforceOne;
552
553 export import EventNotifications = API.EventNotifications;
554
555 export import AIGateway = API.AIGateway;
556
557 export import IAM = API.IAM;
558
559 export import CloudConnector = API.CloudConnector;
560
561 export import ASN = API.ASN;
562 export import AuditLog = API.AuditLog;
563 export import CertificateCA = API.CertificateCA;
564 export import CertificateRequestType = API.CertificateRequestType;
565 export import CloudflareTunnel = API.CloudflareTunnel;
566 export import ErrorData = API.ErrorData;
567 export import Identifier = API.Identifier;
568 export import LoadBalancerPreview = API.LoadBalancerPreview;
569 export import Member = API.Member;
570 export import PaginationInfo = API.PaginationInfo;
571 export import Permission = API.Permission;
572 export import PermissionGrant = API.PermissionGrant;
573 export import RatePlan = API.RatePlan;
574 export import ResponseInfo = API.ResponseInfo;
575 export import Result = API.Result;
576 export import Role = API.Role;
577 export import SortDirection = API.SortDirection;
578 export import Subscription = API.Subscription;
579 export import SubscriptionComponent = API.SubscriptionComponent;
580 export import SubscriptionZone = API.SubscriptionZone;
581}
582
583export default Cloudflare;
584