🌳
pt0/deployF/hostnameF/cfFetchAI.mts
2import { type secretNameType } from '../../serverF/secretsF/getPlainSecAI.mts'
5const cfApiBaseUrl = 'https://api.cloudflare.com/client/v4'
7export const cfFetch = async (path: string, headers: Record<string, string>, options: RequestInit = {}) => {
8 const resp = await fetch(`${cfApiBaseUrl}${path}`, {headers, ...options})
9 const data = await resp.json() as {success: boolean, errors?: unknown[], result?: any}
10 if (!data.success) throPtErr('cfApiFailed', {path, errors: data.errors})
11 return data.result
14export const cfHeadersFromCreds = (cfApiToken: string, cfApiEmail: string): Record<string, string> =>
15 ({'X-Auth-Key': cfApiToken, 'X-Auth-Email': cfApiEmail, 'Content-Type': 'application/json'})
17// env-first for initContainers that envFrom the external-dns secret; falls back to the secret file.
18export function getCfHeaders(opts: {cfApiKeySecretName?: string, required?: true}): Record<string, string>
19export function getCfHeaders(opts: {cfApiKeySecretName?: string, required: false}): Record<string, string> | undefined
20export function getCfHeaders({cfApiKeySecretName, required = true}: {cfApiKeySecretName?: string, required?: boolean}): Record<string, string> | undefined {
21 if (process.env.CF_API_KEY && process.env.CF_API_EMAIL) return cfHeadersFromCreds(process.env.CF_API_KEY, process.env.CF_API_EMAIL)
22 if (!cfApiKeySecretName) {
23 if (required) throPtErr('!cfApiKeySecretName')
24 return undefined
25 }
26 const cfSecret = required ? getReqJsonSecret(cfApiKeySecretName as secretNameType) : getOptJsonSecret(cfApiKeySecretName as secretNameType)
27 if (!cfSecret) return undefined
28 return cfHeadersFromCreds(cfSecret.CF_API_KEY, cfSecret.CF_API_EMAIL)