portTransport.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var portTransport_exports = {};
  20. __export(portTransport_exports, {
  21. PortTransport: () => PortTransport
  22. });
  23. module.exports = __toCommonJS(portTransport_exports);
  24. class PortTransport {
  25. constructor(port, handler) {
  26. this._lastId = 0;
  27. this._callbacks = /* @__PURE__ */ new Map();
  28. this._port = port;
  29. port.addEventListener("message", async (event) => {
  30. const message = event.data;
  31. const { id, ackId, method, params, result } = message;
  32. if (ackId) {
  33. const callback = this._callbacks.get(ackId);
  34. this._callbacks.delete(ackId);
  35. this._resetRef();
  36. callback?.(result);
  37. return;
  38. }
  39. const handlerResult = await handler(method, params);
  40. if (id)
  41. this._port.postMessage({ ackId: id, result: handlerResult });
  42. });
  43. this._resetRef();
  44. }
  45. post(method, params) {
  46. this._port.postMessage({ method, params });
  47. }
  48. async send(method, params) {
  49. return await new Promise((f) => {
  50. const id = ++this._lastId;
  51. this._callbacks.set(id, f);
  52. this._resetRef();
  53. this._port.postMessage({ id, method, params });
  54. });
  55. }
  56. _resetRef() {
  57. if (this._callbacks.size) {
  58. this._port.ref();
  59. } else {
  60. this._port.unref();
  61. }
  62. }
  63. }
  64. // Annotate the CommonJS export names for ESM import in node:
  65. 0 && (module.exports = {
  66. PortTransport
  67. });