diff --git a/dist/resource-translator/index.js b/dist/resource-translator/index.js index 20d5809..edf8b65 100644 --- a/dist/resource-translator/index.js +++ b/dist/resource-translator/index.js @@ -2641,75 +2641,75 @@ exports.toCommandValue = toCommandValue; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PortableObjectParser = void 0; -const po_file_1 = __webpack_require__(390); -const utils_1 = __webpack_require__(834); -class PortableObjectParser { - async parseFrom(fileContent) { - await utils_1.delay(0, null); - let portableObjectFile = { - tokens: [] - }; - if (fileContent) { - portableObjectFile.tokens = - fileContent.split('\n').map(line => new po_file_1.PortableObjectToken(line)); - } - return portableObjectFile; - } - toFileFormatted(instance, defaultValue) { - return !!instance ? instance.tokens.map(t => t.line).join('\n') : defaultValue; - } - applyTranslations(portableObject, translations, targetLocale) { - if (portableObject && translations) { - let lastIndex = 0; - for (let key in translations) { - const value = translations[key]; - if (value) { - lastIndex = utils_1.findNext(portableObject.tokens, lastIndex, token => { - let foundFirst = false; - let secondOffset = 0; - if (!token.isInsignificant) { - if (token.value === key) { - foundFirst = true; - secondOffset = token.id === 'msgid' ? 0 : 1; - } - } - return [foundFirst, secondOffset]; - }, (token, secondOffset) => { - let foundSecond = false; - if (!token.isInsignificant) { - foundSecond = secondOffset - ? token.id.startsWith(`msgstr[${secondOffset}]`) - : token.id.startsWith('msgstr'); - } - return foundSecond; - }, token => token.value = value); - } - } - } - return portableObject; - } - toTranslatableTextMap(instance) { - const textToTranslate = new Map(); - const tokens = instance.tokens; - if (tokens && tokens.length) { - tokens.forEach(token => { - if (token.isCommentLine || token.isInsignificant || !token.value) { - return; - } - if (token.id === 'msgid' || token.id === 'msgid_plural') { - textToTranslate.set(token.value, token.value); - } - }); - } - return { - text: textToTranslate - }; - } -} -exports.PortableObjectParser = PortableObjectParser; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PortableObjectParser = void 0; +const po_file_1 = __webpack_require__(390); +const utils_1 = __webpack_require__(834); +class PortableObjectParser { + async parseFrom(fileContent) { + await utils_1.delay(0, null); + let portableObjectFile = { + tokens: [] + }; + if (fileContent) { + portableObjectFile.tokens = + fileContent.split('\n').map(line => new po_file_1.PortableObjectToken(line)); + } + return portableObjectFile; + } + toFileFormatted(instance, defaultValue) { + return !!instance ? instance.tokens.map(t => t.line).join('\n') : defaultValue; + } + applyTranslations(portableObject, translations, targetLocale) { + if (portableObject && translations) { + let lastIndex = 0; + for (let key in translations) { + const value = translations[key]; + if (value) { + lastIndex = utils_1.findNext(portableObject.tokens, lastIndex, token => { + let foundFirst = false; + let secondOffset = 0; + if (!token.isInsignificant) { + if (token.value === key) { + foundFirst = true; + secondOffset = token.id === 'msgid' ? 0 : 1; + } + } + return [foundFirst, secondOffset]; + }, (token, secondOffset) => { + let foundSecond = false; + if (!token.isInsignificant) { + foundSecond = secondOffset + ? token.id.startsWith(`msgstr[${secondOffset}]`) + : token.id.startsWith('msgstr'); + } + return foundSecond; + }, token => token.value = value); + } + } + } + return portableObject; + } + toTranslatableTextMap(instance) { + const textToTranslate = new Map(); + const tokens = instance.tokens; + if (tokens && tokens.length) { + tokens.forEach(token => { + if (token.isCommentLine || token.isInsignificant || !token.value) { + return; + } + if (token.id === 'msgid' || token.id === 'msgid_plural') { + textToTranslate.set(token.value, token.value); + } + }); + } + return { + text: textToTranslate + }; + } +} +exports.PortableObjectParser = PortableObjectParser; /***/ }), @@ -2841,26 +2841,26 @@ module.exports = require("os"); /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.translationFileParserFactory = void 0; -const json_parser_1 = __webpack_require__(225); -const po_parser_1 = __webpack_require__(85); -const restext_parser_1 = __webpack_require__(893); -const resx_parser_1 = __webpack_require__(537); -const xliff_parser_1 = __webpack_require__(503); -exports.translationFileParserFactory = (translationFileKind) => { - switch (translationFileKind) { - case 'resx': return new resx_parser_1.ResxParser(); - case 'xliff': return new xliff_parser_1.XliffParser(); - case 'restext': return new restext_parser_1.RestextParser(); - case 'ini': return new restext_parser_1.RestextParser(); - case 'po': return new po_parser_1.PortableObjectParser(); - case 'json': return new json_parser_1.JsonParser(); - default: - throw new Error(`Unrecognized resource kind: ${translationFileKind}`); - } -}; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.translationFileParserFactory = void 0; +const json_parser_1 = __webpack_require__(225); +const po_parser_1 = __webpack_require__(85); +const restext_parser_1 = __webpack_require__(893); +const resx_parser_1 = __webpack_require__(537); +const xliff_parser_1 = __webpack_require__(503); +exports.translationFileParserFactory = (translationFileKind) => { + switch (translationFileKind) { + case 'resx': return new resx_parser_1.ResxParser(); + case 'xliff': return new xliff_parser_1.XliffParser(); + case 'restext': return new restext_parser_1.RestextParser(); + case 'ini': return new restext_parser_1.RestextParser(); + case 'po': return new po_parser_1.PortableObjectParser(); + case 'json': return new json_parser_1.JsonParser(); + default: + throw new Error(`Unrecognized resource kind: ${translationFileKind}`); + } +}; /***/ }), @@ -2899,25 +2899,6 @@ function issueCommand(command, message) { exports.issueCommand = issueCommand; //# sourceMappingURL=file-command.js.map -/***/ }), - -/***/ 104: -/***/ (function(module) { - -"use strict"; - - -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -module.exports = function isAxiosError(payload) { - return (typeof payload === 'object') && (payload.isAxiosError === true); -}; - - /***/ }), /***/ 118: @@ -3663,12 +3644,19 @@ module.exports = function xhrAdapter(config) { delete requestHeaders['Content-Type']; // Let the browser set it } + if ( + (utils.isBlob(requestData) || utils.isFile(requestData)) && + requestData.type + ) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + var password = unescape(encodeURIComponent(config.auth.password)) || ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } @@ -3830,71 +3818,71 @@ module.exports = function xhrAdapter(config) { /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonParser = void 0; -class JsonParser { - parseFrom(fileContent) { - const buildMap = (obj, parentPath) => { - for (const [key, value] of Object.entries(obj)) { - const path = parentPath ? `${parentPath}.${key}` : key; - if (typeof value === "string") { - map.set(path, value); - } - else { - buildMap(value, path); - } - } - }; - const map = new Map(); - try { - const content = JSON.parse(fileContent); - buildMap(content); - } - catch (e) { - throw new Error(`Failed to parse json. Error: ${e}. Content: ${fileContent}`); - } - return Promise.resolve(Object.fromEntries(map)); - } - toFileFormatted(instance, defaultValue) { - const content = {}; - const buildObject = (obj, keyParts, value) => { - var _a; - const keyPart = keyParts[0]; - const isLastChild = keyParts.length === 1; - obj[keyPart] = isLastChild ? value : (_a = obj[keyPart]) !== null && _a !== void 0 ? _a : {}; - if (!isLastChild) { - buildObject(obj[keyPart], keyParts.slice(1), value); - } - }; - for (const [key, value] of Object.entries(instance)) { - const keyParts = key.split("."); - buildObject(content, keyParts, value); - } - return JSON.stringify(content, null, "\t"); - } - applyTranslations(instance, translations, targetLocale) { - if (instance && translations) { - for (let key in translations) { - const value = translations[key]; - if (value) { - instance[key] = value; - } - } - } - return instance; - } - toTranslatableTextMap(instance) { - const textToTranslate = new Map(); - for (const [key, value] of Object.entries(instance)) { - textToTranslate.set(key, value); - } - return { - text: textToTranslate - }; - } -} -exports.JsonParser = JsonParser; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonParser = void 0; +class JsonParser { + parseFrom(fileContent) { + const buildMap = (obj, parentPath) => { + for (const [key, value] of Object.entries(obj)) { + const path = parentPath ? `${parentPath}.${key}` : key; + if (typeof value === "string") { + map.set(path, value); + } + else { + buildMap(value, path); + } + } + }; + const map = new Map(); + try { + const content = JSON.parse(fileContent); + buildMap(content); + } + catch (e) { + throw new Error(`Failed to parse json. Error: ${e}. Content: ${fileContent}`); + } + return Promise.resolve(Object.fromEntries(map)); + } + toFileFormatted(instance, defaultValue) { + const content = {}; + const buildObject = (obj, keyParts, value) => { + var _a; + const keyPart = keyParts[0]; + const isLastChild = keyParts.length === 1; + obj[keyPart] = isLastChild ? value : (_a = obj[keyPart]) !== null && _a !== void 0 ? _a : {}; + if (!isLastChild) { + buildObject(obj[keyPart], keyParts.slice(1), value); + } + }; + for (const [key, value] of Object.entries(instance)) { + const keyParts = key.split("."); + buildObject(content, keyParts, value); + } + return JSON.stringify(content, null, "\t"); + } + applyTranslations(instance, translations, targetLocale) { + if (instance && translations) { + for (let key in translations) { + const value = translations[key]; + if (value) { + instance[key] = value; + } + } + } + return instance; + } + toTranslatableTextMap(instance) { + const textToTranslate = new Map(); + for (const [key, value] of Object.entries(instance)) { + textToTranslate.set(key, value); + } + return { + text: textToTranslate + }; + } +} +exports.JsonParser = JsonParser; /***/ }), @@ -4505,53 +4493,53 @@ function range(a, b, str) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.summarize = void 0; -const core_1 = __webpack_require__(470); -/** - * Example output: https://gist.github.com/IEvangelist/8e7101bda2bacce98d418b5d0fdda756 - * @param summary The object representing the summary of the action's execution. - */ -exports.summarize = (summary) => { - const fileCount = summary.totalFileCount.toLocaleString('en'); - const translations = summary.totalTranslations.toLocaleString('en'); - const title = `Machine-translated ${fileCount} files, a total of ${translations} translations`; - const env = process.env; - const server = env['GITHUB_SERVER_URL']; - const repo = env['GITHUB_REPOSITORY']; - const commit = env['GITHUB_SHA']; - const triggeredByUrl = `${server}/${repo}/commit/${commit}`; - const nfc = summary.newFileCount.toLocaleString('en'); - const nft = summary.newFileTranslations.toLocaleString('en'); - const ufc = summary.updatedFileCount.toLocaleString('en'); - const uft = summary.updatedFileTranslations.toLocaleString('en'); - // Pull request message template - let details = [ - '# Translation pull request summary', - '', - `Action triggered by ${triggeredByUrl}.`, - '', - `- Source locale: \`${summary.sourceLocale}\``, - `- Destination locale(s): ${summary.toLocales.map(locale => `\`${locale}\``).join(', ')}`, - '', - '## File translation details', - '', - '| Type | File count | Translation count |', - '|---------|------------|-------------------|', - `| New | ${nfc} | ${nft} |`, - `| Updated | ${ufc} | ${uft} |`, - '', - `Of the ${fileCount} translated files, there are a total of ${translations} individual translations.`, - '', - '> These machine translations are a result of Azure Cognitive Services Translator, and the [Machine Translator](https://github.com/marketplace/actions/resource-translator) GitHub action. For more information, see [Translator v3.0](https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-reference?WT.mc_id=dapine). To post an issue, or feature request please do so [here](https://github.com/IEvangelist/resource-translator/issues).', - ]; - core_1.debug(JSON.stringify({ - title, - details - })); - return [title, details.join('\n')]; -}; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.summarize = void 0; +const core_1 = __webpack_require__(470); +/** + * Example output: https://gist.github.com/IEvangelist/8e7101bda2bacce98d418b5d0fdda756 + * @param summary The object representing the summary of the action's execution. + */ +exports.summarize = (summary) => { + const fileCount = summary.totalFileCount.toLocaleString('en'); + const translations = summary.totalTranslations.toLocaleString('en'); + const title = `Machine-translated ${fileCount} files, a total of ${translations} translations`; + const env = process.env; + const server = env['GITHUB_SERVER_URL']; + const repo = env['GITHUB_REPOSITORY']; + const commit = env['GITHUB_SHA']; + const triggeredByUrl = `${server}/${repo}/commit/${commit}`; + const nfc = summary.newFileCount.toLocaleString('en'); + const nft = summary.newFileTranslations.toLocaleString('en'); + const ufc = summary.updatedFileCount.toLocaleString('en'); + const uft = summary.updatedFileTranslations.toLocaleString('en'); + // Pull request message template + let details = [ + '# Translation pull request summary', + '', + `Action triggered by ${triggeredByUrl}.`, + '', + `- Source locale: \`${summary.sourceLocale}\``, + `- Destination locale(s): ${summary.toLocales.map(locale => `\`${locale}\``).join(', ')}`, + '', + '## File translation details', + '', + '| Type | File count | Translation count |', + '|---------|------------|-------------------|', + `| New | ${nfc} | ${nft} |`, + `| Updated | ${ufc} | ${uft} |`, + '', + `Of the ${fileCount} translated files, there are a total of ${translations} individual translations.`, + '', + '> These machine translations are a result of Azure Cognitive Services Translator, and the [Machine Translator](https://github.com/marketplace/actions/resource-translator) GitHub action. For more information, see [Translator v3.0](https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-reference?WT.mc_id=dapine). To post an issue, or feature request please do so [here](https://github.com/IEvangelist/resource-translator/issues).', + ]; + core_1.debug(JSON.stringify({ + title, + details + })); + return [title, details.join('\n')]; +}; /***/ }), @@ -5259,20 +5247,20 @@ isStream.transform = function (stream) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const core_1 = __webpack_require__(470); -const get_inputs_1 = __webpack_require__(379); -const resource_translator_1 = __webpack_require__(781); -const run = async () => { - try { - await resource_translator_1.start(get_inputs_1.getInputs()); - } - catch (error) { - core_1.setFailed(error); - } -}; -run(); + +Object.defineProperty(exports, "__esModule", { value: true }); +const core_1 = __webpack_require__(470); +const get_inputs_1 = __webpack_require__(379); +const resource_translator_1 = __webpack_require__(781); +const run = async () => { + try { + await resource_translator_1.start(get_inputs_1.getInputs()); + } + catch (error) { + core_1.setFailed(error); + } +}; +run(); /***/ }), @@ -5395,9 +5383,6 @@ axios.all = function all(promises) { }; axios.spread = __webpack_require__(879); -// Expose isAxiosError -axios.isAxiosError = __webpack_require__(104); - module.exports = axios; // Allow use of default import syntax in TypeScript @@ -5416,7 +5401,7 @@ module.exports = require("assert"); /***/ 361: /***/ (function(module) { -module.exports = {"_args":[["axios@0.21.1","D:\\github\\resource-translator"]],"_from":"axios@0.21.1","_id":"axios@0.21.1","_inBundle":false,"_integrity":"sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==","_location":"/axios","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"axios@0.21.1","name":"axios","escapedName":"axios","rawSpec":"0.21.1","saveSpec":null,"fetchSpec":"0.21.1"},"_requiredBy":["/","/@types/axios"],"_resolved":"https://registry.npmjs.org/axios/-/axios-0.21.1.tgz","_spec":"0.21.1","_where":"D:\\github\\resource-translator","author":{"name":"Matt Zabriskie"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"bugs":{"url":"https://github.com/axios/axios/issues"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}],"dependencies":{"follow-redirects":"^1.10.0"},"description":"Promise based HTTP client for the browser and node.js","devDependencies":{"bundlesize":"^0.17.0","coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.0.2","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^20.1.0","grunt-karma":"^2.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^1.0.18","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^1.3.0","karma-chrome-launcher":"^2.2.0","karma-coverage":"^1.1.1","karma-firefox-launcher":"^1.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-opera-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^1.2.0","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^1.7.0","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^5.2.0","sinon":"^4.5.0","typescript":"^2.8.1","url-search-params":"^0.10.0","webpack":"^1.13.1","webpack-dev-server":"^1.14.1"},"homepage":"https://github.com/axios/axios","jsdelivr":"dist/axios.min.js","keywords":["xhr","http","ajax","promise","node"],"license":"MIT","main":"index.js","name":"axios","repository":{"type":"git","url":"git+https://github.com/axios/axios.git"},"scripts":{"build":"NODE_ENV=production grunt build","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","examples":"node ./examples/server.js","fix":"eslint --fix lib/**/*.js","postversion":"git push && git push --tags","preversion":"npm test","start":"node ./sandbox/server.js","test":"grunt test && bundlesize","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"},"typings":"./index.d.ts","unpkg":"dist/axios.min.js","version":"0.21.1"}; +module.exports = {"_args":[["axios@0.20.0","C:\\Users\\dapine\\source\\repos\\resource-translator"]],"_from":"axios@0.20.0","_id":"axios@0.20.0","_inBundle":false,"_integrity":"sha512-ANA4rr2BDcmmAQLOKft2fufrtuvlqR+cXNNinUmvfeSNCOF98PZL+7M/v1zIdGo7OLjEA9J2gXJL+j4zGsl0bA==","_location":"/axios","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"axios@0.20.0","name":"axios","escapedName":"axios","rawSpec":"0.20.0","saveSpec":null,"fetchSpec":"0.20.0"},"_requiredBy":["/","/@types/axios"],"_resolved":"https://registry.npmjs.org/axios/-/axios-0.20.0.tgz","_spec":"0.20.0","_where":"C:\\Users\\dapine\\source\\repos\\resource-translator","author":{"name":"Matt Zabriskie"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"bugs":{"url":"https://github.com/axios/axios/issues"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}],"dependencies":{"follow-redirects":"^1.10.0"},"description":"Promise based HTTP client for the browser and node.js","devDependencies":{"bundlesize":"^0.17.0","coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.0.2","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^20.1.0","grunt-karma":"^2.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^1.0.18","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^1.3.0","karma-chrome-launcher":"^2.2.0","karma-coverage":"^1.1.1","karma-firefox-launcher":"^1.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-opera-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^1.2.0","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^1.7.0","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^5.2.0","sinon":"^4.5.0","typescript":"^2.8.1","url-search-params":"^0.10.0","webpack":"^1.13.1","webpack-dev-server":"^1.14.1"},"homepage":"https://github.com/axios/axios","jsdelivr":"dist/axios.min.js","keywords":["xhr","http","ajax","promise","node"],"license":"MIT","main":"index.js","name":"axios","repository":{"type":"git","url":"git+https://github.com/axios/axios.git"},"scripts":{"build":"NODE_ENV=production grunt build","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","examples":"node ./examples/server.js","fix":"eslint --fix lib/**/*.js","postversion":"git push && git push --tags","preversion":"npm test","start":"node ./sandbox/server.js","test":"grunt test && bundlesize","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"},"typings":"./index.d.ts","unpkg":"dist/axios.min.js","version":"0.20.0"}; /***/ }), @@ -5490,37 +5475,37 @@ module.exports = function enhanceError(error, config, code, request, response) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getQuestionableArray = exports.getInputs = void 0; -const core_1 = __webpack_require__(470); -exports.getInputs = () => { - const inputs = { - subscriptionKey: core_1.getInput('subscriptionKey', { required: true }), - endpoint: core_1.getInput('endpoint', { required: true }), - sourceLocale: core_1.getInput('sourceLocale', { required: true }), - region: core_1.getInput('region'), - toLocales: exports.getQuestionableArray('toLocales') - }; - return inputs; -}; -/** - * Valid formats for parsing string into JS array: - * "'es','de','fr'" - * "[ 'es', 'de', 'fr' ]" -*/ -exports.getQuestionableArray = (inputName) => { - const value = core_1.getInput(inputName); - if (value) { - if (value.indexOf('[') > -1) { - return [...JSON.parse(value)]; - } - else { - return value.replace(/\s/g, '').split(','); - } - } - return undefined; -}; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getQuestionableArray = exports.getInputs = void 0; +const core_1 = __webpack_require__(470); +exports.getInputs = () => { + const inputs = { + subscriptionKey: core_1.getInput('subscriptionKey', { required: true }), + endpoint: core_1.getInput('endpoint', { required: true }), + sourceLocale: core_1.getInput('sourceLocale', { required: true }), + region: core_1.getInput('region'), + toLocales: exports.getQuestionableArray('toLocales') + }; + return inputs; +}; +/** + * Valid formats for parsing string into JS array: + * "'es','de','fr'" + * "[ 'es', 'de', 'fr' ]" +*/ +exports.getQuestionableArray = (inputName) => { + const value = core_1.getInput(inputName); + if (value) { + if (value.indexOf('[') > -1) { + return [...JSON.parse(value)]; + } + else { + return value.replace(/\s/g, '').split(','); + } + } + return undefined; +}; /***/ }), @@ -6053,43 +6038,43 @@ module.exports = readShebang; /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PortableObjectToken = void 0; -const firstWhitespace = /\s+(.*)/; -// https://www.yogihosting.com/portable-object-aspnet-core/ -class PortableObjectToken { - constructor(line) { - this.line = line; - this._identifier = null; - this._value = null; - if (line && line.trim()) { - const keyValuePair = line.split(firstWhitespace); - this._identifier = keyValuePair[0]; - this._value = keyValuePair.length > 1 ? keyValuePair[1] : null; - this._isInsignificant = false; - } - else { - this._isInsignificant = true; - } - } - get id() { - return this._identifier; - } - get value() { - return this._value; - } - set value(value) { - this._value = value; - } - get isInsignificant() { - return this._isInsignificant; - } - get isCommentLine() { - return !!this.line && this.line.startsWith('#:'); - } -} -exports.PortableObjectToken = PortableObjectToken; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PortableObjectToken = void 0; +const firstWhitespace = /\s+(.*)/; +// https://www.yogihosting.com/portable-object-aspnet-core/ +class PortableObjectToken { + constructor(line) { + this.line = line; + this._identifier = null; + this._value = null; + if (line && line.trim()) { + const keyValuePair = line.split(firstWhitespace); + this._identifier = keyValuePair[0]; + this._value = keyValuePair.length > 1 ? keyValuePair[1] : null; + this._isInsignificant = false; + } + else { + this._isInsignificant = true; + } + } + get id() { + return this._identifier; + } + get value() { + return this._value; + } + set value(value) { + this._value = value; + } + get isInsignificant() { + return this._isInsignificant; + } + get isCommentLine() { + return !!this.line && this.line.startsWith('#:'); + } +} +exports.PortableObjectToken = PortableObjectToken; /***/ }), @@ -6700,92 +6685,92 @@ function escapeProperty(s) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.findAllTranslationFiles = void 0; -const core_1 = __webpack_require__(470); -const github_1 = __webpack_require__(469); -const glob_1 = __webpack_require__(281); -const io_util_1 = __webpack_require__(672); -const path_1 = __webpack_require__(622); -const translationFileSchemes = { - ini: (locale) => `**/*.${locale}.ini`, - po: `**/*.po`, - restext: (locale) => `**/*.${locale}.restext`, - resx: (locale) => `**/*.${locale}.resx`, - xliff: (locale) => `**/*.${locale}.xliff`, - json: (locale) => `**/*.${locale}.json` -}; -async function findAllTranslationFiles(sourceLocale) { - const filesToInclude = await getFilesToInclude(); - const includeFile = (filepath) => { - if (filesToInclude && filesToInclude.length > 0) { - const filename = path_1.basename(filepath); - const include = filesToInclude.some(f => f.toLowerCase() === filename.toLowerCase()); - core_1.debug(`include=${include}, ${filename}`); - return include; - } - return true; - }; - const patterns = Object.values(translationFileSchemes).map(fileScheme => { - return "function" === typeof fileScheme ? fileScheme(sourceLocale) : fileScheme; - }); - const globber = await glob_1.create(patterns.join('\n')); - const filesAndDirectories = await globber.glob(); - const promises = filesAndDirectories.map(async (path) => { - return { - path: path_1.normalize(path), - isDirectory: await io_util_1.isDirectory(path), - include: includeFile(path) - }; - }); - const files = await Promise.all(promises); - const results = files.filter(file => file.include && !file.isDirectory) - .map(file => file.path); - core_1.debug(`Files to translate:\n\t${results.join('\n\t')}`); - return { - po: results.filter(f => f.endsWith('.po')), - restext: results.filter(f => f.endsWith('.restext')), - ini: results.filter(f => f.endsWith('.ini')), - resx: results.filter(f => f.endsWith('.resx')), - xliff: results.filter(f => f.endsWith('.xliff')), - json: results.filter(f => f.endsWith('.json')) - }; -} -exports.findAllTranslationFiles = findAllTranslationFiles; -async function getFilesToInclude() { - try { - // Get all files related to trigger. - const token = process.env['GITHUB_TOKEN'] || null; - if (token) { - const octokit = github_1.getOctokit(token); - const options = { - ...github_1.context.repo, - ref: github_1.context.ref - }; - core_1.debug(JSON.stringify(options)); - const response = await octokit.repos.getCommit(options); - core_1.debug(JSON.stringify(response)); - if (response.data) { - const files = [ - ...new Set(response.data.files.map(file => { - const path = path_1.resolve(__dirname, file.filename); - return path_1.basename(path); - })) - ]; - core_1.debug(`Files from trigger:\n\t${files.join('\n\t')}`); - return files; - } - } - else { - core_1.debug("Unable to get the GITHUB_TOKEN from the environment."); - } - } - catch (error) { - core_1.debug(error); - } - return []; -} + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.findAllTranslationFiles = void 0; +const core_1 = __webpack_require__(470); +const github_1 = __webpack_require__(469); +const glob_1 = __webpack_require__(281); +const io_util_1 = __webpack_require__(672); +const path_1 = __webpack_require__(622); +const translationFileSchemes = { + ini: (locale) => `**/*.${locale}.ini`, + po: `**/*.po`, + restext: (locale) => `**/*.${locale}.restext`, + resx: (locale) => `**/*.${locale}.resx`, + xliff: (locale) => `**/*.${locale}.xliff`, + json: (locale) => `**/*.${locale}.json` +}; +async function findAllTranslationFiles(sourceLocale) { + const filesToInclude = await getFilesToInclude(); + const includeFile = (filepath) => { + if (filesToInclude && filesToInclude.length > 0) { + const filename = path_1.basename(filepath); + const include = filesToInclude.some(f => f.toLowerCase() === filename.toLowerCase()); + core_1.debug(`include=${include}, ${filename}`); + return include; + } + return true; + }; + const patterns = Object.values(translationFileSchemes).map(fileScheme => { + return "function" === typeof fileScheme ? fileScheme(sourceLocale) : fileScheme; + }); + const globber = await glob_1.create(patterns.join('\n')); + const filesAndDirectories = await globber.glob(); + const promises = filesAndDirectories.map(async (path) => { + return { + path: path_1.normalize(path), + isDirectory: await io_util_1.isDirectory(path), + include: includeFile(path) + }; + }); + const files = await Promise.all(promises); + const results = files.filter(file => file.include && !file.isDirectory) + .map(file => file.path); + core_1.debug(`Files to translate:\n\t${results.join('\n\t')}`); + return { + po: results.filter(f => f.endsWith('.po')), + restext: results.filter(f => f.endsWith('.restext')), + ini: results.filter(f => f.endsWith('.ini')), + resx: results.filter(f => f.endsWith('.resx')), + xliff: results.filter(f => f.endsWith('.xliff')), + json: results.filter(f => f.endsWith('.json')) + }; +} +exports.findAllTranslationFiles = findAllTranslationFiles; +async function getFilesToInclude() { + try { + // Get all files related to trigger. + const token = process.env['GITHUB_TOKEN'] || null; + if (token) { + const octokit = github_1.getOctokit(token); + const options = { + ...github_1.context.repo, + ref: github_1.context.ref + }; + core_1.debug(JSON.stringify(options)); + const response = await octokit.repos.getCommit(options); + core_1.debug(JSON.stringify(response)); + if (response.data) { + const files = [ + ...new Set(response.data.files.map(file => { + const path = path_1.resolve(__dirname, file.filename); + return path_1.basename(path); + })) + ]; + core_1.debug(`Files from trigger:\n\t${files.join('\n\t')}`); + return files; + } + } + else { + core_1.debug("Unable to get the GITHUB_TOKEN from the environment."); + } + } + catch (error) { + core_1.debug(error); + } + return []; +} /***/ }), @@ -8269,55 +8254,55 @@ module.exports = v4; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.XliffParser = void 0; -const xliff_file_1 = __webpack_require__(574); -const xml_file_parser_1 = __webpack_require__(695); -class XliffParser { - async parseFrom(fileContent) { - return await xml_file_parser_1.XmlFileParser.fromXml(fileContent); - } - toFileFormatted(instance, defaultValue) { - try { - return xml_file_parser_1.XmlFileParser.toXml(instance); - } - catch (error) { - return defaultValue; - } - } - applyTranslations(instance, translations, targetLocale) { - if (instance && translations && targetLocale) { - instance.xliff.$.trgLang = targetLocale; - for (let key in translations) { - const compositeKey = key.split(xliff_file_1.XliffFileKeyDelimiter); - const index = parseInt(compositeKey[0]); - const sourceKey = compositeKey[1]; - const value = translations[key]; - if (value) { - xliff_file_1.traverseXliff(instance, index, sourceKey, s => s.target = [value]); - } - } - } - return instance; - } - toTranslatableTextMap(instance) { - const textToTranslate = new Map(); - for (let i = 0; i < instance.xliff.file.length; ++i) { - const values = instance.xliff.file[i].unit; - if (values && values.length) { - for (let f = 0; f < values.length; ++f) { - const key = values[f].segment[0].source[0]; - textToTranslate.set(`${i}${xliff_file_1.XliffFileKeyDelimiter}${key}`, key); - } - } - } - return { - text: textToTranslate - }; - } -} -exports.XliffParser = XliffParser; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.XliffParser = void 0; +const xliff_file_1 = __webpack_require__(574); +const xml_file_parser_1 = __webpack_require__(695); +class XliffParser { + async parseFrom(fileContent) { + return await xml_file_parser_1.XmlFileParser.fromXml(fileContent); + } + toFileFormatted(instance, defaultValue) { + try { + return xml_file_parser_1.XmlFileParser.toXml(instance); + } + catch (error) { + return defaultValue; + } + } + applyTranslations(instance, translations, targetLocale) { + if (instance && translations && targetLocale) { + instance.xliff.$.trgLang = targetLocale; + for (let key in translations) { + const compositeKey = key.split(xliff_file_1.XliffFileKeyDelimiter); + const index = parseInt(compositeKey[0]); + const sourceKey = compositeKey[1]; + const value = translations[key]; + if (value) { + xliff_file_1.traverseXliff(instance, index, sourceKey, s => s.target = [value]); + } + } + } + return instance; + } + toTranslatableTextMap(instance) { + const textToTranslate = new Map(); + for (let i = 0; i < instance.xliff.file.length; ++i) { + const values = instance.xliff.file[i].unit; + if (values && values.length) { + for (let f = 0; f < values.length; ++f) { + const key = values[f].segment[0].source[0]; + textToTranslate.set(`${i}${xliff_file_1.XliffFileKeyDelimiter}${key}`, key); + } + } + } + return { + text: textToTranslate + }; + } +} +exports.XliffParser = XliffParser; /***/ }), @@ -8379,44 +8364,44 @@ function addHook (state, kind, name, hook) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toResultSet = void 0; -const utils_1 = __webpack_require__(834); -exports.toResultSet = (results, toLocales, translatableText) => { - const translatableKeys = [...translatableText.keys()]; - const resultSet = {}; - if (results && results.length) { - toLocales.forEach(locale => { - let result = {}; - const matches = results.filter(r => r.translations.some(t => t.to === locale)); - if (matches) { - const translations = toRawTextArray(matches, locale); - const zipped = utils_1.zip(translatableKeys, translations); - for (let i = 0; i < zipped.length; ++i) { - const key = zipped[i][0]; - result[key] = zipped[i][1]; - } - resultSet[locale] = result; - } - }); - } - return resultSet; -}; -const toRawTextArray = (translationResults, locale) => { - const rawTextArray = []; - if (translationResults && translationResults.length) { - for (let i = 0; i < translationResults.length; ++i) { - const translations = translationResults[i].translations; - translations.forEach(translation => { - if (translation.to === locale && translation.text) { - rawTextArray.push(translation.text); - } - }); - } - } - return rawTextArray; -}; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toResultSet = void 0; +const utils_1 = __webpack_require__(834); +exports.toResultSet = (results, toLocales, translatableText) => { + const translatableKeys = [...translatableText.keys()]; + const resultSet = {}; + if (results && results.length) { + toLocales.forEach(locale => { + let result = {}; + const matches = results.filter(r => r.translations.some(t => t.to === locale)); + if (matches) { + const translations = toRawTextArray(matches, locale); + const zipped = utils_1.zip(translatableKeys, translations); + for (let i = 0; i < zipped.length; ++i) { + const key = zipped[i][0]; + result[key] = zipped[i][1]; + } + resultSet[locale] = result; + } + }); + } + return resultSet; +}; +const toRawTextArray = (translationResults, locale) => { + const rawTextArray = []; + if (translationResults && translationResults.length) { + for (let i = 0; i < translationResults.length; ++i) { + const translations = translationResults[i].translations; + translations.forEach(translation => { + if (translation.to === locale && translation.text) { + rawTextArray.push(translation.text); + } + }); + } + } + return rawTextArray; +}; /***/ }), @@ -8796,50 +8781,50 @@ module.exports = defaults; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ResxParser = void 0; -const resource_file_1 = __webpack_require__(685); -const xml_file_parser_1 = __webpack_require__(695); -class ResxParser { - async parseFrom(fileContent) { - return await xml_file_parser_1.XmlFileParser.fromXml(fileContent); - } - toFileFormatted(instance, defaultValue) { - try { - return xml_file_parser_1.XmlFileParser.toXml(instance); - } - catch (error) { - return defaultValue; - } - } - applyTranslations(resource, translations, targetLocale) { - if (resource && translations) { - for (let key in translations) { - const value = translations[key]; - if (value) { - resource_file_1.traverseResx(resource, key, (data) => data.value = [value]); - } - } - } - return resource; - } - toTranslatableTextMap(instance) { - const textToTranslate = new Map(); - const values = instance.root.data; - if (values && values.length) { - for (let i = 0; i < values.length; ++i) { - const key = values[i].$.name; - const value = values[i].value[0]; - textToTranslate.set(key, value); - } - } - return { - text: textToTranslate - }; - } -} -exports.ResxParser = ResxParser; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResxParser = void 0; +const resource_file_1 = __webpack_require__(685); +const xml_file_parser_1 = __webpack_require__(695); +class ResxParser { + async parseFrom(fileContent) { + return await xml_file_parser_1.XmlFileParser.fromXml(fileContent); + } + toFileFormatted(instance, defaultValue) { + try { + return xml_file_parser_1.XmlFileParser.toXml(instance); + } + catch (error) { + return defaultValue; + } + } + applyTranslations(resource, translations, targetLocale) { + if (resource && translations) { + for (let key in translations) { + const value = translations[key]; + if (value) { + resource_file_1.traverseResx(resource, key, (data) => data.value = [value]); + } + } + } + return resource; + } + toTranslatableTextMap(instance) { + const textToTranslate = new Map(); + const values = instance.root.data; + if (values && values.length) { + for (let i = 0; i < values.length; ++i) { + const key = values[i].$.name; + const value = values[i].value[0]; + textToTranslate.set(key, value); + } + } + return { + text: textToTranslate + }; + } +} +exports.ResxParser = ResxParser; /***/ }), @@ -9805,7 +9790,7 @@ function wrap(protocols) { var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); // Executes a request, following redirects - function request(input, options, callback) { + wrappedProtocol.request = function (input, options, callback) { // Parse parameters if (typeof input === "string") { var urlStr = input; @@ -9840,20 +9825,14 @@ function wrap(protocols) { assert.equal(options.protocol, protocol, "protocol mismatch"); debug("options", options); return new RedirectableRequest(options, callback); - } + }; // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); + wrappedProtocol.get = function (input, options, callback) { + var request = wrappedProtocol.request(input, options, callback); + request.end(); + return request; + }; }); return exports; } @@ -9915,104 +9894,104 @@ module.exports.wrap = wrap; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.translate = exports.getAvailableTranslations = void 0; -const core_1 = __webpack_require__(470); -const axios_1 = __importDefault(__webpack_require__(53)); -const uuid_1 = __webpack_require__(898); -const api_result_set_mapper_1 = __webpack_require__(513); -const utils_1 = __webpack_require__(834); -/** -* https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate -*/ -exports.getAvailableTranslations = async () => { - const apiUrl = 'https://api.cognitive.microsofttranslator.com/languages'; - const query = 'api-version=3.0&scope=translation'; - const response = await axios_1.default.get(`${apiUrl}?${query}`); - return response.data; -}; -exports.translate = async (translatorResource, toLocales, translatableText, filePath) => { - try { - // Current Azure Translator API rate limit - // https://docs.microsoft.com/azure/cognitive-services/translator/request-limits#character-and-array-limits-per-request - const apiRateLimit = 10000; - const numberOfElementsLimit = 100; - const validationErrors = []; - translatableText.forEach((value, key) => { - const valueStringifiedLength = JSON.stringify(value).length; - if (valueStringifiedLength > apiRateLimit) { - validationErrors.push(`Text for key '${key}' in file '${filePath}' is too long (${valueStringifiedLength}). Must be ${apiRateLimit} at most.`); - } - }); - if (validationErrors.length) { - core_1.setFailed(validationErrors.join('\r\n')); - return undefined; - } - const data = [...translatableText.values()].map(value => { - return { text: value }; - }); - const headers = { - 'Ocp-Apim-Subscription-Key': translatorResource.subscriptionKey, - 'Content-type': 'application/json', - 'X-ClientTraceId': uuid_1.v4() - }; - if (translatorResource.region) { - headers['Ocp-Apim-Subscription-Region'] = translatorResource.region; - } - const options = { - method: 'POST', - headers, - data, - responseType: 'json' - }; - const baseUrl = translatorResource.endpoint.endsWith('/') - ? translatorResource.endpoint - : `${translatorResource.endpoint}/`; - const characters = JSON.stringify(data).length; - const batchedData = characters > apiRateLimit || data.length > numberOfElementsLimit - ? utils_1.batch(data, numberOfElementsLimit, apiRateLimit) - : [data]; - let results = []; - for (let i = 0; i < batchedData.length; i++) { - const batch = batchedData[i]; - const batchCharacters = JSON.stringify(batch).length; - const localeCount = toLocales.length; - const localesBatchSize = Math.floor(apiRateLimit / batchCharacters); - const batchedLocales = localesBatchSize < localeCount - ? utils_1.chunk(toLocales, localesBatchSize) - : [toLocales]; - for (let j = 0; j < batchedLocales.length; j++) { - const locales = batchedLocales[j]; - const to = locales.map(to => `to=${to}`).join('&'); - core_1.debug(`Data batch ${i + 1}, Locales batch ${j + 1}, locales: ${to}`); - const url = `${baseUrl}translate?api-version=3.0&${to}`; - const response = await axios_1.default.post(url, batch, options); - const responseData = response.data; - core_1.debug(`Data batch ${i + 1}, Locales batch ${j + 1}, response: ${JSON.stringify(responseData)}`); - results = [...results, ...responseData]; - } - } - return api_result_set_mapper_1.toResultSet(results, toLocales, translatableText); - } - catch (ex) { - // Try to write explicit error: - // https://docs.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-reference#errors - const e = ex.response - && ex.response.data - && ex.response.data; - if (e) { - core_1.setFailed(`file: ${filePath}, error: { code: ${e.error.code}, message: '${e.error.message}' }}`); - } - else { - core_1.setFailed(`Failed to translate input: file '${filePath}', ${ex}`); - } - return undefined; - } -}; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.translate = exports.getAvailableTranslations = void 0; +const core_1 = __webpack_require__(470); +const axios_1 = __importDefault(__webpack_require__(53)); +const uuid_1 = __webpack_require__(898); +const api_result_set_mapper_1 = __webpack_require__(513); +const utils_1 = __webpack_require__(834); +/** +* https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate +*/ +exports.getAvailableTranslations = async () => { + const apiUrl = 'https://api.cognitive.microsofttranslator.com/languages'; + const query = 'api-version=3.0&scope=translation'; + const response = await axios_1.default.get(`${apiUrl}?${query}`); + return response.data; +}; +exports.translate = async (translatorResource, toLocales, translatableText, filePath) => { + try { + // Current Azure Translator API rate limit + // https://docs.microsoft.com/azure/cognitive-services/translator/request-limits#character-and-array-limits-per-request + const apiRateLimit = 10000; + const numberOfElementsLimit = 100; + const validationErrors = []; + translatableText.forEach((value, key) => { + const valueStringifiedLength = JSON.stringify(value).length; + if (valueStringifiedLength > apiRateLimit) { + validationErrors.push(`Text for key '${key}' in file '${filePath}' is too long (${valueStringifiedLength}). Must be ${apiRateLimit} at most.`); + } + }); + if (validationErrors.length) { + core_1.setFailed(validationErrors.join('\r\n')); + return undefined; + } + const data = [...translatableText.values()].map(value => { + return { text: value }; + }); + const headers = { + 'Ocp-Apim-Subscription-Key': translatorResource.subscriptionKey, + 'Content-type': 'application/json', + 'X-ClientTraceId': uuid_1.v4() + }; + if (translatorResource.region) { + headers['Ocp-Apim-Subscription-Region'] = translatorResource.region; + } + const options = { + method: 'POST', + headers, + data, + responseType: 'json' + }; + const baseUrl = translatorResource.endpoint.endsWith('/') + ? translatorResource.endpoint + : `${translatorResource.endpoint}/`; + const characters = JSON.stringify(data).length; + const batchedData = characters > apiRateLimit || data.length > numberOfElementsLimit + ? utils_1.batch(data, numberOfElementsLimit, apiRateLimit) + : [data]; + let results = []; + for (let i = 0; i < batchedData.length; i++) { + const batch = batchedData[i]; + const batchCharacters = JSON.stringify(batch).length; + const localeCount = toLocales.length; + const localesBatchSize = Math.floor(apiRateLimit / batchCharacters); + const batchedLocales = localesBatchSize < localeCount + ? utils_1.chunk(toLocales, localesBatchSize) + : [toLocales]; + for (let j = 0; j < batchedLocales.length; j++) { + const locales = batchedLocales[j]; + const to = locales.map(to => `to=${to}`).join('&'); + core_1.debug(`Data batch ${i + 1}, Locales batch ${j + 1}, locales: ${to}`); + const url = `${baseUrl}translate?api-version=3.0&${to}`; + const response = await axios_1.default.post(url, batch, options); + const responseData = response.data; + core_1.debug(`Data batch ${i + 1}, Locales batch ${j + 1}, response: ${JSON.stringify(responseData)}`); + results = [...results, ...responseData]; + } + } + return api_result_set_mapper_1.toResultSet(results, toLocales, translatableText); + } + catch (ex) { + // Try to write explicit error: + // https://docs.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-reference#errors + const e = ex.response + && ex.response.data + && ex.response.data; + if (e) { + core_1.setFailed(`file: ${filePath}, error: { code: ${e.error.code}, message: '${e.error.message}' }}`); + } + else { + core_1.setFailed(`Failed to translate input: file '${filePath}', ${ex}`); + } + return undefined; + } +}; /***/ }), @@ -10471,30 +10450,30 @@ module.exports = parse; /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.findInXliff = exports.traverseXliff = exports.XliffFileKeyDelimiter = void 0; -exports.XliffFileKeyDelimiter = '::'; -exports.traverseXliff = (instance, fileIndex, sourceName, segmentAction) => { - if (instance && segmentAction) { - if (instance.xliff.file && instance.xliff.file.length > fileIndex) { - const unit = instance.xliff.file[fileIndex].unit.find(unit => unit.segment.find(s => s.source.includes(sourceName))); - if (unit) { - segmentAction(unit.segment.find(s => s.source.includes(sourceName))); - } - } - } -}; -exports.findInXliff = (instance, fileIndex, sourceName) => { - if (instance) { - if (instance.xliff.file && instance.xliff.file.length > fileIndex) { - const unit = instance.xliff.file[fileIndex].unit.find(unit => unit.segment.find(s => s.source.includes(sourceName))); - if (unit) { - return unit.segment.find(s => s.source.includes(sourceName)); - } - } - } -}; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.findInXliff = exports.traverseXliff = exports.XliffFileKeyDelimiter = void 0; +exports.XliffFileKeyDelimiter = '::'; +exports.traverseXliff = (instance, fileIndex, sourceName, segmentAction) => { + if (instance && segmentAction) { + if (instance.xliff.file && instance.xliff.file.length > fileIndex) { + const unit = instance.xliff.file[fileIndex].unit.find(unit => unit.segment.find(s => s.source.includes(sourceName))); + if (unit) { + segmentAction(unit.segment.find(s => s.source.includes(sourceName))); + } + } + } +}; +exports.findInXliff = (instance, fileIndex, sourceName) => { + if (instance) { + if (instance.xliff.file && instance.xliff.file.length > fileIndex) { + const unit = instance.xliff.file[fileIndex].unit.find(unit => unit.segment.find(s => s.source.includes(sourceName))); + if (unit) { + return unit.segment.find(s => s.source.includes(sourceName)); + } + } + } +}; /***/ }), @@ -13069,31 +13048,6 @@ var enhanceError = __webpack_require__(369); var isHttps = /https:?/; -/** - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} proxy - * @param {string} location - */ -function setProxy(options, proxy, location) { - options.hostname = proxy.host; - options.host = proxy.host; - options.port = proxy.port; - options.path = location; - - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } - - // If a proxy is used, any redirects must also pass through the proxy - options.beforeRedirect = function beforeRedirect(redirection) { - redirection.headers.host = redirection.host; - setProxy(redirection, proxy, redirection.href); - }; -} - /*eslint consistent-return:0*/ module.exports = function httpAdapter(config) { return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { @@ -13204,11 +13158,11 @@ module.exports = function httpAdapter(config) { }); } + if (shouldProxy) { proxy = { host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol + port: parsedProxyUrl.port }; if (parsedProxyUrl.auth) { @@ -13223,8 +13177,17 @@ module.exports = function httpAdapter(config) { } if (proxy) { + options.hostname = proxy.host; + options.host = proxy.host; options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + options.port = proxy.port; + options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path; + + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } } var transport; @@ -13594,17 +13557,17 @@ function isUnixExecutable(stats) { /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.traverseResx = void 0; -exports.traverseResx = (instance, name, dataAction) => { - if (instance && instance.root && instance.root.data && dataAction) { - const data = instance.root.data.find(d => d.$.name === name); - if (data) { - dataAction(data); - } - } -}; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.traverseResx = void 0; +exports.traverseResx = (instance, name, dataAction) => { + if (instance && instance.root && instance.root.data) { + const data = instance.root.data.find(d => d.$.name === name); + if (data) { + dataAction(data); + } + } +}; /***/ }), @@ -13717,23 +13680,23 @@ exports.Deprecation = Deprecation; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.XmlFileParser = void 0; -const xml2js_1 = __webpack_require__(992); -class XmlFileParser { - static async fromXml(xml) { - const parser = new xml2js_1.Parser(); - const xliffXml = await parser.parseStringPromise(xml); - return xliffXml; - } - static toXml(instance) { - const builder = new xml2js_1.Builder(); - var xliffXml = builder.buildObject(instance); - return xliffXml; - } -} -exports.XmlFileParser = XmlFileParser; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.XmlFileParser = void 0; +const xml2js_1 = __webpack_require__(992); +class XmlFileParser { + static async fromXml(xml) { + const parser = new xml2js_1.Parser(); + const xliffXml = await parser.parseStringPromise(xml); + return xliffXml; + } + static toXml(instance) { + const builder = new xml2js_1.Builder(); + var xliffXml = builder.buildObject(instance); + return xliffXml; + } +} +exports.XmlFileParser = XmlFileParser; /***/ }), @@ -17134,8 +17097,7 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, - url: url, - data: (config || {}).data + url: url })); }; }); @@ -17160,115 +17122,127 @@ module.exports = Axios; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.start = void 0; -const core_1 = __webpack_require__(470); -const fs_1 = __webpack_require__(747); -const summary_1 = __webpack_require__(974); -const translation_api_1 = __webpack_require__(553); -const translation_file_parser_factory_1 = __webpack_require__(93); -const summarizer_1 = __webpack_require__(296); -const utils_1 = __webpack_require__(834); -const reader_writer_1 = __webpack_require__(874); -const translation_file_finder_1 = __webpack_require__(442); -async function start(inputs) { - try { - if (!inputs) { - core_1.setFailed('Both a subscriptionKey and endpoint are required.'); - } - else { - const availableTranslations = await translation_api_1.getAvailableTranslations(); - if (!availableTranslations || !availableTranslations.translation) { - core_1.setFailed("Unable to get target translations."); - return; - } - const sourceLocale = inputs.sourceLocale; - const toLocales = Object.keys(availableTranslations.translation) - .filter(locale => { - if (locale === sourceLocale) { - return false; - } - if (inputs.toLocales && inputs.toLocales.length) { - return inputs.toLocales.some(l => l === locale); - } - return true; - }) - .sort((a, b) => utils_1.naturalLanguageCompare(a, b)); - core_1.info(`Detected translation targets to: ${toLocales.join(", ")}`); - const translationFiles = await translation_file_finder_1.findAllTranslationFiles(inputs.sourceLocale); - if (!translationFiles || - (!translationFiles.po && - !translationFiles.restext && - !translationFiles.resx && - !translationFiles.xliff && - !translationFiles.ini && - !translationFiles.json)) { - core_1.setFailed("Unable to get target resource files."); - return; - } - let summary = new summary_1.Summary(sourceLocale, toLocales); - for (let key of Object.keys(translationFiles)) { - const kind = key; - const files = translationFiles[kind]; - if (!files || !files.length) { - continue; - } - const translationFileParser = translation_file_parser_factory_1.translationFileParserFactory(kind); - for (let index = 0; index < files.length; ++index) { - const filePath = files[index]; - const fileContent = reader_writer_1.readFile(filePath); - const parsedFile = await translationFileParser.parseFrom(fileContent); - const translatableTextMap = translationFileParser.toTranslatableTextMap(parsedFile); - core_1.debug(`Translatable text:\n ${JSON.stringify(translatableTextMap, utils_1.stringifyMap)}`); - if (translatableTextMap) { - const resultSet = await translation_api_1.translate(inputs, toLocales, translatableTextMap.text, filePath); - core_1.debug(`Translation result:\n ${JSON.stringify(resultSet)}`); - if (resultSet) { - const length = translatableTextMap.text.size; - toLocales.forEach(locale => { - const translations = resultSet[locale]; - if (!translations) { - return; - } - const clone = Object.assign({}, parsedFile); - const result = translationFileParser.applyTranslations(clone, translations, locale); - const translatedFile = translationFileParser.toFileFormatted(result, ""); - const newPath = utils_1.getLocaleName(filePath, locale); - if (translatedFile && newPath) { - if (fs_1.existsSync(newPath)) { - summary.updatedFileCount++; - summary.updatedFileTranslations += length; - } - else { - summary.newFileCount++; - summary.newFileTranslations += length; - } - reader_writer_1.writeFile(newPath, translatedFile); - } - }); - } - else { - core_1.setFailed("Unable to translate input text."); - } - } - else { - core_1.setFailed("No translatable text to work with"); - } - } - } - core_1.setOutput('has-new-translations', summary.hasNewTranslations); - const [title, details] = summarizer_1.summarize(summary); - core_1.setOutput('summary-title', title); - core_1.setOutput('summary-details', details); - } - } - catch (error) { - console.trace(); - core_1.setFailed(error.message); - } -} -exports.start = start; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.start = void 0; +const core_1 = __webpack_require__(470); +const fs_1 = __webpack_require__(747); +const summary_1 = __webpack_require__(974); +const translation_api_1 = __webpack_require__(553); +const translation_file_parser_factory_1 = __webpack_require__(93); +const summarizer_1 = __webpack_require__(296); +const utils_1 = __webpack_require__(834); +const reader_writer_1 = __webpack_require__(874); +const translation_file_finder_1 = __webpack_require__(442); +async function start(inputs) { + try { + if (!inputs) { + core_1.setFailed('Both a subscriptionKey and endpoint are required.'); + } + else { + const availableTranslations = await translation_api_1.getAvailableTranslations(); + if (!availableTranslations || !availableTranslations.translation) { + core_1.setFailed("Unable to get target translations."); + return; + } + const sourceLocale = inputs.sourceLocale; + const toLocales = Object.keys(availableTranslations.translation) + .filter(locale => { + if (locale === sourceLocale) { + return false; + } + if (inputs.toLocales && inputs.toLocales.length) { + return inputs.toLocales.some(l => l === locale); + } + return true; + }) + .sort((a, b) => utils_1.naturalLanguageCompare(a, b)); + core_1.info(`Detected translation targets to: ${toLocales.join(", ")}`); + const translationFiles = await translation_file_finder_1.findAllTranslationFiles(inputs.sourceLocale); + if (!translationFiles || + (!translationFiles.po && + !translationFiles.restext && + !translationFiles.resx && + !translationFiles.xliff && + !translationFiles.ini && + !translationFiles.json)) { + core_1.setFailed("Unable to get target resource files."); + return; + } + let summary = new summary_1.Summary(sourceLocale, toLocales); + for (let key of Object.keys(translationFiles)) { + core_1.debug(`Iterating translationFiles keys, key: ${key}`); + const kind = key; + const files = translationFiles[kind]; + if (!files || !files.length) { + core_1.debug(`For kind ${kind}, there are no translation files.`); + continue; + } + core_1.debug(`Translation file parser kind: ${kind}`); + const translationFileParser = translation_file_parser_factory_1.translationFileParserFactory(kind); + for (let index = 0; index < files.length; ++index) { + const filePath = files[index]; + const fileContent = reader_writer_1.readFile(filePath); + const parsedFile = await translationFileParser.parseFrom(fileContent); + const translatableTextMap = translationFileParser.toTranslatableTextMap(parsedFile); + core_1.debug(`Translatable text:\n ${JSON.stringify(translatableTextMap, utils_1.stringifyMap)}`); + if (translatableTextMap) { + const resultSet = await translation_api_1.translate(inputs, toLocales, translatableTextMap.text, filePath); + core_1.debug(`Translation result:\n ${JSON.stringify(resultSet)}`); + if (resultSet !== undefined) { + const length = translatableTextMap.text.size; + core_1.debug(`Translation count: ${length}, toLocales size: ${toLocales.length}`); + for (let i = 0; i < toLocales.length; ++i) { + const locale = toLocales[i]; + const translations = resultSet[locale]; + if (translations) { + const clone = Object.assign({}, parsedFile); + const result = translationFileParser.applyTranslations(clone, translations, locale); + const translatedFile = translationFileParser.toFileFormatted(result, ""); + const newPath = utils_1.getLocaleName(filePath, locale); + if (translatedFile && newPath) { + core_1.debug(`The newPath: ${newPath}`); + if (fs_1.existsSync(newPath)) { + summary.updatedFileCount++; + summary.updatedFileTranslations += length; + } + else { + summary.newFileCount++; + summary.newFileTranslations += length; + } + reader_writer_1.writeFile(newPath, translatedFile); + } + else { + core_1.debug(`The translatedFile value is ${translatedFile}`); + core_1.debug(`The newPath would have been ${newPath}`); + } + } + else { + core_1.debug(`Unable to find resulting translations for: ${locale}`); + } + } + } + else { + core_1.setFailed("Unable to translate input text."); + } + } + else { + core_1.setFailed("No translatable text to work with"); + } + } + } + core_1.setOutput('has-new-translations', summary.hasNewTranslations); + const [title, details] = summarizer_1.summarize(summary); + core_1.setOutput('summary-title', title); + core_1.setOutput('summary-details', details); + } + } + catch (error) { + console.trace(); + core_1.setFailed(error.message); + } +} +exports.start = start; /***/ }), @@ -20043,114 +20017,116 @@ exports.FetchError = FetchError; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.batch = exports.findNext = exports.delay = exports.zip = exports.chunk = exports.findValueByKey = exports.stringifyMap = exports.naturalLanguageCompare = exports.getLocaleName = exports.groupBy = void 0; -const path_1 = __webpack_require__(622); -exports.groupBy = (array, key) => array.reduce((result, obj) => { - const value = obj[key]; - result[value] = [...(result[value] || []), obj]; - return result; -}, {}); -exports.getLocaleName = (existingPath, locale) => { - const fileName = path_1.basename(existingPath); - const segments = fileName.split('.'); - switch (segments.length) { - case 3: - return path_1.join(path_1.dirname(existingPath), `${segments[0]}.${locale}.${segments[2]}`); - case 2: - return path_1.join(path_1.dirname(existingPath), `${locale}.${segments[1]}`); - } - return null; -}; -exports.naturalLanguageCompare = (a, b) => { - return !!a && !!b ? a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) : 0; -}; -function stringifyMap(key, value) { - const obj = this[key]; - return (obj instanceof Map) - ? { - dataType: 'Map', - value: Array.from(obj.entries()) - } - : value; -} -exports.stringifyMap = stringifyMap; -function findValueByKey(object, key) { - let value; - Object.keys(object).some(function (k) { - if (k === key) { - value = object[k]; - return true; - } - if (object[k] && typeof object[k] === 'object') { - value = findValueByKey(object[k], key); - return value !== undefined; - } - }); - return value; -} -exports.findValueByKey = findValueByKey; -function chunk(array, size) { - const chunked = []; - let index = 0; - while (index < array.length) { - chunked.push(array.slice(index, size + index)); - index += size; - } - return chunked; -} -exports.chunk = chunk; -function zip(first, second) { - return first.map((value, i) => { - return [value, second[i]]; - }); -} -exports.zip = zip; -exports.delay = (ms, result) => { - return new Promise(resolve => setTimeout(() => resolve(result), ms)); -}; -exports.findNext = (items, startIndex, firstPredicate, secondPredicate, actionOfNext) => { - if (items && items.length) { - let foundFirst = false; - let secondOffset = 0; - for (let index = startIndex; index < items.length; ++index) { - const item = items[index]; - const [first, i] = firstPredicate(item); - if (first) { - foundFirst = true; - secondOffset = i; - continue; - } - if (foundFirst && secondPredicate(item, secondOffset)) { - actionOfNext(item); - return index; - } - } - } - return -1; -}; -function batch(array, maxBatchSize, maxStringifiedSize) { - const batches = []; - let currentStringifiedSize = 0; - let currentBatch = []; - array.forEach((value, index) => { - currentBatch.push(value); - currentStringifiedSize += JSON.stringify(value).length; - const isLastElement = index === array.length - 1; - const batchIsFull = currentBatch.length === maxBatchSize || - isLastElement || - currentStringifiedSize + JSON.stringify(array[index + 1]).length >= maxStringifiedSize; - if (!batchIsFull) { - return; - } - batches.push(currentBatch); - currentBatch = []; - currentStringifiedSize = 0; - }); - return batches; -} -exports.batch = batch; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.batch = exports.findNext = exports.delay = exports.zip = exports.chunk = exports.findValueByKey = exports.stringifyMap = exports.naturalLanguageCompare = exports.getLocaleName = exports.groupBy = void 0; +const path_1 = __webpack_require__(622); +exports.groupBy = (array, key) => array.reduce((result, obj) => { + const value = obj[key]; + result[value] = [...(result[value] || []), obj]; + return result; +}, {}); +exports.getLocaleName = (existingPath, locale) => { + const fileName = path_1.basename(existingPath); + const segments = fileName.split('.'); + switch (segments.length) { + case 4: + return path_1.join(path_1.dirname(existingPath), `${segments[0]}.${segments[1]}.${locale}.${segments[3]}`); + case 3: + return path_1.join(path_1.dirname(existingPath), `${segments[0]}.${locale}.${segments[2]}`); + case 2: + return path_1.join(path_1.dirname(existingPath), `${locale}.${segments[1]}`); + } + return null; +}; +exports.naturalLanguageCompare = (a, b) => { + return !!a && !!b ? a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) : 0; +}; +function stringifyMap(key, value) { + const obj = this[key]; + return (obj instanceof Map) + ? { + dataType: 'Map', + value: Array.from(obj.entries()) + } + : value; +} +exports.stringifyMap = stringifyMap; +function findValueByKey(object, key) { + let value; + Object.keys(object).some(function (k) { + if (k === key) { + value = object[k]; + return true; + } + if (object[k] && typeof object[k] === 'object') { + value = findValueByKey(object[k], key); + return value !== undefined; + } + }); + return value; +} +exports.findValueByKey = findValueByKey; +function chunk(array, size) { + const chunked = []; + let index = 0; + while (index < array.length) { + chunked.push(array.slice(index, size + index)); + index += size; + } + return chunked; +} +exports.chunk = chunk; +function zip(first, second) { + return first.map((value, i) => { + return [value, second[i]]; + }); +} +exports.zip = zip; +exports.delay = (ms, result) => { + return new Promise(resolve => setTimeout(() => resolve(result), ms)); +}; +exports.findNext = (items, startIndex, firstPredicate, secondPredicate, actionOfNext) => { + if (items && items.length) { + let foundFirst = false; + let secondOffset = 0; + for (let index = startIndex; index < items.length; ++index) { + const item = items[index]; + const [first, i] = firstPredicate(item); + if (first) { + foundFirst = true; + secondOffset = i; + continue; + } + if (foundFirst && secondPredicate(item, secondOffset)) { + actionOfNext(item); + return index; + } + } + } + return -1; +}; +function batch(array, maxBatchSize, maxStringifiedSize) { + const batches = []; + let currentStringifiedSize = 0; + let currentBatch = []; + array.forEach((value, index) => { + currentBatch.push(value); + currentStringifiedSize += JSON.stringify(value).length; + const isLastElement = index === array.length - 1; + const batchIsFull = currentBatch.length === maxBatchSize || + isLastElement || + currentStringifiedSize + JSON.stringify(array[index + 1]).length >= maxStringifiedSize; + if (!batchIsFull) { + return; + } + batches.push(currentBatch); + currentBatch = []; + currentStringifiedSize = 0; + }); + return batches; +} +exports.batch = batch; /***/ }), @@ -21522,24 +21498,24 @@ module.exports = require("tty"); /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.writeFile = exports.readFile = void 0; -const core_1 = __webpack_require__(470); -const fs_1 = __webpack_require__(747); -const path_1 = __webpack_require__(622); -function readFile(path) { - const resolved = path_1.resolve(path); - const file = fs_1.readFileSync(resolved, 'utf-8'); - core_1.debug(`Read file: ${file}`); - return file; -} -exports.readFile = readFile; -function writeFile(path, content) { - core_1.debug(`Write file, path: ${path}\nContent: ${content}`); - fs_1.writeFileSync(path, content); -} -exports.writeFile = writeFile; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.writeFile = exports.readFile = void 0; +const core_1 = __webpack_require__(470); +const fs_1 = __webpack_require__(747); +const path_1 = __webpack_require__(622); +function readFile(path) { + const resolved = path_1.resolve(path); + const file = fs_1.readFileSync(resolved, 'utf-8'); + core_1.debug(`Read file: ${file}`); + return file; +} +exports.readFile = readFile; +function writeFile(path, content) { + core_1.debug(`Write file, path: ${path}\nContent: ${content}`); + fs_1.writeFileSync(path, content); +} +exports.writeFile = writeFile; /***/ }), @@ -22175,92 +22151,92 @@ module.exports = function combineURLs(baseURL, relativeURL) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RestextParser = void 0; -const utils_1 = __webpack_require__(834); -const whiteSpace = /\S/; -class RestextParser { - constructor() { - this.isComment = (line) => { - return !!line && line.startsWith(';'); - }; - this.isSection = (line) => { - return !!line && line.startsWith('['); - }; - this.isWhitespace = (line) => { - return !whiteSpace.test(line); - }; - } - async parseFrom(fileContent) { - await utils_1.delay(0, null); - let map = new Map(); - let restextFile = { map: new Map() }; - if (fileContent) { - fileContent.split('\n').map((line, index) => { - if (this.isComment(line) || this.isSection(line) || this.isWhitespace(line)) { - restextFile = { - ...restextFile, - [index]: line - }; - } - else { - const keyValuePair = line.split('='); - const key = keyValuePair[0]; - const val = keyValuePair[1]; - map.set(index, key); - restextFile = { - ...restextFile, - [key]: val - }; - } - }); - } - restextFile.map = map; - return restextFile; - } - toFileFormatted(instance, defaultValue) { - const map = instance.map; - const keys = Object.keys(instance); - const length = map.size + keys.length - 1; - let text = ''; - for (let index = 0; index < length; ++index) { - const line = instance[index]; - const delimiter = index === 0 ? '' : '\n'; - if (this.isComment(line) || this.isSection(line) || this.isWhitespace(line)) { - text += `${delimiter}${line}`; - } - else if (map.has(index)) { - const key = map.get(index); - text += `${delimiter}${key}=${instance[key]}`; - } - } - return text || defaultValue; - } - applyTranslations(instance, translations, targetLocale) { - if (instance && translations) { - for (let key in translations) { - const value = translations[key]; - if (value) { - instance[key] = value; - } - } - } - return instance; - } - toTranslatableTextMap(instance) { - const textToTranslate = new Map(); - for (const [key, value] of Object.entries(instance)) { - if (typeof key !== 'number') { - textToTranslate.set(key, value); - } - } - return { - text: textToTranslate - }; - } -} -exports.RestextParser = RestextParser; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RestextParser = void 0; +const utils_1 = __webpack_require__(834); +const whiteSpace = /\S/; +class RestextParser { + constructor() { + this.isComment = (line) => { + return !!line && line.startsWith(';'); + }; + this.isSection = (line) => { + return !!line && line.startsWith('['); + }; + this.isWhitespace = (line) => { + return !whiteSpace.test(line); + }; + } + async parseFrom(fileContent) { + await utils_1.delay(0, null); + let map = new Map(); + let restextFile = { map: new Map() }; + if (fileContent) { + fileContent.split('\n').map((line, index) => { + if (this.isComment(line) || this.isSection(line) || this.isWhitespace(line)) { + restextFile = { + ...restextFile, + [index]: line + }; + } + else { + const keyValuePair = line.split('='); + const key = keyValuePair[0]; + const val = keyValuePair[1]; + map.set(index, key); + restextFile = { + ...restextFile, + [key]: val + }; + } + }); + } + restextFile.map = map; + return restextFile; + } + toFileFormatted(instance, defaultValue) { + const map = instance.map; + const keys = Object.keys(instance); + const length = map.size + keys.length - 1; + let text = ''; + for (let index = 0; index < length; ++index) { + const line = instance[index]; + const delimiter = index === 0 ? '' : '\n'; + if (this.isComment(line) || this.isSection(line) || this.isWhitespace(line)) { + text += `${delimiter}${line}`; + } + else if (map.has(index)) { + const key = map.get(index); + text += `${delimiter}${key}=${instance[key]}`; + } + } + return text || defaultValue; + } + applyTranslations(instance, translations, targetLocale) { + if (instance && translations) { + for (let key in translations) { + const value = translations[key]; + if (value) { + instance[key] = value; + } + } + } + return instance; + } + toTranslatableTextMap(instance) { + const textToTranslate = new Map(); + for (const [key, value] of Object.entries(instance)) { + if (typeof key !== 'number') { + textToTranslate.set(key, value); + } + } + return { + text: textToTranslate + }; + } +} +exports.RestextParser = RestextParser; /***/ }), @@ -23496,29 +23472,29 @@ exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; /***/ (function(__unusedmodule, exports) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Summary = void 0; -class Summary { - constructor(sourceLocale, toLocales) { - this.sourceLocale = sourceLocale; - this.toLocales = toLocales; - this.newFileCount = 0; - this.newFileTranslations = 0; - this.updatedFileCount = 0; - this.updatedFileTranslations = 0; - } - get totalFileCount() { - return this.newFileCount + this.updatedFileCount; - } - get totalTranslations() { - return this.newFileTranslations + this.updatedFileTranslations; - } - get hasNewTranslations() { - return this.totalTranslations > 0; - } -} -exports.Summary = Summary; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Summary = void 0; +class Summary { + constructor(sourceLocale, toLocales) { + this.sourceLocale = sourceLocale; + this.toLocales = toLocales; + this.newFileCount = 0; + this.newFileTranslations = 0; + this.updatedFileCount = 0; + this.updatedFileTranslations = 0; + } + get totalFileCount() { + return this.newFileCount + this.updatedFileCount; + } + get totalTranslations() { + return this.newFileTranslations + this.updatedFileTranslations; + } + get hasNewTranslations() { + return this.totalTranslations > 0; + } +} +exports.Summary = Summary; /***/ }),