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

runtime.ts

78 lines · 4.0 KB · TypeScript
// Wires the vendored upload engine to this package's storage and Google account auth.
import { packageStorage } from 'kody:runtime'
import {
	createMemorySessionVault,
	createMemoryUploadJobStore,
	createSignerSessionVault,
	createSqlUploadJobStore,
	type HmacSigner,
	type SessionVault,
	type UploadJobStore,
} from './upload-state.ts'
import { CHUNK_MULTIPLE, DEFAULT_CHUNK_BYTES, type EngineLimits, MAX_SAFE_CHUNK_BYTES } from './resumable-engine.ts'

export type LegacyUploadOptions = {
	/** Kody signing (or Key) credential client with HMAC sign(), opened by the caller; seals the session so it survives a crash. */
	sessionSigner?: HmacSigner
	store?: UploadJobStore
	vault?: SessionVault
	sourceFetch?: (input: string, init?: RequestInit) => Promise<Response>
	limits?: EngineLimits
	now?: () => number
	sleep?: (ms: number) => Promise<void>
}

let sqlStore: UploadJobStore | null = null
let memoryStore: UploadJobStore | null = null

export function resolveUploadJobStore(options: LegacyUploadOptions = {}): UploadJobStore {
	if (options.store) return options.store
	if (sqlStore) return sqlStore
	try {
		const storage = packageStorage() as { sql?: unknown }
		if (storage && typeof storage.sql === 'function') return (sqlStore = createSqlUploadJobStore(storage as any))
	} catch {}
	return (memoryStore ??= createMemoryUploadJobStore())
}

/** Live uploads need a durable job row; a memory row cannot prevent a duplicate upload after a crash. */
export function requireDurableUploadJobStore(options: LegacyUploadOptions, helper: string): UploadJobStore {
	const store = resolveUploadJobStore(options)
	if (!store.durable && !options.store) {
		throw new Error(`${helper}: package storage is unavailable in this run, so the upload job cannot be checkpointed. Refusing a live upload that could be duplicated after a crash. Nothing was uploaded.`)
	}
	return store
}

export function resolveSessionVault(options: LegacyUploadOptions = {}): SessionVault {
	if (options.vault) return options.vault
	if (options.sessionSigner) return createSignerSessionVault(options.sessionSigner)
	return createMemorySessionVault()
}

/**
 * Default and HARD max 3 MiB (every size above is refused). Kody 506c4e15 + @kodycodes/cli >= 3.33.1
 * stream binary bodies of any size on local execute; older CLIs still use a 5 MiB base64 JSON envelope
 * and there is no capability marker, so the cap stays until a deliberate package release.
 */
export function legacyChunkSize(value: unknown): number {
	if (value === undefined || value === null) return DEFAULT_CHUNK_BYTES
	const n = typeof value === 'string' && value.trim() ? Number(value) : value
	if (typeof n !== 'number' || !Number.isInteger(n) || n <= 0 || n % CHUNK_MULTIPLE !== 0) throw new Error('chunkSizeBytes must be a positive multiple of 262144 (256 KiB).')
	if (n > MAX_SAFE_CHUNK_BYTES) throw new Error(`chunkSizeBytes must be at most ${MAX_SAFE_CHUNK_BYTES} (3 MiB), the package's chunk cap (safe on every Kody runtime, including CLIs older than 3.33.1).`)
	return n
}

/** The one channel the account's OAuth token is signed in as: the job's immutable channel identity. */
export async function mineChannelIdentity(authFetch: typeof fetch): Promise<string> {
	const res = await authFetch('https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&maxResults=50', { method: 'GET', headers: { accept: 'application/json' } })
	if (!res.ok) {
		await res.body?.cancel()
		throw new Error(`Could not read the signed-in YouTube channel (HTTP ${res.status}); nothing was uploaded.`)
	}
	const data = (await res.json()) as { items?: Array<{ id?: string }> }
	const ids = (data.items ?? []).map((i) => i.id).filter((id): id is string => typeof id === 'string').sort()
	if (!ids.length) throw new Error('The Google account has no YouTube channel; nothing was uploaded.')
	if (ids.length > 1) throw new Error(`The Google account manages ${ids.length} YouTube channels; connect the account as one channel (Brand Account) so the upload target is unambiguous. Nothing was uploaded.`)
	return ids[0]
}