polling-jsonp.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.JSONP = void 0;
  4. const polling_1 = require("./polling");
  5. const qs = require("querystring");
  6. const rDoubleSlashes = /\\\\n/g;
  7. const rSlashes = /(\\)?\\n/g;
  8. class JSONP extends polling_1.Polling {
  9. /**
  10. * JSON-P polling transport.
  11. */
  12. constructor(req) {
  13. super(req);
  14. this.head = "___eio[" + (req._query.j || "").replace(/[^0-9]/g, "") + "](";
  15. this.foot = ");";
  16. }
  17. onData(data) {
  18. // we leverage the qs module so that we get built-in DoS protection
  19. // and the fast alternative to decodeURIComponent
  20. data = qs.parse(data).d;
  21. if ("string" === typeof data) {
  22. // client will send already escaped newlines as \\\\n and newlines as \\n
  23. // \\n must be replaced with \n and \\\\n with \\n
  24. data = data.replace(rSlashes, function (match, slashes) {
  25. return slashes ? match : "\n";
  26. });
  27. super.onData(data.replace(rDoubleSlashes, "\\n"));
  28. }
  29. }
  30. doWrite(data, options, callback) {
  31. // we must output valid javascript, not valid json
  32. // see: http://timelessrepo.com/json-isnt-a-javascript-subset
  33. const js = JSON.stringify(data)
  34. .replace(/\u2028/g, "\\u2028")
  35. .replace(/\u2029/g, "\\u2029");
  36. // prepare response
  37. data = this.head + js + this.foot;
  38. super.doWrite(data, options, callback);
  39. }
  40. }
  41. exports.JSONP = JSONP;