jugaad-stream
v1.0.0
Published
Minimal, extensible async fan-out / fan-in primitives
Maintainers
Readme
🛠️ jugaad
"Elegant hacks for chaotic AI streams."
jugaad is a lightweight, zero-dependency toolkit for fan-out / fan-in streaming with LLMs and generative AI pipelines.
It helps you split, route, and merge async data streams — turning a single LLM output into multiple concurrent AI processes (like TTS, image gen, summarization, etc.) — all in memory, without overkill infra.
Think of it as:
🧠 Async queue + stream multiplexer + orchestrator — in ~100 lines of clean TypeScript.
✨ Why jugaad?
"Jugaad" — a Hindi/Urdu word meaning a clever hack or simple workaround using limited resources.
This library embraces that philosophy:
✅ No heavy frameworks.
✅ No message brokers.
✅ No Kafka, no Redis, no nonsense.
Just streams, queues, and composability.
Built for modern GenAI workflows where LLMs never stop streaming — and you need to pipe that data to multiple concurrent systems now.
📦 Quick Start
npm i jugaad-stream
# or
pnpm add jugaad-stream
# or
yarn add jugaad-stream🤖 LLM ➜ split ➜ concurrent GenAI ➜ stitch (end-to-end)
import { FanOut, fanIn, orderedSelector } from "jugaad-stream";
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// 1) Async token stream from an LLM
async function* llmStream(prompt: string) {
const stream = await openai.chat.completions.create({
model: "gpt-5",
messages: [{ role: "user", content: prompt }],
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices?.[0]?.delta?.content;
if (delta) yield { text: delta, t: Date.now() };
}
}
// 2) Make a hub and subscribe multiple consumers
const hub = new FanOut<{ text: string; t: number }>();
const ttsQ = hub.subscribe();
const imgQ = hub.subscribe();
const logQ = hub.subscribe();
// 3) Start feeding the LLM stream
hub.feed(llmStream("Describe a moody neon city by the sea."));
// 4) Concurrent consumers (TTS, image hints, logging)
(async () => {
for await (const { text } of ttsQ) {
console.log("🎙️ TTS:", text);
}
})();
(async () => {
let buf = "";
for await (const { text } of imgQ) {
buf += text;
if (buf.length > 120) {
console.log("🖼️ IMG PROMPT:", buf);
buf = "";
}
}
})();
(async () => {
for await (const { text } of logQ) {
console.log("📊 LOG:", text.replace(/\s+/g, " "));
}
})();
// 5) Stitch together (ordered by timestamp)
const merged = fanIn(
[ttsQ, imgQ, logQ],
orderedSelector((x) => x.t)
);
for await (const piece of merged) {
process.stdout.write(`🌊 ${piece.text}`);
}🧩 Extensibility Recipes
A. Bring your own queue (throttled/bounded)
import { AsyncQueue, FanOut } from "jugaad-stream";
class ThrottleQueue<T> extends AsyncQueue<T> {
constructor(private delayMs = 50) {
super();
}
push(item: T) {
setTimeout(() => super.push(item), this.delayMs);
}
}
const hub = new FanOut<string>(() => new ThrottleQueue(25));
const sub = hub.subscribe();
hub.feed(
(async function* () {
yield* ["a", "b", "c"];
})()
);
for await (const x of sub) console.log(x);B. Transform streams inline (map/filter style)
async function* mapAsync<T, U>(
src: AsyncIterable<T>,
f: (x: T) => U | Promise<U>
) {
for await (const x of src) yield await f(x);
}
const upper = mapAsync(sub, (s) => s.toUpperCase());
for await (const x of upper) console.log(x);C. Deterministic fan-in (sequence numbers)
import { fanIn, orderedSelector } from "jugaad-stream";
type Chunk = { seq: number, data: string };
const merged =
fanIn < Chunk > ([stream1, stream2, stream3], orderedSelector((c) => c.seq));
for await (const c of merged) process.stdout.write(c.data);D. Routing fan-out (by predicate)
import { FanOut } from "jugaad-stream";
const hub = new FanOut<{ kind: "text"|"audio"|"image"; payload: any }>();
const textQ = hub.subscribe();
const audioQ = hub.subscribe();
const imageQ = hub.subscribe();
hub.feed((async function*(){
yield { kind: "text", payload: "hello" };
yield { kind: "image", payload: { prompt: "sunset" } };
yield { kind: "audio", payload: { transcript: "..." } };
})());
(async () => { for await (const m of textQ) if (m.kind === "text") console.log(m.payload); })();
(async () => { for await (const m of imageQ) if (m.kind === "image") console.log(m.payload); })();
(async () => { for await (const m of audioQ) if (m.kind === "audio") console.log(m.payload); })();🧰 Minimal API Reference
AsyncQueue<T>
push(item: T): enqueueclose(): close queue; iteration endsfor await...of: consume items
FanOut<T>(createQueue?)
subscribe(): create a new subscriber queueunsubscribe(queue): remove and close a subscriberfeed(source): broadcast source to all subscribers
fanIn<T>(sources, selector?)
- Merge multiple streams
- Customizable selector for merge order
orderedSelector(keyFn)
- Returns a selector that merges by smallest key (e.g. timestamp, seq)
🧪 Testing Tip
async function* gen(label: string, count: number, delay: number) {
for (let i = 0; i < count; i++) {
await new Promise((r) => setTimeout(r, delay));
yield { label, i, t: Date.now() };
}
}Combine with FanOut and fanIn(..., orderedSelector(x => x.t)) to verify concurrency and ordering.
🛣️ Roadmap
- Bounded queues & backpressure helpers
- Built-in
mapAsync,filterAsync,bufferoperators - Typed routing (
fanOut(keyFn)) - Tracing hooks (OpenTelemetry-friendly)
- Tiny devtools visualizer
❤️ Contributing
PRs welcome! Keep it simple, clever, and resourceful — just like the name.
📜 License
MIT License
Copyright (c) 2024
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
From one stream, many. From many, one. With a bit of jugaad.
