8.15.162 • Published 11 months ago

@npmtuanmap/tenetur-quisquam-quia-aliquam v8.15.162

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

@npmtuanmap/tenetur-quisquam-quia-aliquam

A simple library to add typesafety to bi-directional communications in full-stack typescript applications. Ts-duplex enables great DX while making your application safer.

Features

Validators

Integrations

Getting started

Installation

npm install @npmtuanmap/tenetur-quisquam-quia-aliquam@latest

To use WebSocketClient install peer dependency reconnecting-websocket:

npm install reconnecting-websocket

Quick example

Define schemas first. DuplexTypes must be a TypePack with Server2Client and Client2Server. These types can be defined directly without using zod, but then typesafety only happens in the IDE. Use InferZodValidatorType to convert schema definitions into types. schema.ts:

import type { TypePack } from '@npmtuanmap/tenetur-quisquam-quia-aliquam';
import type { InferZodValidatorType } from '@npmtuanmap/tenetur-quisquam-quia-aliquam/validators/zod';
import z from 'zod';

// define with zod. shape: Record<string, ZodSchema>
export const Client2Server = {
  sendMessage: z.object({
    as: z.string(),
    content: z.string(),
  }),
  gracefulDisconnect: z.null(),
};

// define as type, as server responses do not need to be validated
type Server2ClientType = {
  newMessage: {
    from: string;
    content: string;
    time: number;
  };
  hello: null;
};

export type DuplexTypes = TypePack<
  InferZodValidatorType<typeof Client2Server>, // client to server communication goes first
  Server2ClientType // then server to client
>;

Create a simple server. server.ts:

import http from 'http';
import { WebSocketServer } from 'ws';
import { WsDuplex } from '@npmtuanmap/tenetur-quisquam-quia-aliquam/integrations/ws';
import { zodValidator } from '@npmtuanmap/tenetur-quisquam-quia-aliquam/validators/zod';
import { type DuplexTypes, Client2Server } from './schema';

const port = 3030;
const server = http.createServer();
server.listen(port, () => {
  console.log('server listening at', `http://localhost:${port}/`);
});

const wss = new WebSocketServer({ server });

wss.on('connection', function (raw) {
  // upgrade default ws into typesafe one and define validators
  const ws = new WsDuplex<DuplexTypes>(raw, {
    Client2Server: zodValidator(Client2Server),
    // Server2Client: zodValidator(Server2Client), // can also provide validator for Server -> Client communcation
  });

  ws.send('hello');

  ws.on('sendMessage', (data) => {
    console.log('got message', data);

    // send to the original sender
    ws.send('newMessage', {
      from: 'me',
      content: data.content,
      time: Date.now(),
    });

    // send to others
    const payload = ws.getSendPayload('newMessage', {
      from: data.as,
      content: data.content,
      time: Date.now(),
    });

    // deploy payload to everyone
    if (payload)
      wss.clients.forEach((c) => {
        c.send(payload);
      });
  });

  // just for sake of example
  ws.on('gracefulDisconnect', () => {
    setTimeout(() => {
      raw.close(1000, 'graceful shutdown');
    }, 2000);
  });
});

And now create a client. client.ts:

import { WebSocketClient } from '@npmtuanmap/tenetur-quisquam-quia-aliquam/WebSocketClient';
import type { DuplexTypes } from './schema';

const form = document.querySelector('form')! as HTMLFormElement;
const messages = document.querySelector('#messages')! as HTMLUListElement;
const messageInput = document.querySelector('#message')! as HTMLInputElement;
const usernameInput = document.querySelector('#username')! as HTMLInputElement;
const stopBtn = document.querySelector('#stop')! as HTMLButtonElement;

usernameInput.value = crypto.randomUUID().substring(0, 8);

const client = new WebSocketClient<DuplexTypes>('ws://localhost:3030');

stopBtn.addEventListener('click', () => {
  client.send('gracefulDisconnect');
});

client.on('newMessage', ({ from, content, time }) => {
  if (from === usernameInput.value) return;
  console.log('got message', content);

  const message = `[${new Date(
    time
  ).toLocaleTimeString()}] ${from}: ${content}`;
  const li = document.createElement('li');
  li.innerText = message;

  messages.appendChild(li);
});

