Skip to content
glamboyosaPublic

About

Lightweight, fully typed JavaScript/TypeScript library for robust streaming and Server-Sent Events (SSE) with retries and framework-friendly APIs.

Topics

Resources

Stars

19 stars

Watchers

1 watching

Forks

Latest commit

 

History

23 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Ore

Ore is a modern, lightweight JavaScript/TypeScript library for robust streaming and Server-Sent Events (SSE) consumption. It provides a simple, bulletproof API for handling streams with automatic retries and easy integration into modern frameworks like React, Next.js, and more.

Features

  • Bulletproof Streaming: Robust handling of connection drops with automatic retries.
  • Dual Mode:
    • stream(): For raw text/byte streaming (e.g. AI responses, logs).
    • streamSSE(): For spec-compliant Server-Sent Events parsing.
  • Modern API: Uses Async Generators for clean, modern usage (for await...of).
  • Universal: Works in Browser, Node.js, and Edge runtimes.
  • Zero Dependencies: Tiny footprint.

Install

npm install @glamboyosa/ore

Usage

Raw Streaming (Text/Bytes)

Perfect for AI chat streams, logs, or custom protocols.

import { stream } from "@glamboyosa/ore";

// Basic usage
for await (const chunk of stream("http://api.example.com/chat")) {
  console.log(chunk); // "Hello", " world", "!"
}

// With options (including POST + JSON body for AI endpoints)
const ac = new AbortController();
const dataStream = stream("http://api.example.com/chat", {
  method: "POST",
  headers: {
    "Authorization": "Bearer token",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ prompt: "Hello" }),
  retries: 3,
  signal: ac.signal,
  decode: true, // Set to false to get Uint8Array
});

for await (const chunk of dataStream) {
  // ...
}

Server-Sent Events (SSE)

Parses standard SSE format (data: ..., event: ..., id: ...).

import { streamSSE } from "@glamboyosa/ore";

for await (const event of streamSSE("http://api.example.com/events")) {
  console.log(event.id);
  console.log(event.event); // e.g., 'update'
  console.log(event.data);  // The message payload
}

Usage with React

import { useEffect, useState } from "react";
import { stream } from "@glamboyosa/ore";

function ChatComponent() {
  const [messages, setMessages] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    (async () => {
      try {
        for await (const chunk of stream("/api/chat", { signal: controller.signal })) {
          setMessages(prev => prev + chunk);
        }
      } catch (err) {
        if (err.name !== 'AbortError') console.error(err);
      }
    })();

    return () => controller.abort();
  }, []);

  return <div>{messages}</div>;
}

Usage with Next.js Server Components

Ore works great with React Server Components (RSC) and Suspense for streaming HTML.

import { stream } from "@glamboyosa/ore";
import { Suspense } from "react";

// Recursive component to stream data
async function StreamViewer({ iterator }) {
  const { value, done } = await iterator.next();
  if (done) return null;
  
  return (
    <span>
      {value}
      <Suspense>
        <StreamViewer iterator={iterator} />
      </Suspense>
    </span>
  );
}

export default function Page() {
  const dataStream = stream("http://api.example.com/stream");
  const iterator = dataStream[Symbol.asyncIterator]();

  return (
    <Suspense fallback="Loading...">
      <StreamViewer iterator={iterator} />
    </Suspense>
  );
}

API Reference

stream(url: string, options?: StreamOptions)

Returns an AsyncGenerator<string> by default (decode: true), or AsyncGenerator<Uint8Array> when decode: false.

Options:

  • method: string (default: "GET") - HTTP request method (e.g. "POST").
  • body: BodyInit | null - Request body payload. Non-replayable ReadableStream bodies are not retried after failure.
  • headers: HeadersInit - Custom headers (Headers, [string, string][], or plain object).
  • credentials: RequestCredentials - Fetch credentials mode (e.g. "include", "same-origin").
  • retries: number (default: 3) - Max retry attempts on transient errors (5xx, 408, 429, network failures). Non-retryable 4xx responses fail immediately.
  • signal: AbortSignal - Cancels the request and any active retry backoff.
  • decode: boolean (default: true) - If true, yields decoded UTF-8 strings. If false, yields Uint8Array.
  • fetch: typeof globalThis.fetch - Custom fetch implementation.

streamSSE(url: string, options?: OreOptions)

Returns an AsyncGenerator<SSEEvent>. Sends Accept: text/event-stream by default, tracks Last-Event-ID across reconnections, and terminates cleanly on HTTP 204 No Content.

Note: Like EventSource, streamSSE() automatically reconnects when the server closes the stream cleanly, up to retries times. For finite SSE endpoints (such as POST LLM completion streams) that close with HTTP 200 instead of 204, pass retries: 0 to prevent replaying the request.

Options:

  • method: string (default: "GET")
  • body: BodyInit | null
  • headers: HeadersInit
  • credentials: RequestCredentials
  • retries: number (default: 3)
  • signal: AbortSignal
  • fetch: typeof globalThis.fetch

SSEEvent Interface:

interface SSEEvent {
  id: string | null;
  event: string | null;
  data: string;
  retry?: number;
}

License

MIT

About

Lightweight, fully typed JavaScript/TypeScript library for robust streaming and Server-Sent Events (SSE) with retries and framework-friendly APIs.

Topics

Resources

Stars

19 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages