Skip to content
← Public packages

@kentcdodds/quiet-hours

Quiet hours for Kent's bots: 10 PM to 8 AM MT (DST-aware) clock, shared overnight queue, override, and the 8 AM digest of finished work and open decisions.

FollowFork

Files

override.ts

55 lines · 2.4 KB · TypeScript
import { nextLocalHour, QUIET_END_HOUR, QUIET_START_HOUR } from './clock.ts'
import { deleteState, OVERRIDE_KEY, setState } from './store.ts'
import { computeStatus, parseNow } from './status-core.ts'
import type { QuietOverride, QuietStatus } from './types.ts'

export type OverrideInput =
	| {
			/** 'off' = quiet off until the next 10 PM; 'on' = quiet on now until the next 8 AM; 'clear' = back to the clock. */
			mode: 'on' | 'off' | 'clear'
			/** Who asked (e.g. 'kent' or a bot name), stored for the record. */
			by?: string
			/** Optional ISO instant to treat as now (tests). */
			now?: string
	  }
	| 'on'
	| 'off'
	| 'clear'

/** Pure: the override record for `mode` set at `now`. */
export function buildOverride(mode: 'on' | 'off', now: Date, by?: string | null): QuietOverride {
	const expires =
		mode === 'off' ? nextLocalHour(now, QUIET_START_HOUR) : nextLocalHour(now, QUIET_END_HOUR)
	return { mode, setAt: now.toISOString(), expiresAt: expires.toISOString(), by: by ?? null }
}

/**
 * Kent's quiet-hours override, shared by every bot.
 * - `'off'` ("quiet off"): quiet hours off until the next 10:00 PM MT.
 * - `'on'` ("quiet on"): quiet on now, until the next 8:00 AM MT.
 * - `'clear'`: drop any override; the clock decides again.
 *
 * @param input.mode - 'on' | 'off' | 'clear' (a bare string also works)
 * @returns `{ ok, mode, override, status }` with the resulting status
 *
 * @example
 * import override from 'kody:@kentcdodds/quiet-hours/override'
 * await override({ mode: 'off', by: 'kent' })
 * // => { ok: true, mode: 'off', override: { mode: 'off', expiresAt: '...' }, status: { quiet: false, ... } }
 */
export default async function override(input: OverrideInput) {
	const normalized = typeof input === 'string' ? { mode: input } : input
	const mode = normalized?.mode
	if (mode !== 'on' && mode !== 'off' && mode !== 'clear') {
		throw new Error("override mode must be 'on', 'off', or 'clear'.")
	}
	const now = parseNow((normalized as { now?: string }).now)
	if (mode === 'clear') {
		await deleteState(OVERRIDE_KEY)
		return { ok: true as const, mode, override: null, status: computeStatus(now, null) as QuietStatus }
	}
	const by = (normalized as { by?: string }).by
	const record = buildOverride(mode, now, typeof by === 'string' ? by.trim() || null : null)
	await setState(OVERRIDE_KEY, record)
	return { ok: true as const, mode, override: record, status: computeStatus(now, record) }
}