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

monorepo-networker

v1.5.2

Published

This is a simple utility package

Downloads

1,879

Readme

What is monorepo-networker?

Consider a scenario where you are maintaining a codebase that follows a monorepo pattern and houses an IPC-like communication mechanism between ends/sides, much like FiveM's scripting SDK and Figma's plugin API. In such a situation, you may find yourself dealing with numerous boilerplate code just to ensure that you are sending the right data under the correct title. The primary aim of this library is to streamline this process by transforming every message type into an isolated artifact, thereby standardizing the process.

How to use it?

Before using it, keep in mind instances you create are supposed to be used commonly accross the sides. So we recommend storing those calls in a /common/network folder for convenience.

  1. Declare and register sides and their handling mechanism under /common/network/sides.ts
import * as Networker from "monorepo-networker";

export namespace NetworkSide {
  export const SERVER = Networker.Side.register(
    new Networker.Side("Server", {
      attachListener: (callback) => server.on("message", callback),
      detachListener: (callback) => server.off("message", callback),
    })
  );

  export const CLIENT = Networker.Side.register(
    new Networker.Side<MessageEvent<any>>("Client", {
      shouldHandle: (event) => event.data?.pluginId != null,
      messageGetter: (event) => event.data.pluginMessage,
      attachListener: (callback) =>
        window.addEventListener("message", callback),
      detachListener: (callback) =>
        window.removeEventListener("message", callback),
    })
  );
}
  • attachListener: declares how given callback is attached to that side's event listening mechanism
  • detachListener: declares how given callback is detached from that side's event listening mechanism
  • shouldHandle?: declares a predicate function, that determines whether incoming event is a network message we are interested in or not
  • messageGetter?: there may be cases where the incoming event is not the actual message, but rather a wrapper around it. To handle such cases, this function specifies how to extract the message from the wrapper.
  1. Create 2 test messages. We'll create a HelloMessage that emits a message to the other side, and other side prints out incoming data. And we'll create a PingServerMessae that will respond with "Pong!" to the requesting side. Create your messages under /common/network/messages/HelloMessage.ts:
import * as Networker from "monorepo-networker";

interface Payload {
  text: string;
}

export class HelloMessage extends Networker.MessageType<Payload> {
  constructor(private side: Networker.Side) {
    super("hello-" + side.getName());
  }

  receivingSide(): Networker.Side {
    return this.side;
  }

  handle(payload: Payload, from: Networker.Side) {
    console.log(`${from.getName()} said "${payload.text}"`);
  }
}

and /common/network/messages/PingServerMessage.ts:

import * as Networker from "monorepo-networker";
import { NetworkSide } from "@common/network/sides";

interface Payload {}

type Response = string;

export class PingServerMessage extends Networker.MessageType<
  Payload,
  Response
> {
  receivingSide(): Networker.Side {
    return NetworkSide.SERVER;
  }

  handle(payload: Payload, from: Networker.Side): string {
    console.log(from.getName(), "has pinged us!");
    return `Pong, ${from.getName()}!`;
  }
}

Some messages can present a response, where some do not. In that case, you should declare a Response type representing what does the handler respond with. This then later be used with Network.MessageType::request, we'll cover in next steps.

  1. Create a registry to stored message types under /common/network/messages.ts
import * as Networker from "monorepo-networker";
import { NetworkSide } from "@common/network/sides";
import { HelloMessage } from "@common/network/messages/HelloMessage";
import { PingServerMessage } from "@common/network/messages/PingServerMessage";

export namespace NetworkMessages {
  export const registry = new Networker.MessageTypeRegistry();

  export const HELLO_SERVER = registry.register(
    new HelloMessage(NetworkSide.SERVER)
  );

  export const HELLO_CLIENT = registry.register(
    new HelloMessage(NetworkSide.CLIENT)
  );

  export const PING = registry.register(new PingMessage("ping"));
}
  1. Finally create an initializer, which also declares how sides communicate with each other. We'll call this initializer on each side later on. Create it under /common/network/init.ts:
import * as Networker from "monorepo-networker";
import { NetworkMessages } from "@common/network/messages";
import { NetworkSide } from "@common/network/sides";

export const initializeNetwork = Networker.createInitializer({
  messagesRegistry: NetworkMessages.registry,

  initTransports: function (register) {
    // Declaring how a message is transported from server to client
    register(NetworkSide.SERVER, NetworkSide.CLIENT, (message) => {
      server.sendMessage(message); // <-- Totally arbitrary
    });

    // Declaring how a message is transported from client to server
    register(NetworkSide.CLIENT, NetworkSide.SERVER, (message) => {
      parent.postMessage({ pluginMessage: message }, "*"); // <-- Totally arbitrary
    });
  },
});
  1. Once done with setting up the common base, we can hop to entry points of each side. We'll need to initialize our network on each side.

server/main.ts

import { initializeNetwork } from "@common/network/init";
import { NetworkSide } from "@common/network/sides";
import { NetworkMessages } from "@common/network/messages";

async function bootstrap() {
  initializeNetwork(NetworkSide.SERVER);

  // ... Omitted code that bootstraps the server

  NetworkMessages.HELLO_CLIENT.send({ text: "Hey there, Client!" });
}

bootstrap();

client/main.ts

import { initializeNetwork } from "@common/network/init";
import { NetworkMessages } from "@common/network/messages";
import { NetworkSide } from "@common/network/sides";
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./app";

initializeNetwork(NetworkSide.UI);

const rootElement = document.getElementById("root") as HTMLElement;
const root = ReactDOM.createRoot(rootElement);

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

NetworkMessages.HELLO_SERVER.send({ text: "Hey there, Server!" });

// Notice this one returns a Promise<T>
NetworkMessages.PING.request({}).then((response) => {
  console.log('Server responded with "' + response + '" !');
});