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/google

Google helpers for Gmail, Calendar, Drive, People, YouTube (including upload), and Analytics.

FollowFork

Files

calendar-free-slots.ts

824 lines · 33.8 KB · TypeScript
import { GoogleApiError } from './core.ts'
import type { CalendarFreeBusyParams, CalendarListParams } from './calendar.ts'
import type { JsonObject } from './types.ts'

/** Accounts checked when `accounts` / `account` is omitted. */
export const FREE_SLOTS_DEFAULT_ACCOUNTS = ['business', 'personal'] as const
export const FREE_SLOTS_DEFAULT_TIME_ZONE = 'America/Denver'
export const FREE_SLOTS_DEFAULT_HOURS = { start: '09:00', end: '17:00' } as const
export const FREE_SLOTS_DEFAULT_STEP_MINUTES = 30
export const FREE_SLOTS_DEFAULT_MAX_RESULTS = 50
/** Upper bound on `maxResults`. */
export const FREE_SLOTS_MAX_RESULTS_CAP = 500
/** Upper bound on the number of dates one call may check. */
export const FREE_SLOTS_MAX_DATES = 120
/** Upper bound on `nextDays`. */
export const FREE_SLOTS_MAX_NEXT_DAYS = 90
/** Longest time span sent in one freeBusy request. */
export const FREE_SLOTS_CHUNK_DAYS = 30
/** Most calendars sent in one freeBusy request (Google's limit is 50). */
export const FREE_SLOTS_CALENDARS_PER_REQUEST = 50

const MINUTE = 60_000
const DAY = 86_400_000
const WEEKDAY_NAMES = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] as const

export type FreeSlotsDateInput = string | { start: string; end: string }
export type FreeSlotsDayOfWeek = number | string

export type FindFreeSlotsParams = {
	/** Slot length in minutes. Required. */
	durationMinutes: number
	/**
	 * Dates to check, in `timeZone`. Each entry is a `'YYYY-MM-DD'` date, a
	 * `'YYYY-MM-DD..YYYY-MM-DD'` inclusive range string, or an inclusive
	 * `{ start, end }` range. Mix freely. Required unless `nextDays` is set.
	 */
	dates?: FreeSlotsDateInput[]
	/**
	 * Check the next N calendar days, starting today (in `timeZone`), that pass
	 * the day-of-week filter and still have room for a slot in the daily window
	 * (today is skipped once its window has passed). `nextDays: 3,
	 * weekdaysOnly: true` is the next 3 weekdays. Merged with `dates` when both
	 * are given.
	 */
	nextDays?: number
	/** Daily window as `'HH:mm'` (or whole hours as numbers). `end` may be `'24:00'`. Defaults to 09:00-17:00. */
	hours?: { start?: string | number; end?: string | number }
	/** Shorthand for `daysOfWeek: ['mon','tue','wed','thu','fri']`. */
	weekdaysOnly?: boolean
	/** Keep only these days: 0-6 (0 is Sunday) or names like `'mon'` / `'monday'`. */
	daysOfWeek?: FreeSlotsDayOfWeek[]
	/** IANA time zone for dates, hours, and local output. Defaults to `America/Denver`. */
	timeZone?: string
	/** Account aliases to check. Defaults to `['business', 'personal']`. */
	accounts?: string[]
	/** Single-account shorthand for `accounts: [account]`. */
	account?: string
	/**
	 * Which calendars count as busy when `calendarIds` is not given.
	 * `'primary'` (default): each account's primary calendar.
	 * `'selected'`: the primary calendar plus every visible calendar the
	 * account has selected in Google Calendar, minus public holiday calendars.
	 */
	calendars?: 'primary' | 'selected'
	/**
	 * Explicit calendars to check. An array is checked through every account in
	 * `accounts`; an object maps account alias to its calendar ids.
	 */
	calendarIds?: string[] | Record<string, string[]>
	/** Minutes of padding added before and after every busy block. Defaults to 0. */
	bufferMinutes?: number
	/** Slot starts land on multiples of this many minutes after local midnight. Defaults to 30. */
	stepMinutes?: number
	/** Most slots returned overall. Defaults to 50, capped at 500. */
	maxResults?: number
	/** Most slots returned per date. Unlimited by default. */
	maxPerDay?: number
}

export type FreeSlot = {
	/** Local date (`YYYY-MM-DD`) in `timeZone`. */
	date: string
	/** UTC ISO instant. */
	start: string
	end: string
	/** Local ISO time with offset, for example `2026-11-03T09:00:00-07:00`. */
	startLocal: string
	endLocal: string
	/** True when a calendar for this date could not be checked. */
	unverified?: true
}

