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

@kody/rooms

Shared rooms where spawned agents and their spawner exchange messages, with push wakes and a blocking wait fallback.

FollowForkOpen app

Files

errors.ts

74 lines · 1.7 KB · TypeScript
export type RoomErrorCode =
	| 'invalid_input'
	| 'unauthorized'
	| 'forbidden'
	| 'not_found'
	| 'room_closed'
	| 'invite_used'
	| 'invite_expired'
	| 'room_full'
	| 'rate_limited'
	| 'too_large'
	| 'unavailable'

const httpStatusByCode: Record<RoomErrorCode, number> = {
	invalid_input: 400,
	unauthorized: 401,
	forbidden: 403,
	not_found: 404,
	room_closed: 410,
	invite_used: 410,
	invite_expired: 410,
	room_full: 409,
	rate_limited: 429,
	too_large: 413,
	unavailable: 503,
}

/** Error with a stable `code`, an HTTP status, and an optional retry hint. */
export class RoomError extends Error {
	code: RoomErrorCode
	retryAfterSeconds: number | null
	hint: string | null

	constructor(
		code: RoomErrorCode,
		message: string,
		options: { retryAfterSeconds?: number; hint?: string } = {},
	) {
		super(message)
		this.name = 'RoomError'
		this.code = code
		this.retryAfterSeconds =
			options.retryAfterSeconds == null ? null : Math.max(1, Math.ceil(options.retryAfterSeconds))
		this.hint = options.hint ?? null
	}

	get httpStatus() {
		return httpStatusByCode[this.code]
	}
}

export type ErrorResult = {
	status: 'error'
	code: RoomErrorCode
	error: string
	retryAfterSeconds?: number
	hint?: string
}

/** Turn a thrown error into a plain `{ status: 'error' }` result. Unknown errors are rethrown. */
export function toErrorResult(error: unknown): ErrorResult {
	if (!(error instanceof RoomError)) throw error
	return {
		status: 'error',
		code: error.code,
		error: error.message,
		...(error.retryAfterSeconds == null ? {} : { retryAfterSeconds: error.retryAfterSeconds }),
		...(error.hint == null ? {} : { hint: error.hint }),
	}
}

export function invalid(message: string): never {
	throw new RoomError('invalid_input', message)
}