summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/fetch/metadata/resources/helper.sub.js
blob: fd179fe6f25d6a3de8267643c4c51ee5f0f32655 (plain)
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
'use strict';

/**
 * Construct a URL which, when followed, will trigger redirection through zero
 * or more specified origins and ultimately resolve in the Python handler
 * `record-headers.py`.
 *
 * @param {string} key - the WPT server "stash" name where the request's
 *                       headers should be stored
 * @param {string[]} [origins] - zero or more origin names through which the
 *                               request should pass; see the function
 *                               implementation for a completel list of names
 *                               and corresponding origins; If specified, the
 *                               final origin will be used to access the
 *                               `record-headers.py` hander.
 * @param {object} [params] - a collection of key-value pairs to include as
 *                            URL "search" parameters in the final request to
 *                            `record-headers.py`
 *
 * @returns {string} an absolute URL
 */
function makeRequestURL(key, origins, params) {
    const byName = {
        httpOrigin: 'http://{{host}}:{{ports[http][0]}}',
        httpSameSite: 'http://{{hosts[][www]}}:{{ports[http][0]}}',
        httpCrossSite: 'http://{{hosts[alt][]}}:{{ports[http][0]}}',
        httpsOrigin: 'https://{{host}}:{{ports[https][0]}}',
        httpsSameSite: 'https://{{hosts[][www]}}:{{ports[https][0]}}',
        httpsCrossSite: 'https://{{hosts[alt][]}}:{{ports[https][0]}}'
    };
    const redirectPath = '/fetch/api/resources/redirect.py?location=';
    const path = '/fetch/metadata/resources/record-headers.py?key=' + key;

    let requestUrl = path;
    if (params) {
      requestUrl += '&' + new URLSearchParams(params).toString();
    }

    if (origins && origins.length) {
      requestUrl = byName[origins.pop()] + requestUrl;

      while (origins.length) {
        requestUrl = byName[origins.pop()] + redirectPath +
          encodeURIComponent(requestUrl);
      }
    } else {
      requestUrl = byName.httpsOrigin + requestUrl;
    }

    return requestUrl;
}

function retrieve(key, options) {
  return fetch('/fetch/metadata/resources/record-headers.py?retrieve&key=' + key)
    .then((response) => {
      if (response.status === 204 && options && options.poll) {
        return new Promise((resolve) => setTimeout(resolve, 300))
          .then(() => retrieve(key, options));
      }

      if (response.status !== 200) {
        throw new Error('Failed to query for recorded headers.');
      }

      return response.text().then((text) => JSON.parse(text));
    });
}