xmlhttprequest.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import * as XMLHttpRequestModule from "xmlhttprequest-ssl";
  2. export const XHR = XMLHttpRequestModule.default || XMLHttpRequestModule;
  3. export function createCookieJar() {
  4. return new CookieJar();
  5. }
  6. /**
  7. * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
  8. */
  9. export function parse(setCookieString) {
  10. const parts = setCookieString.split("; ");
  11. const i = parts[0].indexOf("=");
  12. if (i === -1) {
  13. return;
  14. }
  15. const name = parts[0].substring(0, i).trim();
  16. if (!name.length) {
  17. return;
  18. }
  19. let value = parts[0].substring(i + 1).trim();
  20. if (value.charCodeAt(0) === 0x22) {
  21. // remove double quotes
  22. value = value.slice(1, -1);
  23. }
  24. const cookie = {
  25. name,
  26. value,
  27. };
  28. for (let j = 1; j < parts.length; j++) {
  29. const subParts = parts[j].split("=");
  30. if (subParts.length !== 2) {
  31. continue;
  32. }
  33. const key = subParts[0].trim();
  34. const value = subParts[1].trim();
  35. switch (key) {
  36. case "Expires":
  37. cookie.expires = new Date(value);
  38. break;
  39. case "Max-Age":
  40. const expiration = new Date();
  41. expiration.setUTCSeconds(expiration.getUTCSeconds() + parseInt(value, 10));
  42. cookie.expires = expiration;
  43. break;
  44. default:
  45. // ignore other keys
  46. }
  47. }
  48. return cookie;
  49. }
  50. export class CookieJar {
  51. constructor() {
  52. this.cookies = new Map();
  53. }
  54. parseCookies(xhr) {
  55. const values = xhr.getResponseHeader("set-cookie");
  56. if (!values) {
  57. return;
  58. }
  59. values.forEach((value) => {
  60. const parsed = parse(value);
  61. if (parsed) {
  62. this.cookies.set(parsed.name, parsed);
  63. }
  64. });
  65. }
  66. addCookies(xhr) {
  67. const cookies = [];
  68. this.cookies.forEach((cookie, name) => {
  69. var _a;
  70. if (((_a = cookie.expires) === null || _a === void 0 ? void 0 : _a.getTime()) < Date.now()) {
  71. this.cookies.delete(name);
  72. }
  73. else {
  74. cookies.push(`${name}=${cookie.value}`);
  75. }
  76. });
  77. if (cookies.length) {
  78. xhr.setDisableHeaderCheck(true);
  79. xhr.setRequestHeader("cookie", cookies.join("; "));
  80. }
  81. }
  82. }