The Open Standard for Generative UI
Add callback methods in transformStream function (#115)
Rabi Shanker Guha19ddc2721640
diff --git a/js/packages/stream/package.json b/js/packages/stream/package.jsonindex 6a00fb2b8..f4012a2c4 100644--- a/js/packages/stream/package.json+++ b/js/packages/stream/package.json@@ -1,6 +1,6 @@{"name": "@crayonai/stream",- "version": "0.6.3",+ "version": "0.6.4","description": "Generative UI SDK","main": "dist/index.js","types": "dist/index.d.ts",diff --git a/js/packages/stream/src/utils.ts b/js/packages/stream/src/utils.tsindex 5419b6286..f485e5b3c 100644--- a/js/packages/stream/src/utils.ts+++ b/js/packages/stream/src/utils.ts@@ -1,16 +1,35 @@-export const transformStream = <T, R>(stream: AsyncIterable<T>, transformer: (data: T) => R) => {+export const transformStream = <T, R>(+ stream: AsyncIterable<T>,+ transformer: (data: T) => R,+ options?: {+ onError?: (error: unknown) => void;+ onEnd?: (args: { accumulated: R[] }) => void;+ onStart?: () => void;+ onRawChunk?: (chunk: T) => void;+ onTransformedChunk?: (chunk: R) => void;+ },+) => {+ const accumulate = options?.onEnd ? true : false;return new ReadableStream({async start(c) {+ const accumulated: R[] = [];try {+ options?.onStart?.();for await (const chunk of stream) {+ options?.onRawChunk?.(chunk);const content = transformer(chunk);if (content) {+ // Only accumulate if onEnd is provided to avoid unnecessary memory usage.+ accumulate && accumulated.push(content);+ options?.onTransformedChunk?.(content);c.enqueue(content);}}} catch (error: unknown) {+ options?.onError?.(error);c.error(error as Error);} finally {+ options?.onEnd?.({ accumulated });c.close();}},