export type FreeSlotsDay = {
	dayOfWeek: string
	/** Every slot that fits this date, before `maxResults` / `maxPerDay`. */
	slotCount: number
	/** Local `'HH:mm'` starts of the slots returned in `slots`. */
	slotStarts: string[]
	/** Free stretches (local `'HH:mm'`) at least `durationMinutes` long, after buffers and past time are removed. */
	freeRanges: Array<{ start: string; end: string }>
	/** True when a calendar for this date could not be checked. */
	unverified: boolean
}

export type FreeSlotsErrorStep = 'input' | 'auth' | 'calendar_list' | 'request' | 'calendar'

export type FreeSlotsCheckError = {
	account: string
	/** Null when the failure covered the whole account. */
	calendarId: string | null
	step: Exclude<FreeSlotsErrorStep, 'input'>
	message: string
	status?: number
	/** UTC span the failure covers. */
	timeMin: string
	timeMax: string
}

export type FreeSlotsCheckedCalendar = { account: string; calendarId: string; ok: boolean }

export type FindFreeSlotsResult = {
	timeZone: string
	durationMinutes: number
	stepMinutes: number
	bufferMinutes: number
	hours: { start: string; end: string }
	/** UTC ISO instant used to drop past times. */
	now: string
	slots: FreeSlot[]
	/** All slots that fit, before `maxResults` / `maxPerDay`. */
	totalSlots: number
	truncated: boolean
	byDate: Record<string, FreeSlotsDay>
	/** Dates that were checked, in order. */
	datesChecked: string[]
	/** Dates dropped by the day-of-week filter or because their window already ended. */
	skippedDates: Array<{ date: string; reason: 'dayOfWeek' | 'past' }>
	checkedCalendars: FreeSlotsCheckedCalendar[]
	errors: FreeSlotsCheckError[]
	/** True when any account or calendar failed. Slots on `unverified` dates may overlap busy time there. */
	partial: boolean
	warning: string | null
}

/** Thrown by `findFreeSlots` for bad input, or when no calendar could be checked. */
export class CalendarFreeSlotsError extends Error {
	step: FreeSlotsErrorStep
	errors: FreeSlotsCheckError[]
	constructor(step: FreeSlotsErrorStep, message: string, details: { errors?: FreeSlotsCheckError[]; cause?: unknown } = {}) {
		super('findFreeSlots failed at ' + step + ': ' + message)
		this.name = 'CalendarFreeSlotsError'
		this.step = step
		this.errors = details.errors ?? []
		if (details.cause !== undefined) (this as { cause?: unknown }).cause = details.cause
	}
}

function inputError(message: string): CalendarFreeSlotsError {
	return new CalendarFreeSlotsError('input', message)
}

// ---------------------------------------------------------------------------
// Time zone math (pure)
// ---------------------------------------------------------------------------

const formatterCache = new Map<string, Intl.DateTimeFormat>()

function formatterFor(timeZone: string): Intl.DateTimeFormat {
	let formatter = formatterCache.get(timeZone)
	if (!formatter) {
		formatter = new Intl.DateTimeFormat('en-US', {
			timeZone,
			hourCycle: 'h23',
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
		})
		formatterCache.set(timeZone, formatter)
	}
	return formatter
}

export function isValidTimeZone(timeZone: string): boolean {
	try {
		formatterFor(timeZone)
		return true
	} catch {
		return false
	}
}

/** Wall-clock parts of an instant in a time zone. */
export function zonedParts(ms: number, timeZone: string) {
	const parts: Record<string, number> = {}
	for (const part of formatterFor(timeZone).formatToParts(new Date(ms))) {
		if (part.type !== 'literal') parts[part.type] = Number(part.value)
	}
	const hour = parts.hour === 24 ? 0 : parts.hour
	return { year: parts.year, month: parts.month, day: parts.day, hour, minute: parts.minute, second: parts.second }
}

/** Offset of `timeZone` from UTC at an instant, in milliseconds (Denver in winter is -25200000). */
export function timeZoneOffsetMs(ms: number, timeZone: string): number {
	const p = zonedParts(ms, timeZone)
	const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second)
	return asUtc - (ms - (((ms % 1000) + 1000) % 1000))
}

function pad(n: number): string {
	return String(n).padStart(2, '0')
}

function dateKey(p: { year: number; month: number; day: number }): string {
	return p.year + '-' + pad(p.month) + '-' + pad(p.day)
}

/**
 * Instant for a local wall time: `minutesOfDay` minutes after midnight on
 * `date` in `timeZone`. 1440 means the next midnight. A wall time skipped by a
 * DST jump resolves to the instant just after the jump; a repeated wall time
 * resolves to its first occurrence.
 */
