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

multipart.test.ts

65 lines · 2.6 KB · TypeScript
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
	buildAppendRequest,
	buildMultipartBody,
	LOCAL_HOP_WINDOW_MAX_BYTES,
	LOCAL_HOP_WINDOW_MIN_BYTES,
	planMediaSegments,
} from '../src/multipart.ts'

const MIB = 1024 * 1024

test('buildMultipartBody round-trips through a standard multipart parser', async () => {
	const data = new Uint8Array([0, 1, 2, 13, 10, 45, 45, 255])
	const { body, contentType, boundary } = buildMultipartBody([
		{ name: 'segment_index', value: '7' },
		{ name: 'media', filename: 'chunk-7', contentType: 'video/mp4', data },
	])
	assert.ok(body instanceof Uint8Array)
	assert.equal(contentType, `multipart/form-data; boundary=${boundary}`)
	const form = await new Response(body, { headers: { 'content-type': contentType } }).formData()
	assert.equal(form.get('segment_index'), '7')
	const media = form.get('media') as File
	assert.equal(media.type, 'video/mp4')
	assert.equal(media.name, 'chunk-7')
	assert.deepEqual(new Uint8Array(await media.arrayBuffer()), data)
})

test('buildMultipartBody rejects invalid boundaries', () => {
	assert.throws(() => buildMultipartBody([], 'bad boundary\r\n'), /boundary/)
})

test('buildAppendRequest sends a Uint8Array body, never FormData', async () => {
	const bytes = new Uint8Array(1024).fill(9)
	const { url, init } = buildAppendRequest({
		apiBase: 'https://api.x.com/2',
		mediaId: '123',
		segmentIndex: 3,
		bytes,
		mediaType: 'video/mp4',
	})
	assert.equal(url, 'https://api.x.com/2/media/upload/123/append')
	assert.equal(init.method, 'POST')
	assert.ok(init.body instanceof Uint8Array)
	assert.ok(!(init.body instanceof FormData))
	assert.match(init.headers['content-type'], /^multipart\/form-data; boundary=/)
	const form = await new Response(init.body, { headers: init.headers }).formData()
	assert.equal(form.get('segment_index'), '3')
	assert.equal((form.get('media') as File).size, 1024)
	assert.throws(() => buildAppendRequest({ apiBase: 'x', mediaId: '1', segmentIndex: -1, bytes }), /segmentIndex/)
})

test('planMediaSegments covers every byte in order with sequential indexes', () => {
	const total = 421_522_153
	const segments = planMediaSegments(total, 6 * MIB)
	assert.equal(segments[0].start, 0)
	assert.equal(segments.at(-1)!.end, total)
	segments.forEach((segment, index) => {
		assert.equal(segment.index, index)
		if (index > 0) assert.equal(segment.start, segments[index - 1].end)
		assert.ok(segment.end - segment.start <= 6 * MIB)
	})
})

test('planMediaSegments uses full 4 MiB chunks with the fixed transport',()=>{ const s=planMediaSegments(8*MIB,4*MIB);assert.deepEqual(s.map(x=>x.end-x.start),[4*MIB,4*MIB]);assert.throws(()=>planMediaSegments(10,9*MIB),/chunkBytes/) })