UNPKG

@adobe/reactor-sdk

Version:
212 lines (168 loc) 7.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _nodeFetch = _interopRequireDefault(require("node-fetch")); var _version = require("./version"); var hosts = _interopRequireWildcard(require("./hosts")); var auditEvents = _interopRequireWildcard(require("./audit-events")); var builds = _interopRequireWildcard(require("./builds")); var callbacks = _interopRequireWildcard(require("./callbacks")); var companies = _interopRequireWildcard(require("./companies")); var dataElements = _interopRequireWildcard(require("./data-elements")); var environments = _interopRequireWildcard(require("./environments")); var extensionPackages = _interopRequireWildcard(require("./extension-packages")); var extensions = _interopRequireWildcard(require("./extensions")); var heartbeat = _interopRequireWildcard(require("./heartbeat")); var libraries = _interopRequireWildcard(require("./libraries")); var profiles = _interopRequireWildcard(require("./profiles")); var properties = _interopRequireWildcard(require("./properties")); var ruleComponents = _interopRequireWildcard(require("./rule-components")); var rules = _interopRequireWildcard(require("./rules")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* Copyright 2019 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const defaultReactorOptions = { reactorUrl: 'https://reactor.adobe.io', enableLogging: false }; function removeTrailingSlash(str) { return str.endsWith('/') ? str.slice(0, -1) : str; } function bodyIsJson(httpResponse) { const jsonContentType = 'application/vnd.api+json'; const thisContentType = httpResponse.headers.get('content-type'); return thisContentType && thisContentType.includes(jsonContentType); } class Reactor { constructor(accessToken, userOptions = {}) { const options = { ...defaultReactorOptions, ...userOptions }; this.baseUrl = removeTrailingSlash(options.reactorUrl); this.enableLogging = options.enableLogging; this.customHeaders = options.customHeaders || {}; this.headers = { ...this.reactorHeaders(accessToken), ...this.customHeaders }; if (this.enableLogging) console.info(`Using Reactor at ${this.baseUrl}`); } reactorHeaders(accessToken) { return { Accept: 'application/vnd.api+json;revision=1', 'Content-Type': 'application/vnd.api+json', 'Cache-control': 'no-cache', Authorization: `Bearer ${accessToken}`, 'X-Api-Key': 'Activation-DTM', 'User-Agent': `adobe/reactor-sdk/javascript/${_version.version}` }; } createReviseBody(resourceType, resourceId) { return { data: { id: resourceId, attributes: {}, type: resourceType, meta: { action: 'revise' } } }; } async requestAndLog(url, requestInfo, requestData) { // requestData is requestInfo.body as JavaScript objects (not JSON) const response = await (0, _nodeFetch.default)(url.toString(), requestInfo); const responseData = bodyIsJson(response) ? await response.json() : null; const status = `${response.status} ${response.statusText}`; const source = `${requestInfo.method} ${url.toString()}`; const traceData = { // convenient human-readable summaries status: `${response.status} ${response.statusText}`, // eg '404 not found' source: `${requestInfo.method} ${url.toString()}`, // eg 'GET http://x.io/' // raw capture of all request and response data url: url, request: requestInfo, response: response, // non-JSON versions (i.e., as objects) of request and response bodies requestBody: requestData || {}, responseBody: responseData || {} }; const summary = `${traceData.status} <- ${traceData.source}`; if (!response.ok) { if (this.enableLogging) console.info('[Reactor SDK]', summary, traceData); throw new FetchError(traceData); } if (this.enableLogging) console.debug('[Reactor SDK]', summary, traceData); return responseData; } async request(method, url, requestData = null) { const requestBodyJson = requestData && JSON.stringify(requestData); const requestInfo = { method: method, headers: this.headers, body: requestBodyJson }; return await this.requestAndLog(url, requestInfo, requestData); } async sendMultipartFile(method, url, fileObject) { const multipart = { 'Content-Type': 'multipart/form-data' }; const requestInfo = { method: method, headers: Object.assign({}, this.headers, multipart), body: fileObject }; return await this.requestAndLog(url, requestInfo, fileObject); } get(path, queryParams = {}) { const url = new URL(this.baseUrl + path); Object.entries(queryParams).forEach(([key, val]) => url.searchParams.append(key, val)); return this.request('GET', url); } post(path, data) { return this.request('POST', this.baseUrl + path, data); } patch(path, data) { return this.request('PATCH', this.baseUrl + path, data); } delete(path, data) { return this.request('DELETE', this.baseUrl + path, data); } } exports.default = Reactor; function extractErrorDetails(traceData) { const errorList = traceData.responseBody.errors || []; const details = [traceData.response, ...errorList].map(x => x.detail).filter(x => typeof x !== 'undefined').map(x => `'${x}'`).join('; also, '); return details !== '' ? ` (${details})` : ''; } class FetchError extends Error { constructor(traceData) { const status = traceData.status; const details = extractErrorDetails(traceData); const whence = ` on ${traceData.source}`; super(status + details + whence); if (Error.captureStackTrace) Error.captureStackTrace(this, FetchError); this.status = traceData.response.status; this.statusText = traceData.response.statusText; this.traceData = traceData; } } Object.assign(Reactor.prototype, auditEvents, builds, callbacks, companies, dataElements, environments, extensionPackages, extensions, heartbeat, hosts, libraries, profiles, properties, ruleComponents, rules); if (typeof window !== 'undefined' && typeof window.document !== 'undefined') { window.Reactor = Reactor; } //# sourceMappingURL=index.js.map