export function zonedWallTimeToUtc(date: string, minutesOfDay: number, timeZone: string): number {
	const [year, month, day] = date.split('-').map(Number)
	const guess = Date.UTC(year, month - 1, day, 0, minutesOfDay)
	const want = zonedParts(guess, 'UTC')
	const matches = (t: number) => {
		const p = zonedParts(t, timeZone)
		return p.year === want.year && p.month === want.month && p.day === want.day && p.hour === want.hour && p.minute === want.minute
	}
	const offsetA = timeZoneOffsetMs(guess, timeZone)
	const first = guess - offsetA
	const offsetB = timeZoneOffsetMs(first, timeZone)
	const second = guess - offsetB
	const candidates = [first, second].filter(matches).sort((a, b) => a - b)
	if (candidates.length) return candidates[0]
	return Math.max(first, second)
}

/** Local ISO string with offset, for example `2026-11-03T09:00:00-07:00`. */
export function formatLocalIso(ms: number, timeZone: string): string {
	const p = zonedParts(ms, timeZone)
	const offsetMinutes = Math.round(timeZoneOffsetMs(ms, timeZone) / MINUTE)
	const sign = offsetMinutes < 0 ? '-' : '+'
	const abs = Math.abs(offsetMinutes)
	return dateKey(p) + 'T' + pad(p.hour) + ':' + pad(p.minute) + ':' + pad(p.second) + sign + pad(Math.floor(abs / 60)) + ':' + pad(abs % 60)
}

function formatLocalHm(ms: number, timeZone: string, date: string): string {
	const p = zonedParts(ms, timeZone)
	if (dateKey(p) !== date && p.hour === 0 && p.minute === 0) return '24:00'
	return pad(p.hour) + ':' + pad(p.minute)
}

/** Local `YYYY-MM-DD` for an instant. */
export function localDate(ms: number, timeZone: string): string {
	return dateKey(zonedParts(ms, timeZone))
}

// ---------------------------------------------------------------------------
// Input parsing (pure)
// ---------------------------------------------------------------------------

const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/

function parseDate(value: unknown, label: string): string {
	if (typeof value !== 'string') throw inputError(label + ' must be a YYYY-MM-DD string.')
	const trimmed = value.trim()
	const match = DATE_RE.exec(trimmed)
	if (!match) throw inputError(label + ' "' + value + '" is not a YYYY-MM-DD date.')
	const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]
	const check = new Date(Date.UTC(year, month - 1, day))
	if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) {
		throw inputError(label + ' "' + value + '" is not a real calendar date.')
	}
	return trimmed
}

export function addDays(date: string, days: number): string {
	const [year, month, day] = date.split('-').map(Number)
	const d = new Date(Date.UTC(year, month - 1, day) + days * DAY)
	return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate())
}

/** 0 is Sunday. Calendar dates have the same weekday in every time zone. */
export function dayOfWeek(date: string): number {
	const [year, month, day] = date.split('-').map(Number)
	return new Date(Date.UTC(year, month - 1, day)).getUTCDay()
}

function expandRange(start: string, end: string, label: string, out: string[]): void {
	if (start > end) throw inputError(label + ' range start ' + start + ' is after end ' + end + '.')
	for (let d = start; d <= end; d = addDays(d, 1)) {
		out.push(d)
		if (out.length > FREE_SLOTS_MAX_DATES * 4) throw inputError('Too many dates; check at most ' + FREE_SLOTS_MAX_DATES + ' dates per call.')
	}
}

/** Expand `dates` input into sorted, unique `YYYY-MM-DD` strings. */
export function expandDateInputs(inputs: FreeSlotsDateInput[]): string[] {
	if (!Array.isArray(inputs)) throw inputError('dates must be an array.')
	const out: string[] = []
	inputs.forEach((input, index) => {
		const label = 'dates[' + index + ']'
		if (typeof input === 'string') {
			const parts = input.split('..')
			if (parts.length === 2) expandRange(parseDate(parts[0], label + ' start'), parseDate(parts[1], label + ' end'), label, out)
			else out.push(parseDate(input, label))
		} else if (input && typeof input === 'object') {
			expandRange(parseDate(input.start, label + '.start'), parseDate(input.end, label + '.end'), label, out)
		} else {
			throw inputError(label + ' must be a date string or a { start, end } range.')
		}
	})
	return [...new Set(out)].sort()
}

/** Parse `'HH:mm'` (or a whole hour number) into minutes after midnight. */
export function parseClock(value: unknown, label: string): number {
	if (typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 24) return value * 60
	if (typeof value === 'string') {
		const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
		if (match) {
			const minutes = Number(match[1]) * 60 + Number(match[2])
			if (Number(match[2]) < 60 && minutes <= 1440) return minutes
		}
	}
	throw inputError(label + ' must be "HH:mm" between 00:00 and 24:00.')
}

