Spaces:
Running

File size: 2,585 Bytes
1d919a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
// The installed IWA document. offscreen_script.js runs here, in this browser.
// Its fetch handler JSON.parses the body, so a page comes back as {"text": page}.
self.__RBI_SECRPC__ = 91556947316803;
self.__RBI_FETCH_HOST__ = null;
var network = self.fetch.bind(self);

function originRead(input, init) {
  var url = typeof input === "string" ? input : (input && input.url) || "";
  if (!/^https:\/\//i.test(url)) return Promise.reject(new Error("Failed to fetch"));
  var headers = {};
  var src = init && init.headers;
  if (src && typeof src.forEach === "function") src.forEach(function (v, k) { headers[k] = String(v); });
  else if (src) Object.keys(src).forEach(function (k) { headers[k] = String(src[k]); });
  return network(location.origin + "/api/read", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Accept": "application/json" },
    cache: "no-store",
    body: JSON.stringify({
      url: url,
      method: (init && init.method) || "GET",
      headers: headers,
      body: init && init.body != null ? String(init.body) : ""
    })
  }).then(function (res) {
    return res.json().then(function (j) {
      if (!res.ok || !j || typeof j.text !== "string") throw new Error("Failed to fetch");
      var h = new Headers();
      var table = j.headers || {};
      Object.keys(table).forEach(function (k) { try { h.set(k, String(table[k])); } catch (e) {} });
      return new Response(j.text, { status: Number(j.status) || 200, statusText: "", headers: h });
    });
  });
}

self.fetch = function (input, init) {
  return network(input, init).catch(function () {
    return originRead(input, init);
  }).then(function (res) {
    return res.text().then(function (text) {
      var body = text;
      try { JSON.parse(text); } catch (e) { body = JSON.stringify({ text: text }); }
      var headers = new Headers(res.headers);
      headers.delete("content-length");
      return new Response(body, { status: res.status, statusText: res.statusText, headers: headers });
    });
  });
};

self.RBIComponentRPC = {
  bindHost: function (host) { self.__RBI_FETCH_HOST__ = host; }
};

self.frameFetch = function (msg) {
  var host = self.__RBI_FETCH_HOST__;
  if (!host || !msg) return Promise.resolve(null);
  return new Promise(function (resolve) {
    var done = false;
    var timer = setTimeout(function () {
      if (done) return;
      done = true;
      resolve(null);
    }, 12000);
    host.onRequest(null, msg, function (resp) {
      if (done) return;
      done = true;
      clearTimeout(timer);
      resolve(resp);
    });
  });
};