HandshakeProtocol.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. // Licensed to the .NET Foundation under one or more agreements.
  3. // The .NET Foundation licenses this file to you under the MIT license.
  4. Object.defineProperty(exports, "__esModule", { value: true });
  5. exports.HandshakeProtocol = void 0;
  6. const TextMessageFormat_1 = require("./TextMessageFormat");
  7. const Utils_1 = require("./Utils");
  8. /** @private */
  9. class HandshakeProtocol {
  10. // Handshake request is always JSON
  11. writeHandshakeRequest(handshakeRequest) {
  12. return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(handshakeRequest));
  13. }
  14. parseHandshakeResponse(data) {
  15. let messageData;
  16. let remainingData;
  17. if (Utils_1.isArrayBuffer(data)) {
  18. // Format is binary but still need to read JSON text from handshake response
  19. const binaryData = new Uint8Array(data);
  20. const separatorIndex = binaryData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparatorCode);
  21. if (separatorIndex === -1) {
  22. throw new Error("Message is incomplete.");
  23. }
  24. // content before separator is handshake response
  25. // optional content after is additional messages
  26. const responseLength = separatorIndex + 1;
  27. messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));
  28. remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
  29. }
  30. else {
  31. const textData = data;
  32. const separatorIndex = textData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparator);
  33. if (separatorIndex === -1) {
  34. throw new Error("Message is incomplete.");
  35. }
  36. // content before separator is handshake response
  37. // optional content after is additional messages
  38. const responseLength = separatorIndex + 1;
  39. messageData = textData.substring(0, responseLength);
  40. remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
  41. }
  42. // At this point we should have just the single handshake message
  43. const messages = TextMessageFormat_1.TextMessageFormat.parse(messageData);
  44. const response = JSON.parse(messages[0]);
  45. if (response.type) {
  46. throw new Error("Expected a handshake response from the server.");
  47. }
  48. const responseMessage = response;
  49. // multiple messages could have arrived with handshake
  50. // return additional data to be parsed as usual, or null if all parsed
  51. return [remainingData, responseMessage];
  52. }
  53. }
  54. exports.HandshakeProtocol = HandshakeProtocol;
  55. //# sourceMappingURL=HandshakeProtocol.js.map