client.on('hello', () => {
  const li = document.createElement('b');
  li.innerText = 'Server said hi';

  messages.appendChild(li);
});

form.addEventListener('submit', (ev) => {
  ev.preventDefault();
  const content = messageInput.value;
  const from = usernameInput.value;

  if (!content) return;

  client.send('sendMessage', {
    as: from,
    content,
  });

  messageInput.value = '';
});

And finally html index.html:

<form>
  <label for="username">Username</label>
  <input id="username" name="username" placeholder="Username" value="user" />
  <label for="message">Message</label>
  <input id="message" name="message" placeholder="Message" value="" />
  <button id="send" type="submit">Send</button>
</form>

<button id="stop">Stop</button>
<ul id="messages"></ul>
<script type="module" src="/src/client.ts"></script>

That is all!

Examples

API

TODO. Most things are typed. Try it out and explore!

Caviats

  • When method requires no data, type it as null (because json encoding forces undefined to become null)
  • Refactoring of method names with lsp is not possible in the current version. Proxy client could enable that.
  • The API is more or less final, but I may want to refactor names of functions/type and move exports around before version 1.0
  • This lib really needs a better name
  • Could have import issues if your project does not have "moduleResolution": "Bundler" in tsconfig. Open an issue if it happens!
readwhatwglastgetoptWebSocketsspinnerssortvalidationelasticachewgetcompilereventsSymbolargvObject.keyserror-handlingwordwrapArray.prototype.flattenjQueryes-shimsautoprefixerpnpm9functionsparentshebangstreamFloat32ArrayflatMapwalkinglogArray.prototype.flatinenvironmenttoStringTaguninstallcurleventDispatcherslotcode pointsresttostringtagencryptionpropertiesapollostylesheetemojicors[[Prototype]]computed-typesmake dirmapreducesymlinkaccessortoolkitkeytrimdropbundlingArrayappyamldescriptioniteratornopeviewtypeerrorenvtermhandlersrm -rfrouterframeworkslicebundlerarraysafermdirStreamgetperformantshimoptimistECMAScript 2017es7fast-copygetintrinsiccloudwatchsignalsreacthasOwnPropertywidthdataviewparentsqueueMicrotaskdotenvidlechecksyntaxerrorlengthschemareplaycollectioncall-boundttyequalRxJSextrasetPrototypeOfinvariantworkspace:*toolsRegExp.prototype.flagsstylingformsinterruptsbrowserslistdataViewlintjsonpathArrayBuffer#slicehas-ownmergeStreamsruntimeTypeBoxpushtrimEndjwtjsdomassertionECMAScript 7formatsharedarraybuffer256fromomitbcryptcloudformationfseventsmodulesbatcheslintplugintypergbgraphqlpromisegetterArrayBuffer.prototype.slicefpsIteratorsescss-in-jsprocessmakevariables in cssratelimitcss lesshardlinksinternalsymlinksoncefigletdefineloadingcloudsearches6ESexit-codeeslint-plugintesterarraysESnextinstallerratecssbreaknamereduxmimetypeswatchinglesscsswatch@@toStringTagexpressionassignidhttprangeerrorsyntaxsymbolsInt8ArrayentriesquoteObject.issideexitregexprecursivegroupArray.prototype.findLastdirworkerrandompicomatchescapepathbindhookformES2020awsdatapersistentisConcatSpreadablefastcopyloggingObject.definePropertyjsdifflinewrapstyled-componentsflattencopyRFC-6455rm -fryupexecpreserve-symlinksecmascriptnativeminimalcolumntraverse-0uuidweakmapbyteOffsetes2018gdpres-shim APIwatchercallboundperformanceartserializeES6assertsgroupByoperating-systemclicreatenodejsspeedextendfullwidthrapidbyteLengthgetPrototypeOffull-widthstartercircularsearchhelperssetterECMAScript 2019ec2upclassnamesqueryintrinsictypedarraysloggerArray.prototype.containsjsxpredictabletaskbootstrap cssconcurrencyenvironmentssuperagentstyleguidevisualvpcwrapcallbacknumberbannerrdsdependency managerwarningautoscalingerrorECMAScript 2022linkimportbusyArray.prototype.findLastIndexforEachconcatMapjasminesuperstructconnectinputpasswordinternal slotiterateES2021fastifytypescriptavadayjsprettyCSSStyleDeclarationgradients csstrimRightremovepackage managermochaES3parsingwatchFileresolvegenericsfselmrobustcommandexpress
@tea07001/accusantium-vel-unde@tea07001/alias-alias-veritatis@tea07001/aperiam-tempora-quaerat@tea07001/libero-labore-ipsam@tea07001/maiores-numquam-repellat@tea07001/mollitia-natus-molestias@tea07001/non-expedita-expedita@tea07001/officiis-possimus-repellat@tea07001/quis-ratione-quam@tea07001/saepe-provident-quae@tea07001/sapiente-doloribus-et@tea07001/consequuntur-esse-voluptas@tea07001/corporis-eius-nisi@tea07001/corporis-id-culpa@tea07001/corporis-totam-natus@tea07001/debitis-incidunt-facere@tea07001/dolorem-eos-necessitatibus@tea07001/ea-ad-praesentium@tea07001/error-repellat-occaecati@tea07001/est-nam-officia@tea07001/exercitationem-maiores-eum@tea07001/fugiat-voluptates-illum@tea07001/harum-eaque-quisquam@tea07001/hic-perspiciatis-dolores@tea07001/tempore-dolor-quod@devtea2027/legendary-octo-journey@npmtuanmap/vel-dolorem-eum-id@npmtuanmap/quo-velit-laboriosam-excepturi@npmtuanmap/earum-vel-culpa-saepe@tea062024/sunt-earum-nesciunt@tea062024/totam-vitae-maxime@tea062024/veniam-facere-voluptatum@tea062024/vero-ipsum-similique@tea062024/voluptates-nihil-nisi@tea062024/voluptatibus-ut-asperiores@tea062024/facilis-fugit-quam@tea062024/inventore-sequi-officiis@tea062024/maxime-aliquid-sunt@tea062024/numquam-quo-quibusdam@tea062024/officia-ratione-nostrum@tea062024/ratione-saepe-temporibus@tea062024/repellat-omnis-accusamus@tea062024/soluta-accusantium-a@tea062024/architecto-eos-dignissimos@tea062024/asperiores-quae-ut@tea062024/assumenda-possimus-adipisci@tea062024/beatae-assumenda-dolorum@tea062024/deserunt-repellat-accusamus@tea062024/doloremque-exercitationem-asperiores@tea062024/dolores-magni-laboriosam@tea062024/eveniet-modi-ab@tea062024/facere-dignissimos-aliquam@tea062024/a-soluta-accusantium@tea062024/amet-eum-occaecati
8.15.162

