ai-resumable-stream 2.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +421 -266
- package/dist/adapter-CTz0z2k0.d.mts +82 -0
- package/dist/adapters/redis/index.d.mts +54 -0
- package/dist/adapters/redis/index.mjs +258 -0
- package/dist/adapters/s3-express/index.d.mts +65 -0
- package/dist/adapters/s3-express/index.mjs +751 -0
- package/dist/ai-sdk/index.d.mts +23 -0
- package/dist/ai-sdk/index.mjs +37 -0
- package/dist/core-DAlVpiTc.mjs +173 -0
- package/dist/core-DmhblcmG.d.mts +107 -0
- package/dist/index.d.mts +3 -78
- package/dist/index.mjs +2 -195
- package/package.json +24 -5
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { n as StreamCodec } from "../adapter-CTz0z2k0.mjs";
|
|
2
|
+
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-DmhblcmG.mjs";
|
|
3
|
+
import { UIMessageChunk } from "ai";
|
|
4
|
+
//#region src/ai-sdk/index.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Serializes UI message chunks as JSON and validates them on the way back.
|
|
7
|
+
*
|
|
8
|
+
* Chunks are validated rather than trusted because they may have been written by an
|
|
9
|
+
* older version of the application. A chunk that no longer parses is dropped instead
|
|
10
|
+
* of failing the resume.
|
|
11
|
+
*/
|
|
12
|
+
declare const uiMessageChunkCodec: StreamCodec<UIMessageChunk>;
|
|
13
|
+
type CreateResumableUIMessageStreamOptions = Omit<CreateResumableStreamOptions<UIMessageChunk>, `codec`>;
|
|
14
|
+
/**
|
|
15
|
+
* Creates a resumable stream context for AI SDK UI message streams.
|
|
16
|
+
*/
|
|
17
|
+
declare function createResumableUIMessageStream(options: CreateResumableUIMessageStreamOptions): {
|
|
18
|
+
startStream: (source: ReadableStream<UIMessageChunk>, startOptions?: StartStreamOptions) => Promise<StartStreamResult<UIMessageChunk>>;
|
|
19
|
+
resumeStream: (options: ResumeStreamOptions) => Promise<import("ai").AsyncIterableStream<UIMessageChunk> | null>;
|
|
20
|
+
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { CreateResumableUIMessageStreamOptions, createResumableUIMessageStream, uiMessageChunkCodec };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { t as createResumableStream } from "../core-DAlVpiTc.mjs";
|
|
2
|
+
import { asSchema, uiMessageChunkSchema } from "ai";
|
|
3
|
+
//#region src/ai-sdk/index.ts
|
|
4
|
+
const schema = asSchema(uiMessageChunkSchema);
|
|
5
|
+
/**
|
|
6
|
+
* Serializes UI message chunks as JSON and validates them on the way back.
|
|
7
|
+
*
|
|
8
|
+
* Chunks are validated rather than trusted because they may have been written by an
|
|
9
|
+
* older version of the application. A chunk that no longer parses is dropped instead
|
|
10
|
+
* of failing the resume.
|
|
11
|
+
*/
|
|
12
|
+
const uiMessageChunkCodec = {
|
|
13
|
+
encode(chunk) {
|
|
14
|
+
return JSON.stringify(chunk);
|
|
15
|
+
},
|
|
16
|
+
async decode(data) {
|
|
17
|
+
let value;
|
|
18
|
+
try {
|
|
19
|
+
value = JSON.parse(data);
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const result = await schema.validate(value);
|
|
24
|
+
return result.success ? result.value : void 0;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Creates a resumable stream context for AI SDK UI message streams.
|
|
29
|
+
*/
|
|
30
|
+
function createResumableUIMessageStream(options) {
|
|
31
|
+
return createResumableStream({
|
|
32
|
+
...options,
|
|
33
|
+
codec: uiMessageChunkCodec
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { createResumableUIMessageStream, uiMessageChunkCodec };
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { createAsyncIterableStream } from "ai-stream-utils";
|
|
2
|
+
//#region src/core.ts
|
|
3
|
+
/**
|
|
4
|
+
* Ignores teardown failures so they never mask the original outcome.
|
|
5
|
+
*/
|
|
6
|
+
async function ignoreErrors(fn) {
|
|
7
|
+
try {
|
|
8
|
+
await fn();
|
|
9
|
+
} catch {}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Creates a resumable stream context bound to a storage adapter and a chunk codec.
|
|
13
|
+
*
|
|
14
|
+
* The returned stream is drained once and fanned out to two consumers: the client
|
|
15
|
+
* that started it, and the adapter. The two are independent, so a client that
|
|
16
|
+
* disconnects mid-stream neither stops nor corrupts persistence.
|
|
17
|
+
*/
|
|
18
|
+
function createResumableStream(options) {
|
|
19
|
+
const { adapter, codec, waitUntil, generateId = () => crypto.randomUUID() } = options;
|
|
20
|
+
async function startStream(source, startOptions = {}) {
|
|
21
|
+
const { streamId = generateId(), generationId = generateId(), abortController = new AbortController(), onFinish, onStopSubscriptionError } = startOptions;
|
|
22
|
+
/**
|
|
23
|
+
* Chunks for the client, exactly as produced. Cancelling stops the client fan-out
|
|
24
|
+
* but leaves the drain loop running so the adapter still receives every chunk.
|
|
25
|
+
*/
|
|
26
|
+
let clientCancelled = false;
|
|
27
|
+
let clientController;
|
|
28
|
+
const clientStream = new ReadableStream({
|
|
29
|
+
start(controller) {
|
|
30
|
+
clientController = controller;
|
|
31
|
+
},
|
|
32
|
+
cancel() {
|
|
33
|
+
clientCancelled = true;
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
/**
|
|
37
|
+
* Serialized chunks for the adapter.
|
|
38
|
+
*/
|
|
39
|
+
let adapterController;
|
|
40
|
+
const adapterStream = new ReadableStream({ start(controller) {
|
|
41
|
+
adapterController = controller;
|
|
42
|
+
} });
|
|
43
|
+
/**
|
|
44
|
+
* Acquired before registration so a locked source fails before any state is written.
|
|
45
|
+
*/
|
|
46
|
+
const reader = source.getReader();
|
|
47
|
+
/**
|
|
48
|
+
* Cancelling the source resolves any pending read as done, which ends the drain
|
|
49
|
+
* loop, and propagates upstream so the producer stops doing work. Registered before
|
|
50
|
+
* anything can request a stop, so an early stop is not missed.
|
|
51
|
+
*/
|
|
52
|
+
const onAbort = () => {
|
|
53
|
+
reader.cancel().catch(() => {
|
|
54
|
+
/** The source is already gone */
|
|
55
|
+
});
|
|
56
|
+
};
|
|
57
|
+
abortController.signal.addEventListener(`abort`, onAbort, { once: true });
|
|
58
|
+
/**
|
|
59
|
+
* Set once the source has ended, after which a stop has nothing left to abort and a
|
|
60
|
+
* subscription has nothing left to guard.
|
|
61
|
+
*/
|
|
62
|
+
let finished = false;
|
|
63
|
+
let unsubscribe;
|
|
64
|
+
/**
|
|
65
|
+
* Stops listening, now or as soon as the listener is registered.
|
|
66
|
+
*/
|
|
67
|
+
async function finish() {
|
|
68
|
+
finished = true;
|
|
69
|
+
abortController.signal.removeEventListener(`abort`, onAbort);
|
|
70
|
+
const remove = unsubscribe;
|
|
71
|
+
unsubscribe = void 0;
|
|
72
|
+
if (remove) await ignoreErrors(remove);
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
await adapter.createStream({
|
|
76
|
+
streamId,
|
|
77
|
+
generationId,
|
|
78
|
+
chunks: adapterStream,
|
|
79
|
+
waitUntil
|
|
80
|
+
});
|
|
81
|
+
} catch (error) {
|
|
82
|
+
reader.releaseLock();
|
|
83
|
+
await finish();
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Listening for stops is best effort and never awaited, so a slow or failing store
|
|
88
|
+
* neither delays the client nor fails the stream. A stop requested in the meantime is
|
|
89
|
+
* not lost where the adapter keeps it until the listener asks. Started only once the
|
|
90
|
+
* generation is registered, so a start that is refused never touches the stop listeners
|
|
91
|
+
* of the generation it collided with.
|
|
92
|
+
*/
|
|
93
|
+
(async () => {
|
|
94
|
+
try {
|
|
95
|
+
const remove = await adapter.onStopRequested({
|
|
96
|
+
streamId,
|
|
97
|
+
generationId,
|
|
98
|
+
onStop: () => {
|
|
99
|
+
if (!finished) abortController.abort();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
/** The source ended first, so the listener must not outlive it. */
|
|
103
|
+
if (finished) await ignoreErrors(remove);
|
|
104
|
+
else unsubscribe = remove;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
await ignoreErrors(() => onStopSubscriptionError?.(error));
|
|
107
|
+
}
|
|
108
|
+
})();
|
|
109
|
+
const drained = (async () => {
|
|
110
|
+
try {
|
|
111
|
+
while (true) {
|
|
112
|
+
const { done, value } = await reader.read();
|
|
113
|
+
if (done) {
|
|
114
|
+
if (!clientCancelled) clientController.close();
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
adapterController.enqueue(codec.encode(value));
|
|
118
|
+
if (!clientCancelled) clientController.enqueue(value);
|
|
119
|
+
}
|
|
120
|
+
} catch (error) {
|
|
121
|
+
adapterController.error(error);
|
|
122
|
+
if (!clientCancelled) clientController.error(error);
|
|
123
|
+
} finally {
|
|
124
|
+
reader.releaseLock();
|
|
125
|
+
await finish();
|
|
126
|
+
await ignoreErrors(() => adapterController.close());
|
|
127
|
+
await ignoreErrors(() => onFinish?.());
|
|
128
|
+
}
|
|
129
|
+
})();
|
|
130
|
+
waitUntil?.(drained);
|
|
131
|
+
return {
|
|
132
|
+
streamId,
|
|
133
|
+
generationId,
|
|
134
|
+
stream: createAsyncIterableStream(clientStream)
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Returns the chunks of an in-flight stream, starting from the first one it produced,
|
|
139
|
+
* or `null` when there is nothing to resume: the generation named by `generationId`, or
|
|
140
|
+
* the current one.
|
|
141
|
+
*/
|
|
142
|
+
async function resumeStream(options) {
|
|
143
|
+
const { streamId, generationId } = options;
|
|
144
|
+
const encoded = await adapter.resumeStream(generationId === void 0 ? { streamId } : {
|
|
145
|
+
streamId,
|
|
146
|
+
generationId
|
|
147
|
+
});
|
|
148
|
+
if (!encoded) return null;
|
|
149
|
+
return createAsyncIterableStream(encoded.pipeThrough(new TransformStream({ async transform(data, controller) {
|
|
150
|
+
const chunk = await codec.decode(data);
|
|
151
|
+
if (chunk !== void 0) controller.enqueue(chunk);
|
|
152
|
+
} })));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Asks the process producing a generation of the stream to stop: the one named by
|
|
156
|
+
* `generationId`, or the current one. Resolves once the request is recorded, which may
|
|
157
|
+
* be before the producer has observed it.
|
|
158
|
+
*/
|
|
159
|
+
async function stopStream(options) {
|
|
160
|
+
const { streamId, generationId } = options;
|
|
161
|
+
await adapter.requestStop(generationId === void 0 ? { streamId } : {
|
|
162
|
+
streamId,
|
|
163
|
+
generationId
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
startStream,
|
|
168
|
+
resumeStream,
|
|
169
|
+
stopStream
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
export { createResumableStream as t };
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
|
|
2
|
+
import { AsyncIterableStream } from "ai-stream-utils";
|
|
3
|
+
//#region src/core.d.ts
|
|
4
|
+
type StartStreamOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* A stable identifier for the stream, used to resume and to stop it.
|
|
7
|
+
* Defaults to a generated id.
|
|
8
|
+
*
|
|
9
|
+
* Passing an id the caller already owns (a chat id, a message id) removes the need
|
|
10
|
+
* to track a separate pointer. Reusing an id discards the previous stream's chunks.
|
|
11
|
+
*/
|
|
12
|
+
streamId?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Identifies this generation of the stream id, so it can be resumed and stopped on its
|
|
15
|
+
* own, even after a newer generation of the same stream id has started. Defaults to a
|
|
16
|
+
* generated id, returned as `generationId`.
|
|
17
|
+
*
|
|
18
|
+
* Names exactly one generation, so an id is never used for a second generation of the
|
|
19
|
+
* same stream id: a resume or a stop kept for it reaches the generation that holds it.
|
|
20
|
+
*/
|
|
21
|
+
generationId?: string;
|
|
22
|
+
/**
|
|
23
|
+
* The controller aborted when the stream is stopped. Created if not supplied, so a
|
|
24
|
+
* stream is always stoppable.
|
|
25
|
+
*
|
|
26
|
+
* Supply one when the producer needs the signal, for example to pass it to
|
|
27
|
+
* `streamText({ abortSignal })`, so the provider request is aborted directly instead
|
|
28
|
+
* of relying on stream cancellation propagating upstream.
|
|
29
|
+
*/
|
|
30
|
+
abortController?: AbortController;
|
|
31
|
+
/**
|
|
32
|
+
* Called when listening for stop requests fails. The stream is unaffected, but it
|
|
33
|
+
* cannot be stopped. Errors thrown by the callback are ignored.
|
|
34
|
+
*/
|
|
35
|
+
onStopSubscriptionError?: (error: unknown) => void;
|
|
36
|
+
/**
|
|
37
|
+
* Called once the source has ended and the adapter has been told the stream is
|
|
38
|
+
* complete. Runs on every exit path, including errors and stops. Errors are ignored.
|
|
39
|
+
*/
|
|
40
|
+
onFinish?: () => void | Promise<void>;
|
|
41
|
+
};
|
|
42
|
+
type ResumeStreamOptions = {
|
|
43
|
+
/**
|
|
44
|
+
* The id the stream was started under.
|
|
45
|
+
*/
|
|
46
|
+
streamId: string;
|
|
47
|
+
/**
|
|
48
|
+
* The generation to resume. Defaults to the one the stream id currently points at.
|
|
49
|
+
*/
|
|
50
|
+
generationId?: string;
|
|
51
|
+
};
|
|
52
|
+
type StopStreamOptions = {
|
|
53
|
+
/**
|
|
54
|
+
* The id of the stream to stop.
|
|
55
|
+
*/
|
|
56
|
+
streamId: string;
|
|
57
|
+
/**
|
|
58
|
+
* The generation to stop. Defaults to the one the stream id currently points at.
|
|
59
|
+
*/
|
|
60
|
+
generationId?: string;
|
|
61
|
+
};
|
|
62
|
+
type StartStreamResult<CHUNK> = {
|
|
63
|
+
/**
|
|
64
|
+
* The id the stream was registered under, whether supplied or generated.
|
|
65
|
+
*/
|
|
66
|
+
streamId: string;
|
|
67
|
+
/**
|
|
68
|
+
* The id of this generation, whether supplied or generated. Pass it to `resumeStream` or
|
|
69
|
+
* `stopStream` to address this generation and no other.
|
|
70
|
+
*/
|
|
71
|
+
generationId: string;
|
|
72
|
+
/**
|
|
73
|
+
* The chunks, for the client that started it. Cancelling it does not stop
|
|
74
|
+
* persistence, so a disconnected client can still resume.
|
|
75
|
+
*/
|
|
76
|
+
stream: AsyncIterableStream<CHUNK>;
|
|
77
|
+
};
|
|
78
|
+
type CreateResumableStreamOptions<CHUNK> = {
|
|
79
|
+
adapter: StreamAdapter;
|
|
80
|
+
codec: StreamCodec<CHUNK>;
|
|
81
|
+
/**
|
|
82
|
+
* Keeps the host process alive until persistence finishes. Omit on long-lived servers.
|
|
83
|
+
*/
|
|
84
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
85
|
+
/**
|
|
86
|
+
* Generates a stream id or a generation id when `startStream` is not given one.
|
|
87
|
+
* Defaults to `crypto.randomUUID`.
|
|
88
|
+
*
|
|
89
|
+
* Must return an id that has not been used before: two generations of a stream id can
|
|
90
|
+
* never share a generation id.
|
|
91
|
+
*/
|
|
92
|
+
generateId?: () => string;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Creates a resumable stream context bound to a storage adapter and a chunk codec.
|
|
96
|
+
*
|
|
97
|
+
* The returned stream is drained once and fanned out to two consumers: the client
|
|
98
|
+
* that started it, and the adapter. The two are independent, so a client that
|
|
99
|
+
* disconnects mid-stream neither stops nor corrupts persistence.
|
|
100
|
+
*/
|
|
101
|
+
declare function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUNK>): {
|
|
102
|
+
startStream: (source: ReadableStream<CHUNK>, startOptions?: StartStreamOptions) => Promise<StartStreamResult<CHUNK>>;
|
|
103
|
+
resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
|
|
104
|
+
stopStream: (options: StopStreamOptions) => Promise<void>;
|
|
105
|
+
};
|
|
106
|
+
//#endregion
|
|
107
|
+
export { StopStreamOptions as a, StartStreamResult as i, ResumeStreamOptions as n, createResumableStream as o, StartStreamOptions as r, CreateResumableStreamOptions as t };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,78 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/resumable-ui-message-stream.d.ts
|
|
5
|
-
/**
|
|
6
|
-
* A Redis client, described by the commands this library actually calls rather than
|
|
7
|
-
* by the client type of a specific `redis` release. The generic parameters of
|
|
8
|
-
* `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
|
|
9
|
-
* type would pin consumers to one of them.
|
|
10
|
-
*/
|
|
11
|
-
type Redis = Publisher & Subscriber & {
|
|
12
|
-
isOpen: boolean;
|
|
13
|
-
};
|
|
14
|
-
type CreateResumableUIMessageStream = {
|
|
15
|
-
/**
|
|
16
|
-
* A unique identifier for the stream.
|
|
17
|
-
*/
|
|
18
|
-
streamId: string;
|
|
19
|
-
/**
|
|
20
|
-
* A Redis client from the `redis` package.
|
|
21
|
-
* Checks if the client is already connected before attempting to connect.
|
|
22
|
-
*/
|
|
23
|
-
subscriber: Redis;
|
|
24
|
-
/**
|
|
25
|
-
* A Redis client from the `redis` package.
|
|
26
|
-
* Checks if the client is already connected before attempting to connect.
|
|
27
|
-
*/
|
|
28
|
-
publisher: Redis;
|
|
29
|
-
/**
|
|
30
|
-
* An optional AbortController that, when provided, allows the stream to be stopped by aborting the controller.
|
|
31
|
-
* If not provided, the stream will not be stoppable.
|
|
32
|
-
*/
|
|
33
|
-
abortController?: AbortController;
|
|
34
|
-
/**
|
|
35
|
-
* A function that takes a promise and ensures that the current program stays alive
|
|
36
|
-
* until the promise is resolved.
|
|
37
|
-
*
|
|
38
|
-
* Omit if you are deploying to a server environment, where you don't have to worry about
|
|
39
|
-
* the function getting suspended.
|
|
40
|
-
*/
|
|
41
|
-
waitUntil?: (promise: Promise<unknown>) => void;
|
|
42
|
-
};
|
|
43
|
-
type StartStreamOptions = {
|
|
44
|
-
/**
|
|
45
|
-
* A promise that is awaited before closing the Redis stream, keeping the
|
|
46
|
-
* resumable-stream producer alive so late resume requests can be served
|
|
47
|
-
* from the in-memory buffer. The producer tears down when the promise resolves.
|
|
48
|
-
*
|
|
49
|
-
* Use `Promise.withResolvers()` to create a deferred promise and resolve it
|
|
50
|
-
* after post-stream work (e.g. DB writes) is complete:
|
|
51
|
-
* ```ts
|
|
52
|
-
* const { promise, resolve } = Promise.withResolvers<void>();
|
|
53
|
-
* const stream = await ctx.startStream(input, { keepAlive: promise });
|
|
54
|
-
* for await (const chunk of stream) { ... }
|
|
55
|
-
* await saveToDb();
|
|
56
|
-
* resolve();
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
|
-
keepAlive?: Promise<void>;
|
|
60
|
-
/**
|
|
61
|
-
* Called after the Redis stream is closed and the producer has torn down.
|
|
62
|
-
* Use for post-teardown cleanup.
|
|
63
|
-
*/
|
|
64
|
-
onFlush?: () => void | Promise<void>;
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* Creates a resumable context for starting, resuming and stopping UI message streams.
|
|
68
|
-
*
|
|
69
|
-
* Leverages resumable-stream's internal eager drain pattern which drains the source
|
|
70
|
-
* eagerly and enqueues directly to the output stream.
|
|
71
|
-
*/
|
|
72
|
-
declare function createResumableUIMessageStream(options: CreateResumableUIMessageStream): Promise<{
|
|
73
|
-
startStream: (stream: ReadableStream<UIMessageChunk>, options?: StartStreamOptions) => Promise<AsyncIterableStream<UIMessageChunk>>;
|
|
74
|
-
resumeStream: () => Promise<AsyncIterableStream<UIMessageChunk> | null>;
|
|
75
|
-
stopStream: () => Promise<void>;
|
|
76
|
-
}>;
|
|
77
|
-
//#endregion
|
|
78
|
-
export { createResumableUIMessageStream };
|
|
1
|
+
import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
|
|
2
|
+
import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-DmhblcmG.mjs";
|
|
3
|
+
export { CreateResumableStreamOptions, ResumeStreamOptions, StartStreamOptions, StartStreamResult, StopStreamOptions, type StreamAdapter, type StreamCodec, createResumableStream };
|
package/dist/index.mjs
CHANGED
|
@@ -1,195 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { createResumableStreamContext } from "resumable-stream";
|
|
4
|
-
//#region src/convert-sse-stream-to-ui-message-stream.ts
|
|
5
|
-
/**
|
|
6
|
-
* Converts an SSE stream to a UI message stream.
|
|
7
|
-
*/
|
|
8
|
-
function convertSSEToUIMessageStream(stream, onFlush) {
|
|
9
|
-
return parseJsonEventStream({
|
|
10
|
-
stream: stream.pipeThrough(new TextEncoderStream()),
|
|
11
|
-
schema: uiMessageChunkSchema
|
|
12
|
-
}).pipeThrough(new TransformStream({
|
|
13
|
-
transform(result, controller) {
|
|
14
|
-
if (result.success) controller.enqueue(result.value);
|
|
15
|
-
},
|
|
16
|
-
flush() {
|
|
17
|
-
onFlush?.();
|
|
18
|
-
}
|
|
19
|
-
}));
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/resumable-ui-message-stream.ts
|
|
23
|
-
const KEY_PREFIX = `ai-resumable-stream`;
|
|
24
|
-
/**
|
|
25
|
-
* Creates a resumable context for starting, resuming and stopping UI message streams.
|
|
26
|
-
*
|
|
27
|
-
* Leverages resumable-stream's internal eager drain pattern which drains the source
|
|
28
|
-
* eagerly and enqueues directly to the output stream.
|
|
29
|
-
*/
|
|
30
|
-
async function createResumableUIMessageStream(options) {
|
|
31
|
-
const { streamId, abortController, publisher, subscriber, waitUntil = null } = options;
|
|
32
|
-
const stopChannel = `${KEY_PREFIX}:stop:${streamId}`;
|
|
33
|
-
const context = createResumableStreamContext({
|
|
34
|
-
waitUntil,
|
|
35
|
-
publisher,
|
|
36
|
-
subscriber,
|
|
37
|
-
keyPrefix: KEY_PREFIX
|
|
38
|
-
});
|
|
39
|
-
await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
|
|
40
|
-
/**
|
|
41
|
-
* Unsubscribe from stop channel
|
|
42
|
-
*/
|
|
43
|
-
async function unsubscribe() {
|
|
44
|
-
if (!abortController) return;
|
|
45
|
-
await subscriber.unsubscribe(stopChannel);
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Set up stop subscription if abortController provided
|
|
49
|
-
*/
|
|
50
|
-
if (abortController) {
|
|
51
|
-
await subscriber.subscribe(stopChannel, () => {
|
|
52
|
-
abortController.abort();
|
|
53
|
-
});
|
|
54
|
-
/**
|
|
55
|
-
* Cleanup when abort signal fires
|
|
56
|
-
*/
|
|
57
|
-
abortController.signal.addEventListener(`abort`, () => {
|
|
58
|
-
unsubscribe();
|
|
59
|
-
}, { once: true });
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Start a new stream by creating a new resumable stream in Redis and returning a client stream for the UI.
|
|
63
|
-
*
|
|
64
|
-
* Uses a single drain loop that:
|
|
65
|
-
* 1. Reads from source stream
|
|
66
|
-
* 2. Sends UIMessageChunk directly to client stream (no conversion)
|
|
67
|
-
* 3. Sends SSE to Redis stream → resumable-stream → Redis
|
|
68
|
-
* 4. If `keepAlive` is provided, awaits it before closing the Redis stream
|
|
69
|
-
* 5. Closes the Redis stream, triggering resumable-stream teardown
|
|
70
|
-
* 6. Calls `onFlush` after teardown
|
|
71
|
-
* 7. Propagates errors to both streams
|
|
72
|
-
*/
|
|
73
|
-
async function startStream(stream, options) {
|
|
74
|
-
const { keepAlive = Promise.resolve(), onFlush } = options ?? {};
|
|
75
|
-
/**
|
|
76
|
-
* Track client disconnect to avoid unbounded memory growth
|
|
77
|
-
*/
|
|
78
|
-
let clientCancelled = false;
|
|
79
|
-
/**
|
|
80
|
-
* Client stream for sending UI message chunks directly to the client without conversion.
|
|
81
|
-
*/
|
|
82
|
-
let clientController;
|
|
83
|
-
const clientStream = new ReadableStream({
|
|
84
|
-
start(controller) {
|
|
85
|
-
clientController = controller;
|
|
86
|
-
},
|
|
87
|
-
cancel() {
|
|
88
|
-
clientCancelled = true;
|
|
89
|
-
}
|
|
90
|
-
});
|
|
91
|
-
/**
|
|
92
|
-
* Redis stream with SSE conversion for resumable-stream persistence in Redis.
|
|
93
|
-
* JsonToSseTransformStream converts UIMessageChunk → SSE string and adds [DONE] on flush.
|
|
94
|
-
*/
|
|
95
|
-
let redisController;
|
|
96
|
-
const redisStream = new ReadableStream({ start(controller) {
|
|
97
|
-
redisController = controller;
|
|
98
|
-
} }).pipeThrough(new JsonToSseTransformStream());
|
|
99
|
-
/**
|
|
100
|
-
* Get reader synchronously to fail fast if stream is locked
|
|
101
|
-
*/
|
|
102
|
-
const reader = stream.getReader();
|
|
103
|
-
/**
|
|
104
|
-
* Register Redis stream with resumable-stream for persistence.
|
|
105
|
-
* Release reader lock if registration fails to avoid locking the source stream.
|
|
106
|
-
*/
|
|
107
|
-
try {
|
|
108
|
-
await context.createNewResumableStream(streamId, () => redisStream);
|
|
109
|
-
} catch (error) {
|
|
110
|
-
reader.releaseLock();
|
|
111
|
-
throw error;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Single drain loop.
|
|
115
|
-
* Continues draining to Redis even if client disconnects
|
|
116
|
-
*/
|
|
117
|
-
(async () => {
|
|
118
|
-
/**
|
|
119
|
-
* Tracks whether the source stream completed successfully (reader.read() returned done: true).
|
|
120
|
-
* Used to guard the keepAlive await in finally — on error, the caller may never resolve
|
|
121
|
-
* the keepAlive promise, so awaiting it would hang the drain loop forever.
|
|
122
|
-
*/
|
|
123
|
-
let sourceDone = false;
|
|
124
|
-
try {
|
|
125
|
-
while (true) {
|
|
126
|
-
const { done, value } = await reader.read();
|
|
127
|
-
if (done) {
|
|
128
|
-
if (!clientCancelled) clientController.close();
|
|
129
|
-
sourceDone = true;
|
|
130
|
-
break;
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Always enqueue to Redis for persistence
|
|
134
|
-
*/
|
|
135
|
-
redisController.enqueue(value);
|
|
136
|
-
/**
|
|
137
|
-
* Only enqueue to client if still connected to avoid unbounded memory growth.
|
|
138
|
-
*
|
|
139
|
-
*/
|
|
140
|
-
if (!clientCancelled) clientController.enqueue(value);
|
|
141
|
-
}
|
|
142
|
-
} catch (error) {
|
|
143
|
-
redisController.error(error);
|
|
144
|
-
if (!clientCancelled) clientController.error(error);
|
|
145
|
-
} finally {
|
|
146
|
-
reader.releaseLock();
|
|
147
|
-
try {
|
|
148
|
-
await unsubscribe();
|
|
149
|
-
} catch {}
|
|
150
|
-
/**
|
|
151
|
-
* Await keepAlive promise before closing the Redis stream.
|
|
152
|
-
* This keeps the resumable-stream producer alive so late resume requests
|
|
153
|
-
* can be served from the in-memory chunk buffer.
|
|
154
|
-
* Defaults to a resolved promise (no-op) when not provided.
|
|
155
|
-
* Only await on successful source completion — on error the caller
|
|
156
|
-
* may never resolve the promise, which would hang the drain loop.
|
|
157
|
-
*/
|
|
158
|
-
if (sourceDone) try {
|
|
159
|
-
await keepAlive;
|
|
160
|
-
} catch {}
|
|
161
|
-
try {
|
|
162
|
-
redisController.close();
|
|
163
|
-
} catch {}
|
|
164
|
-
try {
|
|
165
|
-
await onFlush?.();
|
|
166
|
-
} catch {}
|
|
167
|
-
}
|
|
168
|
-
})();
|
|
169
|
-
return createAsyncIterableStream(clientStream);
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Resume an existing stream by fetching the resumable stream from Redis using the stream ID.
|
|
173
|
-
*/
|
|
174
|
-
async function resumeStream() {
|
|
175
|
-
/**
|
|
176
|
-
* Resume the existing stream from Redis using the stream ID.
|
|
177
|
-
*/
|
|
178
|
-
const resumableStream = await context.resumeExistingStream(streamId);
|
|
179
|
-
if (!resumableStream) return null;
|
|
180
|
-
return createAsyncIterableStream(convertSSEToUIMessageStream(resumableStream));
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Publish a stop message to the stop channel, which will trigger the abortController to abort the stream.
|
|
184
|
-
*/
|
|
185
|
-
async function stopStream() {
|
|
186
|
-
await publisher.publish(stopChannel, `stop`);
|
|
187
|
-
}
|
|
188
|
-
return {
|
|
189
|
-
startStream,
|
|
190
|
-
resumeStream,
|
|
191
|
-
stopStream
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
//#endregion
|
|
195
|
-
export { createResumableUIMessageStream };
|
|
1
|
+
import { t as createResumableStream } from "./core-DAlVpiTc.mjs";
|
|
2
|
+
export { createResumableStream };
|