8.15.162 • Published 9 months ago

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

Weekly downloads
-
License
MIT
Repository
github
Last release
9 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

9 months ago

8.15.161

9 months ago

8.15.159

9 months ago

8.15.158

9 months ago

8.15.160

9 months ago

8.15.155

9 months ago

8.15.154

9 months ago

8.15.157

9 months ago

8.15.156

9 months ago

8.15.153

9 months ago

7.15.153

9 months ago

7.15.152

9 months ago

7.15.151

9 months ago

7.15.148

9 months ago

7.15.149

9 months ago

7.15.146

9 months ago

7.15.147

9 months ago

7.15.150

9 months ago

7.15.145

9 months ago

7.15.144

9 months ago

7.15.137

9 months ago

7.15.138

9 months ago

7.15.135

10 months ago

7.15.136

10 months ago

7.15.139

9 months ago

7.15.140

9 months ago

7.15.141

9 months ago

7.15.142

9 months ago

7.15.143

9 months ago

7.15.126

10 months ago

7.15.127

10 months ago

7.15.125

10 months ago

7.15.128

10 months ago

7.15.129

10 months ago

7.15.130

10 months ago

7.15.133

10 months ago

7.15.134

10 months ago

7.15.131

10 months ago

7.15.132

10 months ago

7.15.124

10 months ago

7.15.123

10 months ago

7.15.122

10 months ago

6.15.122

10 months ago

6.15.115

10 months ago

6.15.114

10 months ago

6.15.119

10 months ago

6.15.118

10 months ago

6.15.117

10 months ago

6.15.116

10 months ago

6.15.121

10 months ago

6.15.120

10 months ago

6.15.113

10 months ago

6.15.112

10 months ago

6.15.111

10 months ago

6.15.108

10 months ago

6.15.109

10 months ago

6.15.110

10 months ago

6.15.107

11 months ago

6.13.107

11 months ago

6.14.107

11 months ago

6.13.106

11 months ago

6.13.105

11 months ago

6.13.104

11 months ago

6.13.103

11 months ago

6.13.102

11 months ago

6.13.101

11 months ago

6.13.100

11 months ago

6.13.99

11 months ago

6.12.99

11 months 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

12 months ago

6.4.30

1 year ago

6.8.78

12 months ago

6.8.77

12 months ago

6.8.76

12 months ago

6.8.75

12 months ago

6.8.74

12 months ago

6.8.73

12 months ago

6.8.72

12 months ago

6.8.71

12 months 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

12 months ago

6.9.78

12 months ago

6.12.92

11 months ago

6.12.93

11 months ago

6.12.90

11 months ago

6.12.91

11 months ago

6.7.49

1 year ago

6.12.98

11 months ago

6.12.96

11 months ago

6.12.97

11 months ago

6.12.94

11 months ago

6.12.95

11 months ago

6.9.90

11 months 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

11 months 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

12 months ago

6.9.81

12 months ago

6.9.80

12 months ago

6.5.40

1 year ago

6.5.42

1 year ago

6.5.41

1 year ago

6.9.89

11 months ago

6.9.88

11 months ago

6.9.87

11 months ago

6.9.86

11 months ago

6.9.85

11 months ago

6.9.84

11 months ago

6.9.83

12 months ago

6.4.29

1 year ago

6.8.69

12 months ago

6.8.68

12 months ago

6.6.44

1 year ago

6.6.45

1 year ago

6.11.90

11 months 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

12 months ago

6.8.66

12 months ago

6.8.65

12 months 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

1 year ago