11 months ago

8.15.161

11 months ago

8.15.159

11 months ago

8.15.158

11 months ago

8.15.160

11 months ago

8.15.155

11 months ago

8.15.154

11 months ago

8.15.157

11 months ago

8.15.156

11 months ago

8.15.153

11 months ago

7.15.153

11 months ago

7.15.152

11 months ago

7.15.151

11 months ago

7.15.148

11 months ago

7.15.149

11 months ago

7.15.146

11 months ago

7.15.147

11 months ago

7.15.150

11 months ago

7.15.145

11 months ago

7.15.144

12 months ago

7.15.137

12 months ago

7.15.138

12 months ago

7.15.135

12 months ago

7.15.136

12 months ago

7.15.139

12 months ago

7.15.140

12 months ago

7.15.141

12 months ago

7.15.142

12 months ago

7.15.143

12 months ago

7.15.126

12 months ago

7.15.127

12 months ago

7.15.125

12 months ago

7.15.128

12 months ago

7.15.129

12 months ago

7.15.130

12 months ago

7.15.133

12 months ago

7.15.134

12 months ago

7.15.131

12 months ago

7.15.132

12 months ago

7.15.124

1 year ago

7.15.123

1 year ago

7.15.122

1 year ago

6.15.122

1 year ago

6.15.115

