Skip to content
← Public packages

@kentcdodds/x

X API v2 helpers for posts, search, DMs, and encrypted X Chat. Generic Activity CRC/HMAC utilities only — @kodykoala Pam wake lives in @kentcdodds/kodykoala-activity.

FollowFork

Files

limited-body.ts

37 lines · 1.2 KB · TypeScript
/** Bound convenience uploads before allocation. Large files belong in the local-file runner. */
export const MAX_CONVENIENCE_BYTES = 8 * 1024 * 1024
export async function readLimitedBody(
	response: Response,
	max = MAX_CONVENIENCE_BYTES,
): Promise<Uint8Array> {
	const raw = response.headers.get('content-length')
	if (raw !== null && (!/^\d+$/.test(raw) || Number(raw) > max)) {
		await response.body?.cancel()
		throw new Error('Media exceeds convenience upload limit; use scripts/upload-to-x-media.mjs')
	}
	const reader = response.body?.getReader()
	if (!reader) return new Uint8Array()
	const parts: Uint8Array[] = []
	let size = 0
	try {
		for (;;) {
			const r = await reader.read()
			if (r.done) break
			size += r.value.length
			if (size > max)
				throw new Error('Media exceeds convenience upload limit; use scripts/upload-to-x-media.mjs')
			parts.push(r.value)
		}
		if (raw !== null && size !== Number(raw)) throw new Error('Partial media body')
	} finally {
		await reader.cancel().catch(() => {})
		reader.releaseLock()
	}
	const bytes = new Uint8Array(size)
	let at = 0
	for (const part of parts) {
		bytes.set(part, at)
		at += part.length
	}
	return bytes
}