Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/cloudflare

Cloudflare helpers: API v4, static site publishing to Pages, analytics, WAF rules, logs, and docs.

FollowFork

Files

settings-core.ts

48 lines · 2.2 KB · TypeScript
import { normalizeAccountId, type StoredAccountIds } from './account-id.ts'
import { CLOUDFLARE_ACCOUNT_ALIASES, type CloudflareAccount } from './auth.ts'

export type CloudflareSettingsInput = {
	/** Per-alias account ids to store. A string sets it, `null` clears it, an omitted alias is left unchanged. */
	accountIds?: Partial<Record<CloudflareAccount, string | null>>
}

export type CloudflareSettings = { accountIds: Record<CloudflareAccount, string | null> }

/** Validate settings input strictly. Returns the merged ids, or null when this is a read. */
export function applySettingsInput(raw: unknown, current: StoredAccountIds): { next: StoredAccountIds; updated: string[] } | null {
	if (raw === undefined || raw === null) return null
	if (typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Pass an object: { accountIds?: { default?, kody?, pages? } }.')
	const record = raw as Record<string, unknown>
	const unknown = Object.keys(record).filter((key) => key !== 'accountIds')
	if (unknown.length) throw new Error(`Unknown settings key(s): ${unknown.join(', ')}. Accepted keys: accountIds.`)
	if (record.accountIds === undefined) return null
	const ids = record.accountIds
	if (!ids || typeof ids !== 'object' || Array.isArray(ids)) {
		throw new Error('accountIds must be an object like { pages: "<32-hex account id>" }.')
	}
	const badAliases = Object.keys(ids).filter((key) => !(CLOUDFLARE_ACCOUNT_ALIASES as readonly string[]).includes(key))
	if (badAliases.length) {
		throw new Error(`Unknown account alias(es) in accountIds: ${badAliases.join(', ')}. Accepted: ${CLOUDFLARE_ACCOUNT_ALIASES.join(', ')}.`)
	}
	const next: StoredAccountIds = { ...current }
	const updated: string[] = []
	for (const alias of CLOUDFLARE_ACCOUNT_ALIASES) {
		if (!(alias in ids)) continue
		const value = (ids as Record<string, unknown>)[alias]
		if (value === undefined) continue
		if (value === null) delete next[alias]
		else next[alias] = normalizeAccountId(value, `accountIds.${alias}`)
		updated.push(`accountIds.${alias}`)
	}
	return { next, updated }
}

export function settingsView(ids: StoredAccountIds): CloudflareSettings {
	return {
		accountIds: {
			default: ids.default ?? null,
			kody: ids.kody ?? null,
			pages: ids.pages ?? null,
		},
	}
}