function formatClock(minutes: number): string {
	return pad(Math.floor(minutes / 60)) + ':' + pad(minutes % 60)
}

export function parseDaysOfWeek(input: { weekdaysOnly?: boolean; daysOfWeek?: FreeSlotsDayOfWeek[] }): Set<number> | null {
	let days: Set<number> | null = null
	if (input.daysOfWeek !== undefined) {
		if (!Array.isArray(input.daysOfWeek) || input.daysOfWeek.length === 0) throw inputError('daysOfWeek must be a non-empty array.')
		days = new Set(
			input.daysOfWeek.map((value) => {
				if (typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 6) return value
				if (typeof value === 'string') {
					const index = WEEKDAY_NAMES.indexOf(value.trim().slice(0, 3).toLowerCase() as (typeof WEEKDAY_NAMES)[number])
					if (index >= 0) return index
				}
				throw inputError('daysOfWeek entry "' + String(value) + '" is not 0-6 or a weekday name.')
			}),
		)
	}
	if (input.weekdaysOnly) {
		const weekdays = [1, 2, 3, 4, 5]
		days = new Set(days ? weekdays.filter((d) => days!.has(d)) : weekdays)
		if (days.size === 0) throw inputError('weekdaysOnly with these daysOfWeek leaves no days.')
	}
	return days
}

function positiveInt(value: unknown, label: string, fallback: number, min: number, max: number): number {
	if (value === undefined || value === null) return fallback
	if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
		throw inputError(label + ' must be an integer from ' + min + ' to ' + max + '.')
	}
	return value
}

export type NormalizedFreeSlotsParams = {
	timeZone: string
	durationMinutes: number
	stepMinutes: number
	bufferMinutes: number
	startMinutes: number
	endMinutes: number
	dates: string[]
	skippedDates: Array<{ date: string; reason: 'dayOfWeek' | 'past' }>
	accounts: string[]
	calendars: 'primary' | 'selected'
	calendarIdsByAccount: Record<string, string[]> | null
	maxResults: number
	maxPerDay: number | null
}