1 year ago

6.15.114

1 year ago

6.15.119

1 year ago

6.15.118

1 year ago

6.15.117

1 year ago

6.15.116

1 year ago

6.15.121

1 year ago

6.15.120

1 year ago

6.15.113

1 year ago

6.15.112

1 year ago

6.15.111

1 year ago

6.15.108

1 year ago

6.15.109

1 year ago

6.15.110

1 year ago

6.15.107

1 year ago

6.13.107

1 year ago

6.14.107

1 year ago

6.13.106

1 year ago

6.13.105

1 year ago

6.13.104

1 year ago

6.13.103

1 year ago

6.13.102

1 year ago

6.13.101

1 year ago

6.13.100

1 year ago

6.13.99

1 year ago

6.12.99

1 year ago

5.3.22

1 year ago

5.3.21

1 year ago

6.4.32

1 year ago

6.4.31

1 year ago

6.4.34

1 year ago

6.4.33

1 year ago

6.4.35

1 year ago

6.8.70

1 year ago

6.4.30

1 year ago

6.8.78

1 year ago

6.8.77

1 year ago

6.8.76

1 year ago

6.8.75

1 year ago

6.8.74

1 year ago

6.8.73

1 year ago

6.8.72

1 year ago

6.8.71

1 year ago

6.5.35

1 year ago

6.5.37

1 year ago

6.5.36

1 year ago

6.5.39

1 year ago

6.5.38

1 year ago

6.7.50

1 year ago

6.7.51

1 year ago

6.7.52

1 year ago

6.7.53

1 year ago

6.7.54

1 year ago

6.7.55

1 year ago

6.9.79

1 year ago

6.9.78

1 year ago

6.12.92

1 year ago

6.12.93

1 year ago

6.12.90

1 year ago

6.12.91

1 year ago

6.7.49

1 year ago

6.12.98

1 year ago

6.12.96

1 year ago

6.12.97

1 year ago

6.12.94

1 year ago

6.12.95

1 year ago

6.9.90

1 year ago

4.3.19

1 year ago

6.3.29

1 year ago

6.3.27

1 year ago

6.3.28

1 year ago

6.5.44

1 year ago

6.10.90

1 year ago

6.5.43

1 year ago

6.3.22

1 year ago

6.3.25

1 year ago

6.3.26

1 year ago

6.3.23

1 year ago

6.3.24

1 year ago

6.9.82

1 year ago

6.9.81

1 year ago

6.9.80

1 year ago

6.5.40

1 year ago

6.5.42

1 year ago

6.5.41

1 year ago

6.9.89

1 year ago

6.9.88

1 year ago

6.9.87

1 year ago

6.9.86

1 year ago

6.9.85

1 year ago

6.9.84

1 year ago

6.9.83

1 year ago

6.4.29

1 year ago

6.8.69

1 year ago

6.8.68

1 year ago

6.6.44

1 year ago

6.6.45

1 year ago

6.11.90

1 year ago

6.6.46

1 year ago

6.6.47

1 year ago

6.6.48

1 year ago

6.6.49

1 year ago

6.8.67

1 year ago

6.8.66

1 year ago

6.8.65

1 year ago

6.8.64

1 year ago

6.8.63

1 year ago

6.8.62

1 year ago

6.8.61

1 year ago

6.8.60

1 year ago

6.8.59

1 year ago

6.8.58

1 year ago

6.8.57

1 year ago

4.3.20

1 year ago

4.3.21

1 year ago

6.8.56

1 year ago

6.8.55

1 year ago

4.3.18

1 year ago

4.2.17

1 year ago

4.2.18

1 year ago

4.2.15

1 year ago

4.2.16

1 year ago

4.2.14

1 year ago

4.2.13

1 year ago

4.2.12

1 year ago

3.2.12

1 year ago

3.2.11

1 year ago

2.2.11

1 year ago

1.2.11

1 year ago

1.2.10

1 year ago

1.2.9

1 year ago

1.2.8

1 year ago

1.2.7

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.1.4

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.0

2 years ago