XMLHttpRequest.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const BlobManager = require('../Blob/BlobManager');
  12. const EventTarget = require('event-target-shim');
  13. const GlobalPerformanceLogger = require('react-native/Libraries/Utilities/GlobalPerformanceLogger');
  14. const RCTNetworking = require('./RCTNetworking');
  15. const base64 = require('base64-js');
  16. const invariant = require('invariant');
  17. const warning = require('fbjs/lib/warning');
  18. const DEBUG_NETWORK_SEND_DELAY: false = false; // Set to a number of milliseconds when debugging
  19. export type NativeResponseType = 'base64' | 'blob' | 'text';
  20. export type ResponseType =
  21. | ''
  22. | 'arraybuffer'
  23. | 'blob'
  24. | 'document'
  25. | 'json'
  26. | 'text';
  27. export type Response = ?Object | string;
  28. type XHRInterceptor = {
  29. requestSent(id: number, url: string, method: string, headers: Object): void,
  30. responseReceived(
  31. id: number,
  32. url: string,
  33. status: number,
  34. headers: Object,
  35. ): void,
  36. dataReceived(id: number, data: string): void,
  37. loadingFinished(id: number, encodedDataLength: number): void,
  38. loadingFailed(id: number, error: string): void,
  39. ...
  40. };
  41. // The native blob module is optional so inject it here if available.
  42. if (BlobManager.isAvailable) {
  43. BlobManager.addNetworkingHandler();
  44. }
  45. const UNSENT = 0;
  46. const OPENED = 1;
  47. const HEADERS_RECEIVED = 2;
  48. const LOADING = 3;
  49. const DONE = 4;
  50. const SUPPORTED_RESPONSE_TYPES = {
  51. arraybuffer: typeof global.ArrayBuffer === 'function',
  52. blob: typeof global.Blob === 'function',
  53. document: false,
  54. json: true,
  55. text: true,
  56. '': true,
  57. };
  58. const REQUEST_EVENTS = [
  59. 'abort',
  60. 'error',
  61. 'load',
  62. 'loadstart',
  63. 'progress',
  64. 'timeout',
  65. 'loadend',
  66. ];
  67. const XHR_EVENTS = REQUEST_EVENTS.concat('readystatechange');
  68. class XMLHttpRequestEventTarget extends (EventTarget(...REQUEST_EVENTS): any) {
  69. onload: ?Function;
  70. onloadstart: ?Function;
  71. onprogress: ?Function;
  72. ontimeout: ?Function;
  73. onerror: ?Function;
  74. onabort: ?Function;
  75. onloadend: ?Function;
  76. }
  77. /**
  78. * Shared base for platform-specific XMLHttpRequest implementations.
  79. */
  80. class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
  81. static UNSENT: number = UNSENT;
  82. static OPENED: number = OPENED;
  83. static HEADERS_RECEIVED: number = HEADERS_RECEIVED;
  84. static LOADING: number = LOADING;
  85. static DONE: number = DONE;
  86. static _interceptor: ?XHRInterceptor = null;
  87. UNSENT: number = UNSENT;
  88. OPENED: number = OPENED;
  89. HEADERS_RECEIVED: number = HEADERS_RECEIVED;
  90. LOADING: number = LOADING;
  91. DONE: number = DONE;
  92. // EventTarget automatically initializes these to `null`.
  93. onload: ?Function;
  94. onloadstart: ?Function;
  95. onprogress: ?Function;
  96. ontimeout: ?Function;
  97. onerror: ?Function;
  98. onabort: ?Function;
  99. onloadend: ?Function;
  100. onreadystatechange: ?Function;
  101. readyState: number = UNSENT;
  102. responseHeaders: ?Object;
  103. status: number = 0;
  104. timeout: number = 0;
  105. responseURL: ?string;
  106. withCredentials: boolean = true;
  107. upload: XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();
  108. _requestId: ?number;
  109. _subscriptions: Array<*>;
  110. _aborted: boolean = false;
  111. _cachedResponse: Response;
  112. _hasError: boolean = false;
  113. _headers: Object;
  114. _lowerCaseResponseHeaders: Object;
  115. _method: ?string = null;
  116. _perfKey: ?string = null;
  117. _response: string | ?Object;
  118. _responseType: ResponseType;
  119. _response: string = '';
  120. _sent: boolean;
  121. _url: ?string = null;
  122. _timedOut: boolean = false;
  123. _trackingName: string = 'unknown';
  124. _incrementalEvents: boolean = false;
  125. static setInterceptor(interceptor: ?XHRInterceptor) {
  126. XMLHttpRequest._interceptor = interceptor;
  127. }
  128. constructor() {
  129. super();
  130. this._reset();
  131. }
  132. _reset(): void {
  133. this.readyState = this.UNSENT;
  134. this.responseHeaders = undefined;
  135. this.status = 0;
  136. delete this.responseURL;
  137. this._requestId = null;
  138. this._cachedResponse = undefined;
  139. this._hasError = false;
  140. this._headers = {};
  141. this._response = '';
  142. this._responseType = '';
  143. this._sent = false;
  144. this._lowerCaseResponseHeaders = {};
  145. this._clearSubscriptions();
  146. this._timedOut = false;
  147. }
  148. get responseType(): ResponseType {
  149. return this._responseType;
  150. }
  151. set responseType(responseType: ResponseType): void {
  152. if (this._sent) {
  153. throw new Error(
  154. "Failed to set the 'responseType' property on 'XMLHttpRequest': The " +
  155. 'response type cannot be set after the request has been sent.',
  156. );
  157. }
  158. if (!SUPPORTED_RESPONSE_TYPES.hasOwnProperty(responseType)) {
  159. warning(
  160. false,
  161. `The provided value '${responseType}' is not a valid 'responseType'.`,
  162. );
  163. return;
  164. }
  165. // redboxes early, e.g. for 'arraybuffer' on ios 7
  166. invariant(
  167. SUPPORTED_RESPONSE_TYPES[responseType] || responseType === 'document',
  168. `The provided value '${responseType}' is unsupported in this environment.`,
  169. );
  170. if (responseType === 'blob') {
  171. invariant(
  172. BlobManager.isAvailable,
  173. 'Native module BlobModule is required for blob support',
  174. );
  175. }
  176. this._responseType = responseType;
  177. }
  178. get responseText(): string {
  179. if (this._responseType !== '' && this._responseType !== 'text') {
  180. throw new Error(
  181. "The 'responseText' property is only available if 'responseType' " +
  182. `is set to '' or 'text', but it is '${this._responseType}'.`,
  183. );
  184. }
  185. if (this.readyState < LOADING) {
  186. return '';
  187. }
  188. return this._response;
  189. }
  190. get response(): Response {
  191. const {responseType} = this;
  192. if (responseType === '' || responseType === 'text') {
  193. return this.readyState < LOADING || this._hasError ? '' : this._response;
  194. }
  195. if (this.readyState !== DONE) {
  196. return null;
  197. }
  198. if (this._cachedResponse !== undefined) {
  199. return this._cachedResponse;
  200. }
  201. switch (responseType) {
  202. case 'document':
  203. this._cachedResponse = null;
  204. break;
  205. case 'arraybuffer':
  206. this._cachedResponse = base64.toByteArray(this._response).buffer;
  207. break;
  208. case 'blob':
  209. if (typeof this._response === 'object' && this._response) {
  210. this._cachedResponse = BlobManager.createFromOptions(this._response);
  211. } else if (this._response === '') {
  212. this._cachedResponse = BlobManager.createFromParts([]);
  213. } else {
  214. throw new Error(`Invalid response for blob: ${this._response}`);
  215. }
  216. break;
  217. case 'json':
  218. try {
  219. this._cachedResponse = JSON.parse(this._response);
  220. } catch (_) {
  221. this._cachedResponse = null;
  222. }
  223. break;
  224. default:
  225. this._cachedResponse = null;
  226. }
  227. return this._cachedResponse;
  228. }
  229. // exposed for testing
  230. __didCreateRequest(requestId: number): void {
  231. this._requestId = requestId;
  232. XMLHttpRequest._interceptor &&
  233. XMLHttpRequest._interceptor.requestSent(
  234. requestId,
  235. this._url || '',
  236. this._method || 'GET',
  237. this._headers,
  238. );
  239. }
  240. // exposed for testing
  241. __didUploadProgress(
  242. requestId: number,
  243. progress: number,
  244. total: number,
  245. ): void {
  246. if (requestId === this._requestId) {
  247. this.upload.dispatchEvent({
  248. type: 'progress',
  249. lengthComputable: true,
  250. loaded: progress,
  251. total,
  252. });
  253. }
  254. }
  255. __didReceiveResponse(
  256. requestId: number,
  257. status: number,
  258. responseHeaders: ?Object,
  259. responseURL: ?string,
  260. ): void {
  261. if (requestId === this._requestId) {
  262. this._perfKey != null &&
  263. GlobalPerformanceLogger.stopTimespan(this._perfKey);
  264. this.status = status;
  265. this.setResponseHeaders(responseHeaders);
  266. this.setReadyState(this.HEADERS_RECEIVED);
  267. if (responseURL || responseURL === '') {
  268. this.responseURL = responseURL;
  269. } else {
  270. delete this.responseURL;
  271. }
  272. XMLHttpRequest._interceptor &&
  273. XMLHttpRequest._interceptor.responseReceived(
  274. requestId,
  275. responseURL || this._url || '',
  276. status,
  277. responseHeaders || {},
  278. );
  279. }
  280. }
  281. __didReceiveData(requestId: number, response: string): void {
  282. if (requestId !== this._requestId) {
  283. return;
  284. }
  285. this._response = response;
  286. this._cachedResponse = undefined; // force lazy recomputation
  287. this.setReadyState(this.LOADING);
  288. XMLHttpRequest._interceptor &&
  289. XMLHttpRequest._interceptor.dataReceived(requestId, response);
  290. }
  291. __didReceiveIncrementalData(
  292. requestId: number,
  293. responseText: string,
  294. progress: number,
  295. total: number,
  296. ) {
  297. if (requestId !== this._requestId) {
  298. return;
  299. }
  300. if (!this._response) {
  301. this._response = responseText;
  302. } else {
  303. this._response += responseText;
  304. }
  305. XMLHttpRequest._interceptor &&
  306. XMLHttpRequest._interceptor.dataReceived(requestId, responseText);
  307. this.setReadyState(this.LOADING);
  308. this.__didReceiveDataProgress(requestId, progress, total);
  309. }
  310. __didReceiveDataProgress(
  311. requestId: number,
  312. loaded: number,
  313. total: number,
  314. ): void {
  315. if (requestId !== this._requestId) {
  316. return;
  317. }
  318. this.dispatchEvent({
  319. type: 'progress',
  320. lengthComputable: total >= 0,
  321. loaded,
  322. total,
  323. });
  324. }
  325. // exposed for testing
  326. __didCompleteResponse(
  327. requestId: number,
  328. error: string,
  329. timeOutError: boolean,
  330. ): void {
  331. if (requestId === this._requestId) {
  332. if (error) {
  333. if (this._responseType === '' || this._responseType === 'text') {
  334. this._response = error;
  335. }
  336. this._hasError = true;
  337. if (timeOutError) {
  338. this._timedOut = true;
  339. }
  340. }
  341. this._clearSubscriptions();
  342. this._requestId = null;
  343. this.setReadyState(this.DONE);
  344. if (error) {
  345. XMLHttpRequest._interceptor &&
  346. XMLHttpRequest._interceptor.loadingFailed(requestId, error);
  347. } else {
  348. XMLHttpRequest._interceptor &&
  349. XMLHttpRequest._interceptor.loadingFinished(
  350. requestId,
  351. this._response.length,
  352. );
  353. }
  354. }
  355. }
  356. _clearSubscriptions(): void {
  357. (this._subscriptions || []).forEach(sub => {
  358. if (sub) {
  359. sub.remove();
  360. }
  361. });
  362. this._subscriptions = [];
  363. }
  364. getAllResponseHeaders(): ?string {
  365. if (!this.responseHeaders) {
  366. // according to the spec, return null if no response has been received
  367. return null;
  368. }
  369. const headers = this.responseHeaders || {};
  370. return Object.keys(headers)
  371. .map(headerName => {
  372. return headerName + ': ' + headers[headerName];
  373. })
  374. .join('\r\n');
  375. }
  376. getResponseHeader(header: string): ?string {
  377. const value = this._lowerCaseResponseHeaders[header.toLowerCase()];
  378. return value !== undefined ? value : null;
  379. }
  380. setRequestHeader(header: string, value: any): void {
  381. if (this.readyState !== this.OPENED) {
  382. throw new Error('Request has not been opened');
  383. }
  384. this._headers[header.toLowerCase()] = String(value);
  385. }
  386. /**
  387. * Custom extension for tracking origins of request.
  388. */
  389. setTrackingName(trackingName: string): XMLHttpRequest {
  390. this._trackingName = trackingName;
  391. return this;
  392. }
  393. open(method: string, url: string, async: ?boolean): void {
  394. /* Other optional arguments are not supported yet */
  395. if (this.readyState !== this.UNSENT) {
  396. throw new Error('Cannot open, already sending');
  397. }
  398. if (async !== undefined && !async) {
  399. // async is default
  400. throw new Error('Synchronous http requests are not supported');
  401. }
  402. if (!url) {
  403. throw new Error('Cannot load an empty url');
  404. }
  405. this._method = method.toUpperCase();
  406. this._url = url;
  407. this._aborted = false;
  408. this.setReadyState(this.OPENED);
  409. }
  410. send(data: any): void {
  411. if (this.readyState !== this.OPENED) {
  412. throw new Error('Request has not been opened');
  413. }
  414. if (this._sent) {
  415. throw new Error('Request has already been sent');
  416. }
  417. this._sent = true;
  418. const incrementalEvents =
  419. this._incrementalEvents || !!this.onreadystatechange || !!this.onprogress;
  420. this._subscriptions.push(
  421. RCTNetworking.addListener('didSendNetworkData', args =>
  422. this.__didUploadProgress(...args),
  423. ),
  424. );
  425. this._subscriptions.push(
  426. RCTNetworking.addListener('didReceiveNetworkResponse', args =>
  427. this.__didReceiveResponse(...args),
  428. ),
  429. );
  430. this._subscriptions.push(
  431. RCTNetworking.addListener('didReceiveNetworkData', args =>
  432. this.__didReceiveData(...args),
  433. ),
  434. );
  435. this._subscriptions.push(
  436. RCTNetworking.addListener('didReceiveNetworkIncrementalData', args =>
  437. this.__didReceiveIncrementalData(...args),
  438. ),
  439. );
  440. this._subscriptions.push(
  441. RCTNetworking.addListener('didReceiveNetworkDataProgress', args =>
  442. this.__didReceiveDataProgress(...args),
  443. ),
  444. );
  445. this._subscriptions.push(
  446. RCTNetworking.addListener('didCompleteNetworkResponse', args =>
  447. this.__didCompleteResponse(...args),
  448. ),
  449. );
  450. let nativeResponseType: NativeResponseType = 'text';
  451. if (this._responseType === 'arraybuffer') {
  452. nativeResponseType = 'base64';
  453. }
  454. if (this._responseType === 'blob') {
  455. nativeResponseType = 'blob';
  456. }
  457. const doSend = () => {
  458. const friendlyName =
  459. this._trackingName !== 'unknown' ? this._trackingName : this._url;
  460. this._perfKey = 'network_XMLHttpRequest_' + String(friendlyName);
  461. GlobalPerformanceLogger.startTimespan(this._perfKey);
  462. invariant(
  463. this._method,
  464. 'XMLHttpRequest method needs to be defined (%s).',
  465. friendlyName,
  466. );
  467. invariant(
  468. this._url,
  469. 'XMLHttpRequest URL needs to be defined (%s).',
  470. friendlyName,
  471. );
  472. RCTNetworking.sendRequest(
  473. this._method,
  474. this._trackingName,
  475. this._url,
  476. this._headers,
  477. data,
  478. /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found
  479. * when making Flow check .android.js files. */
  480. nativeResponseType,
  481. incrementalEvents,
  482. this.timeout,
  483. this.__didCreateRequest.bind(this),
  484. this.withCredentials,
  485. );
  486. };
  487. if (DEBUG_NETWORK_SEND_DELAY) {
  488. setTimeout(doSend, DEBUG_NETWORK_SEND_DELAY);
  489. } else {
  490. doSend();
  491. }
  492. }
  493. abort(): void {
  494. this._aborted = true;
  495. if (this._requestId) {
  496. RCTNetworking.abortRequest(this._requestId);
  497. }
  498. // only call onreadystatechange if there is something to abort,
  499. // below logic is per spec
  500. if (
  501. !(
  502. this.readyState === this.UNSENT ||
  503. (this.readyState === this.OPENED && !this._sent) ||
  504. this.readyState === this.DONE
  505. )
  506. ) {
  507. this._reset();
  508. this.setReadyState(this.DONE);
  509. }
  510. // Reset again after, in case modified in handler
  511. this._reset();
  512. }
  513. setResponseHeaders(responseHeaders: ?Object): void {
  514. this.responseHeaders = responseHeaders || null;
  515. const headers = responseHeaders || {};
  516. this._lowerCaseResponseHeaders = Object.keys(headers).reduce(
  517. (lcaseHeaders, headerName) => {
  518. lcaseHeaders[headerName.toLowerCase()] = headers[headerName];
  519. return lcaseHeaders;
  520. },
  521. {},
  522. );
  523. }
  524. setReadyState(newState: number): void {
  525. this.readyState = newState;
  526. this.dispatchEvent({type: 'readystatechange'});
  527. if (newState === this.DONE) {
  528. if (this._aborted) {
  529. this.dispatchEvent({type: 'abort'});
  530. } else if (this._hasError) {
  531. if (this._timedOut) {
  532. this.dispatchEvent({type: 'timeout'});
  533. } else {
  534. this.dispatchEvent({type: 'error'});
  535. }
  536. } else {
  537. this.dispatchEvent({type: 'load'});
  538. }
  539. this.dispatchEvent({type: 'loadend'});
  540. }
  541. }
  542. /* global EventListener */
  543. addEventListener(type: string, listener: EventListener): void {
  544. // If we dont' have a 'readystatechange' event handler, we don't
  545. // have to send repeated LOADING events with incremental updates
  546. // to responseText, which will avoid a bunch of native -> JS
  547. // bridge traffic.
  548. if (type === 'readystatechange' || type === 'progress') {
  549. this._incrementalEvents = true;
  550. }
  551. super.addEventListener(type, listener);
  552. }
  553. }
  554. module.exports = XMLHttpRequest;