123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
export type JsonFragment = {
jsonFragment: string
sha256: string
totalBytes: number
nextFragmentCursor: string | null
}
export type Base64JsonFragment = {
base64: string
sha256: string
totalBytes: number
nextOffset: number | null
}
type Bounds = { maxBytes?: number; maxFragments?: number; signal?: AbortSignal }
async function verifyJson<T>(
bytes: Uint8Array<ArrayBuffer>,
sha256: string
): Promise<T> {
const actual = Array.from(
new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)),
(b) => b.toString(16).padStart(2, "0")
).join("")
if (actual !== sha256) throw new Error("Content checksum mismatch")
return JSON.parse(
new TextDecoder("utf-8", { fatal: true }).decode(bytes)
) as T
}
function bounds(options: Bounds) {
const maxBytes = options.maxBytes ?? 4 * 1024 * 1024
const maxFragments = options.maxFragments ?? 1024
if (
!Number.isSafeInteger(maxBytes) ||
maxBytes < 1 ||
!Number.isSafeInteger(maxFragments) ||
maxFragments < 1
)
throw new Error("Invalid reconstruction bounds")
return { maxBytes, maxFragments }
}
function manifest(
fragment: { totalBytes: number; sha256: string },
maxBytes: number
) {
if (
!Number.isSafeInteger(fragment.totalBytes) ||
fragment.totalBytes < 1 ||
fragment.totalBytes > maxBytes ||
!/^[a-f0-9]{64}$/.test(fragment.sha256)
)
throw new Error("Invalid or oversized content manifest")
}
/** Keep query, page and identity unchanged. Retry a conflict by starting a new read. */
export async function collectJsonFragments<T = unknown>(
load: (cursor?: string) => Promise<JsonFragment>,
options: Bounds = {}
): Promise<T> {
const { maxBytes, maxFragments } = bounds(options)
const seen = new Set<string>()
let cursor: string | undefined,
text = "",
expected: JsonFragment | undefined
for (let count = 0; count < maxFragments; count++) {
options.signal?.throwIfAborted()
const page = await load(cursor)
options.signal?.throwIfAborted()
manifest(page, maxBytes)
expected ??= page
if (
page.sha256 !== expected.sha256 ||
page.totalBytes !== expected.totalBytes
)
throw new Error("Content snapshot changed")
text += page.jsonFragment
if (text.length > maxBytes * 2)
throw new Error("Content exceeds reconstruction bounds")
if (page.nextFragmentCursor === null) {
const bytes = new TextEncoder().encode(text)
if (bytes.length !== expected.totalBytes)
throw new Error("Incomplete content")
return verifyJson<T>(bytes, expected.sha256)
}
if (!page.nextFragmentCursor || seen.has(page.nextFragmentCursor))
throw new Error("Content continuation did not progress")
seen.add(page.nextFragmentCursor)
cursor = page.nextFragmentCursor
}
throw new Error("Content exceeds fragment limit")
}
/** Decode each base64 fragment separately; offsets count bytes, not JS characters. */
export async function collectBase64JsonFragments<T = unknown>(
load: (offset: number) => Promise<Base64JsonFragment>,
options: Bounds = {}
): Promise<T> {
const { maxBytes, maxFragments } = bounds(options)
let offset = 0,
output: Uint8Array<ArrayBuffer> | undefined,
expected: Base64JsonFragment | undefined
for (let count = 0; count < maxFragments; count++) {
options.signal?.throwIfAborted()
const page = await load(offset)
options.signal?.throwIfAborted()
manifest(page, maxBytes)
expected ??= page
if (
page.sha256 !== expected.sha256 ||
page.totalBytes !== expected.totalBytes
)
throw new Error("Content snapshot changed")
output ??= new Uint8Array(expected.totalBytes)
if (page.base64.length > Math.ceil(maxBytes / 3) * 4 + 4)
throw new Error("Content exceeds reconstruction bounds")
const bytes = Uint8Array.from(atob(page.base64), (character) =>
character.charCodeAt(0)
)
if (!bytes.length || offset + bytes.length > output.length)
throw new Error("Invalid content offset")
output.set(bytes, offset)
offset += bytes.length
if (page.nextOffset === null) {
if (offset !== output.length) throw new Error("Incomplete content")
return verifyJson<T>(output, expected.sha256)
}
if (page.nextOffset !== offset)
throw new Error("Content continuation did not progress")
}
throw new Error("Content exceeds fragment limit")
}