UNPKG

@amplitude/analytics-browser

Version:
61 lines 3.03 kB
import { __assign, __awaiter, __extends, __generator, __read, __values } from "tslib"; import { BaseTransport } from '@amplitude/analytics-core'; var XHRTransport = /** @class */ (function (_super) { __extends(XHRTransport, _super); function XHRTransport(customHeaders) { if (customHeaders === void 0) { customHeaders = {}; } var _this = _super.call(this) || this; _this.state = { done: 4, }; _this.customHeaders = customHeaders; return _this; } XHRTransport.prototype.send = function (serverUrl, payload) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve, reject) { var e_1, _a; /* istanbul ignore if */ if (typeof XMLHttpRequest === 'undefined') { reject(new Error('XHRTransport is not supported.')); } var xhr = new XMLHttpRequest(); xhr.open('POST', serverUrl, true); xhr.onreadystatechange = function () { if (xhr.readyState === _this.state.done) { var responseText = xhr.responseText; try { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument resolve(_this.buildResponse(JSON.parse(responseText))); } catch (_a) { resolve(_this.buildResponse({ code: xhr.status })); } } }; // Merge headers: custom headers override defaults (consistent with FetchTransport) var headers = __assign({ 'Content-Type': 'application/json', Accept: '*/*' }, _this.customHeaders); try { for (var _b = __values(Object.entries(headers)), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = __read(_c.value, 2), key = _d[0], value = _d[1]; xhr.setRequestHeader(key, value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } xhr.send(JSON.stringify(payload)); })]; }); }); }; return XHRTransport; }(BaseTransport)); export { XHRTransport }; //# sourceMappingURL=xhr.js.map