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

@c10k/jsonrpc2-ws

v1.0.9

Published

A simple implementation of JSON-RPC 2.0 over WebSocket for Node.js

Downloads

7

Readme

jsonrpc2-ws

A simple implementation of JSON-RPC 2.0 over WebSocket for Node.js

Install

npm i @c10k/jsonrpc2-ws

Usage

Server

JsonRpcWsServer constructor params same as WebSocketServer.

const port = 8080;
const server = new JsonRpcWsServer({port});

const sleep = async (ms) => new Promise(resolve => setTimeout(resolve, ms));
const echo = (params) => params;
const error = (params) => {
    throw new Error(`${params[0]}`)
};
const time = () => Date.now();

server.setMethod('echo', echo);
server.setMethod('sleep', sleep);
server.setMethod('error', error);
server.setMethod('time', time);

Client

JsonRpcWsClient constructor params same as WebSocket.

const url = `ws://localhost:8080`;
const client = await JsonRpcWsClient.connect(url);

const timeFromServer = await client.request('time');
console.info(`${timeFromServer}`);

Use case

Stream

const port = 8080;
const server = new JsonRpcWsServer({port}, () => {
    setInterval(async () => {
        for (const ws of server.wss.clients) {
            // you can check ws context here
            server.notification(ws, 'ping', [Date.now]);
        }
    }, 1000);
});
const url = `ws://localhost:8080`;
const client = await JsonRpcWsClient.connect(url);
client.setMethod('ping', (params) => {
    const [time] = params;
    console.info(`client receive server time=${time}`);
});

Batch

const port = 8080;
const server = new JsonRpcWsServer({port});

let count = 0;
server.setMethod('counter', () => ++count);
const url = `ws://localhost:8080`;
const client = await JsonRpcWsClient.connect(url);

const pipeline = client.createPipeline();
await pipeline.request('counter');
await pipeline.request('counter');
await pipeline.request('counter');
const responses = await pipeline.execute();
for (const response of responses) {
    const {id, result, error} = response;
    // do something
}

Define ID generator

const url = `ws://localhost:8080`;
const client = await JsonRpcWsClient.connect(url);

client.idGenerator = () => uuid();

Auth

const port = 8080;
const server = new JsonRpcWsServer({port});
server.handler.getMethod = async ({id, method, params}, socket) => {
    const auth = await socket.getContext('auth');
    if (!auth && method.startsWith('private')) {
        return () => {
            throw new JsonRpcError(JSON_RPC_ERROR, 'Need auth', undefined);
        }
    }
    return server.handler.methods.get(method);
};

const login = async (params, socket) => {
    const [username, password] = params;
    const auth = password === username;
    socket.setContext('auth', auth);
    if (auth) {
        await socket.setContext('username', username);
    } else {
        await socket.deleteContext('username');
    }
    return auth;
};

const whoami = async (params, socket) => {
    return await socket.getContext('username');
}

server.setMethod('public.login', login);
server.setMethod('private.whoami', whoami);
const url = `ws://localhost:8080`;
const client = await JsonRpcWsClient.connect(url);
await client.request('public.login', ['hello', 'hello']);
await client.request('private.whoami');

Authentication before connection, see https://github.com/websockets/ws/tree/8.6.0#client-authentication, example see authenticate-when-upgrade

Dependencies

  • https://github.com/websockets/ws
  • https://jestjs.io/zh-Hans/docs/getting-started
  • https://jestjs.io/zh-Hans/docs/expect#expectclosetonumber-numdigits
  • https://github.com/sindresorhus/get-port

Ref

  • https://github.com/jershell/simple-jsonrpc-js/blob/master/simple-jsonrpc-js.js#L230-L275

binary data

  1. Binary Data in JSON String. Something better than Base64
    1. https://en.wikipedia.org/wiki/Ascii85
    2. https://github.com/bwaldvogel/base91/blob/main/src/main/java/de/bwaldvogel/base91/Base91.java
    3. https://github.com/kevinAlbs/Base122
  2. https://en.wikipedia.org/wiki/Binary-to-text_encoding