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.test.ts

406 lines · 18.4 KB · TypeScript
import assert from 'node:assert/strict'
import { afterEach, describe, it } from 'node:test'
import calendar, { CalendarFreeSlotsError as ExportedError, findFreeSlots } from './calendar.ts'
import {
	CalendarFreeSlotsError,
	chunkWindows,
	buildDateWindows,
	computeFreeSlots,
	expandDateInputs,
	findFreeSlotsWith,
	formatLocalIso,
	mergeBusy,
	normalizeFreeSlotsParams,
	pickSelectedCalendarIds,
	zonedWallTimeToUtc,
	type FreeSlotsDeps,
} from './calendar-free-slots.ts'
import { GoogleApiError } from './core.ts'
import type { CalendarFreeBusyParams } from './calendar.ts'
import type { JsonObject } from './types.ts'

const TZ = 'America/Denver'
const at = (iso: string) => Date.parse(iso)
// Tuesday 2026-10-27 06:00 in Denver (MDT, UTC-6).
const NOW = at('2026-10-27T12:00:00Z')

function baseCompute(overrides: Partial<Parameters<typeof computeFreeSlots>[0]> = {}) {
	return computeFreeSlots({
		dates: ['2026-11-03'],
		timeZone: TZ,
		startMinutes: 9 * 60,
		endMinutes: 17 * 60,
		durationMinutes: 30,
		stepMinutes: 30,
		bufferMinutes: 0,
		busy: [],
		nowMs: NOW,
		maxResults: 500,
		maxPerDay: null,
		...overrides,
	})
}

describe('time zone math', () => {
	it('maps local wall time to UTC with the offset of each date (DST ends 2026-11-01)', () => {
		assert.equal(new Date(zonedWallTimeToUtc('2026-10-30', 9 * 60, TZ)).toISOString(), '2026-10-30T15:00:00.000Z')
		assert.equal(new Date(zonedWallTimeToUtc('2026-11-02', 9 * 60, TZ)).toISOString(), '2026-11-02T16:00:00.000Z')
		assert.equal(new Date(zonedWallTimeToUtc('2026-11-02', 1440, TZ)).toISOString(), '2026-11-03T07:00:00.000Z')
	})

	it('moves a wall time skipped by spring forward to just after the jump', () => {
		// 2027-03-14 02:30 does not exist in Denver; 03:30 MDT is 09:30Z.
		assert.equal(new Date(zonedWallTimeToUtc('2027-03-14', 150, TZ)).toISOString(), '2027-03-14T09:30:00.000Z')
	})

	it('picks the first occurrence of a repeated wall time on fall back', () => {
		assert.equal(new Date(zonedWallTimeToUtc('2026-11-01', 90, TZ)).toISOString(), '2026-11-01T07:30:00.000Z')
	})

	it('formats local ISO strings with the right offset', () => {
		assert.equal(formatLocalIso(at('2026-10-30T15:00:00Z'), TZ), '2026-10-30T09:00:00-06:00')
		assert.equal(formatLocalIso(at('2026-11-02T16:00:00Z'), TZ), '2026-11-02T09:00:00-07:00')
		assert.equal(formatLocalIso(at('2026-11-02T16:00:00Z'), 'Asia/Kolkata'), '2026-11-02T21:30:00+05:30')
	})
})

describe('expandDateInputs', () => {
	it('mixes single dates, range objects, and range strings, sorted and unique', () => {
		assert.deepEqual(expandDateInputs(['2026-11-12', { start: '2026-11-10', end: '2026-11-12' }, '2026-11-03', '2026-11-30..2026-12-01']), [
			'2026-11-03',
			'2026-11-10',
			'2026-11-11',
			'2026-11-12',
			'2026-11-30',
			'2026-12-01',
		])
	})

	it('rejects bad dates and reversed ranges with input errors', () => {
		assert.throws(() => expandDateInputs(['2026-02-30']), (e: unknown) => e instanceof CalendarFreeSlotsError && e.step === 'input')
		assert.throws(() => expandDateInputs(['11/3/2026']), /not a YYYY-MM-DD/)
		assert.throws(() => expandDateInputs([{ start: '2026-11-14', end: '2026-11-10' }]), /after end/)
	})
})

