Blame view

lib/jsdom/living/xhr/xhr-sync-worker.js 1.64 KB
858f2bdf5   Boyan Georgiev   fixes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  "use strict";
  /* eslint-disable no-process-exit */
  const util = require("util");
  const { JSDOM } = require("../../../api");
  const { READY_STATES } = require("./xhr-utils");
  const idlUtils = require("../generated/utils");
  const tough = require("tough-cookie");
  
  const dom = new JSDOM();
  const xhr = new dom.window.XMLHttpRequest();
  const xhrImpl = idlUtils.implForWrapper(xhr);
  
  const chunks = [];
  
  process.stdin.on("data", chunk => {
    chunks.push(chunk);
  });
  
  process.stdin.on("end", () => {
    const buffer = Buffer.concat(chunks);
  
    const flag = JSON.parse(buffer.toString());
    if (flag.body && flag.body.type === "Buffer" && flag.body.data) {
      flag.body = Buffer.from(flag.body.data);
    }
    if (flag.cookieJar) {
      flag.cookieJar = tough.CookieJar.fromJSON(flag.cookieJar);
    }
  
    flag.synchronous = false;
    Object.assign(xhrImpl.flag, flag);
    const { properties } = xhrImpl;
    xhrImpl.readyState = READY_STATES.OPENED;
    try {
      xhr.addEventListener("loadend", () => {
        if (properties.error) {
          properties.error = properties.error.stack || util.inspect(properties.error);
        }
        process.stdout.write(JSON.stringify({
          responseURL: xhrImpl.responseURL,
          status: xhrImpl.status,
          statusText: xhrImpl.statusText,
          properties
        }), () => {
          process.exit(0);
        });
      }, false);
      xhr.send(flag.body);
    } catch (error) {
      properties.error += error.stack || util.inspect(error);
      process.stdout.write(JSON.stringify({
        responseURL: xhrImpl.responseURL,
        status: xhrImpl.status,
        statusText: xhrImpl.statusText,
        properties
      }), () => {
        process.exit(0);
      });
    }
  });