@viewdo/dxp-story-cli
Version:
DXP Story Management CLI
733 lines • 38 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SyncManager = void 0;
const typedi_1 = require("typedi");
const APIService_1 = require("../services/APIService");
const ConsoleService_1 = require("../services/ConsoleService");
const FileService_1 = require("../services/FileService");
const TaskService_1 = require("../services/TaskService");
const BucketService_1 = require("./../services/BucketService");
const AuthenticationManager_1 = require("./AuthenticationManager");
const ConfigurationManager_1 = require("./ConfigurationManager");
const ContentType_1 = require("../models/configuration/support/ContentType");
const StripoAPIService_1 = require("../services/StripoAPIService");
const KpiSourceType_1 = require("../models/configuration/support/KpiSourceType");
let SyncManager = class SyncManager {
constructor(file_service, configuration_manager, auth_manager, api_service, stripo_api_service, task_service, console_service, bucketService) {
this.file_service = file_service;
this.configuration_manager = configuration_manager;
this.auth_manager = auth_manager;
this.api_service = api_service;
this.stripo_api_service = stripo_api_service;
this.task_service = task_service;
this.console_service = console_service;
this.bucketService = bucketService;
}
_getToken() {
this.api_service = this.api_service.withToken(this.auth_manager.token);
}
_getStripoToken(token) {
this.stripo_api_service = this.stripo_api_service.withToken(token);
}
_sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// domain API proxy -----
storyExists(story_key) {
this._getToken();
return this.api_service.storyExists(story_key);
}
getStory(story_key) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
return yield this.api_service.getStory(story_key);
});
}
_getStoryExport(story_key) {
this._getToken();
return this.api_service.exportStory(story_key);
}
_storyImport(story_key, story_data) {
this._getToken();
return this.api_service.importStory(story_key, story_data);
}
_setStory(story_key_1, sync_id_1) {
return __awaiter(this, arguments, void 0, function* (story_key, sync_id, validateOnly = false) {
this._getToken();
let story_config = this.configuration_manager.getStoryConfig(story_key);
const identifierInputs = story_config.inputs.some((i) => i.required && i.isIdentifier);
if (!identifierInputs)
throw Error(`No Primary Identifier found for story - ${story_config.name}.\n
Ensure that there is at least one input that satisfies the criteria of a “Primary Identifier”
- Must be marked as "isIdentifier"
- Must be marked as "required\n"`);
let order = 0;
story_config.inputs.forEach((i) => (i.order = order++));
story_config.externalSyncId = sync_id;
// hydrate local organization when validateOnly, should null during proper story pushes
if (validateOnly) {
story_config.organization = this.configuration_manager.getOrganizationConfig(story_config.organizationKey);
}
return yield this.api_service.setStory(story_key, story_config, validateOnly);
});
}
getOrganization(organization_key) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
let organization = yield this.api_service.getOrganization(organization_key);
let services = yield this.api_service.getOrganizationServices(organization_key);
organization.services = services;
organization.secrets = yield this.getOrganizationSecrets(organization_key);
return organization;
});
}
getOrganizationSecrets(organization_key) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
return this.api_service.getOrganizationSecrets(organization_key);
});
}
organizationSecretExists(organization_key, secret_key) {
return __awaiter(this, void 0, void 0, function* () {
try {
this._getToken();
yield this.api_service.organizationSecretsExists(organization_key, secret_key);
return true;
}
catch (e) {
// 404 indicates non-existence, not an error
return false;
}
});
}
setOrganizationSecret(organization_key, secret_key, secret_value) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
return this.api_service.setOrganizationSecret(organization_key, secret_key, secret_value);
});
}
_setOrganization(organization_key, sync_id) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
let organization_config = this.configuration_manager.getOrganizationConfig(organization_key);
organization_config.externalSyncId = sync_id;
return yield this.api_service.setOrganization(organization_key, organization_config);
});
}
getOrganizationStories(organization_key) {
this._getToken();
return this.api_service.getOrganizationStories(organization_key);
}
_getOrganizationExport(organization_key) {
this._getToken();
return this.api_service.exportOrganization(organization_key);
}
_organizationImport(organization_key, organization_data) {
this._getToken();
return this.api_service.importOrganization(organization_key, organization_data);
}
// Organizations ----------------------------------------------
_setupCDN() {
if (this.configuration_manager.config.cdn &&
this.configuration_manager.config.cdn.enabled) {
this.bucketService.setupBucket(this.configuration_manager.config.cdn.bucket);
}
}
// PULL
pullOrganizations(organization_keys) {
return __awaiter(this, void 0, void 0, function* () {
this._setupCDN();
const ctx = yield this.task_service
.runTasks(organization_keys.map((org_key) => this._pullOrganization(org_key)));
return ctx.success == false ? 1 : 0;
});
}
_pullOrganization(org_key) {
return this.task_service.createTaskSet(`Get Organization ${org_key} from DXP`, (ctx, task) => __awaiter(this, void 0, void 0, function* () {
const org = yield this.getOrganization(org_key);
let config = this.configuration_manager.setOrganizationConfig(org);
this.configuration_manager.setOrganizationAssetConfig(config);
return yield this._getOrganizationPullTasks(org_key);
}));
}
_getOrganizationPullTasks(org_key) {
return __awaiter(this, void 0, void 0, function* () {
let organization_config = this.configuration_manager.getOrganizationConfig(org_key);
let asset_config = this.configuration_manager.getOrganizationAssetConfig(org_key);
return this.task_service.createSubTasksFromCollection(organization_config.getAssets(), (t) => t.name, () => false, (ctx, task, file) => __awaiter(this, void 0, void 0, function* () {
try {
const content = yield this._pullAsset(file);
this.file_service.write(asset_config.getLocalPath(file), content || "");
}
catch (e) {
task.skip(e.message);
}
}));
});
}
// PUSH
pushOrganizations(organization_keys, sync_id, cdn) {
return __awaiter(this, void 0, void 0, function* () {
this._setupCDN();
const ctx = yield this.task_service
.runTasks(organization_keys.map((organization_key) => this._pushOrganization(organization_key, sync_id, cdn)));
return (ctx.success == false ? 1 : 0);
});
}
_pushOrganization(organization_key, sync_id, cdn) {
if (!this.configuration_manager.organization_keys.includes(organization_key))
throw new Error(`Org ${organization_key} is not part of this repo`);
let tasks = this.task_service.createTaskSet(`Push Organization ${organization_key} to DXP`, (ctx, task) => __awaiter(this, void 0, void 0, function* () {
if (!this.validateFlashboardConfiguration(organization_key))
throw new Error(`Fix reported issues with flashboard configuration before attempting to push to DXP.`);
yield this._setOrganization(organization_key, sync_id);
return this._getOrganizationPushTasks(organization_key, cdn);
}));
return tasks;
}
_getOrganizationPushTasks(organization_key, cdn) {
let organization_config = this.configuration_manager.getOrganizationConfig(organization_key);
let asset_config = this.configuration_manager.getOrganizationAssetConfig(organization_key);
let tasks = this.task_service.createSubTasksFromCollection(organization_config.getAssets(), (t) => t.name, () => false, (ctx, task, file) => __awaiter(this, void 0, void 0, function* () {
try {
let content = this.file_service.read(asset_config.getLocalPath(file));
yield this._pushAsset(file, content);
}
catch (e) {
task.skip(e.message);
}
}));
if (cdn &&
this.configuration_manager.config.cdn &&
this.configuration_manager.config.cdn.enabled) {
let pushCDN = this._getCDNPushTask(organization_config.assets_directory, organization_config.cdn_root);
tasks = [pushCDN, ...tasks];
}
return tasks;
}
_getCDNPushTask(assets_directory, cdn_root) {
const self = this;
return this.task_service.createTask("Push CDN Assets", (t, ctx) => {
let files = this.file_service
.listFiles(assets_directory)
.filter((f) => !f.endsWith(".md"))
.map((f) => {
var remote_path = f
.replace(/([\\]+)/g, "/")
.replace(assets_directory.replace("./", ""), cdn_root);
return {
local_path: f,
remote_path,
};
});
let filePromises = [];
files.forEach((file) => filePromises.push(self.bucketService.upload(file.local_path, file.remote_path)));
return Promise.all(filePromises);
});
}
validateFlashboardConfiguration(org_key) {
let organization_config = this.configuration_manager.getOrganizationConfig(org_key);
if (!organization_config || !organization_config.flashboards)
return true;
const org_story_keys = this.configuration_manager.getOrganizationStoryKeys(org_key);
this.console_service.log("Validating Organization Flashboard Configuration");
let isValid = true;
for (const board of organization_config.flashboards) {
for (const metric of board.metrics) {
if (!metric.storyKey || !org_story_keys.includes(metric.storyKey)) {
this.console_service.warn(`Metric ${metric.kpiKey} for flashboard ${board.key} is missing a storykey.`);
isValid = false;
continue;
}
const story = this.configuration_manager.getStoryConfig(metric.storyKey);
if (!story) {
this.console_service.warn(`Unable to locate story ${metric.storyKey} in DXP config.`);
isValid = false;
continue;
}
switch (metric.type) {
case "StoryEvent" /* KpiSourceType.StoryEvent */:
if (story.events.findIndex((s) => s.key == metric.kpiKey) == -1) {
this.console_service.warn(`Story ${story.key} does not contain ${"StoryEvent" /* KpiSourceType.StoryEvent */} key ${metric.kpiKey}.`);
isValid = false;
}
break;
case "ExternalEvent" /* KpiSourceType.ExternalEvent */:
if (story.externalEvents.findIndex((s) => s.key == metric.kpiKey) == -1) {
this.console_service.warn(`Story ${story.key} does not contain ${"ExternalEvent" /* KpiSourceType.ExternalEvent */} key ${metric.kpiKey}.`);
isValid = false;
}
break;
case "Link" /* KpiSourceType.Link */:
if (story.customLinks.findIndex((s) => s.key == metric.kpiKey) == -1) {
this.console_service.warn(`Story ${story.key} does not contain ${"Link" /* KpiSourceType.Link */} key ${metric.kpiKey}.`);
isValid = false;
}
break;
case "Custom" /* KpiSourceType.Custom */:
if (story.customKpis.findIndex((s) => s.key == metric.kpiKey) == -1) {
this.console_service.warn(`Story ${story.key} does not contain ${"Custom" /* KpiSourceType.Custom */} key ${metric.kpiKey}.`);
isValid = false;
}
break;
case "Standard" /* KpiSourceType.Standard */:
// These are preconfigured KPIs defined in DXP
if (!Object.values(KpiSourceType_1.KpiStandardKeys).includes(metric.kpiKey)) {
this.console_service.warn(`${"Standard" /* KpiSourceType.Standard */} metric ${metric.kpiKey} does not match the allowed DXP Standard metrics.`);
isValid = false;
}
break; // these map to DXP constant values
default:
this.console_service.warn(`Metric ${metric.kpiKey} does not match any of the allowed DXP KPI Source Types`);
isValid = false;
break;
}
}
}
if (isValid)
this.console_service.log(`Organization flashboard configuration valid!`);
return isValid;
}
// Stories ----------------------------------------------
// PULL
pullStories(story_keys) {
this._setupCDN();
return this.task_service
.runTasks(story_keys.map((story_key) => this._pullStory(story_key)))
.then((ctx) => {
return ctx.success == false ? 1 : 0;
});
}
pullStoryAs(story_key, as_key, as_org_key) {
return this.task_service
.runTask(`Pull Story ${story_key} as ${as_key}`, () => [
this._pullStory(story_key, as_key, as_org_key),
])
.then((ctx) => {
return ctx.success == false ? 1 : 0;
});
}
_pullStory(story_key, as_key, as_org_key) {
return this.task_service.createTaskSet(`Get Story ${story_key} from DXP`, (ctx, task) => __awaiter(this, void 0, void 0, function* () {
const story = yield this.getStory(story_key);
if (as_key)
story.key = as_key;
if (as_org_key)
story.organizationKey = as_org_key;
let config = this.configuration_manager.setStoryConfig(story);
this.configuration_manager.setStoryAssetConfig(config);
this.configuration_manager.setPreviewConfig(config);
return yield this._getStoryPullTasks(story.key, story_key);
}));
}
_pullAsset(asset) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
const content = yield this.api_service.getFile(asset.remote_path);
return asset.convertFromRemote(content);
});
}
_getStoryPullTasks(story_key, from_key) {
return __awaiter(this, void 0, void 0, function* () {
let story_config = this.configuration_manager.getStoryConfig(story_key);
// Check if we the platform has templates that aren't synced to this repo
const dxpStoryConfiguration = yield this.getStory(story_key);
if (dxpStoryConfiguration) {
this.processTemplates('htmlTemplates', story_config, dxpStoryConfiguration);
this.processTemplates('emailTemplates', story_config, dxpStoryConfiguration);
this.processTemplates('textTemplates', story_config, dxpStoryConfiguration);
}
const asset_config = this.configuration_manager.getStoryAssetConfig(story_key);
return this.task_service.createSubTasksFromCollection(story_config.getAssets(from_key), (t) => t.name, () => false, (ctx, task, file) => __awaiter(this, void 0, void 0, function* () {
task.output = file.remote_path;
try {
const content = yield this._pullAsset(file);
const localPath = asset_config.getLocalPath(file);
// If content is available, write it and return early
if (content) {
this.file_service.write(localPath, content);
return;
}
// If the file exists and has content, log and return early
if (this.file_service.exists(localPath) && this.file_service.hasContent(localPath)) {
console.log(`File ${localPath} already exists and has content. Skipping overwrite.`);
return;
}
// If the file doesn't exist or doesn't have content, write blank content
this.file_service.write(localPath, "");
}
catch (e) {
return task.skip(e.message);
}
}));
});
}
processTemplates(templateType, story_config, dxpStoryConfiguration) {
var _a;
if (dxpStoryConfiguration[templateType]) {
(_a = dxpStoryConfiguration[templateType]) === null || _a === void 0 ? void 0 : _a.forEach((template) => {
const exists = story_config[templateType].some((existingTemplate) => existingTemplate.key === template.key);
if (!exists) {
const fileExtension = ContentType_1.contentTypeToExtension[templateType == 'textTemplates' ? template.type : ContentType_1.ContentType.LIQUID];
const parsedData = this.file_service.parseKeyToPathAndFile(template.key);
story_config[templateType].push({
key: template.key,
name: template.name,
file: `${parsedData.file}${fileExtension}`,
path: parsedData.path,
type: template.type
});
}
});
}
}
pullStoriesEmailTemplates(storyKeys, stripoApiKey) {
return __awaiter(this, void 0, void 0, function* () {
const tasks = yield Promise.all(storyKeys.map(storyKey => this._pullStoryEmailTemplateTask(storyKey, stripoApiKey)));
try {
const ctx = yield this.task_service.runTasks(tasks);
return ctx.success === false ? 1 : 0;
}
catch (error) {
this.console_service.error(`Error running tasks: ${error.message}`);
return 1;
}
});
}
_pullStoryEmailTemplateTask(storyKey, stripoApiKey) {
return __awaiter(this, void 0, void 0, function* () {
this._getStripoToken(stripoApiKey);
const storyConfig = this.configuration_manager.getStoryConfig(storyKey);
const folders = yield this.stripo_api_service.getFolders();
// Helper function to find folder by path
const findFolderByPath = (folders, path) => {
let currentFolders = folders;
let targetFolder;
for (const segment of path) {
targetFolder = currentFolders.find(folder => folder.name === segment);
if (targetFolder && targetFolder.children) {
currentFolders = targetFolder.children;
}
else {
break;
}
}
return targetFolder;
};
const rootDir = storyConfig.stripoRootDirectory.replace('{{org-key}}', storyConfig.organizationKey);
// remove any leading (^\/) or trailing (\/$) slashes from the rootDir string,
// ensuring that the split('/') operation creates the correct path segments without any empty entries
const pathSegments = rootDir.replace(/^\/|\/$/g, '').split('/');
const storyFolder = findFolderByPath(folders, [...pathSegments, storyKey]);
if (!storyFolder) {
throw new Error(`Cannot find folder for story key: ${storyKey}`);
}
return {
title: `Retrieving Stripo Email templates from: '${rootDir}'`,
task: (ctx, task) => __awaiter(this, void 0, void 0, function* () {
try {
task.output = `Found '${storyFolder.name}', proceeding to download email templates...`;
const emails = yield this.stripo_api_service.getEmails(storyFolder.id);
for (const email of emails) {
const emailExport = yield this.stripo_api_service.getEmailExport(email.emailId);
if (emailExport) {
const formattedName = email.name.toLowerCase().replace(/\s+/g, '-');
task.output = `Saving ${formattedName}`;
this.file_service.write(`${storyConfig.local_root}/email-templates/${formattedName}.liquid`, emailExport);
}
}
}
catch (e) {
return task.skip(e.message);
}
})
};
});
}
// PUSH API ----------------------------------------------
pushStories(story_keys, sync_id, cdn) {
return __awaiter(this, void 0, void 0, function* () {
this._setupCDN();
const ctx = yield this.task_service
.runTasks(story_keys.map((story_key) => this._pushStory(story_key, sync_id, cdn)));
ctx.success == false ? 1 : 0;
if (ctx.warnings && ctx.warnings.length) {
ctx.warnings.forEach((m) => this.console_service.warn(m));
}
});
}
_pushStory(story_key, sync_id, cdn) {
if (!this.configuration_manager.story_keys.includes(story_key))
throw new Error(`Story ${story_key} is not part of this repo`);
return this.task_service.createTaskSet(`Push Story ${story_key} to DXP`, (ctx, task) => __awaiter(this, void 0, void 0, function* () {
try {
yield this._setStory(story_key, sync_id);
// wait for the api to process before pushing assets
yield this._sleep(5000);
return this._getStoryPushTasks(story_key, cdn);
}
catch (e) {
throw new Error(`Error${e && e.message ? ': ' + JSON.stringify(e.message) : '!'}`);
}
}));
}
_pushAsset(asset, content) {
this._getToken();
return this.api_service.putFile(asset.remote_path, asset.convertFromLocal(content));
}
_getStoryPushTasks(story_key, cdn) {
let story_config = this.configuration_manager.getStoryConfig(story_key);
let org_config = this.configuration_manager.getOrganizationConfig(story_config.organizationKey);
let asset_config = this.configuration_manager.getStoryAssetConfig(story_key);
let tasks = this.task_service.createSubTasksFromCollection(story_config.getAssets(), (t) => t.name, () => false, (ctx, task, file) => {
let content = this.file_service.read(asset_config.getLocalPath(file));
if (content != null) {
if (content.trim() == "") {
task.output = "Skipping Validation (Empty File)";
return this._pushAsset(file, content).catch((e) => task.skip(e.message +
" (Empty files are not yet allowed through the API. Clear them by hand if necessary) "));
}
if (!file.remote_validation_path) {
task.output = "Skipping Validation for this file-type.";
return this._pushAsset(file, content).catch((e) => task.skip(e.message));
}
task.output = "Validating...";
return this._validateAsset(file, content, story_config, org_config).then((results) => {
if (results.isValid) {
task.output = "👍 Valid";
return this._pushAsset(file, content);
}
let first_error = results.errors[0];
ctx.success = false;
throw new Error(`Line ${first_error.line}: ${first_error.message}`);
});
}
task.skip("No local file to push.");
});
if (cdn &&
this.configuration_manager.config.cdn &&
this.configuration_manager.config.cdn.enabled) {
let pushCDN = this._getCDNPushTask(story_config.assets_directory, story_config.cdn_root);
tasks = [pushCDN, ...tasks];
}
return tasks;
}
// CHECK
checkStories(story_keys) {
return this.task_service
.runTasks(story_keys.map((story_key) => this._checkStory(story_key)))
.then((ctx) => {
this.console_service.log(`${ctx.changes || 0} changed files detected`);
return ctx.success == false ? 1 : 0;
});
}
_checkStory(story_key) {
if (!this.configuration_manager.story_keys.includes(story_key))
throw new Error(`Story ${story_key} is not part of this repo`);
return this.task_service.createTaskSet(`Check Story ${story_key} with DXP`, (ctx, task) => this._setStory(story_key, null, true).then((s) => this._getCheckStoryTasks(story_key)));
}
_getAsset(asset) {
this._getToken();
return this.api_service.getFile(asset.remote_path);
}
_getCheckStoryTasks(story_key) {
let story_config = this.configuration_manager.getStoryConfig(story_key);
let asset_config = this.configuration_manager.getStoryAssetConfig(story_key);
return this.task_service.createSubTasksFromCollection(story_config.getAssets(), (t) => t.name, (t) => t.remote_validation_path == undefined, (ctx, task, file) => this._getAsset(file)
.then((content) => {
if (content != null) {
let local_content = file.convertFromLocal(this.file_service.read(asset_config.getLocalPath(file)));
if (local_content != content) {
if (!ctx.changes)
ctx.changes = 1;
else
ctx.changes++;
task.skip("⚠️ Local file is different and will be replaced on the server (skipped=changed) ");
// this.console_service.debug('Local content:')
// this.console_service.debug(local_content)
// this.console_service.debug('Remote content:')
// this.console_service.debug(content)
}
}
else {
task.title = `No Remote ${task.title}`;
}
})
.catch((e) => task.skip(e.message)));
}
// VALIDATE API ----------------------------------------------
validateStories(story_keys) {
return __awaiter(this, void 0, void 0, function* () {
const ctx = yield this.task_service
.runTasks(story_keys.map((story_key) => this._validateStory(story_key)));
ctx.success == false ? 1 : 0;
if (ctx.warnings && ctx.warnings.length) {
ctx.warnings.forEach((m) => this.console_service.warn(m));
}
});
}
_validateStory(story_key) {
if (!this.configuration_manager.story_keys.includes(story_key))
throw new Error(`Story ${story_key} is not part of this repo`);
return this.task_service.createTaskSet(`Validate Story ${story_key} from DXP`, (ctx, task) => __awaiter(this, void 0, void 0, function* () {
try {
yield this._setStory(story_key, null, true);
return yield this._getStoryValidateTasks(story_key);
}
catch (e) {
throw new Error(`Error${e && e.message ? ': ' + JSON.stringify(e.message) : '!'}`);
}
}));
}
_validateAsset(asset, content, story, organization) {
return __awaiter(this, void 0, void 0, function* () {
this._getToken();
return yield this.api_service.validateFile(asset.remote_validation_path, asset.convertFromLocal(content), story, organization);
});
}
_getStoryValidateTasks(story_key) {
return __awaiter(this, void 0, void 0, function* () {
let story_config = this.configuration_manager.getStoryConfig(story_key);
let org_config = this.configuration_manager.getOrganizationConfig(story_config.organizationKey);
let asset_config = this.configuration_manager.getStoryAssetConfig(story_key);
return this.task_service.createSubTasksFromCollection(story_config.getAssets(), (t) => t.name, (t) => !t.remote_validation_path, (ctx, task, file) => __awaiter(this, void 0, void 0, function* () {
try {
let content = this.file_service.read(asset_config.getLocalPath(file));
if (content != null) {
task.output = "Validating...";
if (content.trim() == "") {
task.skip("Local file is empty.");
return;
}
const results = yield this._validateAsset(file, content, story_config, org_config);
if (!results.isValid) {
task.output = "Invalid!";
let first_error = results.errors[0];
throw new Error(`Line ${first_error.line}: ${first_error.message}`);
}
// Handle warnings here
if (results.warnings && results.warnings.length) {
if (!ctx.warnings)
ctx.warnings = [];
let warningMessages = results.warnings.map(m => `File ${file.local_path} - Line ${m.line}: ${m.message}`);
warningMessages.forEach(msg => ctx.warnings.push(msg));
}
task.output = "Valid!";
return true;
}
task.skip("No local file to validate.");
}
catch (e) {
throw new Error(`Error${e && e.message ? ': ' + JSON.stringify(e.message) : '!'}`);
}
}));
});
}
// EXPORT STORY ----------------------------------------------
exportStories(story_keys) {
return this.task_service
.runTasks(story_keys.map((story_key) => this._exportStory(story_key)))
.then((ctx) => (ctx.success == false ? 1 : 0));
}
_exportStory(story_key) {
let export_path = this.configuration_manager
.getStoryConfig(story_key)
.getExportPath();
return this.task_service.createTaskSet(`Export Story ${story_key} from DXP`, (ctx, task) => this._getStoryExport(story_key).then((data) => {
this.file_service.write(export_path, JSON.stringify(data, null, 2));
}));
}
// IMPORT STORY ----------------------------------------------
importStories(story_keys) {
return this.task_service
.runTasks(story_keys.map((story_key) => this._importStory(story_key)))
.then((ctx) => (ctx.success == false ? 1 : 0));
}
_importStory(story_key) {
let export_path = this.configuration_manager
.getStoryConfig(story_key)
.getExportPath();
if (!this.file_service.exists(export_path))
throw new Error(`Local export file does not exist at ${export_path}. Export the story first using the export command`);
let content = this.file_service.read(export_path);
if (content == null || content.trim() == "")
throw new Error("Local export file is empty. Export it first using the export command");
let data = JSON.parse(content);
return this.task_service.createTaskSet(`Import Story ${story_key} from DXP`, (ctx, task) => this._storyImport(story_key, data)
.then((r) => {
task.output = "Success!";
return r;
})
.catch((e) => task.skip(e.message)));
}
// EXPORT ORG ----------------------------------------------
exportOrganizations(organization_keys) {
return this.task_service
.runTasks(organization_keys.map((organization_key) => this._exportOrganization(organization_key)))
.then((ctx) => (ctx.success == false ? 1 : 0));
}
_exportOrganization(organization_key) {
let export_path = this.configuration_manager
.getOrganizationConfig(organization_key)
.getExportPath();
return this.task_service.createTaskSet(`Export Organization ${organization_key} from DXP`, (ctx, task) => this._getOrganizationExport(organization_key).then((data) => {
this.file_service.write(export_path, JSON.stringify(data, null, 2));
}));
}
// IMPORT ORG ----------------------------------------------
importOrganizations(organization_keys) {
return this.task_service
.runTasks(organization_keys.map((organization_key) => this._importOrganization(organization_key)))
.then((ctx) => (ctx.success == false ? 1 : 0));
}
_importOrganization(organization_key) {
let export_path = this.configuration_manager
.getOrganizationConfig(organization_key)
.getExportPath();
if (!this.file_service.exists(export_path))
throw new Error(`Local export file does not exist at ${export_path}. Export the organization first using the export command`);
let content = this.file_service.read(export_path);
if (content == null || content.trim() == "")
throw new Error("Local export file is empty. Export it first using the export command");
let data = JSON.parse(content);
return this.task_service.createTaskSet(`Import Organization ${organization_key} from DXP`, (ctx, task) => this._organizationImport(organization_key, data)
.then((r) => {
task.output = "Success!";
return r;
})
.catch((e) => task.skip(e.message)));
}
};
exports.SyncManager = SyncManager;
exports.SyncManager = SyncManager = __decorate([
(0, typedi_1.Service)(),
__metadata("design:paramtypes", [FileService_1.FileService,
ConfigurationManager_1.ConfigurationManager,
AuthenticationManager_1.AuthenticationManager,
APIService_1.ApiService,
StripoAPIService_1.StripoApiService,
TaskService_1.TaskService,
ConsoleService_1.ConsoleService,
BucketService_1.BucketFileService])
], SyncManager);
//# sourceMappingURL=SyncManager.js.map