-
Notifications
You must be signed in to change notification settings - Fork 42
/
jsonpipe.js
247 lines (207 loc) · 7.21 KB
/
jsonpipe.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
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.jsonpipe=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/* eslint no-param-reassign:0 */
'use strict';
var xhr = _dereq_('./net/xhr'),
utils = _dereq_('./utils.js'),
Parser = _dereq_('./parsers/json-chunk'),
/**
* @param {String} url A string containing the URL to which the request is sent.
* @param {Object} url A set of key/value pairs that configure the Ajax request.
* @return {XMLHttpRequest} The XMLHttpRequest object for this request.
* @method ajax
*/
ajax = function(url, options) {
// Do all prerequisite checks
if (!url) {
return undefined;
}
// Set arguments if first argument is not string
if (!utils.isString(url)) {
options = url;
url = options.url;
}
// Check if all mandatory attributes are present
if (!url ||
!options ||
!(options.success || options.error || options.complete)) {
return undefined;
}
// Init the parser
var parser = new Parser(options);
// Assign onChunk to options with parse function, binded to the parser object
options.onChunk = parser.parse.bind(parser);
return xhr.send(url, options);
};
module.exports = {
flow: ajax
};
},{"./net/xhr":2,"./parsers/json-chunk":3,"./utils.js":4}],2:[function(_dereq_,module,exports){
'use strict';
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
lines.pop(); // trailing CRLF
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
function send(url, options) {
if (!url || !options) {
return undefined;
}
var xhr = new XMLHttpRequest(),
state = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
},
noop = function() {},
method = (options.method || '').toUpperCase(),
headers = options.headers,
onChunk = options.onChunk || noop,
onHeaders = options.onHeaders || noop,
errorFn = options.error || noop,
completeFn = options.complete || noop,
addContentHeader = method === 'POST',
timer;
xhr.open(method || 'GET', url, true);
// Attach onreadystatechange
xhr.onreadystatechange = function() {
if (xhr.readyState === state.HEADERS_RECEIVED) {
onHeaders(xhr.statusText, parseHeader(xhr.getAllResponseHeaders()));
} else if (xhr.readyState === state.LOADING) {
if (xhr.responseText) {
onChunk(xhr.responseText);
}
} else if (xhr.readyState === state.DONE) {
// clear timeout first
clearTimeout(timer);
// Check for error first
if (xhr.status < 200 || xhr.status > 299) {
errorFn(xhr.statusText);
} else {
onChunk(xhr.responseText, true);
}
// Call complete at the end
completeFn(xhr.statusText);
}
};
// Add headers
if (headers) {
for (var key in headers) { // eslint-disable-line guard-for-in
xhr.setRequestHeader(key, headers[key]);
if (key.toLowerCase() === 'content-type') {
addContentHeader = false;
}
}
}
if (addContentHeader) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
// Add timeout
if (options.timeout) {
timer = setTimeout(function() {
xhr.abort();
clearTimeout(timer);
}, options.timeout);
}
// Set credentials
if (options.hasOwnProperty("withCredentials")) {
xhr.withCredentials = options.withCredentials;
} else {
xhr.withCredentials = true;
}
xhr.send(options.data);
return xhr;
}
module.exports = {
send: send
};
},{}],3:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils.js');
function Parser(options) {
this.offset = 0;
this.token = options.delimiter || '\n\n';
this.success = options.success;
this.error = options.error;
}
Parser.prototype.parse = function(text, finalChunk) {
var chunk = text.substring(this.offset),
start = 0,
finish = chunk.indexOf(this.token, start),
subChunk;
if (finish === 0) { // The delimiter is at the beginning so move the start
start = this.token.length;
}
// Re-assign finish to the next token
finish = chunk.indexOf(this.token, start);
while (finish > -1) {
subChunk = chunk.substring(start, finish);
if (subChunk) {
utils.parse(subChunk, this.success, this.error);
}
start = finish + this.token.length; // move the start
finish = chunk.indexOf(this.token, start); // Re-assign finish to the next token
}
this.offset += start; // move the offset
// Get the remaning chunk
chunk = text.substring(this.offset);
// If final chunk and still unprocessed chunk and no delimiter, then execute the full chunk
if (finalChunk && chunk && finish === -1) {
utils.parse(chunk, this.success, this.error);
}
};
module.exports = Parser;
},{"../utils.js":4}],4:[function(_dereq_,module,exports){
'use strict';
function isString(str) {
return Object.prototype.toString.call(str) === '[object String]';
}
function isFunction(fn) {
return Object.prototype.toString.call(fn) === '[object Function]';
}
// Do the eval trick, since JSON object not present
function customParse(chunk) {
if (!chunk || !/^[\{|\[].*[\}|\]]$/.test(chunk)) {
throw new Error('parseerror');
}
return eval('(' + chunk + ')'); // eslint-disable-line no-eval
}
function parse(chunk, successCb, errorCb) {
var jsonObj;
try {
jsonObj = typeof JSON !== 'undefined' ? JSON.parse(chunk) : customParse(chunk);
} catch (ex) {
if (isFunction(errorCb)) {
errorCb('parsererror');
}
return;
}
// No parse error proceed to success
if (jsonObj && isFunction(successCb)) {
successCb(jsonObj);
}
}
module.exports = {
isString: isString,
isFunction: isFunction,
parse: parse
};
},{}]},{},[1])
(1)
});