describe('normalizeFreeSlotsParams', () => {
	it('applies defaults', () => {
		const n = normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-03'] }, NOW)
		assert.equal(n.timeZone, TZ)
		assert.equal(n.startMinutes, 540)
		assert.equal(n.endMinutes, 1020)
		assert.equal(n.stepMinutes, 30)
		assert.equal(n.bufferMinutes, 0)
		assert.equal(n.maxResults, 50)
		assert.equal(n.maxPerDay, null)
		assert.deepEqual(n.accounts, ['business', 'personal'])
		assert.equal(n.calendars, 'primary')
	})

	it('filters weekends with weekdaysOnly and records skipped dates', () => {
		const n = normalizeFreeSlotsParams({ durationMinutes: 30, dates: [{ start: '2026-11-13', end: '2026-11-16' }], weekdaysOnly: true }, NOW)
		assert.deepEqual(n.dates, ['2026-11-13', '2026-11-16'])
		assert.deepEqual(n.skippedDates, [
			{ date: '2026-11-14', reason: 'dayOfWeek' },
			{ date: '2026-11-15', reason: 'dayOfWeek' },
		])
	})

	it('accepts daysOfWeek names and numbers', () => {
		const n = normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-02..2026-11-08'], daysOfWeek: ['Tuesday', 4] }, NOW)
		assert.deepEqual(n.dates, ['2026-11-03', '2026-11-05'])
	})

	it('picks the next N matching days that still have room, in the time zone', () => {
		// Friday 2026-10-30 at 23:30 Denver is already Saturday in UTC.
		const fridayNight = at('2026-10-31T05:30:00Z')
		const n = normalizeFreeSlotsParams({ durationMinutes: 30, nextDays: 3, weekdaysOnly: true }, fridayNight)
		assert.deepEqual(n.dates, ['2026-11-02', '2026-11-03', '2026-11-04'])
		// Friday morning still counts today.
		const fridayMorning = at('2026-10-30T14:00:00Z')
		assert.deepEqual(normalizeFreeSlotsParams({ durationMinutes: 30, nextDays: 3, weekdaysOnly: true }, fridayMorning).dates, ['2026-10-30', '2026-11-02', '2026-11-03'])
	})

	it('maps calendarIds per account and narrows accounts to those keys', () => {
		const n = normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-03'], calendarIds: { business: ['primary', 'team@example.com'] } }, NOW)
		assert.deepEqual(n.accounts, ['business'])
		assert.deepEqual(n.calendarIdsByAccount, { business: ['primary', 'team@example.com'] })
	})

	it('rejects bad input', () => {
		const isInput = (e: unknown) => e instanceof CalendarFreeSlotsError && e.step === 'input'
		assert.throws(() => normalizeFreeSlotsParams({ dates: ['2026-11-03'] } as never, NOW), isInput)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 30 }, NOW), /dates, nextDays/)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-03'], timeZone: 'Mars/Base' }, NOW), isInput)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-03'], hours: { start: '17:00', end: '09:00' } }, NOW), /after hours.start/)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 600, dates: ['2026-11-03'] }, NOW), /longer than/)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-03'], stepMinutes: 0 }, NOW), isInput)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-11-03'], calendars: 'all' as never }, NOW), isInput)
		assert.throws(() => normalizeFreeSlotsParams({ durationMinutes: 30, dates: ['2026-01-01..2026-12-31'] }, NOW), /at most 120/)
	})
})

