GT2/GT2-Android/node_modules/xdl/build/Api.js

360 lines
12 KiB
JavaScript

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
let _callMethodAsync = (() => {
var _ref = _asyncToGenerator(function* (url, method, requestBody, requestOptions) {
const clientId = yield (_Session || _load_Session()).clientIdAsync();
const user = (yield (_User || _load_User()).default.getCurrentUserAsync()) || {};
const { idToken, accessToken } = user;
const skipValidationToken = process.env['EXPO_SKIP_MANIFEST_VALIDATION_TOKEN'];
let headers = {
'Exp-ClientId': clientId
};
if (skipValidationToken) {
headers['Exp-Skip-Manifest-Validation-Token'] = skipValidationToken;
}
if (idToken) {
headers['Authorization'] = `Bearer ${idToken}`;
}
if (accessToken) {
headers['Exp-Access-Token'] = accessToken;
}
let options = {
url,
method: method || 'get',
headers
};
if (requestBody) {
options = _extends({}, options, {
data: requestBody
});
}
if (requestOptions) {
if (requestOptions.formData) {
let data = requestOptions.formData;
if ((0, (_EnvironmentHelper || _load_EnvironmentHelper()).isNode)()) {
let convertedFormData = yield _convertFormDataToBuffer(requestOptions.formData);
data = convertedFormData.data;
options.headers = _extends({}, options.headers, requestOptions.formData.getHeaders());
}
options = _extends({}, options, { data });
} else {
options = _extends({}, options, requestOptions);
}
}
let response = yield (_axios || _load_axios()).default.request(options);
if (!response) {
throw new Error('Unexpected error: Request failed.');
}
let responseBody = response.data;
var responseObj;
if ((_lodash || _load_lodash()).default.isString(responseBody)) {
try {
responseObj = JSON.parse(responseBody);
} catch (e) {
throw new (_XDLError || _load_XDLError()).default((_ErrorCode || _load_ErrorCode()).default.INVALID_JSON, 'Invalid JSON returned from API: ' + e + '. Response body: ' + responseBody);
}
} else {
responseObj = responseBody;
}
if (responseObj.err) {
let err = ApiError(responseObj.code || 'API_ERROR', 'API Response Error: ' + responseObj.err);
// $FlowFixMe can't add arbitrary properties to error
err.serverError = responseObj.err;
throw err;
} else {
return responseObj;
}
});
return function _callMethodAsync(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
})();
let _convertFormDataToBuffer = (() => {
var _ref2 = _asyncToGenerator(function* (formData) {
return new Promise(function (resolve) {
formData.pipe((0, (_concatStream || _load_concatStream()).default)({ encoding: 'buffer' }, function (data) {
return resolve({ data });
}));
});
});
return function _convertFormDataToBuffer(_x5) {
return _ref2.apply(this, arguments);
};
})();
let _downloadAsync = (() => {
var _ref3 = _asyncToGenerator(function* (url, outputPath, progressFunction, retryFunction) {
let promptShown = false;
let currentProgress = 0;
let warningTimer = setTimeout(function () {
if (retryFunction) {
retryFunction();
}
promptShown = true;
}, TIMER_DURATION);
let config;
// Checks if the call is being made in XDE or exp. (If XDE = XHR, if exp = HTTP);
if (!(0, (_EnvironmentHelper || _load_EnvironmentHelper()).isNode)()) {
config = {
timeout: TIMEOUT,
responseType: 'arraybuffer',
onDownloadProgress: function (progressEvent) {
const roundedProgress = Math.floor(progressEvent.loaded / progressEvent.total * 100);
if (currentProgress !== roundedProgress) {
currentProgress = roundedProgress;
clearTimeout(warningTimer);
if (!promptShown) {
warningTimer = setTimeout(function () {
if (retryFunction) {
retryFunction();
}
promptShown = true;
}, TIMER_DURATION);
}
}
if (progressFunction) {
progressFunction(roundedProgress);
}
}
};
let response = yield (0, (_axios || _load_axios()).default)(url, config);
yield (_fsExtra || _load_fsExtra()).default.writeFile(outputPath, Buffer.from(response.data));
clearTimeout(warningTimer);
} else {
const tmpPath = `${outputPath}.download`;
config = {
timeout: TIMEOUT,
responseType: 'stream'
};
let response = yield (0, (_axios || _load_axios()).default)(url, config);
yield new Promise(function (resolve) {
let totalDownloadSize = response.data.headers['content-length'];
let downloadProgress = 0;
response.data.on('data', function (chunk) {
downloadProgress += chunk.length;
const roundedProgress = Math.floor(downloadProgress / totalDownloadSize * 100);
if (currentProgress !== roundedProgress) {
currentProgress = roundedProgress;
clearTimeout(warningTimer);
if (!promptShown) {
warningTimer = setTimeout(function () {
if (retryFunction) {
retryFunction();
}
promptShown = true;
}, TIMER_DURATION);
}
if (progressFunction) {
progressFunction(roundedProgress);
}
}
}).on('end', function () {
clearTimeout(warningTimer);
if (progressFunction && currentProgress !== 100) {
progressFunction(100);
}
resolve();
}).pipe((_fsExtra || _load_fsExtra()).default.createWriteStream(tmpPath));
});
yield (_fsExtra || _load_fsExtra()).default.rename(tmpPath, outputPath);
}
});
return function _downloadAsync(_x6, _x7, _x8, _x9) {
return _ref3.apply(this, arguments);
};
})();
var _lodash;
function _load_lodash() {
return _lodash = _interopRequireDefault(require('lodash'));
}
var _fsExtra;
function _load_fsExtra() {
return _fsExtra = _interopRequireDefault(require('fs-extra'));
}
var _rimraf;
function _load_rimraf() {
return _rimraf = _interopRequireDefault(require('rimraf'));
}
var _path = _interopRequireDefault(require('path'));
var _axios;
function _load_axios() {
return _axios = _interopRequireDefault(require('axios'));
}
var _concatStream;
function _load_concatStream() {
return _concatStream = _interopRequireDefault(require('concat-stream'));
}
var _FsCache;
function _load_FsCache() {
return _FsCache = require('./tools/FsCache');
}
var _Config;
function _load_Config() {
return _Config = _interopRequireDefault(require('./Config'));
}
var _EnvironmentHelper;
function _load_EnvironmentHelper() {
return _EnvironmentHelper = require('./tools/EnvironmentHelper');
}
var _ErrorCode;
function _load_ErrorCode() {
return _ErrorCode = _interopRequireDefault(require('./ErrorCode'));
}
var _Extract;
function _load_Extract() {
return _Extract = _interopRequireWildcard(require('./Extract'));
}
var _Session;
function _load_Session() {
return _Session = _interopRequireWildcard(require('./Session'));
}
var _User;
function _load_User() {
return _User = _interopRequireDefault(require('./User'));
}
var _UserSettings;
function _load_UserSettings() {
return _UserSettings = _interopRequireDefault(require('./UserSettings'));
}
var _XDLError;
function _load_XDLError() {
return _XDLError = _interopRequireDefault(require('./XDLError'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const TIMER_DURATION = 30000;
const TIMEOUT = 3600000;
function ApiError(code, message) {
let err = new Error(message);
// $FlowFixMe error has no property code
err.code = code;
// $FlowFixMe error has no property _isApiError
err._isApiError = true;
return err;
}
let ROOT_BASE_URL = `${(_Config || _load_Config()).default.api.scheme}://${(_Config || _load_Config()).default.api.host}`;
if ((_Config || _load_Config()).default.api.port) {
ROOT_BASE_URL += ':' + (_Config || _load_Config()).default.api.port;
}
let API_BASE_URL = ROOT_BASE_URL + '/--/api/';
class ApiClient {
static callMethodAsync(methodName, args, method, requestBody, requestOptions = {}) {
return _asyncToGenerator(function* () {
let url = API_BASE_URL + encodeURIComponent(methodName) + '/' + encodeURIComponent(JSON.stringify(args));
return _callMethodAsync(url, method, requestBody, requestOptions);
})();
}
static callPathAsync(path, method, requestBody, requestOptions = {}) {
return _asyncToGenerator(function* () {
let url = ROOT_BASE_URL + path;
return _callMethodAsync(url, method, requestBody, requestOptions);
})();
}
static versionsAsync() {
return _asyncToGenerator(function* () {
return yield ApiClient._versionCache.getAsync();
})();
}
static xdlSchemaAsync(sdkVersion) {
return _asyncToGenerator(function* () {
if (!ApiClient._schemaCaches.hasOwnProperty(sdkVersion)) {
ApiClient._schemaCaches[sdkVersion] = new (_FsCache || _load_FsCache()).Cacher(_asyncToGenerator(function* () {
return yield ApiClient.callPathAsync(`/--/xdl-schema/${sdkVersion}`);
}), `schema-${sdkVersion}.json`, 0, _path.default.join(__dirname, `../caches/schema-${sdkVersion}.json`));
}
return yield ApiClient._schemaCaches[sdkVersion].getAsync();
})();
}
static sdkVersionsAsync() {
return _asyncToGenerator(function* () {
let versions = yield ApiClient.versionsAsync();
return versions.sdkVersions;
})();
}
static downloadAsync(url, outputPath, options = {}, progressFunction, retryFunction) {
return _asyncToGenerator(function* () {
if (options.extract) {
let dotExpoHomeDirectory = (_UserSettings || _load_UserSettings()).default.dotExpoHomeDirectory();
let tmpPath = _path.default.join(dotExpoHomeDirectory, 'tmp-download-file');
yield _downloadAsync(url, tmpPath);
yield (_Extract || _load_Extract()).extractAsync(tmpPath, outputPath);
(_rimraf || _load_rimraf()).default.sync(tmpPath);
} else {
yield _downloadAsync(url, outputPath, progressFunction, retryFunction);
}
})();
}
}
exports.default = ApiClient;
ApiClient.host = (_Config || _load_Config()).default.api.host;
ApiClient.port = (_Config || _load_Config()).default.api.port || 80;
ApiClient._versionCache = new (_FsCache || _load_FsCache()).Cacher(_asyncToGenerator(function* () {
return yield ApiClient.callPathAsync('/--/versions');
}), 'versions.json', 0, _path.default.join(__dirname, '../caches/versions.json'));
ApiClient._schemaCaches = {};
//# sourceMappingURL=__sourcemaps__/Api.js.map