Open History to see the last commit
1import { StreamError } from './errors.js'
2
3export interface PreparedPayload {
4 readonly bytes: Buffer
5 /** Byte ends including each trailing comma. Null means binary mode. */
6 readonly messageEnds: readonly number[] | null
7}
8
9export function mediaType(value: string): string {
10 return value.split(';', 1)[0]!.trim().toLowerCase()
11}
12
13/** Validate without round-tripping numeric values through JavaScript numbers. */
14export function preparePayload(input: Uint8Array, contentType: string, initial = false): PreparedPayload {
15 if (mediaType(contentType) !== 'application/json') return { bytes: Buffer.from(input), messageEnds: null }
16 if (input.byteLength === 0 && initial) return { bytes: Buffer.alloc(0), messageEnds: [] }
17 let text: string
18 let isArray: boolean
19 try {
20 const decoded = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(input)
21 isArray = Array.isArray(JSON.parse(decoded) as unknown)
22 text = decoded.trim()
23 } catch {
24 throw new StreamError(400, 'INVALID_JSON', 'Body must be valid UTF-8 JSON')
25 }
26 const messages: string[] = []
27 if (!isArray) {
28 messages.push(text)
29 } else if (text.slice(1, -1).trim() !== '') {
30 let start = 1
31 let depth = 0
32 let quoted = false
33 let escaped = false
34 for (let i = 1; i < text.length - 1; i++) {
35 const c = text[i]!
36 if (quoted) {
37 if (escaped) escaped = false
38 else if (c === '\\') escaped = true
39 else if (c === '"') quoted = false
40 } else if (c === '"') quoted = true
41 else if (c === '[' || c === '{') depth++
42 else if (c === ']' || c === '}') depth--
43 else if (c === ',' && depth === 0) {
44 messages.push(text.slice(start, i).trim())
45 start = i + 1
46 }
47 }
48 messages.push(text.slice(start, -1).trim())
49 }
50 if (!messages.length && !initial) throw new StreamError(400, 'EMPTY_JSON_BATCH', 'Empty JSON batches cannot be appended')
51 const fragments = messages.map((m) => Buffer.from(`${m},`))
52 let length = 0
53 const messageEnds = fragments.map((fragment) => (length += fragment.length))
54 return { bytes: Buffer.concat(fragments), messageEnds }
55}
56
57export function formatPayloads(payloads: readonly Uint8Array[], contentType: string): Buffer<ArrayBuffer> {
58 if (mediaType(contentType) !== 'application/json') return Buffer.concat(payloads)
59 const length = payloads.reduce((sum, payload) => sum + payload.byteLength, 0)
60 if (!length) return Buffer.from('[]')
61 const last = payloads.findLast((payload) => payload.byteLength > 0)!
62 if (last[last.byteLength - 1] !== 44) throw new Error('Invalid stored JSON frame')
63 const bytes = Buffer.allocUnsafe(length + 1)
64 bytes[0] = 91
65 let position = 1
66 for (const payload of payloads) {
67 bytes.set(payload, position)
68 position += payload.byteLength
69 }
70 bytes[length] = 93
71 return bytes
72}