You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-request-runtime.js

169 lines
7.9 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

(function (global) {
'use strict';
function mutationId(cryptoImpl) {
return cryptoImpl && typeof cryptoImpl.randomUUID === 'function'
? cryptoImpl.randomUUID()
: 'admin-' + Date.now() + '-' + Math.random().toString(36).slice(2)
+ '-' + Math.random().toString(36).slice(2);
}
function messageFromPayload(payload, status) {
var detail = Array.isArray(payload && payload.detail)
? payload.detail.map(function (item) { return item && item.msg ? item.msg : '输入错误'; }).join(';')
: payload && payload.detail;
return typeof detail === 'string' && detail
? detail : String(payload && (payload.message || payload.error || payload.msg)
|| '请求失败 (' + status + ')');
}
function createError(message, properties) {
var error = new Error(message);
Object.keys(properties || {}).forEach(function (key) { error[key] = properties[key]; });
return error;
}
function isLocalLocation(locationImpl) {
return locationImpl && ['localhost', '127.0.0.1', '[::1]'].indexOf(locationImpl.hostname) !== -1;
}
function create(options) {
var config = options && typeof options === 'object' ? options : {};
var fetchImpl = config.fetchImpl || (global.fetch && global.fetch.bind(global));
var locationImpl = config.locationImpl || global.location;
var cryptoImpl = config.cryptoImpl || global.crypto;
var csrfToken = typeof config.csrfToken === 'function'
? config.csrfToken : function () { return global.ADMIN_CSRF_TOKEN || ''; };
var taskReceiptValidator = typeof config.taskReceiptValidator === 'function'
? config.taskReceiptValidator : null;
var setTimer = config.setTimeoutImpl || global.setTimeout.bind(global);
var clearTimer = config.clearTimeoutImpl || global.clearTimeout.bind(global);
var AbortControllerImpl = config.AbortControllerImpl || global.AbortController;
if (typeof fetchImpl !== 'function') throw new TypeError('fetch is unavailable');
if (typeof AbortControllerImpl !== 'function') throw new TypeError('AbortController is unavailable');
async function execute(path, input, mutation) {
var request = input && typeof input === 'object' ? input : {};
var method = String(request.method || (mutation ? 'POST' : 'GET')).toUpperCase();
var allowed = mutation
? ['POST', 'PUT', 'PATCH', 'DELETE'] : ['GET', 'HEAD'];
if (allowed.indexOf(method) === -1) {
throw new TypeError(mutation
? 'mutation method must be POST, PUT, PATCH or DELETE'
: 'read method must be GET or HEAD');
}
var timeoutMs = Math.max(1000, Number(request.timeoutMs) || (mutation ? 30000 : 15000));
var responseKind = mutation ? String(request.response || 'json') : 'json';
if (mutation && responseKind !== 'json' && responseKind !== 'task') {
throw new TypeError('mutation response must be json or task');
}
if (mutation && locationImpl && locationImpl.protocol !== 'https:' && !isLocalLocation(locationImpl)) {
throw createError('请通过 HTTPS 执行管理员修改操作。', {
code: 'https_required', mutationMayHaveApplied: false, safeToRetry: true,
});
}
var token = mutation ? String(csrfToken() || '') : '';
if (mutation && !/^[a-f0-9]{64}$/.test(token)) {
throw createError('页面安全令牌缺失,请刷新页面。', {
code: 'csrf_missing', mutationMayHaveApplied: false, safeToRetry: true,
});
}
var controller = new AbortControllerImpl();
var externalSignal = request.signal;
var externallyAborted = externalSignal && externalSignal.aborted;
if (externallyAborted) {
throw createError('请求已取消。', {
code: 'cancelled', mutationMayHaveApplied: false, safeToRetry: true,
});
}
var forwardAbort = function () { controller.abort(externalSignal.reason || 'cancelled'); };
if (externalSignal && typeof externalSignal.addEventListener === 'function') {
externalSignal.addEventListener('abort', forwardAbort, { once: true });
if (externalSignal.aborted) forwardAbort();
}
var timeout = setTimer(function () { controller.abort('timeout'); }, timeoutMs);
var headers = new Headers({ Accept: 'application/json' });
Object.keys(request.headers || {}).forEach(function (key) { headers.set(key, request.headers[key]); });
var idempotencyKey = '';
if (mutation) {
idempotencyKey = String(request.idempotencyKey || mutationId(cryptoImpl));
headers.set('X-Admin-CSRF-Token', token);
headers.set('Idempotency-Key', idempotencyKey);
if (request.body !== undefined) headers.set('Content-Type', 'application/json');
}
var dispatched = false;
try {
dispatched = true;
var response = await fetchImpl(path, {
method: method,
headers: headers,
credentials: 'same-origin',
cache: 'no-store',
signal: controller.signal,
body: request.body === undefined ? undefined : JSON.stringify(request.body),
});
var payload = null;
if (response.status !== 204) {
try { payload = await response.json(); }
catch (error) {
throw createError('服务返回了无效数据。', {
code: 'invalid_json', status: response.status,
mutationMayHaveApplied: mutation, safeToRetry: !mutation,
idempotencyKey: idempotencyKey,
});
}
}
if (!response.ok || (payload && payload.ret === 0)) {
var uncertain = mutation && (response.status >= 500 || response.status === 408);
throw createError(messageFromPayload(payload, response.status), {
code: response.status === 401 ? 'unauthorized' : 'http_error',
status: response.status,
mutationMayHaveApplied: uncertain,
safeToRetry: !uncertain,
idempotencyKey: idempotencyKey,
});
}
if (mutation && responseKind === 'task') {
if (response.status !== 202 || !taskReceiptValidator || !taskReceiptValidator(payload)) {
throw createError('请求已送达,但任务回执协议无效。请勿重复提交,并联系管理员核查。', {
code: 'invalid_task_receipt', status: response.status,
mutationMayHaveApplied: true, safeToRetry: false,
idempotencyKey: idempotencyKey,
});
}
}
return request.returnMeta === true
? Object.freeze({ payload: payload, status: response.status }) : payload;
} catch (error) {
if (error && Object.prototype.hasOwnProperty.call(error, 'mutationMayHaveApplied')) throw error;
var reason = controller.signal.reason;
if (!mutation) {
if (reason === 'timeout') throw createError('请求超时,请稍后重试。', { code: 'timeout', safeToRetry: true });
throw error;
}
throw createError(reason === 'timeout'
? '请求超时,操作结果无法确认。请勿重复提交,并联系管理员核查。'
: '请求连接中断,操作结果无法确认。请勿重复提交,并联系管理员核查。', {
code: reason === 'timeout' ? 'timeout' : 'transport_error',
mutationMayHaveApplied: dispatched,
safeToRetry: !dispatched,
idempotencyKey: idempotencyKey,
cause: error,
});
} finally {
clearTimer(timeout);
if (externalSignal && typeof externalSignal.removeEventListener === 'function') {
externalSignal.removeEventListener('abort', forwardAbort);
}
}
}
return Object.freeze({
read: function (path, options) { return execute(path, options, false); },
mutate: function (path, options) { return execute(path, options, true); },
});
}
global.VenixAdminRequestRuntime = Object.freeze({ create: create });
}(typeof window !== 'undefined' ? window : globalThis));