webtransport.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { Transport } from "../transport.js";
  2. import { nextTick } from "./websocket-constructor.js";
  3. import { createPacketDecoderStream, createPacketEncoderStream, } from "engine.io-parser";
  4. export class WT extends Transport {
  5. get name() {
  6. return "webtransport";
  7. }
  8. doOpen() {
  9. // @ts-ignore
  10. if (typeof WebTransport !== "function") {
  11. return;
  12. }
  13. // @ts-ignore
  14. this.transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
  15. this.transport.closed
  16. .then(() => {
  17. this.onClose();
  18. })
  19. .catch((err) => {
  20. this.onError("webtransport error", err);
  21. });
  22. // note: we could have used async/await, but that would require some additional polyfills
  23. this.transport.ready.then(() => {
  24. this.transport.createBidirectionalStream().then((stream) => {
  25. const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
  26. const reader = stream.readable.pipeThrough(decoderStream).getReader();
  27. const encoderStream = createPacketEncoderStream();
  28. encoderStream.readable.pipeTo(stream.writable);
  29. this.writer = encoderStream.writable.getWriter();
  30. const read = () => {
  31. reader
  32. .read()
  33. .then(({ done, value }) => {
  34. if (done) {
  35. return;
  36. }
  37. this.onPacket(value);
  38. read();
  39. })
  40. .catch((err) => {
  41. });
  42. };
  43. read();
  44. const packet = { type: "open" };
  45. if (this.query.sid) {
  46. packet.data = `{"sid":"${this.query.sid}"}`;
  47. }
  48. this.writer.write(packet).then(() => this.onOpen());
  49. });
  50. });
  51. }
  52. write(packets) {
  53. this.writable = false;
  54. for (let i = 0; i < packets.length; i++) {
  55. const packet = packets[i];
  56. const lastPacket = i === packets.length - 1;
  57. this.writer.write(packet).then(() => {
  58. if (lastPacket) {
  59. nextTick(() => {
  60. this.writable = true;
  61. this.emitReserved("drain");
  62. }, this.setTimeoutFn);
  63. }
  64. });
  65. }
  66. }
  67. doClose() {
  68. var _a;
  69. (_a = this.transport) === null || _a === void 0 ? void 0 : _a.close();
  70. }
  71. }