UNPKG

52.9 kBSource Map (JSON)View Raw
1{"version":3,"sources":["../src/http-api.js"],"names":["parseContentType","require","parse","utils","callbacks","module","exports","PREFIX_R0","PREFIX_UNSTABLE","PREFIX_IDENTITY_V1","PREFIX_MEDIA_R0","MatrixHttpApi","event_emitter","opts","checkObjectHasKeys","onlyData","useAuthorizationHeader","Boolean","uploads","prototype","getContentUri","params","access_token","accessToken","base","baseUrl","path","uploadContent","file","isFunction","callback","undefined","includeFilename","contentType","type","fileName","name","body","stream","rawResponse","global","XMLHttpRequest","console","warn","onlyContentUri","upload","loaded","total","promise","bodyParser","rawBody","JSON","content_uri","Error","defer","Promise","xhr","cb","requestCallback","timeout_fn","abort","timeout_timer","setTimeout","onreadystatechange","readyState","DONE","clearTimeout","resp","responseText","err","http_status","status","addEventListener","ev","progressHandler","url","queryArgs","push","encodeURIComponent","length","join","open","setRequestHeader","send","bind","queryParams","filename","authedRequest","prefix","headers","json","self","promise0","finally","i","splice","cancelUpload","getCurrentUploads","idServerRequest","method","fullUri","idBaseUrl","uri","withCredentials","_matrix_opts","qs","form","request","then","response","data","isFinite","localTimeoutMs","Authorization","requestPromise","catch","errcode","emit","message","consent_uri","requestOtherUrl","authedRequestWithPrefix","requestWithPrefix","_request","getUrl","queryString","encodeParams","extraParams","key","hasOwnProperty","extend","timeoutId","timedOut","req","resetTimeout","reject","MatrixError","error","timeout","reqPromise","qsStringifyOptions","useQuerystring","handlerFn","onprogress","e","ex","userDefinedCallback","statusCode","parseErrorResponse","res","code","resolve","httpStatus","getResponseContentType","getResponseHeader","errorJson","constructor"],"mappings":"AAAA;;;;;;;;;;;;;;;AAeA;AACA;;;;;;;;;;;;;;;;;AAIA;;;;;;AACA,IAAMA,mBAAmBC,QAAQ,cAAR,EAAwBC,KAAjD;;AAEA,IAAMC,QAAQF,QAAQ,SAAR,CAAd;;AAEA;AACA;AACA;AACA,IAAMG,YAAYH,QAAQ,sBAAR,CAAlB;;AAEA;;;;;;AAMA;;;AAGAI,OAAOC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Af,CAA2BrH,SAA3B,CAAqCyI,WAArC,GAAmDvJ,OAAOC,OAAP,CAAekI,WAAlE","file":"http-api.js","sourcesContent":["/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n * @module http-api\n */\nimport Promise from 'bluebird';\nconst parseContentType = require('content-type').parse;\n\nconst utils = require(\"./utils\");\n\n// we use our own implementation of setTimeout, so that if we get suspended in\n// the middle of a /sync, we cancel the sync as soon as we awake, rather than\n// waiting for the delay to elapse.\nconst callbacks = require(\"./realtime-callbacks\");\n\n/*\nTODO:\n- CS: complete register function (doing stages)\n- Identity server: linkEmail, authEmail, bindEmail, lookup3pid\n*/\n\n/**\n * A constant representing the URI path for release 0 of the Client-Server HTTP API.\n */\nmodule.exports.PREFIX_R0 = \"/_matrix/client/r0\";\n\n/**\n * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n */\nmodule.exports.PREFIX_UNSTABLE = \"/_matrix/client/unstable\";\n\n/**\n * URI path for the identity API\n */\nmodule.exports.PREFIX_IDENTITY_V1 = \"/_matrix/identity/api/v1\";\n\n/**\n * URI path for the media repo API\n */\nmodule.exports.PREFIX_MEDIA_R0 = \"/_matrix/media/r0\";\n\n/**\n * Construct a MatrixHttpApi.\n * @constructor\n * @param {EventEmitter} event_emitter The event emitter to use for emitting events\n * @param {Object} opts The options to use for this HTTP API.\n * @param {string} opts.baseUrl Required. The base client-server URL e.g.\n * 'http://localhost:8008'.\n * @param {Function} opts.request Required. The function to call for HTTP\n * requests. This function must look like function(opts, callback){ ... }.\n * @param {string} opts.prefix Required. The matrix client prefix to use, e.g.\n * '/_matrix/client/r0'. See PREFIX_R0 and PREFIX_UNSTABLE for constants.\n *\n * @param {boolean} opts.onlyData True to return only the 'data' component of the\n * response (e.g. the parsed HTTP body). If false, requests will return an\n * object with the properties <tt>code</tt>, <tt>headers</tt> and <tt>data</tt>.\n *\n * @param {string} opts.accessToken The access_token to send with requests. Can be\n * null to not send an access token.\n * @param {Object=} opts.extraParams Optional. Extra query parameters to send on\n * requests.\n * @param {Number=} opts.localTimeoutMs The default maximum amount of time to wait\n * before timing out the request. If not specified, there is no timeout.\n * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use\n * Authorization header instead of query param to send the access token to the server.\n */\nmodule.exports.MatrixHttpApi = function MatrixHttpApi(event_emitter, opts) {\n utils.checkObjectHasKeys(opts, [\"baseUrl\", \"request\", \"prefix\"]);\n opts.onlyData = opts.onlyData || false;\n this.event_emitter = event_emitter;\n this.opts = opts;\n this.useAuthorizationHeader = Boolean(opts.useAuthorizationHeader);\n this.uploads = [];\n};\n\nmodule.exports.MatrixHttpApi.prototype = {\n\n /**\n * Get the content repository url with query parameters.\n * @return {Object} An object with a 'base', 'path' and 'params' for base URL,\n * path and query parameters respectively.\n */\n getContentUri: function() {\n const params = {\n access_token: this.opts.accessToken,\n };\n return {\n base: this.opts.baseUrl,\n path: \"/_matrix/media/v1/upload\",\n params: params,\n };\n },\n\n /**\n * Upload content to the Home Server\n *\n * @param {object} file The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a Buffer, String or ReadStream.\n *\n * @param {object} opts options object\n *\n * @param {string=} opts.name Name to give the file on the server. Defaults\n * to <tt>file.name</tt>.\n *\n * @param {boolean=} opts.includeFilename if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n *\n * @param {string=} opts.type Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n *\n * @param {boolean=} opts.rawResponse Return the raw body, rather than\n * parsing the JSON. Defaults to false (except on node.js, where it\n * defaults to true for backwards compatibility).\n *\n * @param {boolean=} opts.onlyContentUri Just return the content URI,\n * rather than the whole body. Defaults to false (except on browsers,\n * where it defaults to true for backwards compatibility). Ignored if\n * opts.rawResponse is true.\n *\n * @param {Function=} opts.callback Deprecated. Optional. The callback to\n * invoke on success/failure. See the promise return values for more\n * information.\n *\n * @param {Function=} opts.progressHandler Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n *\n * @return {module:client.Promise} Resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n uploadContent: function(file, opts) {\n if (utils.isFunction(opts)) {\n // opts used to be callback\n opts = {\n callback: opts,\n };\n } else if (opts === undefined) {\n opts = {};\n }\n\n // default opts.includeFilename to true (ignoring falsey values)\n const includeFilename = opts.includeFilename !== false;\n\n // if the file doesn't have a mime type, use a default since\n // the HS errors if we don't supply one.\n const contentType = opts.type || file.type || 'application/octet-stream';\n const fileName = opts.name || file.name;\n\n // we used to recommend setting file.stream to the thing to upload on\n // nodejs.\n const body = file.stream ? file.stream : file;\n\n // backwards-compatibility hacks where we used to do different things\n // between browser and node.\n let rawResponse = opts.rawResponse;\n if (rawResponse === undefined) {\n if (global.XMLHttpRequest) {\n rawResponse = false;\n } else {\n console.warn(\n \"Returning the raw JSON from uploadContent(). Future \" +\n \"versions of the js-sdk will change this default, to \" +\n \"return the parsed object. Set opts.rawResponse=false \" +\n \"to change this behaviour now.\",\n );\n rawResponse = true;\n }\n }\n\n let onlyContentUri = opts.onlyContentUri;\n if (!rawResponse && onlyContentUri === undefined) {\n if (global.XMLHttpRequest) {\n console.warn(\n \"Returning only the content-uri from uploadContent(). \" +\n \"Future versions of the js-sdk will change this \" +\n \"default, to return the whole response object. Set \" +\n \"opts.onlyContentUri=false to change this behaviour now.\",\n );\n onlyContentUri = true;\n } else {\n onlyContentUri = false;\n }\n }\n\n // browser-request doesn't support File objects because it deep-copies\n // the options using JSON.parse(JSON.stringify(options)). Instead of\n // loading the whole file into memory as a string and letting\n // browser-request base64 encode and then decode it again, we just\n // use XMLHttpRequest directly.\n // (browser-request doesn't support progress either, which is also kind\n // of important here)\n\n const upload = { loaded: 0, total: 0 };\n let promise;\n\n // XMLHttpRequest doesn't parse JSON for us. request normally does, but\n // we're setting opts.json=false so that it doesn't JSON-encode the\n // request, which also means it doesn't JSON-decode the response. Either\n // way, we have to JSON-parse the response ourselves.\n let bodyParser = null;\n if (!rawResponse) {\n bodyParser = function(rawBody) {\n let body = JSON.parse(rawBody);\n if (onlyContentUri) {\n body = body.content_uri;\n if (body === undefined) {\n throw Error('Bad response');\n }\n }\n return body;\n };\n }\n\n if (global.XMLHttpRequest) {\n const defer = Promise.defer();\n const xhr = new global.XMLHttpRequest();\n upload.xhr = xhr;\n const cb = requestCallback(defer, opts.callback, this.opts.onlyData);\n\n const timeout_fn = function() {\n xhr.abort();\n cb(new Error('Timeout'));\n };\n\n // set an initial timeout of 30s; we'll advance it each time we get\n // a progress notification\n xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);\n\n xhr.onreadystatechange = function() {\n switch (xhr.readyState) {\n case global.XMLHttpRequest.DONE:\n callbacks.clearTimeout(xhr.timeout_timer);\n var resp;\n try {\n if (!xhr.responseText) {\n throw new Error('No response body.');\n }\n resp = xhr.responseText;\n if (bodyParser) {\n resp = bodyParser(resp);\n }\n } catch (err) {\n err.http_status = xhr.status;\n cb(err);\n return;\n }\n cb(undefined, xhr, resp);\n break;\n }\n };\n xhr.upload.addEventListener(\"progress\", function(ev) {\n callbacks.clearTimeout(xhr.timeout_timer);\n upload.loaded = ev.loaded;\n upload.total = ev.total;\n xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);\n if (opts.progressHandler) {\n opts.progressHandler({\n loaded: ev.loaded,\n total: ev.total,\n });\n }\n });\n let url = this.opts.baseUrl + \"/_matrix/media/v1/upload\";\n\n const queryArgs = [];\n\n if (includeFilename && fileName) {\n queryArgs.push(\"filename=\" + encodeURIComponent(fileName));\n }\n\n if (!this.useAuthorizationHeader) {\n queryArgs.push(\"access_token=\"\n + encodeURIComponent(this.opts.accessToken));\n }\n\n if (queryArgs.length > 0) {\n url += \"?\" + queryArgs.join(\"&\");\n }\n\n xhr.open(\"POST\", url);\n if (this.useAuthorizationHeader) {\n xhr.setRequestHeader(\"Authorization\", \"Bearer \" + this.opts.accessToken);\n }\n xhr.setRequestHeader(\"Content-Type\", contentType);\n xhr.send(body);\n promise = defer.promise;\n\n // dirty hack (as per _request) to allow the upload to be cancelled.\n promise.abort = xhr.abort.bind(xhr);\n } else {\n const queryParams = {};\n\n if (includeFilename && fileName) {\n queryParams.filename = fileName;\n }\n\n promise = this.authedRequest(\n opts.callback, \"POST\", \"/upload\", queryParams, body, {\n prefix: \"/_matrix/media/v1\",\n headers: {\"Content-Type\": contentType},\n json: false,\n bodyParser: bodyParser,\n },\n );\n }\n\n const self = this;\n\n // remove the upload from the list on completion\n const promise0 = promise.finally(function() {\n for (let i = 0; i < self.uploads.length; ++i) {\n if (self.uploads[i] === upload) {\n self.uploads.splice(i, 1);\n return;\n }\n }\n });\n\n // copy our dirty abort() method to the new promise\n promise0.abort = promise.abort;\n\n upload.promise = promise0;\n this.uploads.push(upload);\n\n return promise0;\n },\n\n cancelUpload: function(promise) {\n if (promise.abort) {\n promise.abort();\n return true;\n }\n return false;\n },\n\n getCurrentUploads: function() {\n return this.uploads;\n },\n\n idServerRequest: function(callback, method, path, params, prefix) {\n const fullUri = this.opts.idBaseUrl + prefix + path;\n\n if (callback !== undefined && !utils.isFunction(callback)) {\n throw Error(\n \"Expected callback to be a function but got \" + typeof callback,\n );\n }\n\n const opts = {\n uri: fullUri,\n method: method,\n withCredentials: false,\n json: false,\n _matrix_opts: this.opts,\n };\n if (method == 'GET') {\n opts.qs = params;\n } else {\n opts.form = params;\n }\n\n const defer = Promise.defer();\n this.opts.request(\n opts,\n requestCallback(defer, callback, this.opts.onlyData),\n );\n // ID server does not always take JSON, so we can't use requests' 'json'\n // option as we do with the home server, but it does return JSON, so\n // parse it manually\n return defer.promise.then(function(response) {\n return JSON.parse(response);\n });\n },\n\n /**\n * Perform an authorised request to the homeserver.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param {Object=} queryParams A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param {Object} data The HTTP JSON body.\n *\n * @param {Object|Number=} opts additional options. If a number is specified,\n * this is treated as `opts.localTimeoutMs`.\n *\n * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n *\n * @param {sting=} opts.prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n *\n * @param {Object=} opts.headers map of additional request headers\n *\n * @return {module:client.Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n authedRequest: function(callback, method, path, queryParams, data, opts) {\n if (!queryParams) {\n queryParams = {};\n }\n if (this.useAuthorizationHeader) {\n if (isFinite(opts)) {\n // opts used to be localTimeoutMs\n opts = {\n localTimeoutMs: opts,\n };\n }\n if (!opts) {\n opts = {};\n }\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = \"Bearer \" + this.opts.accessToken;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else {\n if (!queryParams.access_token) {\n queryParams.access_token = this.opts.accessToken;\n }\n }\n\n const requestPromise = this.request(\n callback, method, path, queryParams, data, opts,\n );\n\n const self = this;\n requestPromise.catch(function(err) {\n if (err.errcode == 'M_UNKNOWN_TOKEN') {\n self.event_emitter.emit(\"Session.logged_out\");\n } else if (err.errcode == 'M_CONSENT_NOT_GIVEN') {\n self.event_emitter.emit(\n \"no_consent\",\n err.message,\n err.data.consent_uri,\n );\n }\n });\n\n // return the original promise, otherwise tests break due to it having to\n // go around the event loop one more time to process the result of the request\n return requestPromise;\n },\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param {Object=} queryParams A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param {Object} data The HTTP JSON body.\n *\n * @param {Object=} opts additional options\n *\n * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n *\n * @param {sting=} opts.prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n *\n * @param {Object=} opts.headers map of additional request headers\n *\n * @return {module:client.Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n request: function(callback, method, path, queryParams, data, opts) {\n opts = opts || {};\n const prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix;\n const fullUri = this.opts.baseUrl + prefix + path;\n\n return this.requestOtherUrl(\n callback, method, fullUri, queryParams, data, opts,\n );\n },\n\n /**\n * Perform an authorised request to the homeserver with a specific path\n * prefix which overrides the default for this call only. Useful for hitting\n * different Matrix Client-Server versions.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n * @param {Object} queryParams A dict of query params (these will NOT be\n * urlencoded).\n * @param {Object} data The HTTP JSON body.\n * @param {string} prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\".\n * @param {Number=} localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n * @return {module:client.Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n *\n * @deprecated prefer authedRequest with opts.prefix\n */\n authedRequestWithPrefix: function(callback, method, path, queryParams, data,\n prefix, localTimeoutMs) {\n return this.authedRequest(\n callback, method, path, queryParams, data, {\n localTimeoutMs: localTimeoutMs,\n prefix: prefix,\n },\n );\n },\n\n /**\n * Perform a request to the homeserver without any credentials but with a\n * specific path prefix which overrides the default for this call only.\n * Useful for hitting different Matrix Client-Server versions.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n * @param {Object} queryParams A dict of query params (these will NOT be\n * urlencoded).\n * @param {Object} data The HTTP JSON body.\n * @param {string} prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\".\n * @param {Number=} localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n * @return {module:client.Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n *\n * @deprecated prefer request with opts.prefix\n */\n requestWithPrefix: function(callback, method, path, queryParams, data, prefix,\n localTimeoutMs) {\n return this.request(\n callback, method, path, queryParams, data, {\n localTimeoutMs: localTimeoutMs,\n prefix: prefix,\n },\n );\n },\n\n /**\n * Perform a request to an arbitrary URL.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} uri The HTTP URI\n *\n * @param {Object=} queryParams A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param {Object} data The HTTP JSON body.\n *\n * @param {Object=} opts additional options\n *\n * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n *\n * @param {sting=} opts.prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n *\n * @param {Object=} opts.headers map of additional request headers\n *\n * @return {module:client.Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n requestOtherUrl: function(callback, method, uri, queryParams, data,\n opts) {\n if (opts === undefined || opts === null) {\n opts = {};\n } else if (isFinite(opts)) {\n // opts used to be localTimeoutMs\n opts = {\n localTimeoutMs: opts,\n };\n }\n\n return this._request(\n callback, method, uri, queryParams, data, opts,\n );\n },\n\n /**\n * Form and return a homeserver request URL based on the given path\n * params and prefix.\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n * @param {Object} queryParams A dict of query params (these will NOT be\n * urlencoded).\n * @param {string} prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\".\n * @return {string} URL\n */\n getUrl: function(path, queryParams, prefix) {\n let queryString = \"\";\n if (queryParams) {\n queryString = \"?\" + utils.encodeParams(queryParams);\n }\n return this.opts.baseUrl + prefix + path + queryString;\n },\n\n /**\n * @private\n *\n * @param {function} callback\n * @param {string} method\n * @param {string} uri\n * @param {object} queryParams\n * @param {object|string} data\n * @param {object=} opts\n *\n * @param {boolean} [opts.json =true] Json-encode data before sending, and\n * decode response on receipt. (We will still json-decode error\n * responses, even if this is false.)\n *\n * @param {object=} opts.headers extra request headers\n *\n * @param {number=} opts.localTimeoutMs client-side timeout for the\n * request. Default timeout if falsy.\n *\n * @param {function=} opts.bodyParser function to parse the body of the\n * response before passing it to the promise and callback.\n *\n * @return {module:client.Promise} a promise which resolves to either the\n * response object (if this.opts.onlyData is truthy), or the parsed\n * body. Rejects\n */\n _request: function(callback, method, uri, queryParams, data, opts) {\n if (callback !== undefined && !utils.isFunction(callback)) {\n throw Error(\n \"Expected callback to be a function but got \" + typeof callback,\n );\n }\n opts = opts || {};\n\n const self = this;\n if (this.opts.extraParams) {\n for (const key in this.opts.extraParams) {\n if (!this.opts.extraParams.hasOwnProperty(key)) {\n continue;\n }\n queryParams[key] = this.opts.extraParams[key];\n }\n }\n\n const headers = utils.extend({}, opts.headers || {});\n const json = opts.json === undefined ? true : opts.json;\n let bodyParser = opts.bodyParser;\n\n // we handle the json encoding/decoding here, because request and\n // browser-request make a mess of it. Specifically, they attempt to\n // json-decode plain-text error responses, which in turn means that the\n // actual error gets swallowed by a SyntaxError.\n\n if (json) {\n if (data) {\n data = JSON.stringify(data);\n headers['content-type'] = 'application/json';\n }\n\n if (!headers['accept']) {\n headers['accept'] = 'application/json';\n }\n\n if (bodyParser === undefined) {\n bodyParser = function(rawBody) {\n return JSON.parse(rawBody);\n };\n }\n }\n\n const defer = Promise.defer();\n\n let timeoutId;\n let timedOut = false;\n let req;\n const localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs;\n\n const resetTimeout = () => {\n if (localTimeoutMs) {\n if (timeoutId) {\n callbacks.clearTimeout(timeoutId);\n }\n timeoutId = callbacks.setTimeout(function() {\n timedOut = true;\n if (req && req.abort) {\n req.abort();\n }\n defer.reject(new module.exports.MatrixError({\n error: \"Locally timed out waiting for a response\",\n errcode: \"ORG.MATRIX.JSSDK_TIMEOUT\",\n timeout: localTimeoutMs,\n }));\n }, localTimeoutMs);\n }\n };\n resetTimeout();\n\n const reqPromise = defer.promise;\n\n try {\n req = this.opts.request(\n {\n uri: uri,\n method: method,\n withCredentials: false,\n qs: queryParams,\n qsStringifyOptions: opts.qsStringifyOptions,\n useQuerystring: true,\n body: data,\n json: false,\n timeout: localTimeoutMs,\n headers: headers || {},\n _matrix_opts: this.opts,\n },\n function(err, response, body) {\n if (localTimeoutMs) {\n callbacks.clearTimeout(timeoutId);\n if (timedOut) {\n return; // already rejected promise\n }\n }\n\n const handlerFn = requestCallback(\n defer, callback, self.opts.onlyData,\n bodyParser,\n );\n handlerFn(err, response, body);\n },\n );\n if (req) {\n // This will only work in a browser, where opts.request is the\n // `browser-request` import. Currently `request` does not support progress\n // updates - see https://github.com/request/request/pull/2346.\n // `browser-request` returns an XHRHttpRequest which exposes `onprogress`\n if ('onprogress' in req) {\n req.onprogress = (e) => {\n // Prevent the timeout from rejecting the deferred promise if progress is\n // seen with the request\n resetTimeout();\n };\n }\n\n // FIXME: This is EVIL, but I can't think of a better way to expose\n // abort() operations on underlying HTTP requests :(\n if (req.abort) reqPromise.abort = req.abort.bind(req);\n }\n } catch (ex) {\n defer.reject(ex);\n if (callback) {\n callback(ex);\n }\n }\n return reqPromise;\n },\n};\n\n/*\n * Returns a callback that can be invoked by an HTTP request on completion,\n * that will either resolve or reject the given defer as well as invoke the\n * given userDefinedCallback (if any).\n *\n * HTTP errors are transformed into javascript errors and the deferred is rejected.\n *\n * If bodyParser is given, it is used to transform the body of the successful\n * responses before passing to the defer/callback.\n *\n * If onlyData is true, the defer/callback is invoked with the body of the\n * response, otherwise the result object (with `code` and `data` fields)\n *\n */\nconst requestCallback = function(\n defer, userDefinedCallback, onlyData,\n bodyParser,\n) {\n userDefinedCallback = userDefinedCallback || function() {};\n\n return function(err, response, body) {\n if (!err) {\n try {\n if (response.statusCode >= 400) {\n err = parseErrorResponse(response, body);\n } else if (bodyParser) {\n body = bodyParser(body);\n }\n } catch (e) {\n err = new Error(`Error parsing server response: ${e}`);\n }\n }\n\n if (err) {\n defer.reject(err);\n userDefinedCallback(err);\n } else {\n const res = {\n code: response.statusCode,\n\n // XXX: why do we bother with this? it doesn't work for\n // XMLHttpRequest, so clearly we don't use it.\n headers: response.headers,\n data: body,\n };\n defer.resolve(onlyData ? body : res);\n userDefinedCallback(null, onlyData ? body : res);\n }\n };\n};\n\n/**\n * Attempt to turn an HTTP error response into a Javascript Error.\n *\n * If it is a JSON response, we will parse it into a MatrixError. Otherwise\n * we return a generic Error.\n *\n * @param {XMLHttpRequest|http.IncomingMessage} response response object\n * @param {String} body raw body of the response\n * @returns {Error}\n */\nfunction parseErrorResponse(response, body) {\n const httpStatus = response.statusCode;\n const contentType = getResponseContentType(response);\n\n let err;\n if (contentType) {\n if (contentType.type === 'application/json') {\n err = new module.exports.MatrixError(JSON.parse(body));\n } else if (contentType.type === 'text/plain') {\n err = new Error(`Server returned ${httpStatus} error: ${body}`);\n }\n }\n\n if (!err) {\n err = new Error(`Server returned ${httpStatus} error`);\n }\n err.httpStatus = httpStatus;\n return err;\n}\n\n\n/**\n * extract the Content-Type header from the response object, and\n * parse it to a `{type, parameters}` object.\n *\n * returns null if no content-type header could be found.\n *\n * @param {XMLHttpRequest|http.IncomingMessage} response response object\n * @returns {{type: String, parameters: Object}?} parsed content-type header, or null if not found\n */\nfunction getResponseContentType(response) {\n let contentType;\n if (response.getResponseHeader) {\n // XMLHttpRequest provides getResponseHeader\n contentType = response.getResponseHeader(\"Content-Type\");\n } else if (response.headers) {\n // request provides http.IncomingMessage which has a message.headers map\n contentType = response.headers['content-type'] || null;\n }\n\n if (!contentType) {\n return null;\n }\n\n try {\n return parseContentType(contentType);\n } catch(e) {\n throw new Error(`Error parsing Content-Type '${contentType}': ${e}`);\n }\n}\n\n/**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @constructor\n * @param {Object} errorJson The Matrix error JSON returned from the homeserver.\n * @prop {string} errcode The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n * @prop {string} name Same as MatrixError.errcode but with a default unknown string.\n * @prop {string} message The Matrix 'error' value, e.g. \"Missing token.\"\n * @prop {Object} data The raw Matrix error JSON used to construct this object.\n * @prop {integer} httpStatus The numeric HTTP status code given\n */\nmodule.exports.MatrixError = function MatrixError(errorJson) {\n errorJson = errorJson || {};\n this.errcode = errorJson.errcode;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.message = errorJson.error || \"Unknown message\";\n this.data = errorJson;\n};\nmodule.exports.MatrixError.prototype = Object.create(Error.prototype);\n/** */\nmodule.exports.MatrixError.prototype.constructor = module.exports.MatrixError;\n"]}
\No newline at end of file