npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

asyncsse

v1.3.1

Published

Fetch Server-Sent Events (SSE) as an async iterable

Downloads

618

Readme

asyncSSE

npm version License: MIT

Fetch Server-Sent Events (SSE) as an async iterable.

Features

  • 🚀 Lightweight (<1KB) and dependency-free
  • 🔄 Works with any SSE-compatible API
  • 🌐 Browser and Node.js compatible
  • 📦 Easy to use with ES modules

Installation

npm install asyncsse

Usage

Browser (via CDN)

<script type="module">
  import { asyncSSE } from "https://cdn.jsdelivr.net/npm/asyncsse@1";

  // Example usage
  (async () => {
    for await (const event of asyncSSE("https://api.example.com/sse")) {
      console.log(event);
    }
  })();
</script>

Node.js or bundled projects

import { asyncSSE } from "asyncsse";

// Example usage
(async () => {
  for await (const event of asyncSSE("https://api.example.com/sse")) {
    console.log(event);
  }
})();

API

asyncSSE(url: string, options?: RequestInit, config?: SSEConfig): AsyncIterable<SSEEvent>

Fetches Server-Sent Events from the specified URL and returns an async iterable.

  • url: The URL to fetch SSE from
  • options: Optional fetch options
  • config: Optional configuration object
    • fetch: Custom fetch implementation (defaults to global fetch)
    • onResponse: Async callback to inspect or modify the Response before streaming begins

Returns an async iterable that yields SSEEvent objects.

Example: OpenAI Chat Completions

import { asyncSSE } from "asyncsse";

const apiKey = "YOUR_OPENAI_API_KEY";
const url = "https://api.openai.com/v1/chat/completions";

const options = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${apiKey}`,
  },
  body: JSON.stringify({
    model: "gpt-4",
    stream: true,
    messages: [{ role: "user", content: "Hello, world!" }],
  }),
};

const config = {
  onResponse: async (response) => {
    console.log("Requests remaining:", response.headers.get("X-Ratelimit-Remaining-Requests"));
  },
};

// Fetch the stream, event by event
for await (const event of asyncSSE(url, options, config)) {
  console.log(JSON.parse(event.data));
}

Testing with Text Input

You can directly stream SSE events from a text string using the provided fetchText helper:

import { asyncSSE } from "https://cdn.jsdelivr.net/npm/asyncsse@1";
import { fetchText } from "https://cdn.jsdelivr.net/npm/asyncsse@1/dist/fetchtext.js";

const text = "data: Hello\n\ndata: World\n\n";

// Stream events from text
for await (const event of asyncSSE(text, {}, { fetch: fetchText })) {
  console.log(event);
}

This outputs:

{ data: "Hello" }
{ data: "World" }

This is particularly useful for testing SSE parsing without making actual HTTP requests.

Changelog

  • 1.3.1: Add fetchText helper for mocking SSE responses. Add source maps and TypeScript
  • 1.2.1: Add config.fetch parameter for custom fetch implementations
  • 1.1.0: Add config.onResponse callback
  • 1.0.0: Initial release

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.