describe('computeFreeSlots', () => {
	it('fills an empty day 09:00-17:00 with 30 minute slots on the half hour', () => {
		const result = baseCompute()
		assert.equal(result.totalSlots, 16)
		assert.equal(result.slots[0].startLocal, '2026-11-03T09:00:00-07:00')
		assert.equal(result.slots[0].start, '2026-11-03T16:00:00.000Z')
		assert.equal(result.slots[15].endLocal, '2026-11-03T17:00:00-07:00')
		assert.deepEqual(result.byDate['2026-11-03'].freeRanges, [{ start: '09:00', end: '17:00' }])
		assert.equal(result.byDate['2026-11-03'].dayOfWeek, 'tue')
	})

	it('aligns starts to the clock even when the window starts off the step', () => {
		const result = baseCompute({ startMinutes: 9 * 60 + 10, endMinutes: 11 * 60, durationMinutes: 45, stepMinutes: 30 })
		assert.deepEqual(result.byDate['2026-11-03'].slotStarts, ['09:30', '10:00'])
	})

	it('removes busy time padded by bufferMinutes', () => {
		const busy = [{ start: at('2026-11-03T17:00:00Z'), end: at('2026-11-03T18:00:00Z') }] // 10:00-11:00 local
		const plain = baseCompute({ busy, startMinutes: 9 * 60, endMinutes: 12 * 60 })
		assert.deepEqual(plain.byDate['2026-11-03'].slotStarts, ['09:00', '09:30', '11:00', '11:30'])
		const buffered = baseCompute({ busy, startMinutes: 9 * 60, endMinutes: 12 * 60, bufferMinutes: 15 })
		assert.deepEqual(buffered.byDate['2026-11-03'].slotStarts, ['09:00', '11:30'])
		assert.deepEqual(buffered.byDate['2026-11-03'].freeRanges, [
			{ start: '09:00', end: '09:45' },
			{ start: '11:15', end: '12:00' },
		])
	})

	it('treats back-to-back and overlapping busy blocks as one', () => {
		assert.deepEqual(
			mergeBusy([
				{ start: 30, end: 40 },
				{ start: 0, end: 10 },
				{ start: 10, end: 20 },
				{ start: 35, end: 50 },
			]),
			[
				{ start: 0, end: 20 },
				{ start: 30, end: 50 },
			],
		)
	})

	it('skips times already in the past', () => {
		const now = at('2026-11-03T18:10:00Z') // 11:10 local
		const result = baseCompute({ nowMs: now, endMinutes: 13 * 60 })
		assert.deepEqual(result.byDate['2026-11-03'].slotStarts, ['11:30', '12:00', '12:30'])
		assert.deepEqual(result.byDate['2026-11-03'].freeRanges, [{ start: '11:10', end: '13:00' }])
	})

	it('keeps local hours across the DST change and reports per-date offsets', () => {
		const result = baseCompute({ dates: ['2026-10-30', '2026-11-02'], endMinutes: 10 * 60 })
		assert.deepEqual(
			result.slots.map((s) => [s.startLocal, s.start]),
			[
				['2026-10-30T09:00:00-06:00', '2026-10-30T15:00:00.000Z'],
				['2026-10-30T09:30:00-06:00', '2026-10-30T15:30:00.000Z'],
				['2026-11-02T09:00:00-07:00', '2026-11-02T16:00:00.000Z'],
				['2026-11-02T09:30:00-07:00', '2026-11-02T16:30:00.000Z'],
			],
		)
	})

	it('keeps real elapsed duration on the fall back night', () => {
		// 00:00-04:00 on 2026-11-01 is 5 real hours; 60 minute slots on the hour.
		const result = baseCompute({ dates: ['2026-11-01'], startMinutes: 0, endMinutes: 4 * 60, durationMinutes: 60, stepMinutes: 60, nowMs: 0 })
		assert.deepEqual(result.byDate['2026-11-01'].slotStarts, ['00:00', '01:00', '02:00', '03:00'])
		assert.ok(result.slots.every((s) => Date.parse(s.end) - Date.parse(s.start) === 3_600_000))
	})

	it('caps results with maxResults and maxPerDay and flags truncation', () => {
		const capped = baseCompute({ dates: ['2026-11-03', '2026-11-04'], maxResults: 5 })
		assert.equal(capped.slots.length, 5)
		assert.equal(capped.totalSlots, 32)
		assert.equal(capped.truncated, true)
		assert.equal(capped.byDate['2026-11-04'].slotCount, 16)
		assert.deepEqual(capped.byDate['2026-11-04'].slotStarts, [])
		const perDay = baseCompute({ dates: ['2026-11-03', '2026-11-04'], maxPerDay: 2 })
		assert.deepEqual(perDay.slots.map((s) => s.date), ['2026-11-03', '2026-11-03', '2026-11-04', '2026-11-04'])
		assert.equal(perDay.truncated, true)
		assert.equal(baseCompute().truncated, false)
	})
})

describe('chunkWindows', () => {
	it('splits long ranges into freeBusy spans of at most 30 days', () => {
		const dates = expandDateInputs([{ start: '2026-11-01', end: '2027-01-09' }])
		const chunks = chunkWindows(buildDateWindows(dates, 540, 1020, TZ), 15)
		assert.equal(chunks.length, 3)
		for (const chunk of chunks) assert.ok(chunk.timeMax - chunk.timeMin <= 30 * 86_400_000)
		assert.equal(chunks.reduce((sum, c) => sum + c.dates.length, 0), dates.length)
		assert.equal(new Date(chunks[0].timeMin).toISOString(), '2026-11-01T15:45:00.000Z')
	})
})

describe('pickSelectedCalendarIds', () => {
	it('keeps primary and selected visible calendars, minus holidays', () => {
		assert.deepEqual(
			pickSelectedCalendarIds({
				items: [
					{ id: 'me@example.com', primary: true },
					{ id: 'team@example.com', selected: true },
					{ id: 'hidden@example.com', selected: true, hidden: true },
					{ id: 'off@example.com' },
					{ id: 'en.usa#holiday@group.v.calendar.google.com', selected: true },
				],
			}),
			['primary', 'team@example.com'],
		)
	})
})

type FreeBusyHandler = (params: CalendarFreeBusyParams) => JsonObject | Promise<JsonObject>

function fakeDeps(handler: FreeBusyHandler, calendarLists: Record<string, JsonObject> = {}) {
	const calls: CalendarFreeBusyParams[] = []
	const deps: FreeSlotsDeps = {
		now: () => NOW,
		queryFreeBusy: async (params) => {
			calls.push(params)
			return await handler(params)
		},
		listCalendars: async ({ account }) => {
			const list = calendarLists[account]
			if (!list) throw new GoogleApiError('Could not authenticate Google account "' + account + '"', { account, causeMessage: 'not connected' })
			return list
		},
	}
	return { deps, calls }
}

function busyResponse(params: CalendarFreeBusyParams, busy: Record<string, Array<{ start: string; end: string }>>) {
	const calendars: JsonObject = {}
	for (const { id } of params.items ?? []) calendars[id] = { busy: busy[params.account + ':' + id] ?? [] }
	return { calendars }
}

