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> } export type CloudflareSettings = { accountIds: Record } /** 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 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)[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, }, } }