-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel-data.js
372 lines (297 loc) · 10.8 KB
/
parallel-data.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// ParallelData v1.3.0 by Sean Roberts @DevelopSean
(function () {
'use strict';
var version = "1.3.0";
var LIB = 'ParallelData';
function error() {
try {
var _console2;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
(_console2 = console).error.apply(_console2, [LIB].concat(args));
} catch (e) {}
}
function assign(target, varArgs) {
return Object.assign.apply(Object, arguments);
}
var xhrRequests = {};
var fetchRequests = {};
var allRequestsOptions = {};
var getKey = function getKey(method, url) {
return method.toUpperCase() + '-' + url;
};
var makeXHRRequest = function makeXHRRequest() {};
{
makeXHRRequest = function makeXHRRequest(method, url, headers, options) {
var key = getKey(method, url);
// don't allow duplicate fetches for the same url/method combo
if (xhrRequests[key]) {
return;
}
var xhr = new XMLHttpRequest();
var storedRequest = xhrRequests[key] = {
url: url,
method: method,
headers: headers,
xhrRef: xhr,
events: {
load: null,
error: null,
timeout: null
}
};
xhr.__PDInternal__ = true;
xhr.open(method, url);
// merge in the allRequests headers with the request specific headers
headers = assign({}, allRequestsOptions.headers, headers || {});
Object.keys(headers).forEach(function (key) {
xhr.setRequestHeader(key, headers[key]);
});
if (options && options.onParallelDataResponse) {
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4) {
options.onParallelDataResponse(xhr, {
transferredToApp: !!xhr.__PDConsumed__
});
}
});
}
Object.keys(storedRequest.events).forEach(function (eventName) {
xhr.addEventListener(eventName, function (event) {
storedRequest.events[eventName] = event;
});
});
xhr.send();
};
}
var makeFetchRequest = function makeFetchRequest() {};
{
makeFetchRequest = function makeFetchRequest(method, url, options) {
var key = getKey(method, url);
// don't allow duplicate fetches for the same url/method combo
if (fetchRequests[key]) {
return;
}
var fetchSent = fetchRequests[key] = fetch(url, assign({}, options, {
__PDFetch__: true,
method: method,
// combine with allRequests configuration
headers: assign({}, allRequestsOptions.headers, options.headers || {}),
// forced if not defined
credentials: options.credentials || 'include',
redirect: options.redirect || 'follow'
})).then(function (response) {
if (options && options.onParallelDataResponse) {
// note, cloning because interfaces like .text() and .json() can only be used once
options.onParallelDataResponse(response.clone(), {
transferredToApp: !!fetchSent.__PDConsumed__
});
}
return response;
}).catch(function (e) {
error('fetch request failed', e);
throw e;
});
};
}
function getForXHR(url, options) {
options = options || {};
try {
{
makeXHRRequest('GET', url, options.headers, options);
}
} catch (e) {
error('makeXHRRequest failed', e);
}
}
function getForFetch(url, options) {
options = options || {};
try {
if ('fetch' in window && 'Promise' in window) {
makeFetchRequest('GET', url, options);
} else {
// falling back to XHR if it is not supported
{
getForXHR(url, options);
}
}
} catch (e) {
error('fetch request failed', e);
}
}
function getRequestReference(request, type) {
if (request && request.method && request.url) {
var key = getKey(request.method, request.url);
return type === 'xhr' ? xhrRequests[key] : fetchRequests[key];
}
}
function configureAllRequests(options) {
allRequestsOptions = assign({}, allRequestsOptions, options || {});
}
function XHRInterceptor() {
try {
var XHRProto = XMLHttpRequest.prototype;
XHRProto.__PDListeners__ = [];
Object.keys(XHRProto).forEach(function (prop) {
var descriptor = Object.getOwnPropertyDescriptor(XHRProto, prop);
// Ignore the static fields which have value set already
if (descriptor.value === undefined) {
// map the existing descriptor while overriding the fields we need
// Defining a new getter for xhr fields allows us to redirect where
// values we return come from, allowing in app callbacks to reference
// the ParallelData xhr values
Object.defineProperty(XHRProto, prop, assign({}, descriptor, {
get: function get() {
if (!this.__PDInternal__ && this.__PDRequest__) {
return this.__PDRequest__[prop];
}
return descriptor.get.call(this);
}
}));
}
});
var originalOpen = XHRProto.open;
XHRProto.open = function (method, url) {
this.__PDOpen__ = {
method: method,
url: url
};
originalOpen.apply(this, arguments);
};
var originalAddEventListener = XHRProto.addEventListener;
XHRProto.addEventListener = function () {
if (!this.__PDInternal__) {
if (this.__PDRequest__) {
// register events directly if request is available
return this.__PDRequest__.addEventListener.apply(this.__PDRequest__, arguments);
} else {
// keep a memory of the register so we can apply them later
this.__PDListeners__.push({ action: 'add', args: arguments });
}
}
return originalAddEventListener.apply(this, arguments);
};
var originalRemoveEventListener = XHRProto.removeEventListener;
XHRProto.removeEventListener = function () {
if (!this.__PDInternal__) {
if (this.__PDRequest__) {
// register events directly if request is available
return this.__PDRequest__.removeEventListener.apply(this.__PDRequest__, arguments);
} else {
// keep a memory of the register so we can apply them later
this.__PDListeners__.push({ action: 'remove', args: arguments });
}
}
return originalRemoveEventListener.apply(this, arguments);
};
var originalSend = XHRProto.send;
XHRProto.send = function (body) {
var _this = this;
var parallelRequest = getRequestReference(this.__PDOpen__, 'xhr');
var parallelXHR = parallelRequest && parallelRequest.xhrRef;
if (!this.__PDInternal__ && parallelXHR && !parallelXHR.__PDConsumed__) {
// currently we only want to allow ParallelData get req
parallelXHR.__PDConsumed__ = true
// execute the next set of controls asynchronously
// NOTE: all reassignments should happen inside of this
// async path so that the PD request does not start invoking
// callbacks before we are ready for everything to start invoking
;(window.setImmediate || window.setTimeout)(function () {
try {
// map xhr functions over
parallelXHR.onreadystatechange = _this.onreadystatechange;
// map all event target functions over
// If the XHR has not finished the request, these event reassignments
// will be automatically picked up
var onEventProps = ['onloadstart', 'onprogress', 'onabort', 'onerror', 'onload', 'ontimeout', 'onloadend'];
onEventProps.forEach(function (prop) {
parallelXHR[prop] = _this[prop];
});
while (_this.__PDListeners__.length) {
var listener = _this.__PDListeners__.shift();
parallelXHR[listener.action + 'EventListener'].apply(parallelXHR, listener.args);
}
// access all properties from the original xhr (the current this context)
// before we assign this property as it is the pivot property in accessors
_this.__PDRequest__ = parallelXHR;
// NOTE: The decision here is that we will not invoke the
// onreadystatechange function for all states up to where it currently is
if (parallelXHR.onreadystatechange) {
parallelXHR.onreadystatechange();
}
Object.keys(parallelRequest.events).forEach(function (eventName) {
if (parallelRequest.events[eventName]) {
// dispatchin will fire the "on" events and registered event listeners
_this.dispatchEvent(parallelRequest.events[eventName]);
}
});
} catch (e) {
error('transferring events failed', e);
}
}, 0);
} else {
// empty the watching of new event listeners to not block GC
this.__PDListeners__ = [];
originalSend.call(this, body);
}
};
} catch (e) {
error('failed to run XHRInterceptor', e);
}
}
function fetchInterceptor() {
try {
var originalFetch = window.fetch;
if (!originalFetch || !window.Promise) {
// fetch is not available
return;
}
window.fetch = function (input, init) {
input = input || {};
init = init || {};
var url = void 0;
var method = void 0;
if (typeof input === 'string') {
url = input;
} else if (input.url) {
url = input.url;
}
if (init.method) {
method = init.method;
} else if (input.method) {
method = input.method;
} else {
method = 'GET';
}
var parallelFetch = getRequestReference({ method: method, url: url }, 'fetch');
// ensure the fetch request is there but it's not consumed
// more than once
if (!init.__PDFetch__ && parallelFetch && !parallelFetch.__PDConsumed__) {
parallelFetch.__PDConsumed__ = true;
return parallelFetch;
}
return originalFetch.apply(window, arguments);
};
} catch (e) {
error('failed to run fetchInterceptor', e);
}
}
window.ParallelData = {
version: version,
configure: function configure(config) {
config = config || {};
if (config.allRequests) {
configureAllRequests(config.allRequests);
}
}
};
{
window.ParallelData.getForXHR = getForXHR;
XHRInterceptor();
}
{
window.ParallelData.getForFetch = getForFetch;
fetchInterceptor();
}
}());