/** Validate input and resolve defaults. Throws `CalendarFreeSlotsError` with step `input`. */
export function normalizeFreeSlotsParams(params: FindFreeSlotsParams, nowMs: number): NormalizedFreeSlotsParams {
	if (!params || typeof params !== 'object') throw inputError('params object is required.')
	const timeZone = params.timeZone ?? FREE_SLOTS_DEFAULT_TIME_ZONE
	if (typeof timeZone !== 'string' || !isValidTimeZone(timeZone)) throw inputError('timeZone "' + String(timeZone) + '" is not a valid IANA time zone.')
	if (params.durationMinutes === undefined) throw inputError('durationMinutes is required.')
	const durationMinutes = positiveInt(params.durationMinutes, 'durationMinutes', 0, 1, 1440)
	const stepMinutes = positiveInt(params.stepMinutes, 'stepMinutes', FREE_SLOTS_DEFAULT_STEP_MINUTES, 1, 1440)
	const bufferMinutes = positiveInt(params.bufferMinutes, 'bufferMinutes', 0, 0, 720)
	const maxResults = positiveInt(params.maxResults, 'maxResults', FREE_SLOTS_DEFAULT_MAX_RESULTS, 1, FREE_SLOTS_MAX_RESULTS_CAP)
	const maxPerDay = params.maxPerDay === undefined || params.maxPerDay === null ? null : positiveInt(params.maxPerDay, 'maxPerDay', 0, 1, 1440)
	const startMinutes = parseClock(params.hours?.start ?? FREE_SLOTS_DEFAULT_HOURS.start, 'hours.start')
	const endMinutes = parseClock(params.hours?.end ?? FREE_SLOTS_DEFAULT_HOURS.end, 'hours.end')
	if (endMinutes <= startMinutes) throw inputError('hours.end must be after hours.start (windows that cross midnight are not supported).')
	if (endMinutes - startMinutes < durationMinutes) throw inputError('durationMinutes is longer than the daily hours window.')

	const filter = parseDaysOfWeek(params)
	if (params.dates === undefined && params.nextDays === undefined) throw inputError('Pass dates, nextDays, or both.')
	let candidates = params.dates === undefined ? [] : expandDateInputs(params.dates)
	const skippedDates: NormalizedFreeSlotsParams['skippedDates'] = []
	const passes = (date: string) => !filter || filter.has(dayOfWeek(date))
	const explicit: string[] = []
	for (const date of candidates) {
		if (passes(date)) explicit.push(date)
		else skippedDates.push({ date, reason: 'dayOfWeek' })
	}
	candidates = explicit
	if (params.nextDays !== undefined) {
		const nextDays = positiveInt(params.nextDays, 'nextDays', 0, 1, FREE_SLOTS_MAX_NEXT_DAYS)
		let date = localDate(nowMs, timeZone)
		const picked: string[] = []
		// Only count days whose window still has room for one slot after now.
		const hasRoom = (d: string) => zonedWallTimeToUtc(d, endMinutes, timeZone) - Math.max(zonedWallTimeToUtc(d, startMinutes, timeZone), nowMs) >= durationMinutes * 60_000
		for (let guard = 0; picked.length < nextDays && guard < 400; guard++, date = addDays(date, 1)) {
			if (passes(date) && hasRoom(date)) picked.push(date)
		}
		candidates = [...new Set([...candidates, ...picked])].sort()
	}
	if (candidates.length > FREE_SLOTS_MAX_DATES) throw inputError('Too many dates (' + candidates.length + '); check at most ' + FREE_SLOTS_MAX_DATES + ' dates per call.')

	let accounts: string[]
	if (params.accounts !== undefined) {
		if (!Array.isArray(params.accounts) || params.accounts.length === 0 || params.accounts.some((a) => typeof a !== 'string' || !a)) {
			throw inputError('accounts must be a non-empty array of account aliases.')
		}
		accounts = [...new Set(params.accounts)]
	} else if (params.account !== undefined) {
		if (typeof params.account !== 'string' || !params.account) throw inputError('account must be an account alias string.')
		accounts = [params.account]
	} else {
		accounts = [...FREE_SLOTS_DEFAULT_ACCOUNTS]
	}

	const calendars = params.calendars ?? 'primary'
	if (calendars !== 'primary' && calendars !== 'selected') throw inputError('calendars must be "primary" or "selected".')
	let calendarIdsByAccount: Record<string, string[]> | null = null
	if (params.calendarIds !== undefined) {
		const ids = params.calendarIds
		const validList = (list: unknown) => Array.isArray(list) && list.length > 0 && list.every((id) => typeof id === 'string' && id)
		calendarIdsByAccount = {}
		if (Array.isArray(ids)) {
			if (!validList(ids)) throw inputError('calendarIds must be a non-empty array of calendar id strings.')
			for (const account of accounts) calendarIdsByAccount[account] = [...new Set(ids)]
		} else if (ids && typeof ids === 'object') {
			for (const [account, list] of Object.entries(ids)) {
				if (!validList(list)) throw inputError('calendarIds.' + account + ' must be a non-empty array of calendar id strings.')
				calendarIdsByAccount[account] = [...new Set(list)]
			}
			if (params.accounts === undefined && params.account === undefined) accounts = Object.keys(calendarIdsByAccount)
			const missing = accounts.filter((a) => !calendarIdsByAccount![a])
			if (missing.length) throw inputError('calendarIds has no entry for account(s): ' + missing.join(', ') + '.')
			accounts = accounts.filter((a) => calendarIdsByAccount![a])
		} else {
			throw inputError('calendarIds must be an array or an object keyed by account.')
		}
	}

	return {
		timeZone,
		durationMinutes,
		stepMinutes,
		bufferMinutes,
		startMinutes,
		endMinutes,
		dates: candidates,
		skippedDates,
		accounts,
		calendars,
		calendarIdsByAccount,
		maxResults,
		maxPerDay,
	}
}

// ---------------------------------------------------------------------------
// Slot computation (pure)
// ---------------------------------------------------------------------------

export type BusyInterval = { start: number; end: number }

export type DateWindow = { date: string; start: number; end: number }

/** Daily windows as UTC instants. Each date's own offset is used, so DST is handled per date. */
export function buildDateWindows(dates: string[], startMinutes: number, endMinutes: number, timeZone: string): DateWindow[] {
	return dates.map((date) => ({
		date,
		start: zonedWallTimeToUtc(date, startMinutes, timeZone),
		end: zonedWallTimeToUtc(date, endMinutes, timeZone),
	}))
}

/** Sort, pad by `bufferMinutes` on both sides, and merge overlapping busy blocks. */
export function mergeBusy(intervals: BusyInterval[], bufferMinutes = 0): BusyInterval[] {
	const padMs = bufferMinutes * MINUTE
	const sorted = intervals
		.filter((i) => Number.isFinite(i.start) && Number.isFinite(i.end) && i.end > i.start)
		.map((i) => ({ start: i.start - padMs, end: i.end + padMs }))
		.sort((a, b) => a.start - b.start)
	const merged: BusyInterval[] = []
	for (const interval of sorted) {
		const last = merged[merged.length - 1]
		if (last && interval.start <= last.end) last.end = Math.max(last.end, interval.end)
		else merged.push({ ...interval })
	}
	return merged
}

