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

@fakehost/exchange

v1.0.0-beta.2

Published

A basic package for building fake messaging services that communicate over websockets. Can run as a nodejs service, or be bundled inside the browser.

Downloads

6,743

Readme

@fakehost/exchange

NPM Version

Overview

See the docs for more info.

A basic package for building fake messaging services that communicate over websockets. Can run as a nodejs service, or be bundled inside the browser.

This library won't give you much on its own. Instead its used to support running the same fake service code hosted within the browser or running as a node process.

Provides two main objects:

  • WsHost. For starting a websocket service. This runs as a node process which can be started from the command line, or started from nodejs tests e.g. jest, vitest, playwright, webdriver etc.
  • BrowserWsHost. For starting a "mocked" websocket service. This runs directly within the browser, and is useful for bundling "fake" services within Storybook, or a demo application, and for running browser based tests such as Cypress.

⚠️ Don't use this in production environments. This is for testing, and demo purposes only.

Example Usage

For a full example see @fakehost/fake-signalr.

Protocol Handler

Messaging services have many different types of protocols to manage the exchange of messages. Many of these are custom.

Lets say we are building a fake protocol handler for a service that has the following incoming message and outgoing message structure:

type IncomingMessage = {
    destination: string
    payload: unknown
}

type OutgoingMessage = {
    destination: string
    payload: unknown
}

Messages are all in JSON, so we can easily inspect what the service is doing by examining the network tab and looking at the messages.

An extremely basic protocol that only supports simple request/response messages could look like:

import { Host, ConnectionId, Connection, ExchangeEvent } from '@fakehost/exchange'

type MessageHandler = (payload: unknown) => unknown

export class MyProtocolHandler {

    private messageHandlers = new Map<string, MessageHandler>()

    constructor(host: Host) {
        host.on('connection', this.onConnection.bind(this))
        host.on('disconnection', this.onDisconnection.bind(this))
        host.on('message', this.onMessage.bind(this))
    }

    onConnection({ connection }: ExchangeEvent<'connection'>) {
        console.log(`a new connection "${connection.id}"`)
    }

    onDisconnection({ connection }: ExchangeEvent<'disconnect'>) {
        console.log(`connection "${connection.id}" has disconnected`)
    }

    onMessage({ connection, message: rawMessage }: ExchangeEvent<'message'>) {
        // deserialize the incoming message
        const message: IncomingMessage = this.deserialize(rawMessage)

        // get the handler for the service + method
        const handler = this.messageHandlers.get(message.destination)

        if(!handler) {
            console.log(`"${destination}" not handled`)
            return
        }

        // call the handler
        const result = handler(message.payload)

        // send the handler's response
        connection.write(JSON.stringify({
            destination: message.destination,
            payload: result
        }))
    }

    deserialize(message: string | Buffer) {
        const parsed = typeof message === 'string' ? message : new TextDecoder('utf-8').decode(message);
        return JSON.parse(parsed) as IncomingMessage;
    }

    register(destination: string, handler: MessageHandler) {
        this.messageHandlers.set(destination, handler)
    }
}

And lets wire up a handler, and start MyProtocolHandler running as a localhost service:

import { WsHost } from '@fakehost/exchange'

// start a websocket service listening on port 5000 at /json
const host = new WsHost({
    name: 'fake',
    debug: true,
    port: 5000,
    path: '/json'
})

// create a new protocol handler
const protocol = new MyProtocolHandler(host)

// create a simple handler and register it to handle incoming messages with destination of `greeting`
const greetingHandler = (payload: { name: string }) => {
    return `Hello, ${name}!`
}
protocol.register('greeting', greetingHandler)

Debug

Debug logging can be enabled through the constructors, or via the environment variable:

DEBUG=@fakehost/exchange

License

@fakehost/exchange is licensed under the MIT License.

Migrating from v0.x

See Migrating from v0.x