UNPKG

@crowdin/crowdin-apps-functions

Version:

Utility library to easily and quickly develop Crowdin App

346 lines (345 loc) 14.9 kB
"use strict"; 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.generateReport = exports.getSubscription = exports.PaymentRequiredError = exports.createOrUpdateWebhook = exports.handleTranslations = exports.updateSourceFiles = exports.uploadTranslations = exports.getOrCreateFolder = exports.getFolder = exports.updateOrCreateFile = void 0; const axios_1 = require("axios"); function isUpdateOrCreateFileArgs(arg) { // @ts-expect-error: Type guard property check return arg.client && arg.projectId; } function updateOrCreateFile(clientOrArgs, projectId, name, title, type, directoryId, data, file, excludedTargetLanguages, importOptions) { return __awaiter(this, void 0, void 0, function* () { let options; if (isUpdateOrCreateFileArgs(clientOrArgs)) { options = clientOrArgs; } else { options = { client: clientOrArgs, // @ts-expect-error: Handling potential undefined value projectId, // @ts-expect-error: Handling potential undefined value name, title, type, directoryId, data, file, excludedTargetLanguages, importOptions, }; } const storageFile = yield options.client.uploadStorageApi.addStorage(options.name, options.data); if (options.file) { yield options.client.sourceFilesApi.updateOrRestoreFile(options.projectId, options.file.id, Object.assign({ storageId: storageFile.data.id }, (options.importOptions && { importOptions: options.importOptions }))); const updates = []; if (options.title && options.title !== options.file.title) { updates.push({ value: options.title, op: 'replace', path: '/title', }); } if (options.excludedTargetLanguages) { updates.push({ value: options.excludedTargetLanguages, op: 'replace', path: '/excludedTargetLanguages', }); } if (updates.length > 0) { yield options.client.sourceFilesApi.editFile(options.projectId, options.file.id, updates); } return options.file.id; } else { const newFile = yield options.client.sourceFilesApi.createFile(options.projectId, { storageId: storageFile.data.id, name: options.name, title: options.title, type: options.type, directoryId: options.directoryId, excludedTargetLanguages: options.excludedTargetLanguages, importOptions: options.importOptions, }); return newFile.data.id; } }); } exports.updateOrCreateFile = updateOrCreateFile; function isGetFolderArgs(arg) { return !Array.isArray(arg); } function getFolder(directoriesOrArgs, crowdinClient, projectId, directoryName, parentDirectory) { return __awaiter(this, void 0, void 0, function* () { let args; if (isGetFolderArgs(directoriesOrArgs)) { args = directoriesOrArgs; } else { // @ts-expect-error: Handling potential undefined value args = { directories: directoriesOrArgs, client: crowdinClient, projectId, directoryName, parentDirectory }; } const folder = args.directories.find(d => { var _a; return d.name === args.directoryName && ((!args.parentDirectory && !d.directoryId) || d.directoryId === ((_a = args.parentDirectory) === null || _a === void 0 ? void 0 : _a.id)); }); let files = []; if (folder) { files = (yield args.client.sourceFilesApi.withFetchAll().listProjectFiles(args.projectId, { directoryId: folder.id })).data.map(e => e.data); } return { folder, files }; }); } exports.getFolder = getFolder; function isGetOrCreateFolderArgs(args) { return !Array.isArray(args); } function getOrCreateFolder(directoriesOrArgs, crowdinClient, projectId, directoryName, parentDirectory) { return __awaiter(this, void 0, void 0, function* () { let args; if (isGetOrCreateFolderArgs(directoriesOrArgs)) { args = directoriesOrArgs; } else { // @ts-expect-error: Handling potential undefined value args = { directories: directoriesOrArgs, client: crowdinClient, projectId, directoryName, parentDirectory }; } let { folder, files } = yield getFolder(args); let created = false; if (!folder) { created = true; folder = (yield args.client.sourceFilesApi.createDirectory(args.projectId, { name: args.directoryName, directoryId: args.parentDirectory ? args.parentDirectory.id : undefined, })).data; files = (yield args.client.sourceFilesApi.withFetchAll().listProjectFiles(args.projectId, { directoryId: folder.id })).data.map(e => e.data); } return { folder, files, created }; }); } exports.getOrCreateFolder = getOrCreateFolder; function isUploadTranslationsArgs(args) { // @ts-expect-error: Type guard property check return args.client && args.projectId; } function uploadTranslations(crowdinClientOrArgs, projectId, fileId, language, fileName, fileContent, request) { return __awaiter(this, void 0, void 0, function* () { let args; if (isUploadTranslationsArgs(crowdinClientOrArgs)) { args = crowdinClientOrArgs; } else { // @ts-expect-error: Handling potential undefined value args = { client: crowdinClientOrArgs, projectId, fileId, fileContent, fileName, language, request }; } const storage = yield args.client.uploadStorageApi.addStorage(args.fileName, args.fileContent); return (yield args.client.translationsApi.uploadTranslation(args.projectId, args.language, Object.assign({ fileId: args.fileId, storageId: storage.data.id }, (args.request || {})))).data; }); } exports.uploadTranslations = uploadTranslations; function isUpdateSourceFilesArgs(args) { // @ts-expect-error: Type guard property check return args.client && args.projectId; } function updateSourceFiles(crowdinClientOrArgs, projectId, directory, fileEntities, parentDirectory) { return __awaiter(this, void 0, void 0, function* () { let args; if (isUpdateSourceFilesArgs(crowdinClientOrArgs)) { args = crowdinClientOrArgs; } else { // @ts-expect-error: Handling potential undefined value args = { client: crowdinClientOrArgs, projectId, directory, fileEntities, parentDirectory }; } const directories = yield args.client.sourceFilesApi.withFetchAll().listProjectDirectories(args.projectId); const { folder, files } = yield getOrCreateFolder({ directories: directories.data.map(d => d.data), client: args.client, projectId: args.projectId, directoryName: args.directory, parentDirectory: args.parentDirectory, }); yield Promise.all(args.fileEntities.map((fileEntity) => __awaiter(this, void 0, void 0, function* () { return yield updateOrCreateFile({ client: args.client, projectId: args.projectId, name: fileEntity.name, title: fileEntity.title, type: fileEntity.type, directoryId: folder.id, data: fileEntity.data, file: files.find(f => f.name === fileEntity.name), }); }))); }); } exports.updateSourceFiles = updateSourceFiles; function isHandleTranslationsArgs(args) { // @ts-expect-error: Type guard property check return args.client && args.projectId; } function handleTranslations(crowdinClientOrArgs, projectId, directory, request, handleFn, parentDirectory) { return __awaiter(this, void 0, void 0, function* () { let args; if (isHandleTranslationsArgs(crowdinClientOrArgs)) { args = crowdinClientOrArgs; } else { // @ts-expect-error: Handling potential undefined value args = { client: crowdinClientOrArgs, projectId, directory, handleFn, request, parentDirectory }; } const directories = yield args.client.sourceFilesApi.withFetchAll().listProjectDirectories(args.projectId); const { files } = yield getFolder({ directories: directories.data.map(d => d.data), client: args.client, projectId: args.projectId, directoryName: args.directory, parentDirectory: args.parentDirectory, }); for (const [fileId, targetLanguages] of Object.entries(args.request)) { const file = files.find(f => f.id === parseInt(fileId)); if (!file) { continue; } yield Promise.all(targetLanguages.map((languageCode) => __awaiter(this, void 0, void 0, function* () { const translationsLink = yield args.client.translationsApi.buildProjectFileTranslation(args.projectId, file.id, { targetLanguageId: languageCode, }); if (!translationsLink) { return; } const response = yield axios_1.default.get(translationsLink.data.url); yield args.handleFn(response.data, languageCode, file); }))); } }); } exports.handleTranslations = handleTranslations; /** * Function to update or create webhook * * @returns updated or created webhook id */ function createOrUpdateWebhook(args) { return __awaiter(this, void 0, void 0, function* () { const { client, projectId, events, name, url, payload, requestType = 'POST', batchingEnabled = true, headers, contentType, webhookId, webhookMatch, } = args; let id = webhookId; if (webhookMatch) { const webhooks = yield client.webhooksApi.withFetchAll().listWebhooks(projectId); const webhook = webhooks.data.find(e => webhookMatch(e.data)); if (webhook) { id = webhook.data.id; } } if (id) { yield client.webhooksApi.editWebhook(projectId, id, [ { value: events, op: 'replace', path: '/events', }, { value: payload, op: 'replace', path: '/payload', }, { value: url, op: 'replace', path: '/url', }, ]); return id; } else { const newWebhook = yield client.webhooksApi.addWebhook(projectId, { name, url, events, requestType, payload, batchingEnabled, headers, contentType, }); return newWebhook.data.id; } }); } exports.createOrUpdateWebhook = createOrUpdateWebhook; class PaymentRequiredError extends Error { constructor(subscribeLink, initializedAt) { super('Payment required'); this.subscribeLink = subscribeLink; this.initializedAt = initializedAt; // @ts-expect-error: Adding custom property this.code = 402; } } exports.PaymentRequiredError = PaymentRequiredError; /** * * @param param0.appIdentifier method request * @param param0.token bearer token * @param param0.organization crowdin organization */ function getSubscription({ appIdentifier, token, organization, baseUrl, }) { var _a, _b, _c, _d; return __awaiter(this, void 0, void 0, function* () { let requestUrl; if (baseUrl) { requestUrl = `${baseUrl}/api/v2/applications/${appIdentifier}/subscription`; } else if (!!organization) { requestUrl = `https://${organization}.api.crowdin.com/api/v2/applications/${appIdentifier}/subscription`; } else { requestUrl = `https://crowdin.com/api/v2/applications/${appIdentifier}/subscription`; } try { const response = yield axios_1.default.get(requestUrl, { headers: { Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { const e = error; if (e.response) { if (e.response.status === 402) { throw new PaymentRequiredError((_a = e.response.data) === null || _a === void 0 ? void 0 : _a.subscribeLink, (_b = e.response.data) === null || _b === void 0 ? void 0 : _b.initializedAt); } else if ((_d = (_c = e.response.data) === null || _c === void 0 ? void 0 : _c.error) === null || _d === void 0 ? void 0 : _d.message) { throw new Error(e.response.data.error.message); } } throw e; } }); } exports.getSubscription = getSubscription; function generateReport({ client, projectId, request, }) { return __awaiter(this, void 0, void 0, function* () { const report = yield client.reportsApi.generateReport(projectId, request); while (true) { const status = yield client.reportsApi.checkReportStatus(projectId, report.data.identifier); if (status.data.status === 'finished') { const downloadRes = yield client.reportsApi.downloadReport(projectId, report.data.identifier); const reportBlob = yield axios_1.default.get(downloadRes.data.url); return reportBlob.data; } } }); } exports.generateReport = generateReport;