Personal Telegram developer console for GitHub

feat(cloudflare): add read-only provider service

davoodmehraban89 committed Oct 4, 2026 at 23:25 UTC d7759cd5615c054b672f916b40456362c65b66dd
1 file changed +121
src/plugins/cloudflare/service.js new
+121
@@ -0,0 +1,121 @@
1 +const API_BASE = 'https://api.cloudflare.com/client/v4';
2 +
3 +const clean = value => String(value ?? '').trim();
4 +const safe = value => encodeURIComponent(clean(value));
5 +
6 +function redact(message, token) {
7 + const text = String(message || 'Cloudflare request failed');
8 + return token ? text.split(token).join('[REDACTED]') : text;
9 +}
10 +
11 +function firstError(payload) {
12 + const errors = Array.isArray(payload?.errors) ? payload.errors : [];
13 + return errors.map(item => item?.message).filter(Boolean).join('; ');
14 +}
15 +
16 +export class CloudflareService {
17 + constructor({ token = '', accountId = '', workerName = '', fetchImpl = globalThis.fetch } = {}) {
18 + this.token = clean(token);
19 + this.accountId = clean(accountId);
20 + this.workerName = clean(workerName);
21 + this.fetchImpl = fetchImpl;
22 + }
23 +
24 + isConfigured() {
25 + return Boolean(this.token && this.accountId && this.workerName && typeof this.fetchImpl === 'function');
26 + }
27 +
28 + requireConfigured() {
29 + if (!this.isConfigured()) throw new Error('Cloudflare provider is not configured');
30 + }
31 +
32 + get headers() {
33 + return {
34 + Authorization: `Bearer ${this.token}`,
35 + 'Content-Type': 'application/json'
36 + };
37 + }
38 +
39 + endpoint(suffix) {
40 + return `${API_BASE}/accounts/${safe(this.accountId)}/workers/scripts/${safe(this.workerName)}${suffix}`;
41 + }
42 +
43 + async requestJson(suffix, label) {
44 + this.requireConfigured();
45 + let response;
46 + try {
47 + response = await this.fetchImpl(this.endpoint(suffix), { method: 'GET', headers: this.headers });
48 + } catch (error) {
49 + throw new Error(redact(`${label} failed: ${error?.message || error}`, this.token));
50 + }
51 +
52 + let raw = '';
53 + try {
54 + raw = await response.text();
55 + } catch {
56 + raw = '';
57 + }
58 +
59 + let payload = null;
60 + if (raw) {
61 + try { payload = JSON.parse(raw); } catch { payload = null; }
62 + }
63 +
64 + if (!response.ok || payload?.success === false) {
65 + const detail = firstError(payload) || raw.slice(0, 240) || 'request failed';
66 + throw new Error(redact(`${label} failed: ${response.status} ${detail}`, this.token));
67 + }
68 +
69 + if (payload === null) throw new Error(`${label} failed: invalid JSON response`);
70 + return payload?.result ?? payload;
71 + }
72 +
73 + async getWorkerSnapshot() {
74 + this.requireConfigured();
75 + const [deploymentsResult, versionsResult, settingsResult] = await Promise.all([
76 + this.requestJson('/deployments', 'Cloudflare deployments'),
77 + this.requestJson('/versions', 'Cloudflare versions'),
78 + this.requestJson('/settings', 'Cloudflare settings')
79 + ]);
80 +
81 + const deployments = Array.isArray(deploymentsResult?.deployments)
82 + ? deploymentsResult.deployments
83 + : Array.isArray(deploymentsResult) ? deploymentsResult : [];
84 + const versions = Array.isArray(versionsResult?.items)
85 + ? versionsResult.items
86 + : Array.isArray(versionsResult) ? versionsResult : [];
87 +
88 + const latestDeployment = deployments[0] || null;
89 + const latestVersion = versions[0] || null;
90 + const bindings = Array.isArray(settingsResult?.bindings)
91 + ? settingsResult.bindings
92 + .map(binding => ({ name: clean(binding?.name), type: clean(binding?.type) }))
93 + .filter(binding => binding.name || binding.type)
94 + : [];
95 + const observability = settingsResult?.observability || {};
96 +
97 + return {
98 + workerName: this.workerName,
99 + deployment: latestDeployment ? {
100 + id: clean(latestDeployment.id),
101 + createdOn: clean(latestDeployment.created_on),
102 + versions: (Array.isArray(latestDeployment.versions) ? latestDeployment.versions : []).map(item => ({
103 + versionId: clean(item?.version_id),
104 + percentage: Number.isFinite(Number(item?.percentage)) ? Number(item.percentage) : 0
105 + }))
106 + } : null,
107 + version: latestVersion ? {
108 + id: clean(latestVersion.id),
109 + createdOn: clean(latestVersion.created_on),
110 + triggeredBy: clean(latestVersion.annotations?.['workers/triggered_by'])
111 + } : null,
112 + bindings,
113 + observability: {
114 + enabled: observability.enabled === true,
115 + logsEnabled: observability.logs?.enabled === true,
116 + invocationLogs: observability.logs?.invocation_logs === true,
117 + tracesEnabled: observability.traces?.enabled === true
118 + }
119 + };
120 + }
121 +}