vitejs / vite

Next generation frontend tooling. It's fast!
http://vite.dev
MIT License
68.52k stars 6.19k forks source link

Type issue with custom websocket events #18476

Open JakobHock opened 2 weeks ago

JakobHock commented 2 weeks ago

Describe the bug

I'm building a custom devtools plugin that auto generates types for the user. For this i am using the custom websocket events.

The example works great for sending and receiving events on the client side. The type inference works for sending events on the server side but doesn't work for receiving events.

This seems to be caused be ws.on to be extending the WebSocket.Server['on'] type of node. This has the type:

on(event: string | symbol, listener: (this: Server<T>, ...args: any[]) => void): this

and thus doesn't get inferred correctly.

This can be worked around by manually forcing the type of the call back function.

Reproduction

https://stackblitz.com/edit/stackblitz-starters-vipdit?file=vite.config.ts

Steps to reproduce

  1. Create custom events via events.d.ts file like in example
  2. Look at types inferred in import.meta.hot (client) and server.ws.on / server.ws.send

System Info

System:
    OS: Linux 5.15 Ubuntu 22.04.4 LTS 22.04.4 LTS (Jammy Jellyfish)
    CPU: (12) x64 AMD Ryzen 5 5600X 6-Core Processor
    Memory: 5.06 GB / 15.58 GB
    Container: Yes
    Shell: 5.8.1 - /usr/bin/zsh
  Binaries:
    Node: 22.8.0 - ~/.asdf/installs/nodejs/22.8.0/bin/node
    npm: 10.8.2 - ~/.asdf/plugins/nodejs/shims/npm
    pnpm: 9.12.1 - ~/.asdf/shims/pnpm

Used Package Manager

pnpm

Logs

No response

Validations

hi-ogawa commented 2 weeks ago

Not sure if server.ws is fixable since it assumes websocket server api. But, new ones like server.hot and server.environments.client.hot (on Vite 6) seems to work fine https://stackblitz.com/edit/stackblitz-starters-szagyj?file=vite.config.ts

JakobHock commented 2 weeks ago

Thank you very much. Then i will be using the server.hot for now.

It might be helpful to add something regarding the missing types to the docs, so that the user has to force it manually or use server.hot in vite 5 / environment api in v6. Should I open a PR for that?