function overlapsBusy(start: number, end: number, busy: BusyInterval[]): boolean {
	for (const b of busy) {
		if (b.start >= end) return false
		if (b.end > start) return true
	}
	return false
}

export type ComputeSlotsInput = {
	dates: string[]
	timeZone: string
	startMinutes: number
	endMinutes: number
	durationMinutes: number
	stepMinutes: number
	bufferMinutes: number
	/** Raw busy blocks (buffers are applied here). */
	busy: BusyInterval[]
	nowMs: number
	maxResults: number
	maxPerDay: number | null
	/** Dates where a calendar could not be checked. */
	unverifiedDates?: Set<string>
}

/**
 * Pure slot finder. Slot starts sit on local wall-clock multiples of
 * `stepMinutes` after midnight, inside the daily window, not in the past, and
 * not overlapping any (buffered) busy block.
 */
export function computeFreeSlots(input: ComputeSlotsInput) {
	const { timeZone, durationMinutes, stepMinutes, nowMs } = input
	const busy = mergeBusy(input.busy, input.bufferMinutes)
	const unverified = input.unverifiedDates ?? new Set<string>()
	const durationMs = durationMinutes * MINUTE
	const slots: FreeSlot[] = []
	const byDate: Record<string, FreeSlotsDay> = {}
	let totalSlots = 0
	let truncated = false
	for (const window of buildDateWindows(input.dates, input.startMinutes, input.endMinutes, timeZone)) {
		const day: FreeSlotsDay = {
			dayOfWeek: WEEKDAY_NAMES[dayOfWeek(window.date)],
			slotCount: 0,
			slotStarts: [],
			freeRanges: [],
			unverified: unverified.has(window.date),
		}
		byDate[window.date] = day

		// Free ranges: window, minus past time, minus buffered busy blocks.
		let cursor = Math.max(window.start, nowMs)
		const pushRange = (start: number, end: number) => {
			if (end - start >= durationMs) day.freeRanges.push({ start: formatLocalHm(start, timeZone, window.date), end: formatLocalHm(end, timeZone, window.date) })
		}
		for (const b of busy) {
			if (b.end <= cursor) continue
			if (b.start >= window.end) break
			if (b.start > cursor) pushRange(cursor, b.start)
			cursor = Math.max(cursor, b.end)
		}
		if (cursor < window.end) pushRange(cursor, window.end)

		const seen = new Set<number>()
		const first = Math.ceil(input.startMinutes / stepMinutes) * stepMinutes
		for (let minutes = first; minutes < input.endMinutes; minutes += stepMinutes) {
			const start = zonedWallTimeToUtc(window.date, minutes, timeZone)
			const end = start + durationMs
			if (seen.has(start) || start < window.start || end > window.end) continue
			seen.add(start)
			if (start < nowMs || overlapsBusy(start, end, busy)) continue
			day.slotCount++
			totalSlots++
			if (slots.length >= input.maxResults || (input.maxPerDay !== null && day.slotStarts.length >= input.maxPerDay)) {
				truncated = true
				continue
			}
			const slot: FreeSlot = {
				date: window.date,
				start: new Date(start).toISOString(),
				end: new Date(end).toISOString(),
				startLocal: formatLocalIso(start, timeZone),
				endLocal: formatLocalIso(end, timeZone),
			}
			if (day.unverified) slot.unverified = true
			slots.push(slot)
			day.slotStarts.push(formatLocalHm(start, timeZone, window.date))
		}
	}
	return { slots, byDate, totalSlots, truncated }
}

/** Group date windows into freeBusy query spans of at most `chunkDays` days. */
export function chunkWindows(windows: DateWindow[], bufferMinutes: number, chunkDays = FREE_SLOTS_CHUNK_DAYS) {
	const padMs = bufferMinutes * MINUTE
	const limit = chunkDays * DAY
	const chunks: Array<{ timeMin: number; timeMax: number; dates: string[] }> = []
	for (const window of [...windows].sort((a, b) => a.start - b.start)) {
		const start = window.start - padMs
		const end = window.end + padMs
		const last = chunks[chunks.length - 1]
		if (last && end - last.timeMin <= limit) {
			last.timeMax = Math.max(last.timeMax, end)
			last.dates.push(window.date)
		} else {
			chunks.push({ timeMin: start, timeMax: end, dates: [window.date] })
		}
	}
	return chunks
}

