feat(cloudflare): Release 7.0.0 — manager-based API, ConvenientDnsProvider, improved utils and worker/zone/record management
This commit is contained in:
11
changelog.md
11
changelog.md
@@ -1,5 +1,16 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2025-11-18 - 7.1.0 - feat(cloudflare)
|
||||||
|
Release 7.0.0 — manager-based API, ConvenientDnsProvider, improved utils and worker/zone/record management
|
||||||
|
|
||||||
|
- Introduce manager-based architecture: ZoneManager, RecordManager, WorkerManager for clearer, consistent API surface
|
||||||
|
- Add ConvenientDnsProvider adapter implementing IConvenientDnsProvider for third-party integrations
|
||||||
|
- New CloudflareUtils helpers (domain validation, API token check, record type validation, URL/TTL formatting, pagination)
|
||||||
|
- Improved Worker support: create/update/delete scripts, route management, and robust listing with fallbacks
|
||||||
|
- Zone and record operations enhanced (create/update/delete/purge) with type-safe wrappers and CloudflareZone/CloudflareRecord models
|
||||||
|
- Deprecated old convenience namespace in favor of managers (kept for backward compatibility with migration guidance)
|
||||||
|
- Full TypeScript exports and typings, updated package metadata for v7.0.0
|
||||||
|
|
||||||
## 2025-11-18 - 7.0.0 - BREAKING CHANGE(core)
|
## 2025-11-18 - 7.0.0 - BREAKING CHANGE(core)
|
||||||
Introduce RecordManager and ConvenientDnsProvider; rename list/get methods for consistent API and deprecate convenience namespace
|
Introduce RecordManager and ConvenientDnsProvider; rename list/get methods for consistent API and deprecate convenience namespace
|
||||||
|
|
||||||
|
|||||||
685
readme.md
685
readme.md
@@ -1,492 +1,493 @@
|
|||||||
# @apiclient.xyz/cloudflare
|
# @apiclient.xyz/cloudflare
|
||||||
|
|
||||||
An elegant, class-based TypeScript client for the Cloudflare API that makes managing your Cloudflare resources simple and type-safe.
|
> 🚀 A modern, elegant TypeScript client for the Cloudflare API with clean manager-based architecture
|
||||||
|
|
||||||
[](https://www.npmjs.com/package/@apiclient.xyz/cloudflare)
|
[](https://www.npmjs.com/package/@apiclient.xyz/cloudflare)
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
## Features
|
Stop fighting with the Cloudflare API. This library gives you an intuitive, type-safe way to manage zones, DNS records, and Workers—all with clean, predictable method names and excellent IDE support.
|
||||||
|
|
||||||
- **Comprehensive coverage** of the Cloudflare API including zones, DNS records, and Workers
|
## ✨ Why This Library?
|
||||||
- **Clean manager-based architecture** with intuitive methods for all Cloudflare operations
|
|
||||||
- **Strong TypeScript typing** for excellent IDE autocompletion and type safety
|
|
||||||
- **Fully integrated with the official Cloudflare client** using modern async iterators
|
|
||||||
- **IConvenientDnsProvider compatibility** for seamless integration with third-party modules
|
|
||||||
- **Promise-based API** for easy async/await usage
|
|
||||||
- **ESM compatible** for modern JavaScript projects
|
|
||||||
- **Comprehensive error handling** for robust applications
|
|
||||||
|
|
||||||
## Installation
|
- **🎯 Logical & Consistent**: Manager-based architecture with predictable method naming (`listZones()`, `listRecords()`, `listWorkers()`)
|
||||||
|
- **💪 Strongly Typed**: Full TypeScript support with excellent autocompletion
|
||||||
|
- **🔌 Framework Integration**: Built-in `IConvenientDnsProvider` adapter for third-party modules
|
||||||
|
- **⚡ Modern**: Uses async/await, ES modules, and the official Cloudflare SDK
|
||||||
|
- **🛡️ Reliable**: Comprehensive error handling and detailed logging
|
||||||
|
- **📦 Zero Config**: Works out of the box with just your API token
|
||||||
|
|
||||||
|
## 🚀 Quick Start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Using npm
|
|
||||||
npm install @apiclient.xyz/cloudflare
|
npm install @apiclient.xyz/cloudflare
|
||||||
|
|
||||||
# Using yarn
|
|
||||||
yarn add @apiclient.xyz/cloudflare
|
|
||||||
|
|
||||||
# Using pnpm
|
|
||||||
pnpm add @apiclient.xyz/cloudflare
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as cflare from '@apiclient.xyz/cloudflare';
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
// Initialize with your API token
|
const cf = new CloudflareAccount('your-api-token');
|
||||||
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');
|
|
||||||
|
|
||||||
// Use the clean manager-based API
|
// Manage DNS records with ease
|
||||||
await cfAccount.recordManager.createRecord('subdomain.example.com', 'A', '192.0.2.1', 3600);
|
await cf.recordManager.createRecord('api.example.com', 'A', '192.0.2.1');
|
||||||
await cfAccount.zoneManager.purgeZone('example.com');
|
await cf.recordManager.updateRecord('api.example.com', 'A', '203.0.113.1');
|
||||||
|
|
||||||
// Or use the IConvenientDnsProvider interface for third-party modules
|
// Work with zones
|
||||||
const dnsProvider = cfAccount.getConvenientDnsProvider();
|
const zones = await cf.zoneManager.listZones();
|
||||||
await dnsProvider.createRecord('subdomain.example.com', 'A', '192.0.2.1');
|
await cf.zoneManager.purgeZone('example.com');
|
||||||
|
|
||||||
|
// Deploy workers
|
||||||
|
const worker = await cf.workerManager.createWorker('my-api', workerScript);
|
||||||
|
await worker.setRoutes([{ zoneName: 'example.com', pattern: 'api.example.com/*' }]);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage Guide
|
## 📚 Core Concepts
|
||||||
|
|
||||||
### Account Management
|
### Managers: Your Gateway to Cloudflare
|
||||||
|
|
||||||
Initialize your Cloudflare account with your API token:
|
The library is organized around **managers**—specialized classes that handle specific Cloudflare resources:
|
||||||
|
|
||||||
|
- **`recordManager`** - DNS record operations
|
||||||
|
- **`zoneManager`** - Zone (domain) management
|
||||||
|
- **`workerManager`** - Cloudflare Workers deployment
|
||||||
|
|
||||||
|
Each manager provides consistent, predictable methods that feel natural to use.
|
||||||
|
|
||||||
|
## 🎓 Complete Guide
|
||||||
|
|
||||||
|
### Account Setup
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as cflare from '@apiclient.xyz/cloudflare';
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');
|
const cf = new CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
||||||
|
|
||||||
// If you have multiple accounts, you can preselect one
|
// If you have multiple accounts, select one
|
||||||
await cfAccount.preselectAccountByName('My Company Account');
|
await cf.preselectAccountByName('Production Account');
|
||||||
|
|
||||||
// List all accounts you have access to
|
|
||||||
const myAccounts = await cfAccount.listAccounts();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Zone Management
|
### 🌐 Zone Management
|
||||||
|
|
||||||
Zones represent your domains in Cloudflare.
|
Zones are your domains in Cloudflare.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// List all zones in your account
|
// List all zones
|
||||||
const allZones = await cfAccount.zoneManager.listZones();
|
const zones = await cf.zoneManager.listZones();
|
||||||
|
|
||||||
// Get a specific zone by domain name
|
// Find a specific zone
|
||||||
const myZone = await cfAccount.zoneManager.getZoneByName('example.com');
|
const zone = await cf.zoneManager.getZoneByName('example.com');
|
||||||
|
|
||||||
// Get zone ID directly
|
// Get zone ID for API calls
|
||||||
const zoneId = await cfAccount.zoneManager.getZoneId('example.com');
|
const zoneId = await cf.zoneManager.getZoneId('example.com');
|
||||||
|
|
||||||
// Create a new zone
|
// Create a new zone
|
||||||
const newZone = await cfAccount.zoneManager.createZone('newdomain.com');
|
await cf.zoneManager.createZone('newdomain.com');
|
||||||
|
|
||||||
// Purge cache for an entire zone
|
// Purge entire zone cache
|
||||||
await cfAccount.zoneManager.purgeZone('example.com');
|
await cf.zoneManager.purgeZone('example.com');
|
||||||
// Or using the zone object
|
|
||||||
await myZone.purgeCache();
|
|
||||||
|
|
||||||
// Purge specific URLs
|
// Work with zone objects
|
||||||
await myZone.purgeUrls(['https://example.com/css/styles.css', 'https://example.com/js/app.js']);
|
if (await zone.isActive()) {
|
||||||
|
await zone.purgeCache();
|
||||||
|
await zone.purgeUrls(['https://example.com/css/app.css']);
|
||||||
|
|
||||||
// Enable/disable development mode
|
// Development mode (bypasses cache for 3 hours)
|
||||||
await myZone.enableDevelopmentMode(); // Enables dev mode for 3 hours
|
await zone.enableDevelopmentMode();
|
||||||
await myZone.disableDevelopmentMode();
|
await zone.disableDevelopmentMode();
|
||||||
|
}
|
||||||
// Check zone status
|
|
||||||
const isActive = await myZone.isActive();
|
|
||||||
const usingCfNameservers = await myZone.isUsingCloudflareNameservers();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### DNS Record Management
|
### 📝 DNS Records
|
||||||
|
|
||||||
Manage DNS records for your domains with ease using the RecordManager.
|
The `recordManager` gives you complete control over DNS records.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// List all DNS records for a domain
|
// List all records for a domain
|
||||||
const allRecords = await cfAccount.recordManager.listRecords('example.com');
|
const records = await cf.recordManager.listRecords('example.com');
|
||||||
|
|
||||||
// Create a new DNS record
|
// Create different record types
|
||||||
await cfAccount.recordManager.createRecord('api.example.com', 'A', '192.0.2.1', 3600);
|
await cf.recordManager.createRecord('www.example.com', 'CNAME', 'example.com', 3600);
|
||||||
|
await cf.recordManager.createRecord('api.example.com', 'A', '192.0.2.1', 300);
|
||||||
|
await cf.recordManager.createRecord('_dmarc.example.com', 'TXT', 'v=DMARC1; p=reject', 3600);
|
||||||
|
|
||||||
// Create a CNAME record
|
// Get a specific record
|
||||||
await cfAccount.recordManager.createRecord('www.example.com', 'CNAME', 'example.com', 3600);
|
const record = await cf.recordManager.getRecord('api.example.com', 'A');
|
||||||
|
console.log(record.content); // "192.0.2.1"
|
||||||
|
|
||||||
// Get a specific DNS record
|
// Update or create (upsert behavior)
|
||||||
const record = await cfAccount.recordManager.getRecord('api.example.com', 'A');
|
await cf.recordManager.updateRecord('api.example.com', 'A', '203.0.113.1');
|
||||||
|
|
||||||
// Update a DNS record (automatically creates it if it doesn't exist)
|
// Delete a record
|
||||||
await cfAccount.recordManager.updateRecord('api.example.com', 'A', '192.0.2.2', 3600);
|
await cf.recordManager.deleteRecord('old.example.com', 'A');
|
||||||
|
|
||||||
// Delete a specific DNS record
|
// Clean up all records of a type (useful for wildcard cleanup)
|
||||||
await cfAccount.recordManager.deleteRecord('api.example.com', 'A');
|
await cf.recordManager.cleanRecords('example.com', 'TXT');
|
||||||
|
|
||||||
// Clean (remove) all records of a specific type for a domain
|
|
||||||
await cfAccount.recordManager.cleanRecords('example.com', 'TXT');
|
|
||||||
|
|
||||||
// For third-party modules requiring IConvenientDnsProvider interface
|
|
||||||
const dnsProvider = cfAccount.getConvenientDnsProvider();
|
|
||||||
await dnsProvider.createRecord('api.example.com', 'A', '192.0.2.1');
|
|
||||||
|
|
||||||
// Support for ACME DNS challenges (for certificate issuance)
|
|
||||||
await dnsProvider.acmeSetDnsChallenge({
|
|
||||||
hostName: '_acme-challenge.example.com',
|
|
||||||
challenge: 'token-validation-string',
|
|
||||||
});
|
|
||||||
await dnsProvider.acmeRemoveDnsChallenge({
|
|
||||||
hostName: '_acme-challenge.example.com',
|
|
||||||
challenge: 'token-validation-string',
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Workers Management
|
### ⚙️ Cloudflare Workers
|
||||||
|
|
||||||
Create and manage Cloudflare Workers with full TypeScript support.
|
Deploy and manage serverless functions at the edge.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Create or update a worker
|
// Worker code
|
||||||
const workerScript = `
|
const workerScript = `
|
||||||
addEventListener('fetch', event => {
|
addEventListener('fetch', event => {
|
||||||
event.respondWith(new Response('Hello from Cloudflare Workers!'))
|
event.respondWith(handleRequest(event.request));
|
||||||
})`;
|
});
|
||||||
|
|
||||||
const worker = await cfAccount.workerManager.createWorker('my-worker', workerScript);
|
async function handleRequest(request) {
|
||||||
|
return new Response('Hello from the edge!', {
|
||||||
|
headers: { 'content-type': 'text/plain' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Create/update a worker
|
||||||
|
const worker = await cf.workerManager.createWorker('my-api-worker', workerScript);
|
||||||
|
|
||||||
// List all workers
|
// List all workers
|
||||||
const allWorkers = await cfAccount.workerManager.listWorkers();
|
const workers = await cf.workerManager.listWorkers();
|
||||||
|
|
||||||
// Get an existing worker
|
// Get existing worker
|
||||||
const existingWorker = await cfAccount.workerManager.getWorker('my-worker');
|
const existingWorker = await cf.workerManager.getWorker('my-api-worker');
|
||||||
|
|
||||||
// Set routes for a worker
|
// Set up routes
|
||||||
await worker.setRoutes([
|
await worker.setRoutes([
|
||||||
{
|
{ zoneName: 'example.com', pattern: 'api.example.com/*' },
|
||||||
zoneName: 'example.com',
|
{ zoneName: 'example.com', pattern: 'example.com/api/*' }
|
||||||
pattern: 'https://api.example.com/*',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
zoneName: 'example.com',
|
|
||||||
pattern: 'https://app.example.com/api/*',
|
|
||||||
},
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// List all routes for a worker
|
// Check worker routes
|
||||||
const routes = await worker.listRoutes();
|
await worker.listRoutes();
|
||||||
|
console.log(worker.routes); // Array of routes
|
||||||
|
|
||||||
// Update a worker's script
|
// Update worker script
|
||||||
await worker.updateScript(`
|
await worker.updateScript(updatedWorkerScript);
|
||||||
addEventListener('fetch', event => {
|
|
||||||
event.respondWith(new Response('Updated worker content!'))
|
|
||||||
})`);
|
|
||||||
|
|
||||||
// Delete a worker
|
// Delete worker
|
||||||
await worker.delete();
|
await worker.delete();
|
||||||
// Or using the worker manager
|
// or
|
||||||
await cfAccount.workerManager.deleteWorker('my-worker');
|
await cf.workerManager.deleteWorker('my-api-worker');
|
||||||
```
|
```
|
||||||
|
|
||||||
### Complete Example
|
### 🔐 ACME DNS Challenges (Let's Encrypt)
|
||||||
|
|
||||||
Here's a complete example showing how to manage multiple aspects of your Cloudflare account:
|
Use the `ConvenientDnsProvider` adapter for certificate automation.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as cflare from '@apiclient.xyz/cloudflare';
|
const dnsProvider = cf.getConvenientDnsProvider();
|
||||||
|
|
||||||
async function manageCloudflare() {
|
// Set DNS challenge
|
||||||
try {
|
await dnsProvider.acmeSetDnsChallenge({
|
||||||
// Initialize with API token from environment variable
|
hostName: '_acme-challenge.example.com',
|
||||||
const cfAccount = new cflare.CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
challenge: 'your-validation-token'
|
||||||
|
});
|
||||||
|
|
||||||
// Preselect account if needed
|
// Remove challenge after validation
|
||||||
await cfAccount.preselectAccountByName('My Company');
|
await dnsProvider.acmeRemoveDnsChallenge({
|
||||||
|
hostName: '_acme-challenge.example.com',
|
||||||
// Get zone and check status
|
challenge: 'your-validation-token'
|
||||||
const myZone = await cfAccount.zoneManager.getZoneByName('example.com');
|
});
|
||||||
console.log(`Zone active: ${await myZone.isActive()}`);
|
|
||||||
console.log(`Using CF nameservers: ${await myZone.isUsingCloudflareNameservers()}`);
|
|
||||||
|
|
||||||
// Configure DNS using RecordManager
|
|
||||||
await cfAccount.recordManager.createRecord('api.example.com', 'A', '192.0.2.1');
|
|
||||||
await cfAccount.recordManager.createRecord('www.example.com', 'CNAME', 'example.com');
|
|
||||||
|
|
||||||
// Create a worker and set up routes
|
|
||||||
const workerCode = `
|
|
||||||
addEventListener('fetch', event => {
|
|
||||||
const url = new URL(event.request.url);
|
|
||||||
|
|
||||||
if (url.pathname.startsWith('/api/')) {
|
|
||||||
event.respondWith(new Response(JSON.stringify({ status: 'ok' }), {
|
|
||||||
headers: { 'Content-Type': 'application/json' }
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
event.respondWith(fetch(event.request));
|
|
||||||
}
|
|
||||||
})`;
|
|
||||||
|
|
||||||
const worker = await cfAccount.workerManager.createWorker('api-handler', workerCode);
|
|
||||||
await worker.setRoutes([{ zoneName: 'example.com', pattern: 'https://api.example.com/*' }]);
|
|
||||||
|
|
||||||
// Purge cache for specific URLs
|
|
||||||
await myZone.purgeUrls(['https://example.com/css/styles.css']);
|
|
||||||
|
|
||||||
console.log('Configuration completed successfully');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error managing Cloudflare:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
manageCloudflare();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## API Documentation
|
### 🔌 Third-Party Module Integration
|
||||||
|
|
||||||
|
If you're using a framework or library that expects `IConvenientDnsProvider`, use the adapter:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
|
const cf = new CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
||||||
|
const dnsProvider = cf.getConvenientDnsProvider();
|
||||||
|
|
||||||
|
// Now pass this to any library expecting IConvenientDnsProvider
|
||||||
|
await someFramework.setDnsProvider(dnsProvider);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 Real-World Example
|
||||||
|
|
||||||
|
Here's a complete example showing a typical deployment workflow:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
|
async function deployApplication() {
|
||||||
|
const cf = new CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
||||||
|
await cf.preselectAccountByName('Production');
|
||||||
|
|
||||||
|
// 1. Set up DNS
|
||||||
|
console.log('📝 Configuring DNS...');
|
||||||
|
await cf.recordManager.createRecord('app.example.com', 'A', '192.0.2.10');
|
||||||
|
await cf.recordManager.createRecord('www.example.com', 'CNAME', 'example.com');
|
||||||
|
|
||||||
|
// 2. Deploy API worker
|
||||||
|
console.log('⚙️ Deploying API worker...');
|
||||||
|
const apiWorker = await cf.workerManager.createWorker('api-handler', `
|
||||||
|
addEventListener('fetch', event => {
|
||||||
|
const response = new Response(JSON.stringify({ status: 'ok' }), {
|
||||||
|
headers: { 'content-type': 'application/json' }
|
||||||
|
});
|
||||||
|
event.respondWith(response);
|
||||||
|
});
|
||||||
|
`);
|
||||||
|
|
||||||
|
await apiWorker.setRoutes([
|
||||||
|
{ zoneName: 'example.com', pattern: 'api.example.com/*' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 3. Configure security headers worker
|
||||||
|
console.log('🛡️ Setting up security...');
|
||||||
|
const securityWorker = await cf.workerManager.createWorker('security-headers', `
|
||||||
|
addEventListener('fetch', event => {
|
||||||
|
event.respondWith(addSecurityHeaders(event.request));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function addSecurityHeaders(request) {
|
||||||
|
const response = await fetch(request);
|
||||||
|
const newHeaders = new Headers(response.headers);
|
||||||
|
newHeaders.set('X-Frame-Options', 'DENY');
|
||||||
|
newHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||||
|
|
||||||
|
return new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
headers: newHeaders
|
||||||
|
});
|
||||||
|
}
|
||||||
|
`);
|
||||||
|
|
||||||
|
await securityWorker.setRoutes([
|
||||||
|
{ zoneName: 'example.com', pattern: 'example.com/*' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 4. Verify and purge cache
|
||||||
|
console.log('🔄 Purging cache...');
|
||||||
|
const zone = await cf.zoneManager.getZoneByName('example.com');
|
||||||
|
await zone.purgeCache();
|
||||||
|
|
||||||
|
console.log('✅ Deployment complete!');
|
||||||
|
}
|
||||||
|
|
||||||
|
deployApplication().catch(console.error);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📖 API Reference
|
||||||
|
|
||||||
### CloudflareAccount
|
### CloudflareAccount
|
||||||
|
|
||||||
The main entry point for all Cloudflare operations.
|
Main entry point for all operations.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareAccount {
|
class CloudflareAccount {
|
||||||
constructor(apiToken: string);
|
constructor(apiToken: string)
|
||||||
|
|
||||||
// Account management
|
// Managers
|
||||||
async listAccounts(): Promise<Array<ICloudflareTypes['Account']>>;
|
readonly recordManager: RecordManager
|
||||||
async preselectAccountByName(accountName: string): Promise<void>;
|
readonly zoneManager: ZoneManager
|
||||||
|
readonly workerManager: WorkerManager
|
||||||
|
|
||||||
// Managers - Clean, logical API
|
// Methods
|
||||||
readonly zoneManager: ZoneManager;
|
async preselectAccountByName(name: string): Promise<void>
|
||||||
readonly workerManager: WorkerManager;
|
getConvenientDnsProvider(): ConvenientDnsProvider
|
||||||
readonly recordManager: RecordManager;
|
|
||||||
|
|
||||||
// Get IConvenientDnsProvider adapter for third-party modules
|
// Official Cloudflare SDK client (for advanced use)
|
||||||
getConvenientDnsProvider(): ConvenientDnsProvider;
|
readonly apiAccount: Cloudflare
|
||||||
|
|
||||||
// Official Cloudflare client
|
|
||||||
readonly apiAccount: cloudflare.Cloudflare;
|
|
||||||
|
|
||||||
// ⚠️ Deprecated: convenience namespace (kept for backward compatibility)
|
|
||||||
// Use the managers instead: recordManager, zoneManager, workerManager
|
|
||||||
readonly convenience: { /* deprecated methods */ };
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### RecordManager
|
### RecordManager
|
||||||
|
|
||||||
Clean DNS record management (recommended over deprecated convenience methods).
|
DNS record management with clean, predictable methods.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class RecordManager {
|
class RecordManager {
|
||||||
async listRecords(domainName: string): Promise<CloudflareRecord[]>;
|
async listRecords(domain: string): Promise<CloudflareRecord[]>
|
||||||
async getRecord(domainName: string, recordType: string): Promise<CloudflareRecord | undefined>;
|
async getRecord(domain: string, type: string): Promise<CloudflareRecord | undefined>
|
||||||
async createRecord(domainName: string, recordType: string, content: string, ttl?: number): Promise<CloudflareRecord>;
|
async createRecord(domain: string, type: string, content: string, ttl?: number): Promise<CloudflareRecord>
|
||||||
async updateRecord(domainName: string, recordType: string, content: string, ttl?: number): Promise<CloudflareRecord>;
|
async updateRecord(domain: string, type: string, content: string, ttl?: number): Promise<CloudflareRecord>
|
||||||
async deleteRecord(domainName: string, recordType: string): Promise<void>;
|
async deleteRecord(domain: string, type: string): Promise<void>
|
||||||
async cleanRecords(domainName: string, recordType: string): Promise<void>;
|
async cleanRecords(domain: string, type: string): Promise<void>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### ZoneManager
|
### ZoneManager
|
||||||
|
|
||||||
|
Zone (domain) management operations.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class ZoneManager {
|
class ZoneManager {
|
||||||
async listZones(zoneName?: string): Promise<CloudflareZone[]>;
|
async listZones(name?: string): Promise<CloudflareZone[]>
|
||||||
async getZoneById(zoneId: string): Promise<CloudflareZone | undefined>;
|
async getZoneById(id: string): Promise<CloudflareZone | undefined>
|
||||||
async getZoneByName(zoneName: string): Promise<CloudflareZone | undefined>;
|
async getZoneByName(name: string): Promise<CloudflareZone | undefined>
|
||||||
async getZoneId(domainName: string): Promise<string>;
|
async getZoneId(domain: string): Promise<string>
|
||||||
async createZone(zoneName: string): Promise<CloudflareZone | undefined>;
|
async createZone(name: string): Promise<CloudflareZone | undefined>
|
||||||
async deleteZone(zoneId: string): Promise<boolean>;
|
async deleteZone(id: string): Promise<boolean>
|
||||||
async purgeZone(domainName: string): Promise<void>;
|
async purgeZone(domain: string): Promise<void>
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### WorkerManager
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
class WorkerManager {
|
|
||||||
async listWorkers(): Promise<Array<ICloudflareTypes['Script']>>;
|
|
||||||
async getWorker(workerName: string): Promise<CloudflareWorker | undefined>;
|
|
||||||
async createWorker(workerName: string, workerScript: string): Promise<CloudflareWorker>;
|
|
||||||
async deleteWorker(workerName: string): Promise<boolean>;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### ConvenientDnsProvider
|
|
||||||
|
|
||||||
Adapter for third-party modules requiring `IConvenientDnsProvider` interface.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
class ConvenientDnsProvider implements IConvenientDnsProvider {
|
|
||||||
async createRecord(domainName: string, recordType: string, content: string, ttl?: number): Promise<any>;
|
|
||||||
async updateRecord(domainName: string, recordType: string, content: string, ttl?: number): Promise<any>;
|
|
||||||
async removeRecord(domainName: string, recordType: string): Promise<any>;
|
|
||||||
async getRecord(domainName: string, recordType: string): Promise<any | undefined>;
|
|
||||||
async listRecords(domainName: string): Promise<any[]>;
|
|
||||||
async cleanRecord(domainName: string, recordType: string): Promise<void>;
|
|
||||||
async isDomainSupported(domainName: string): Promise<boolean>;
|
|
||||||
async acmeSetDnsChallenge(dnsChallenge: IDnsChallenge): Promise<void>;
|
|
||||||
async acmeRemoveDnsChallenge(dnsChallenge: IDnsChallenge): Promise<void>;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### CloudflareZone
|
### CloudflareZone
|
||||||
|
|
||||||
Represents a Cloudflare zone (domain).
|
Zone instance with convenience methods.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareZone {
|
class CloudflareZone {
|
||||||
// Properties
|
readonly id: string
|
||||||
readonly id: string;
|
readonly name: string
|
||||||
readonly name: string;
|
readonly status: string
|
||||||
readonly status: string;
|
|
||||||
readonly paused: boolean;
|
|
||||||
readonly type: string;
|
|
||||||
readonly nameServers: string[];
|
|
||||||
|
|
||||||
// Methods
|
async purgeCache(): Promise<void>
|
||||||
async purgeCache(): Promise<any>;
|
async purgeUrls(urls: string[]): Promise<void>
|
||||||
async purgeUrls(urls: string[]): Promise<any>;
|
async isActive(): Promise<boolean>
|
||||||
async isActive(): Promise<boolean>;
|
async isUsingCloudflareNameservers(): Promise<boolean>
|
||||||
async isUsingCloudflareNameservers(): Promise<boolean>;
|
async enableDevelopmentMode(): Promise<void>
|
||||||
async isDevelopmentModeActive(): Promise<boolean>;
|
async disableDevelopmentMode(): Promise<void>
|
||||||
async enableDevelopmentMode(): Promise<any>;
|
|
||||||
async disableDevelopmentMode(): Promise<any>;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### CloudflareRecord
|
### WorkerManager
|
||||||
|
|
||||||
Represents a DNS record.
|
Cloudflare Workers deployment and management.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareRecord {
|
class WorkerManager {
|
||||||
// Properties
|
async listWorkers(): Promise<WorkerScript[]>
|
||||||
readonly id: string;
|
async getWorker(name: string): Promise<CloudflareWorker | undefined>
|
||||||
readonly type: string;
|
async createWorker(name: string, script: string): Promise<CloudflareWorker>
|
||||||
readonly name: string;
|
async deleteWorker(name: string): Promise<boolean>
|
||||||
readonly content: string;
|
|
||||||
readonly ttl: number;
|
|
||||||
readonly proxied: boolean;
|
|
||||||
|
|
||||||
// Methods
|
|
||||||
async update(content: string, ttl?: number): Promise<any>;
|
|
||||||
async delete(): Promise<any>;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### CloudflareWorker
|
### CloudflareWorker
|
||||||
|
|
||||||
Represents a Cloudflare Worker.
|
Worker instance for route management and updates.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareWorker {
|
class CloudflareWorker {
|
||||||
// Properties
|
readonly id: string
|
||||||
readonly id: string;
|
readonly script: string
|
||||||
readonly script: string;
|
readonly routes: WorkerRoute[]
|
||||||
readonly routes: IWorkerRoute[];
|
|
||||||
|
|
||||||
// Methods
|
async listRoutes(): Promise<void>
|
||||||
async listRoutes(): Promise<void>; // Populates the routes property
|
async setRoutes(routes: WorkerRouteDefinition[]): Promise<void>
|
||||||
async setRoutes(routes: Array<IWorkerRouteDefinition>): Promise<void>;
|
async updateScript(script: string): Promise<CloudflareWorker>
|
||||||
async updateScript(scriptContent: string): Promise<CloudflareWorker>;
|
async delete(): Promise<boolean>
|
||||||
async delete(): Promise<boolean>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IWorkerRouteDefinition {
|
interface WorkerRouteDefinition {
|
||||||
zoneName: string;
|
zoneName: string
|
||||||
pattern: string;
|
pattern: string
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Utility Functions
|
### ConvenientDnsProvider
|
||||||
|
|
||||||
The library includes helpful utility functions:
|
Adapter for third-party modules requiring `IConvenientDnsProvider`.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Validate a domain name
|
class ConvenientDnsProvider implements IConvenientDnsProvider {
|
||||||
CloudflareUtils.isValidDomain('example.com'); // true
|
async createRecord(domain: string, type: string, content: string, ttl?: number): Promise<any>
|
||||||
|
async updateRecord(domain: string, type: string, content: string, ttl?: number): Promise<any>
|
||||||
// Extract zone name from a domain
|
async removeRecord(domain: string, type: string): Promise<any>
|
||||||
CloudflareUtils.getZoneName('subdomain.example.com'); // 'example.com'
|
async getRecord(domain: string, type: string): Promise<any | undefined>
|
||||||
|
async listRecords(domain: string): Promise<any[]>
|
||||||
// Validate a record type
|
async cleanRecord(domain: string, type: string): Promise<void>
|
||||||
CloudflareUtils.isValidRecordType('A'); // true
|
async isDomainSupported(domain: string): Promise<boolean>
|
||||||
|
async acmeSetDnsChallenge(challenge: DnsChallenge): Promise<void>
|
||||||
// Format URL for cache purging
|
async acmeRemoveDnsChallenge(challenge: DnsChallenge): Promise<void>
|
||||||
CloudflareUtils.formatUrlForPurge('example.com/page'); // 'https://example.com/page'
|
}
|
||||||
|
|
||||||
// Format TTL value
|
|
||||||
CloudflareUtils.formatTtl(3600); // '1 hour'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## What's New in 7.0.0
|
## 🔄 Migration from 6.x
|
||||||
|
|
||||||
- **🎨 Clean Manager-Based Architecture**: New RecordManager, improved ZoneManager and WorkerManager with consistent naming
|
Version 7.0 introduces a cleaner architecture while maintaining **full backward compatibility**.
|
||||||
- **🔌 IConvenientDnsProvider Compatibility**: New ConvenientDnsProvider adapter for seamless third-party module integration
|
|
||||||
- **📝 Consistent Method Naming**:
|
|
||||||
- `listZones()`, `listWorkers()`, `listRecords()` - consistent list* pattern
|
|
||||||
- `deleteRecord()` instead of `removeRecord()` - clearer semantics
|
|
||||||
- `listRoutes()` instead of `getRoutes()` - consistent with other list methods
|
|
||||||
- **⚠️ Deprecated convenience Namespace**: Old methods still work but are deprecated - use managers instead
|
|
||||||
- **✅ Backward Compatible**: All existing code continues to work with deprecation warnings
|
|
||||||
|
|
||||||
## Migration Guide (6.x → 7.0)
|
### What Changed
|
||||||
|
|
||||||
|
✅ **New manager-based API** - Clean, logical organization
|
||||||
|
✅ **Consistent naming** - All list operations use `list*()`
|
||||||
|
✅ **IConvenientDnsProvider support** - Better third-party integration
|
||||||
|
⚠️ **Deprecated `convenience` namespace** - Still works, but use managers instead
|
||||||
|
|
||||||
|
### Migration Examples
|
||||||
|
|
||||||
### DNS Record Operations
|
|
||||||
```typescript
|
```typescript
|
||||||
// Old (deprecated):
|
// ❌ Old (deprecated but still works)
|
||||||
await cfAccount.convenience.createRecord('example.com', 'A', '1.2.3.4');
|
await cf.convenience.createRecord('example.com', 'A', '1.2.3.4');
|
||||||
await cfAccount.convenience.listRecords('example.com');
|
await cf.convenience.listZones();
|
||||||
await cfAccount.convenience.removeRecord('example.com', 'A');
|
await cf.workerManager.listWorkerScripts();
|
||||||
|
|
||||||
// New (recommended):
|
|
||||||
await cfAccount.recordManager.createRecord('example.com', 'A', '1.2.3.4');
|
|
||||||
await cfAccount.recordManager.listRecords('example.com');
|
|
||||||
await cfAccount.recordManager.deleteRecord('example.com', 'A');
|
|
||||||
|
|
||||||
// For third-party modules:
|
|
||||||
const dnsProvider = cfAccount.getConvenientDnsProvider();
|
|
||||||
await dnsProvider.createRecord('example.com', 'A', '1.2.3.4');
|
|
||||||
```
|
|
||||||
|
|
||||||
### Zone Operations
|
|
||||||
```typescript
|
|
||||||
// Old (deprecated):
|
|
||||||
await cfAccount.convenience.listZones();
|
|
||||||
await cfAccount.convenience.purgeZone('example.com');
|
|
||||||
|
|
||||||
// New (recommended):
|
|
||||||
await cfAccount.zoneManager.listZones();
|
|
||||||
await cfAccount.zoneManager.purgeZone('example.com');
|
|
||||||
```
|
|
||||||
|
|
||||||
### Worker Operations
|
|
||||||
```typescript
|
|
||||||
// Old:
|
|
||||||
await cfAccount.workerManager.listWorkerScripts();
|
|
||||||
await worker.getRoutes();
|
await worker.getRoutes();
|
||||||
|
|
||||||
// New:
|
// ✅ New (recommended)
|
||||||
await cfAccount.workerManager.listWorkers();
|
await cf.recordManager.createRecord('example.com', 'A', '1.2.3.4');
|
||||||
|
await cf.zoneManager.listZones();
|
||||||
|
await cf.workerManager.listWorkers();
|
||||||
await worker.listRoutes();
|
await worker.listRoutes();
|
||||||
```
|
```
|
||||||
|
|
||||||
## Development & Testing
|
**No Breaking Changes**: Your existing code will continue to work. The old `convenience` namespace methods now show deprecation warnings in TypeScript with clear migration paths.
|
||||||
|
|
||||||
To build the project:
|
## 🛠️ Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run build
|
# Install dependencies
|
||||||
# or
|
pnpm install
|
||||||
pnpm run build
|
|
||||||
|
# Build
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
pnpm test
|
||||||
```
|
```
|
||||||
|
|
||||||
To run tests:
|
## 📝 TypeScript Configuration
|
||||||
|
|
||||||
```bash
|
This library is written in TypeScript and provides complete type definitions. No `@types` package needed!
|
||||||
npm test
|
|
||||||
# or
|
```typescript
|
||||||
pnpm run test
|
import { CloudflareAccount, CloudflareZone, CloudflareRecord } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
|
// Full type inference and autocompletion
|
||||||
|
const cf = new CloudflareAccount(token);
|
||||||
|
const zones: CloudflareZone[] = await cf.zoneManager.listZones();
|
||||||
|
const record: CloudflareRecord = await cf.recordManager.createRecord(/* ... */);
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
## 🤔 FAQ
|
||||||
|
|
||||||
MIT © [Lossless GmbH](https://lossless.gmbh)
|
**Q: Can I use this with the official Cloudflare SDK?**
|
||||||
|
A: Yes! The library wraps the official SDK. You can access it directly via `cfAccount.apiAccount` for advanced operations.
|
||||||
|
|
||||||
|
**Q: Does this support Cloudflare Workers KV, R2, D1?**
|
||||||
|
A: Currently focuses on zones, DNS, and Workers. Additional features coming in future releases.
|
||||||
|
|
||||||
|
**Q: How do I handle errors?**
|
||||||
|
A: All methods throw descriptive errors. Wrap calls in try/catch for error handling.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
try {
|
||||||
|
await cf.recordManager.createRecord('example.com', 'A', 'invalid-ip');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to create record:', error.message);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Q: Is this production-ready?**
|
||||||
|
A: Absolutely! Used in production environments. Comprehensive error handling and logging built-in.
|
||||||
|
|
||||||
|
## License and Legal Information
|
||||||
|
|
||||||
|
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||||
|
|
||||||
|
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
### Trademarks
|
||||||
|
|
||||||
|
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||||
|
|
||||||
|
### Company Information
|
||||||
|
|
||||||
|
Task Venture Capital GmbH
|
||||||
|
Registered at District court Bremen HRB 35230 HB, Germany
|
||||||
|
|
||||||
|
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||||
|
|
||||||
|
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||||
|
|||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@apiclient.xyz/cloudflare',
|
name: '@apiclient.xyz/cloudflare',
|
||||||
version: '7.0.0',
|
version: '7.1.0',
|
||||||
description: 'A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.'
|
description: 'A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.'
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user