index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // src/helper/websocket/index.ts
  2. var WSContext = class {
  3. #init;
  4. constructor(init) {
  5. this.#init = init;
  6. this.raw = init.raw;
  7. this.url = init.url ? new URL(init.url) : null;
  8. this.protocol = init.protocol ?? null;
  9. }
  10. send(source, options) {
  11. this.#init.send(source, options ?? {});
  12. }
  13. raw;
  14. binaryType = "arraybuffer";
  15. get readyState() {
  16. return this.#init.readyState;
  17. }
  18. url;
  19. protocol;
  20. close(code, reason) {
  21. this.#init.close(code, reason);
  22. }
  23. };
  24. var createWSMessageEvent = (source) => {
  25. return new MessageEvent("message", {
  26. data: source
  27. });
  28. };
  29. var defineWebSocketHelper = (handler) => {
  30. return ((...args) => {
  31. if (typeof args[0] === "function") {
  32. const [createEvents, options] = args;
  33. return async function upgradeWebSocket(c, next) {
  34. const events = await createEvents(c);
  35. const result = await handler(c, events, options);
  36. if (result) {
  37. return result;
  38. }
  39. await next();
  40. };
  41. } else {
  42. const [c, events, options] = args;
  43. return (async () => {
  44. const upgraded = await handler(c, events, options);
  45. if (!upgraded) {
  46. throw new Error("Failed to upgrade WebSocket");
  47. }
  48. return upgraded;
  49. })();
  50. }
  51. });
  52. };
  53. export {
  54. WSContext,
  55. createWSMessageEvent,
  56. defineWebSocketHelper
  57. };