Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

RawStreamJSONPlugin.ts

64 lines1.9 KB

1import { createPlugin } from 'seroval'
2import { RawStream } from './RawStream'
3import {
4 decodeText,
5 encodeText,
6 fromBase64,
7 fromEncodedStream,
8 pumpEncodedStream,
9 toBase64,
10} from './rawStreamCodec'
11import type { createStream } from 'seroval'
12import type { RawStreamJSONNode } from './RawStream'
13​
14/**
15 * Serializes a RawStream into JSON requests and static-cache responses.
16 * The optional signal stops the source pump when the request is aborted.
17 */
18/* @__NO_SIDE_EFFECTS__ */
19export function createRawStreamJSONPlugin(signal?: AbortSignal) {
20 return /* @__PURE__ */ createPlugin<RawStream, RawStreamJSONNode>({
21 tag: 'tss/RawStream',
22 test: (value) => value instanceof RawStream,
23 parse: {
24 async: async (value, ctx) => {
25 // Parse the hint before touching the source so a failed parse never
26 // locks the caller's stream.
27 const text = await ctx.parse(value.hint === 'text')
28 const [stream] = pumpEncodedStream(
29 value.stream,
30 value.hint === 'text' ? encodeText : toBase64,
31 signal,
32 )
33 return { text, stream: await ctx.parse(stream) }
34 },
35 },
36 serialize: undefined as never,
37 deserialize: undefined as never,
38 })
40​
41export const RawStreamJSONPlugin = /* @__PURE__ */ createRawStreamJSONPlugin()
42​
43/**
44 * Deserializes the JSON shape above back into a `ReadableStream<Uint8Array>`.
45 * `test` never matches, so this plugin is inert during serialization and can
46 * share a plugin list with `RawStreamJSONPlugin`.
47 */
48export const RawStreamJSONDeserializePlugin = /* @__PURE__ */ createPlugin<
49 ReadableStream<Uint8Array>,
50 RawStreamJSONNode
51>({
52 tag: 'tss/RawStream',
53 test: () => false,
54 parse: {},
55 serialize: undefined as never,
56 deserialize(node, ctx) {
57 return fromEncodedStream(
58 ctx.deserialize<ReturnType<typeof createStream<string | undefined>>>(
59 node.stream,
60 ),
61 ctx.deserialize<boolean>(node.text) ? decodeText : fromBase64,
62 )
63 },
64})