Skip to content

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

Package listing

@kody/twilio

src/config.ts

67 lines · 2.0 KB · TypeScript
import { packageStorage } from 'kody:runtime'
import { assertMessagingServiceSid, optionalString } from './validation.ts'

export const MESSAGING_SERVICE_SID_KEY = 'messagingServiceSid'

export type TwilioConfig = {
	messagingServiceSid: 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/twilio` 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<TwilioConfig> {
	const messagingServiceSid = await readString(MESSAGING_SERVICE_SID_KEY)
	return {
		messagingServiceSid,
		note: "These defaults live in this package's packageStorage. Fork or invoke your own copy before setting them.",
	}
}

/** Persist an optional default Messaging Service SID (MG...). */
export async function setMessagingServiceSid(params: {
	messagingServiceSid: string
}) {
	const messagingServiceSid = assertMessagingServiceSid(
		params.messagingServiceSid,
	)
	const store = packageStorage()
	await store.set(MESSAGING_SERVICE_SID_KEY, messagingServiceSid)
	return { messagingServiceSid }
}

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

export async function resolveMessagingServiceSid(params: {
	messagingServiceSid?: unknown
}): Promise<string | undefined> {
	const fromInput = optionalString(
		{ messagingServiceSid: params.messagingServiceSid },
		'messagingServiceSid',
	)
	if (fromInput) return assertMessagingServiceSid(fromInput)
	const stored = await readString(MESSAGING_SERVICE_SID_KEY)
	return stored ? assertMessagingServiceSid(stored) : undefined
}

export default getConfig