/** Calendars counted for `calendars: 'selected'`: primary plus visible selected calendars, minus public holiday calendars. */
export function pickSelectedCalendarIds(calendarList: JsonObject): string[] {
	const items = Array.isArray(calendarList.items) ? (calendarList.items as JsonObject[]) : []
	const ids: string[] = []
	for (const item of items) {
		const id = typeof item.id === 'string' ? item.id : null
		if (!id || item.deleted === true || item.hidden === true) continue
		if (id.endsWith('#holiday@group.v.calendar.google.com')) continue
		if (item.primary === true || item.selected === true) ids.push(item.primary === true ? 'primary' : id)
	}
	if (!ids.includes('primary')) ids.unshift('primary')
	return ids
}

// ---------------------------------------------------------------------------
// Orchestration (API calls injected)
// ---------------------------------------------------------------------------

export type FreeSlotsDeps = {
	queryFreeBusy: (params: CalendarFreeBusyParams) => Promise<JsonObject>
	listCalendars: (params: CalendarListParams) => Promise<JsonObject>
	now?: () => number
}

function describeError(error: unknown): { step: 'auth' | 'request'; message: string; status?: number } {
	if (error instanceof GoogleApiError) {
		const step = error.status === undefined && error.causeMessage !== undefined ? 'auth' : 'request'
		return { step, message: error.message, ...(error.status !== undefined ? { status: error.status } : {}) }
	}
	return { step: 'request', message: error instanceof Error ? error.message : String(error) }
}

function parseInstant(value: unknown): number {
	return typeof value === 'string' ? Date.parse(value) : NaN
}

/**
 * Find open slots across accounts and calendars. See `findFreeSlots` in
 * `./calendar` for the documented entry point; this variant takes the API
 * functions as dependencies so it can be tested without network calls.
 */
