portTransport.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.PortTransport = void 0;
  6. /**
  7. * Copyright (c) Microsoft Corporation.
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. class PortTransport {
  22. constructor(port, handler) {
  23. this._lastId = 0;
  24. this._port = void 0;
  25. this._callbacks = new Map();
  26. this._port = port;
  27. port.onmessage = async event => {
  28. const message = event.data;
  29. const {
  30. id,
  31. ackId,
  32. method,
  33. params,
  34. result
  35. } = message;
  36. if (id) {
  37. const result = await handler(method, params);
  38. this._port.postMessage({
  39. ackId: id,
  40. result
  41. });
  42. return;
  43. }
  44. if (ackId) {
  45. const callback = this._callbacks.get(ackId);
  46. this._callbacks.delete(ackId);
  47. callback === null || callback === void 0 ? void 0 : callback(result);
  48. return;
  49. }
  50. };
  51. }
  52. async send(method, params) {
  53. return await new Promise(f => {
  54. const id = ++this._lastId;
  55. this._callbacks.set(id, f);
  56. this._port.postMessage({
  57. id,
  58. method,
  59. params
  60. });
  61. });
  62. }
  63. }
  64. exports.PortTransport = PortTransport;