@alfresco/js-api
Version:
JavaScript client library for the Alfresco REST API
269 lines • 11.4 kB
JavaScript
/*!
* @license
* Copyright © 2005-2025 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuperagentHttpClient = void 0;
const tslib_1 = require("tslib");
const superagent_1 = tslib_1.__importDefault(require("superagent"));
const utils_1 = require("./utils");
const isProgressEvent = (event) => event === null || event === void 0 ? void 0 : event.lengthComputable;
class SuperagentHttpClient {
constructor() {
this.timeout = undefined;
}
post(url, options, securityOptions, emitters) {
return this.request(url, Object.assign(Object.assign({}, options), { httpMethod: 'POST' }), securityOptions, emitters);
}
put(url, options, securityOptions, emitters) {
return this.request(url, Object.assign(Object.assign({}, options), { httpMethod: 'PUT' }), securityOptions, emitters);
}
get(url, options, securityOptions, emitters) {
return this.request(url, Object.assign(Object.assign({}, options), { httpMethod: 'GET' }), securityOptions, emitters);
}
delete(url, options, securityOptions, emitters) {
return this.request(url, Object.assign(Object.assign({}, options), { httpMethod: 'DELETE' }), securityOptions, emitters);
}
request(url, options, securityOptions, emitters) {
const { httpMethod, queryParams, headerParams, formParams, bodyParam, contentType, accept, responseType, returnType } = options;
const { eventEmitter, apiClientEmitter } = emitters;
let request = this.buildRequest(httpMethod, url, queryParams, headerParams, formParams, bodyParam, contentType, accept, responseType, eventEmitter, returnType, securityOptions);
if (returnType === 'Binary') {
request = request.buffer(true).parse(superagent_1.default.parse['application/octet-stream']);
}
const promise = new Promise((resolve, reject) => {
request.on('abort', () => {
eventEmitter.emit('abort');
});
request.end((error, response) => {
if (error) {
apiClientEmitter.emit('error', error);
eventEmitter.emit('error', error);
if (error.status === 401) {
apiClientEmitter.emit('unauthorized');
eventEmitter.emit('unauthorized');
}
if (response === null || response === void 0 ? void 0 : response.text) {
error = error || {};
reject(Object.assign(error, { message: response.text }));
}
else {
reject({ error });
}
}
else {
if (securityOptions.isBpmRequest) {
const hasSetCookie = Object.prototype.hasOwnProperty.call(response.header, 'set-cookie');
if (response.header && hasSetCookie) {
securityOptions.authentications.cookie = response.header['set-cookie'][0];
}
}
let data = {};
if (response.type === 'text/html') {
data = SuperagentHttpClient.deserialize(response);
}
else {
data = SuperagentHttpClient.deserialize(response, returnType);
}
eventEmitter.emit('success', data);
resolve(data);
}
});
});
promise.abort = function () {
request.abort();
return this;
};
return promise;
}
buildRequest(httpMethod, url, queryParams, headerParams, formParams, bodyParam, contentType, accept, responseType, eventEmitter, returnType, securityOptions) {
const request = (0, superagent_1.default)(httpMethod, url);
const { isBpmRequest, authentications, defaultHeaders = {}, enableCsrf, withCredentials = false } = securityOptions;
this.applyAuthToRequest(request, authentications);
request.query(SuperagentHttpClient.normalizeParams(queryParams));
request.set(defaultHeaders).set(SuperagentHttpClient.normalizeParams(headerParams));
if (isBpmRequest && enableCsrf) {
this.setCsrfToken(request);
}
if (withCredentials) {
request.withCredentials();
}
if (isBpmRequest) {
request.withCredentials();
if (securityOptions.authentications.cookie) {
if (!(0, utils_1.isBrowser)()) {
request.set('Cookie', securityOptions.authentications.cookie);
}
}
}
request.timeout(this.timeout);
if (contentType && contentType !== 'multipart/form-data') {
request.type(contentType);
}
else if (!request.header['Content-Type'] && contentType !== 'multipart/form-data') {
request.type('application/json');
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(SuperagentHttpClient.normalizeParams(formParams)).on('progress', (event) => {
this.progress(event, eventEmitter);
});
}
else if (contentType === 'multipart/form-data') {
const _formParams = SuperagentHttpClient.normalizeParams(formParams);
for (const key in _formParams) {
if (Object.prototype.hasOwnProperty.call(_formParams, key)) {
if (SuperagentHttpClient.isFileParam(_formParams[key])) {
request.attach(key, _formParams[key]).on('progress', (event) => {
this.progress(event, eventEmitter);
});
}
else {
request.field(key, _formParams[key]).on('progress', (event) => {
this.progress(event, eventEmitter);
});
}
}
}
}
else if (bodyParam) {
request.send(bodyParam).on('progress', (event) => {
this.progress(event, eventEmitter);
});
}
if (accept) {
request.accept(accept);
}
if (returnType === 'blob' || returnType === 'Blob' || responseType === 'blob' || responseType === 'Blob') {
request.responseType('blob');
}
else if (returnType === 'String') {
request.responseType('string');
}
return request;
}
setCsrfToken(request) {
const token = SuperagentHttpClient.createCSRFToken();
request.set('X-CSRF-TOKEN', token);
if (!(0, utils_1.isBrowser)()) {
request.set('Cookie', 'CSRF-TOKEN=' + token + ';path=/');
}
try {
document.cookie = 'CSRF-TOKEN=' + token + ';path=/';
}
catch (_a) {
}
}
applyAuthToRequest(request, authentications) {
if (authentications) {
switch (authentications.type) {
case 'basic': {
const basicAuth = authentications.basicAuth;
if (basicAuth.username || basicAuth.password) {
request.auth(basicAuth.username || '', basicAuth.password || '');
}
break;
}
case 'activiti': {
if (authentications.basicAuth.ticket) {
request.set({ Authorization: authentications.basicAuth.ticket });
}
break;
}
case 'oauth2': {
const oauth2 = authentications.oauth2;
if (oauth2.accessToken) {
request.set({ Authorization: 'Bearer ' + oauth2.accessToken });
}
break;
}
default:
throw new Error('Unknown authentication type: ' + authentications.type);
}
}
}
progress(event, eventEmitter) {
if (isProgressEvent(event)) {
const percent = Math.round((event.loaded / event.total) * 100);
const progress = {
total: event.total,
loaded: event.loaded,
percent
};
eventEmitter.emit('progress', progress);
}
}
static createCSRFToken(a) {
return a
? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
: ([1e16] + (1e16).toString()).replace(/[01]/g, SuperagentHttpClient.createCSRFToken);
}
static deserialize(response, returnType) {
if (response === null) {
return null;
}
let data = response.body;
if (data === null) {
data = response.text;
}
if (returnType) {
if (returnType === 'blob' && (0, utils_1.isBrowser)()) {
data = new Blob([data], { type: response.header['content-type'] });
}
else if (returnType === 'blob' && !(0, utils_1.isBrowser)()) {
data = new Buffer.from(data, 'binary');
}
else if (Array.isArray(data)) {
data = data.map((element) => new returnType(element));
}
else {
data = new returnType(data);
}
}
return data;
}
static normalizeParams(params) {
const newParams = {};
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key) && params[key] !== undefined && params[key] !== null) {
const value = params[key];
if (SuperagentHttpClient.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
}
else {
newParams[key] = (0, utils_1.paramToString)(value);
}
}
}
return newParams;
}
static isFileParam(param) {
if (typeof Buffer === 'function' && (param instanceof Buffer || param.path)) {
return true;
}
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
}
if (typeof File === 'function' && param instanceof File) {
return true;
}
if (typeof File === 'object' && param instanceof File) {
return true;
}
return false;
}
}
exports.SuperagentHttpClient = SuperagentHttpClient;
//# sourceMappingURL=../../../../lib/js-api/src/superagentHttpClient.js.map
;