describe('findFreeSlotsWith', () => {
	it('merges busy time from both accounts by default', async () => {
		const { deps, calls } = fakeDeps((params) =>
			busyResponse(params, {
				'business:primary': [{ start: '2026-11-03T16:00:00Z', end: '2026-11-03T17:00:00Z' }],
				'personal:primary': [{ start: '2026-11-03T18:00:00Z', end: '2026-11-03T19:00:00Z' }],
			}),
		)
		const result = await findFreeSlotsWith(deps, { durationMinutes: 60, dates: ['2026-11-03'], hours: { start: '09:00', end: '13:00' }, stepMinutes: 60 })
		assert.deepEqual(calls.map((c) => c.account).sort(), ['business', 'personal'])
		assert.equal(calls[0].timeMin, '2026-11-03T16:00:00.000Z')
		assert.equal(calls[0].timeMax, '2026-11-03T20:00:00.000Z')
		assert.deepEqual(result.byDate['2026-11-03'].slotStarts, ['10:00', '12:00'])
		assert.equal(result.partial, false)
		assert.equal(result.warning, null)
		assert.deepEqual(result.errors, [])
		assert.deepEqual(result.checkedCalendars, [
			{ account: 'business', calendarId: 'primary', ok: true },
			{ account: 'personal', calendarId: 'primary', ok: true },
		])
	})

	it('returns partial results and flags unverified dates when one account fails', async () => {
		const { deps } = fakeDeps((params) => {
			if (params.account === 'personal') throw new GoogleApiError('Could not authenticate Google account "personal"', { account: 'personal', causeMessage: 'token revoked' })
			return busyResponse(params, {})
		})
		const result = await findFreeSlotsWith(deps, { durationMinutes: 30, dates: ['2026-11-03'] })
		assert.equal(result.partial, true)
		assert.equal(result.errors.length, 1)
		assert.equal(result.errors[0].account, 'personal')
		assert.equal(result.errors[0].step, 'auth')
		assert.equal(result.byDate['2026-11-03'].unverified, true)
		assert.equal(result.slots[0].unverified, true)
		assert.match(result.warning ?? '', /2026-11-03/)
		assert.deepEqual(result.checkedCalendars.find((c) => c.account === 'personal'), { account: 'personal', calendarId: 'primary', ok: false })
	})

	it('throws a typed error when nothing could be checked', async () => {
		const { deps } = fakeDeps(() => {
			throw new GoogleApiError('Forbidden', { status: 403 })
		})
		await assert.rejects(findFreeSlotsWith(deps, { durationMinutes: 30, dates: ['2026-11-03'] }), (error: unknown) => {
			assert.ok(error instanceof CalendarFreeSlotsError)
			assert.equal(error.step, 'request')
			assert.equal(error.errors.length, 2)
			assert.equal(error.errors[0].status, 403)
			return true
		})
	})

	it('reports per-calendar freeBusy errors but counts a calendar read through another account', async () => {
		const { deps } = fakeDeps((params) => {
			const calendars: JsonObject = {}
			for (const { id } of params.items ?? []) {
				if (id === 'shared@example.com' && params.account === 'business') calendars[id] = { errors: [{ domain: 'global', reason: 'notFound' }], busy: [] }
				else if (id === 'gone@example.com') calendars[id] = { errors: [{ domain: 'global', reason: 'notFound' }], busy: [] }
				else calendars[id] = { busy: [] }
			}
			return { calendars }
		})
		const result = await findFreeSlotsWith(deps, { durationMinutes: 30, dates: ['2026-11-03'], calendarIds: ['shared@example.com', 'gone@example.com'] })
		assert.deepEqual(
			result.errors.map((e) => [e.account, e.calendarId, e.step]),
			[
				['business', 'gone@example.com', 'calendar'],
				['personal', 'gone@example.com', 'calendar'],
			],
		)
		assert.equal(result.partial, true)
	})

	it('uses selected calendars per account and flags an account whose list fails', async () => {
		const { deps, calls } = fakeDeps((params) => busyResponse(params, {}), {
			business: { items: [{ id: 'me@example.com', primary: true }, { id: 'team@example.com', selected: true }] },
		})
		const result = await findFreeSlotsWith(deps, { durationMinutes: 30, dates: ['2026-11-03'], calendars: 'selected' })
		assert.deepEqual(calls.map((c) => [c.account, (c.items ?? []).map((i) => i.id)]), [['business', ['primary', 'team@example.com']]])
		assert.equal(result.errors[0].account, 'personal')
		assert.equal(result.errors[0].step, 'auth')
		assert.equal(result.partial, true)
	})

	it('chunks long ranges into several freeBusy calls per account', async () => {
		const { deps, calls } = fakeDeps((params) => busyResponse(params, {}))
		const result = await findFreeSlotsWith(deps, { durationMinutes: 30, dates: [{ start: '2026-11-02', end: '2027-01-15' }], weekdaysOnly: true, account: 'business', maxResults: 10 })
		assert.equal(calls.length, 3)
		assert.equal(result.slots.length, 10)
		assert.equal(result.truncated, true)
		assert.ok(result.totalSlots > 500)
	})

	it('skips past dates without calling Google', async () => {
		const { deps, calls } = fakeDeps((params) => busyResponse(params, {}))
		const result = await findFreeSlotsWith(deps, { durationMinutes: 30, dates: ['2026-10-20', '2026-10-26'] })
		assert.equal(calls.length, 0)
		assert.deepEqual(result.slots, [])
		assert.deepEqual(result.skippedDates, [
			{ date: '2026-10-20', reason: 'past' },
			{ date: '2026-10-26', reason: 'past' },
		])
	})
})

describe('findFreeSlots wiring', () => {
	afterEach(() => {
		delete (globalThis as { __kodyTestFetch?: unknown }).__kodyTestFetch
	})

	it('is on the calendar namespace and posts freeBusy with each account credential', async () => {
		assert.equal(calendar().findFreeSlots, findFreeSlots)
		assert.equal(ExportedError, CalendarFreeSlotsError)
		const seen: Array<{ credential: string; method: string; path: string; body: JsonObject }> = []
		;(globalThis as { __kodyTestFetch?: unknown }).__kodyTestFetch = async (input: string, init: RequestInit = {}, credential: string) => {
			const body = JSON.parse(String(init.body)) as JsonObject
			seen.push({ credential, method: String(init.method), path: new URL(input).pathname, body })
			const calendars: JsonObject = {}
			for (const item of body.items as Array<{ id: string }>) calendars[item.id] = { busy: [] }
			return new Response(JSON.stringify({ calendars }), { status: 200, headers: { 'content-type': 'application/json' } })
		}
		const result = await findFreeSlots({ durationMinutes: 30, dates: ['2099-01-05'], maxResults: 3 })
		assert.deepEqual(seen.map((s) => s.credential).sort(), ['google', 'google-business'])
		assert.ok(seen.every((s) => s.method === 'POST' && s.path === '/calendar/v3/freeBusy'))
		assert.equal(result.slots.length, 3)
		assert.equal(result.slots[0].startLocal, '2099-01-05T09:00:00-07:00')
	})
})