Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/aws

src/config.ts

60 lines · 1.7 KB · TypeScript
import { packageStorage } from 'kody:runtime'
import { DEFAULT_REGION, assertRegion, optionalString } from './validation.ts'

export const DEFAULT_REGION_KEY = 'defaultRegion'

export type AwsConfig = {
	region: string | null
	note: string
}

async function readString(key: string): Promise<string | null> {
	try {
		const store = packageStorage()
		if (!store) return null
		const raw = await store.get(key)
		return typeof raw === 'string' && raw.trim() ? raw.trim() : null
	} catch {
		return null
	}
}

/**
 * Read fork-local defaults from `packageStorage()`.
 *
 * Live `@kody/aws` storage is the platform package bucket, not yours.
 * Fork first (or `packages.invoke` your copy) before relying on these defaults.
 */
export async function getConfig(): Promise<AwsConfig> {
	const region = await readString(DEFAULT_REGION_KEY)
	return {
		region,
		note: "These defaults live in this package's packageStorage. Fork or invoke your own copy before setting them.",
	}
}

/** Persist an optional default AWS region (for example us-west-2). */
export async function setDefaultRegion(params: { region: string }) {
	const region = assertRegion(params.region)
	const store = packageStorage()
	await store.set(DEFAULT_REGION_KEY, region)
	return { region }
}

/** Clear the stored region default. */
export async function clearConfig() {
	const store = packageStorage()
	await store.set(DEFAULT_REGION_KEY, '')
	return { cleared: true }
}

export async function resolveRegion(
	explicit?: string,
): Promise<string> {
	const fromInput = optionalString({ region: explicit }, 'region')
	if (fromInput) return assertRegion(fromInput)
	const stored = await readString(DEFAULT_REGION_KEY)
	return stored ? assertRegion(stored) : DEFAULT_REGION
}

export default getConfig