export async function findFreeSlotsWith(deps: FreeSlotsDeps, params: FindFreeSlotsParams): Promise<FindFreeSlotsResult> {
	const nowMs = (deps.now ?? Date.now)()
	const n = normalizeFreeSlotsParams(params, nowMs)
	const skippedDates = [...n.skippedDates]
	const allWindows = buildDateWindows(n.dates, n.startMinutes, n.endMinutes, n.timeZone)
	const windows = allWindows.filter((w) => {
		if (w.end - Math.max(w.start, nowMs) >= n.durationMinutes * MINUTE) return true
		skippedDates.push({ date: w.date, reason: 'past' })
		return false
	})
	skippedDates.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0))
	const base = {
		timeZone: n.timeZone,
		durationMinutes: n.durationMinutes,
		stepMinutes: n.stepMinutes,
		bufferMinutes: n.bufferMinutes,
		hours: { start: formatClock(n.startMinutes), end: formatClock(n.endMinutes) },
		now: new Date(nowMs).toISOString(),
	}
	const errors: FreeSlotsCheckError[] = []
	const checked = new Map<string, FreeSlotsCheckedCalendar>()
	if (windows.length === 0) {
		return { ...base, slots: [], totalSlots: 0, truncated: false, byDate: {}, datesChecked: [], skippedDates, checkedCalendars: [], errors, partial: false, warning: null }
	}

	const chunks = chunkWindows(windows, n.bufferMinutes)
	const spanMin = new Date(chunks[0].timeMin).toISOString()
	const spanMax = new Date(Math.max(...chunks.map((c) => c.timeMax))).toISOString()
	const unverifiedDates = new Set<string>()
	const busy: BusyInterval[] = []

	// Resolve calendars per account.
	const calendarsByAccount = new Map<string, string[]>()
	await Promise.all(
		n.accounts.map(async (account) => {
			if (n.calendarIdsByAccount) {
				calendarsByAccount.set(account, n.calendarIdsByAccount[account])
				return
			}
			if (n.calendars === 'primary') {
				calendarsByAccount.set(account, ['primary'])
				return
			}
			try {
				const list = await deps.listCalendars({ account, maxResults: 250, fields: 'items(id,primary,selected,hidden,deleted)' })
				calendarsByAccount.set(account, pickSelectedCalendarIds(list))
			} catch (error) {
				const info = describeError(error)
				errors.push({ account, calendarId: null, step: info.step === 'auth' ? 'auth' : 'calendar_list', message: info.message, ...(info.status !== undefined ? { status: info.status } : {}), timeMin: spanMin, timeMax: spanMax })
				for (const w of windows) unverifiedDates.add(w.date)
			}
		}),
	)

	// Query every (account, calendar batch, time chunk). A calendar id visible
	// from several accounts counts as checked when any account could read it.
	type Outcome = { account: string; id: string; chunkIndex: number; ok: boolean; step?: FreeSlotsCheckError['step']; message?: string; status?: number }
	const outcomes: Outcome[] = []
	const requests: Array<{ account: string; ids: string[]; chunkIndex: number }> = []
	for (const account of n.accounts) {
		const ids = calendarsByAccount.get(account) ?? []
		for (let i = 0; i < ids.length; i += FREE_SLOTS_CALENDARS_PER_REQUEST) {
			chunks.forEach((_, chunkIndex) => requests.push({ account, ids: ids.slice(i, i + FREE_SLOTS_CALENDARS_PER_REQUEST), chunkIndex }))
		}
	}

	await Promise.all(
		requests.map(async ({ account, ids, chunkIndex }) => {
			const chunk = chunks[chunkIndex]
			let response: JsonObject
			try {
				response = await deps.queryFreeBusy({
					account,
					timeMin: new Date(chunk.timeMin).toISOString(),
					timeMax: new Date(chunk.timeMax).toISOString(),
					timeZone: 'UTC',
					items: ids.map((id) => ({ id })),
				})
			} catch (error) {
				const info = describeError(error)
				for (const id of ids) outcomes.push({ account, id, chunkIndex, ok: false, ...info })
				return
			}
			const calendars = (response && typeof response.calendars === 'object' && response.calendars) as Record<string, JsonObject> | null
			for (const id of ids) {
				const entry = calendars?.[id]
				const entryErrors = Array.isArray(entry?.errors) ? (entry!.errors as JsonObject[]) : []
				if (!entry || entryErrors.length) {
					const reason = entryErrors.map((e) => String(e.reason ?? 'unknown')).join(', ') || 'missing from freeBusy response'
					outcomes.push({ account, id, chunkIndex, ok: false, step: 'calendar', message: 'Calendar could not be checked: ' + reason + '.' })
					continue
				}
				outcomes.push({ account, id, chunkIndex, ok: true })
				for (const b of Array.isArray(entry.busy) ? (entry.busy as JsonObject[]) : []) {
					busy.push({ start: parseInstant(b.start), end: parseInstant(b.end) })
				}
			}
		}),
	)

	const coverageKey = (o: Outcome) => (o.id === 'primary' ? o.account + '\u0000primary' : o.id) + '\u0000' + o.chunkIndex
	const covered = new Set(outcomes.filter((o) => o.ok).map(coverageKey))
	const okChecks = covered.size
	const reported = new Set<string>()
	for (const o of outcomes) {
		const key = o.account + '\u0000' + o.id
		const existing = checked.get(key)
		if (!existing) checked.set(key, { account: o.account, calendarId: o.id, ok: o.ok })
		else if (!o.ok) existing.ok = false
		if (o.ok || covered.has(coverageKey(o))) continue
		// One error per failed request when the whole request failed, otherwise one per calendar.
		const requestWide = o.step !== 'calendar'
		const dedupeKey = o.account + '\u0000' + o.chunkIndex + '\u0000' + (requestWide ? '*' : o.id)
		if (reported.has(dedupeKey)) continue
		reported.add(dedupeKey)
		const chunk = chunks[o.chunkIndex]
		errors.push({
			account: o.account,
			calendarId: requestWide ? null : o.id,
			step: o.step ?? 'request',
			message: o.message ?? 'Unknown error.',
			...(o.status !== undefined ? { status: o.status } : {}),
			timeMin: new Date(chunk.timeMin).toISOString(),
			timeMax: new Date(chunk.timeMax).toISOString(),
		})
		for (const date of chunk.dates) unverifiedDates.add(date)
	}

	if (okChecks === 0) {
		const step = errors.length > 0 && errors.every((e) => e.step === 'auth') ? 'auth' : 'request'
		throw new CalendarFreeSlotsError(step, 'no calendar could be checked. ' + errors.map((e) => e.account + (e.calendarId ? '/' + e.calendarId : '') + ': ' + e.message).join(' | '), { errors })
	}

	const computed = computeFreeSlots({
		dates: windows.map((w) => w.date),
		timeZone: n.timeZone,
		startMinutes: n.startMinutes,
		endMinutes: n.endMinutes,
		durationMinutes: n.durationMinutes,
		stepMinutes: n.stepMinutes,
		bufferMinutes: n.bufferMinutes,
		busy,
		nowMs,
		maxResults: n.maxResults,
		maxPerDay: n.maxPerDay,
		unverifiedDates,
	})
	const partial = errors.length > 0
	const unverifiedList = [...unverifiedDates].sort()
	return {
		...base,
		...computed,
		datesChecked: windows.map((w) => w.date),
		skippedDates,
		checkedCalendars: [...checked.values()],
		errors,
		partial,
		warning: partial
			? 'Some calendars could not be checked (see errors). Slots on these dates may overlap busy time: ' + unverifiedList.join(', ') + '.'
			: null,
	}
}