uniapp,h5

globals.node.js 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. export const nextTick = process.nextTick;
  2. export const globalThisShim = global;
  3. export const defaultBinaryType = "nodebuffer";
  4. export function createCookieJar() {
  5. return new CookieJar();
  6. }
  7. /**
  8. * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
  9. */
  10. export function parse(setCookieString) {
  11. const parts = setCookieString.split("; ");
  12. const i = parts[0].indexOf("=");
  13. if (i === -1) {
  14. return;
  15. }
  16. const name = parts[0].substring(0, i).trim();
  17. if (!name.length) {
  18. return;
  19. }
  20. let value = parts[0].substring(i + 1).trim();
  21. if (value.charCodeAt(0) === 0x22) {
  22. // remove double quotes
  23. value = value.slice(1, -1);
  24. }
  25. const cookie = {
  26. name,
  27. value,
  28. };
  29. for (let j = 1; j < parts.length; j++) {
  30. const subParts = parts[j].split("=");
  31. if (subParts.length !== 2) {
  32. continue;
  33. }
  34. const key = subParts[0].trim();
  35. const value = subParts[1].trim();
  36. switch (key) {
  37. case "Expires":
  38. cookie.expires = new Date(value);
  39. break;
  40. case "Max-Age":
  41. const expiration = new Date();
  42. expiration.setUTCSeconds(expiration.getUTCSeconds() + parseInt(value, 10));
  43. cookie.expires = expiration;
  44. break;
  45. default:
  46. // ignore other keys
  47. }
  48. }
  49. return cookie;
  50. }
  51. export class CookieJar {
  52. constructor() {
  53. this._cookies = new Map();
  54. }
  55. parseCookies(values) {
  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. get cookies() {
  67. const now = Date.now();
  68. this._cookies.forEach((cookie, name) => {
  69. var _a;
  70. if (((_a = cookie.expires) === null || _a === void 0 ? void 0 : _a.getTime()) < now) {
  71. this._cookies.delete(name);
  72. }
  73. });
  74. return this._cookies.entries();
  75. }
  76. addCookies(xhr) {
  77. const cookies = [];
  78. for (const [name, cookie] of this.cookies) {
  79. cookies.push(`${name}=${cookie.value}`);
  80. }
  81. if (cookies.length) {
  82. xhr.setDisableHeaderCheck(true);
  83. xhr.setRequestHeader("cookie", cookies.join("; "));
  84. }
  85. }
  86. appendCookies(headers) {
  87. for (const [name, cookie] of this.cookies) {
  88. headers.append("cookie", `${name}=${cookie.value}`);
  89. }
  90. }
  91. }