Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

tant-intl

Package Overview
Dependencies
Maintainers
1
Versions
51
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tant-intl - npm Package Compare versions

Comparing version 0.1.8 to 0.2.0

es/cli.d.ts

1046

es/cli.js
#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, unlinkSync } from 'fs';
import dayjs from 'dayjs';
import fetch from 'node-fetch';
import { cloneDeep } from 'lodash';
var csvtojsonV2 = require("csvtojson");
var error = function error(obj) {
console.log('\x1B[31m', "\u3010".concat(dayjs().format('YYYY-MM-DD hh:mm:ss.SSS'), "\u3011\u3010tant-intl\u3011").concat(obj), '\x1B[37m');
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const dayjs_1 = __importDefault(require("dayjs"));
const superagent_1 = __importDefault(require("superagent"));
const lodash_1 = require("lodash");
const error = (obj) => {
console.log('\x1B[31m', `【${(0, dayjs_1.default)().format('YYYY-MM-DD hh:mm:ss.SSS')}】【tant-intl】${obj.stack || obj}`, '\x1B[37m');
var warn = function warn(obj) {
console.log('\x1B[33m', "\u3010".concat(dayjs().format('YYYY-MM-DD hh:mm:ss.SSS'), "\u3011\u3010tant-intl\u3011").concat(obj), '\x1B[37m');
};
const warn = (obj) => {
console.log('\x1B[33m', `【${(0, dayjs_1.default)().format('YYYY-MM-DD hh:mm:ss.SSS')}】【tant-intl】${obj.stack || obj}`, '\x1B[37m');
var success = function success(obj) {
console.log('\x1B[32m', "\u3010".concat(dayjs().format('YYYY-MM-DD hh:mm:ss.SSS'), "\u3011\u3010tant-intl\u3011").concat(obj), '\x1B[37m');
};
const success = (obj) => {
console.log('\x1B[32m', `【${(0, dayjs_1.default)().format('YYYY-MM-DD hh:mm:ss.SSS')}】【tant-intl】${obj.stack || obj}`, '\x1B[37m');
};
let projectDir = process.cwd();
class Cli {
_token = '';
_branch = '';
_projectIds = [];
_tags = [];
_loading = false;
_localeList = [];
_lastMap = {};
_isBuild = false;
constructor(isBuild) {
this._isBuild = isBuild;
const config = JSON.parse((0, fs_1.readFileSync)(`${projectDir}/intl.json`).toString());
if (!config) {
var projectDir = process.cwd();
var Cli = /*#__PURE__*/_createClass(function Cli() {
var _this = this;
_classCallCheck(this, Cli);
_defineProperty(this, "_config", {});
_defineProperty(this, "_tranMap", {});
_defineProperty(this, "_oldTranMap", {});
_defineProperty(this, "_loading", false);
_defineProperty(this, "init", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _this._download(function () {}, true);
case 2:
case "end":
return _context.stop();
}
if (!config.token) {
error('配置文件缺少token配置');
throw (null);
}
}, _callee);
})));
_defineProperty(this, "listen", /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(cb) {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return _this._download(cb, false);
case 2:
setInterval( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _this._download(cb, false);
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2);
})), 10000);
case 3:
case "end":
return _context3.stop();
}
}
this._token = config.token;
if (!config.projectIds || config.projectIds.length === 0) {
error('配置文件至少需要配置一个项目id');
throw (null);
}, _callee3);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}());
_defineProperty(this, "_download", /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(cb, isBuild) {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!_this._loading) {
_context4.next = 3;
break;
}
warn('本次更新堵塞,下次周期重试');
return _context4.abrupt("return");
case 3:
_this._loading = true;
_this._oldTranMap = cloneDeep(_this._tranMap);
if (!(isBuild && _this._config.usePhrase)) {
_context4.next = 10;
break;
}
_context4.next = 8;
return _this._queryLocale(isBuild);
case 8:
_context4.next = 12;
break;
case 10:
_context4.next = 12;
return _this._queryLocaleDev(isBuild);
case 12:
_context4.next = 14;
return _this._saveToFile(cb, isBuild);
case 14:
_this._loading = false;
case 15:
case "end":
return _context4.stop();
}
}
this._projectIds = config.projectIds;
this._tags = config.tags?.map(v => v.trim())?.filter(v => v);
this._branch = config.branch || '';
}
init = async () => {
await this._queryLocaleDev();
await this._download(() => { }, true);
}, _callee4);
}));
return function (_x2, _x3) {
return _ref4.apply(this, arguments);
};
listen = async (cb) => {
await this._queryLocaleDev();
await this._download(cb, true);
setInterval(async () => {
await this._download(cb, true);
}, 10000);
}());
_defineProperty(this, "_queryLocaleDev", /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(isBuild) {
var flagMap, _iterator, _step, projectIds, _iterator2, _step2, _step2$value, projectId, branch, list, _iterator3, _step3, _step3$value, id, name;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
flagMap = {};
_iterator = _createForOfIteratorHelper(_this._config.outPaths);
_context5.prev = 2;
_iterator.s();
case 4:
if ((_step = _iterator.n()).done) {
_context5.next = 46;
break;
}
projectIds = _step.value.projectIds;
_iterator2 = _createForOfIteratorHelper(projectIds);
_context5.prev = 7;
_iterator2.s();
case 9:
if ((_step2 = _iterator2.n()).done) {
_context5.next = 36;
break;
}
_step2$value = _step2.value, projectId = _step2$value.projectId, branch = _step2$value.branch;
if (!flagMap["".concat(projectId, "_").concat(branch)]) {
_context5.next = 13;
break;
}
return _context5.abrupt("continue", 34);
case 13:
flagMap["".concat(projectId, "_").concat(branch)] = true;
_context5.next = 16;
return fetch('https://ta-tant-intl.thinkingdata.cn:10000/locale/queryLocales', {
method: 'POST',
headers: {
"content-type": "application/json;charset=UTF-8"
},
body: JSON.stringify({
projectId: projectId,
branchName: branch
})
}).then(function (res) {
return res.json();
}).then(function (res) {
return res.data;
}).catch(function () {
return [];
});
case 16:
list = _context5.sent;
_iterator3 = _createForOfIteratorHelper(list);
_context5.prev = 18;
_iterator3.s();
case 20:
if ((_step3 = _iterator3.n()).done) {
_context5.next = 26;
break;
}
_step3$value = _step3.value, id = _step3$value.id, name = _step3$value.name;
_context5.next = 24;
return _this._queryDev(projectId, branch, id, name, isBuild);
case 24:
_context5.next = 20;
break;
case 26:
_context5.next = 31;
break;
case 28:
_context5.prev = 28;
_context5.t0 = _context5["catch"](18);
_iterator3.e(_context5.t0);
case 31:
_context5.prev = 31;
_iterator3.f();
return _context5.finish(31);
case 34:
_context5.next = 9;
break;
case 36:
_context5.next = 41;
break;
case 38:
_context5.prev = 38;
_context5.t1 = _context5["catch"](7);
_iterator2.e(_context5.t1);
case 41:
_context5.prev = 41;
_iterator2.f();
return _context5.finish(41);
case 44:
_context5.next = 4;
break;
case 46:
_context5.next = 51;
break;
case 48:
_context5.prev = 48;
_context5.t2 = _context5["catch"](2);
_iterator.e(_context5.t2);
case 51:
_context5.prev = 51;
_iterator.f();
return _context5.finish(51);
case 54:
case "end":
return _context5.stop();
}
}
}, _callee5, null, [[2, 48, 51, 54], [7, 38, 41, 44], [18, 28, 31, 34]]);
}));
return function (_x4) {
return _ref5.apply(this, arguments);
};
_download = async (cb, isDev) => {
if (this._loading) {
warn('本次更新堵塞,下次周期重试');
return;
}());
_defineProperty(this, "_queryLocale", /*#__PURE__*/function () {
var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(isBuild) {
var flagMap, _iterator4, _step4, projectIds, _iterator5, _step5, _step5$value, projectId, branch, list, _iterator6, _step6, _step6$value, id, name;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
flagMap = {};
_iterator4 = _createForOfIteratorHelper(_this._config.outPaths);
_context6.prev = 2;
_iterator4.s();
case 4:
if ((_step4 = _iterator4.n()).done) {
_context6.next = 46;
break;
}
projectIds = _step4.value.projectIds;
_iterator5 = _createForOfIteratorHelper(projectIds);
_context6.prev = 7;
_iterator5.s();
case 9:
if ((_step5 = _iterator5.n()).done) {
_context6.next = 36;
break;
}
_step5$value = _step5.value, projectId = _step5$value.projectId, branch = _step5$value.branch;
if (!flagMap["".concat(projectId, "_").concat(branch)]) {
_context6.next = 13;
break;
}
return _context6.abrupt("continue", 34);
case 13:
flagMap["".concat(projectId, "_").concat(branch)] = true;
_context6.next = 16;
return _this.request("https://api.phrase.com/v2/projects/".concat(projectId, "/locales?per_page=100&branch=").concat(encodeURIComponent(branch)), true);
case 16:
list = _context6.sent;
_iterator6 = _createForOfIteratorHelper(list);
_context6.prev = 18;
_iterator6.s();
case 20:
if ((_step6 = _iterator6.n()).done) {
_context6.next = 26;
break;
}
_step6$value = _step6.value, id = _step6$value.id, name = _step6$value.name;
_context6.next = 24;
return _this._query(projectId, branch, id, name, isBuild);
case 24:
_context6.next = 20;
break;
case 26:
_context6.next = 31;
break;
case 28:
_context6.prev = 28;
_context6.t0 = _context6["catch"](18);
_iterator6.e(_context6.t0);
case 31:
_context6.prev = 31;
_iterator6.f();
return _context6.finish(31);
case 34:
_context6.next = 9;
break;
case 36:
_context6.next = 41;
break;
case 38:
_context6.prev = 38;
_context6.t1 = _context6["catch"](7);
_iterator5.e(_context6.t1);
case 41:
_context6.prev = 41;
_iterator5.f();
return _context6.finish(41);
case 44:
_context6.next = 4;
break;
case 46:
_context6.next = 51;
break;
case 48:
_context6.prev = 48;
_context6.t2 = _context6["catch"](2);
_iterator4.e(_context6.t2);
case 51:
_context6.prev = 51;
_iterator4.f();
return _context6.finish(51);
case 54:
case "end":
return _context6.stop();
}
}
this._loading = true;
const map = {};
if (isDev) {
await this._queryDev(map);
}
await this._saveToFile(map, cb);
this._loading = false;
}, _callee6, null, [[2, 48, 51, 54], [7, 38, 41, 44], [18, 28, 31, 34]]);
}));
return function (_x5) {
return _ref6.apply(this, arguments);
};
_queryLocaleDev = async () => {
this._localeList = [];
for (const pid of this._projectIds) {
const list = await superagent_1.default
.post('https://ta-tant-intl.thinkingdata.cn:10000/locale/queryLocales')
.send({ projectId: pid, branchName: this._branch })
.then((response) => {
return response.body?.data || [];
})
.catch((err) => {
}());
_defineProperty(this, "_queryDev", /*#__PURE__*/function () {
var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(projectId, branch, localeId, lan, isBuild) {
var list, _iterator7, _step7, _loop;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return fetch('https://ta-tant-intl.thinkingdata.cn:10000/tran/downloadtrans', {
method: 'POST',
headers: {
"content-type": "application/json;charset=UTF-8"
},
body: JSON.stringify({
projectId: projectId,
branchName: branch,
localeId: localeId
})
}).then(function (res) {
return res.json();
}).then(function (res) {
return res.data;
}).catch(function () {
return [];
});
list.forEach((locale) => {
this._localeList.push({ pid, lid: locale.id, code: locale.code });
});
});
case 2:
list = _context7.sent;
_iterator7 = _createForOfIteratorHelper(_this._config.outPaths);
try {
_loop = function _loop() {
var _step7$value = _step7.value,
projectIds = _step7$value.projectIds,
path = _step7$value.path,
buildPath = _step7$value.buildPath;
var dir = isBuild ? buildPath : path;
var _iterator8 = _createForOfIteratorHelper(projectIds),
_step8;
try {
var _loop2 = function _loop2() {
var project = _step8.value;
if (project.branch === branch && project.projectId === projectId) {
if (!_this._tranMap[dir]) {
_this._tranMap[dir] = {};
}
list.forEach(function (_ref8) {
var _project$tags;
var name = _ref8.name,
content = _ref8.content,
tagNameMap = _ref8.tagNameMap;
if (((_project$tags = project.tags) === null || _project$tags === void 0 ? void 0 : _project$tags.length) > 0) {
var _iterator9 = _createForOfIteratorHelper(project.tags),
_step9;
try {
for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
var tag = _step9.value;
if (tagNameMap[tag]) {
if (!_this._tranMap[dir]["".concat(lan, "-").concat(tag)]) {
_this._tranMap[dir]["".concat(lan, "-").concat(tag)] = {};
}
_this._tranMap[dir]["".concat(lan, "-").concat(tag)][name] = content;
}
}
} catch (err) {
_iterator9.e(err);
} finally {
_iterator9.f();
}
} else {
for (var _i = 0, _Object$keys = Object.keys(tagNameMap); _i < _Object$keys.length; _i++) {
var _tag = _Object$keys[_i];
if (!_this._tranMap[dir]["".concat(lan, "-").concat(_tag)]) {
_this._tranMap[dir]["".concat(lan, "-").concat(_tag)] = {};
}
_this._tranMap[dir]["".concat(lan, "-").concat(_tag)][name] = content;
}
}
});
}
};
for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
_loop2();
}
} catch (err) {
_iterator8.e(err);
} finally {
_iterator8.f();
}
};
for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
_loop();
}
} catch (err) {
_iterator7.e(err);
} finally {
_iterator7.f();
}
case 5:
case "end":
return _context7.stop();
}
}
}, _callee7);
}));
return function (_x6, _x7, _x8, _x9, _x10) {
return _ref7.apply(this, arguments);
};
_queryDev = async (map) => {
const tranArrList = await Promise.all(this._localeList.map(({ pid, lid }) => superagent_1.default
.post('https://ta-tant-intl.thinkingdata.cn:10000/tran/downloadtrans')
.send({ projectId: pid, branchName: this._branch, localeId: lid })
.then((response) => {
return response.body?.data || [];
})
.catch((err) => {
return [];
})));
tranArrList.forEach((tranArr, index) => {
const code = this._localeList[index].code;
tranArr.forEach((tran) => {
Object.keys(tran.tagNameMap || {}).forEach((tag) => {
if (!this._tags.find(v => v === tag) || tag.includes('-')) {
return;
}());
_defineProperty(this, "_query", /*#__PURE__*/function () {
var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(projectId, branch, localeId, lan, isBuild) {
var result, list, _iterator10, _step10, _loop3;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return _this.request("https://api.phrase.com/v2/projects/".concat(projectId, "/locales/").concat(localeId, "/download?branch=").concat(encodeURIComponent(branch), "&file_format=csv&format_options[export_tags]=true&format_options[export_max_characters_allowed]=true"), false);
case 2:
result = _context8.sent;
_context8.next = 5;
return csvtojsonV2().fromString(result);
case 5:
list = _context8.sent;
_iterator10 = _createForOfIteratorHelper(_this._config.outPaths);
try {
_loop3 = function _loop3() {
var _step10$value = _step10.value,
projectIds = _step10$value.projectIds,
path = _step10$value.path,
buildPath = _step10$value.buildPath;
var dir = isBuild ? buildPath : path;
var _iterator11 = _createForOfIteratorHelper(projectIds),
_step11;
try {
var _loop4 = function _loop4() {
var project = _step11.value;
if (project.branch === branch && project.projectId === projectId) {
if (!_this._tranMap[dir]) {
_this._tranMap[dir] = {};
}
list.forEach(function (v) {
var _v$tags, _v$tags$split, _v$key_name, _project$tags2;
var tagNameMap = {};
(_v$tags = v.tags) === null || _v$tags === void 0 ? void 0 : (_v$tags$split = _v$tags.split(',')) === null || _v$tags$split === void 0 ? void 0 : _v$tags$split.forEach(function (tag) {
tagNameMap[tag] = tag;
});
var name = (_v$key_name = v.key_name) === null || _v$key_name === void 0 ? void 0 : _v$key_name.trim();
var content = v[lan];
if (((_project$tags2 = project.tags) === null || _project$tags2 === void 0 ? void 0 : _project$tags2.length) > 0) {
var _iterator12 = _createForOfIteratorHelper(project.tags),
_step12;
try {
for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
var tag = _step12.value;
if (tagNameMap[tag]) {
if (!_this._tranMap[dir]["".concat(lan, "-").concat(tag)]) {
_this._tranMap[dir]["".concat(lan, "-").concat(tag)] = {};
}
_this._tranMap[dir]["".concat(lan, "-").concat(tag)][name] = content;
}
}
} catch (err) {
_iterator12.e(err);
} finally {
_iterator12.f();
}
} else {
for (var _i2 = 0, _Object$keys2 = Object.keys(tagNameMap); _i2 < _Object$keys2.length; _i2++) {
var _tag2 = _Object$keys2[_i2];
if (!_this._tranMap[dir]["".concat(lan, "-").concat(_tag2)]) {
_this._tranMap[dir]["".concat(lan, "-").concat(_tag2)] = {};
}
_this._tranMap[dir]["".concat(lan, "-").concat(_tag2)][name] = content;
}
}
});
}
};
for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
_loop4();
}
const key = `${code}-${tag}`;
if (!map[key]) {
map[key] = {};
}
map[key][tran.name] = tran.content;
});
});
});
};
/**
* 将数据保存进本地
*/
_saveToFile = async (map, cb) => {
const path = this._isBuild ? `${projectDir}/dist/intl` : `${projectDir}/apps/portal/public/intl`;
if (!(0, fs_1.existsSync)(path)) {
(0, fs_1.mkdirSync)(path, { recursive: true });
}
let hasChange = false;
for (const key of Object.keys(map)) {
const str = JSON.stringify(map[key]) || '';
const oldStr = JSON.stringify(this._lastMap[key] || '{}') || '';
if (str !== oldStr) {
hasChange = true;
break;
}
}
if (hasChange) {
(0, fs_1.readdirSync)(path).forEach((fileName) => {
if (fileName.endsWith('.json')) {
(0, fs_1.unlinkSync)(`${path}/${fileName}`);
} catch (err) {
_iterator11.e(err);
} finally {
_iterator11.f();
}
};
for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
_loop3();
}
});
Object.keys(map).forEach((key) => {
const str = JSON.stringify(map[key]) || '';
(0, fs_1.writeFileSync)(`${path}/${key}.json`, str);
});
this._lastMap = (0, lodash_1.cloneDeep)(map);
cb();
} catch (err) {
_iterator10.e(err);
} finally {
_iterator10.f();
}
case 8:
case "end":
return _context8.stop();
}
}
}, _callee8);
}));
return function (_x11, _x12, _x13, _x14, _x15) {
return _ref9.apply(this, arguments);
};
request = (path) => new Promise((r) => {
superagent_1.default
.get(path)
.set('Authorization', `token ${this._token}`)
.then((response) => {
if (response.status === 200) {
r(response.text || response.body);
return '';
}
r('');
return '';
})
.catch((err) => {
if (err?.response?.status === 429) {
const date = Number(err?.response?.header['x-rate-limit-reset'] || 0) * 1000;
const now = Date.now();
if (date) {
setTimeout(async () => {
r(await this.request(path));
}, date - now + 500);
}());
_defineProperty(this, "_saveToFile", /*#__PURE__*/function () {
var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(cb, isBuild) {
var hasChange;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
hasChange = false;
Object.entries(_this._tranMap).forEach(function (_ref11) {
var _ref12 = _slicedToArray(_ref11, 2),
dir = _ref12[0],
map = _ref12[1];
var intlDir = "".concat(projectDir).concat(dir);
if (!existsSync(intlDir)) {
mkdirSync(intlDir, {
recursive: true
});
}
else {
r('');
if (JSON.stringify(map) !== JSON.stringify(_this._oldTranMap[dir])) {
hasChange = true;
readdirSync(intlDir).forEach(function (fileName) {
if (fileName.endsWith('.json')) {
unlinkSync("".concat(intlDir).concat(fileName));
}
});
Object.entries(map).forEach(function (_ref13) {
var _ref14 = _slicedToArray(_ref13, 2),
key = _ref14[0],
content = _ref14[1];
writeFileSync("".concat(intlDir).concat(key, ".json"), JSON.stringify(content));
});
}
return '';
});
if (hasChange) {
cb();
}
case 3:
case "end":
return _context9.stop();
}
}
}, _callee9);
}));
return function (_x16, _x17) {
return _ref10.apply(this, arguments);
};
}());
_defineProperty(this, "request", function (path, isJSON) {
return new Promise(function (r) {
console.log(1);
fetch(path, {
method: 'GET',
headers: {
Authorization: "token ".concat(_this._config.token)
}
}).then( /*#__PURE__*/function () {
var _ref15 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(response) {
return _regeneratorRuntime().wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (!(response.status === 200)) {
_context10.next = 14;
break;
}
if (!isJSON) {
_context10.next = 8;
break;
}
_context10.t0 = r;
_context10.next = 5;
return response.json();
case 5:
_context10.t1 = _context10.sent;
(0, _context10.t0)(_context10.t1);
return _context10.abrupt("return", '');
case 8:
_context10.t2 = r;
_context10.next = 11;
return response.text();
case 11:
_context10.t3 = _context10.sent;
(0, _context10.t2)(_context10.t3);
return _context10.abrupt("return", '');
case 14:
r('');
return _context10.abrupt("return", '');
case 16:
case "end":
return _context10.stop();
}
}
r('');
return '';
});
}, _callee10);
}));
return function (_x18) {
return _ref15.apply(this, arguments);
};
}()).catch(function (err) {
console.log(err);
setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
return _regeneratorRuntime().wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
_context11.t0 = r;
_context11.next = 3;
return _this.request(path, false);
case 3:
_context11.t1 = _context11.sent;
(0, _context11.t0)(_context11.t1);
case 5:
case "end":
return _context11.stop();
}
}
}, _callee11);
})), 300000);
});
});
}
const cli = new Cli(process.argv[2] === 'build');
(async () => {
if (process.argv[2] !== 'build') {
cli.listen(() => {
});
if (!existsSync("".concat(projectDir, "/intl.json"))) {
warn('未找到配置文件intl.json,获取国际化文案跳过');
}
var config = {};
try {
var _config;
config = JSON.parse(readFileSync("".concat(projectDir, "/intl.json")).toString());
if (!config || !((_config = config) !== null && _config !== void 0 && _config.token)) {
error('配置文件intl.json内容缺少或不正确');
return;
}
} catch (_unused) {
error('配置文件intl.json内容不正确');
return;
}
this._config = config;
});
var cli = new Cli();
_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
return _regeneratorRuntime().wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
if (!(process.argv[2] !== 'build')) {
_context12.next = 4;
break;
}
cli.listen(function () {
success('本地国际化文案已更新,请刷新页面');
});
});
_context12.next = 7;
break;
case 4:
_context12.next = 6;
return cli.init();
case 6:
success('获取最新文案成功');
case 7:
case "end":
return _context12.stop();
}
}
else {
await cli.init();
success('获取最新文案成功');
}
})();
}, _callee12);
}))();

198

es/index.js

@@ -1,10 +0,14 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatMessage = exports.getIntlMessage = exports.getLocale = exports.setLocale = void 0;
const react_1 = __importDefault(require("react"));
const superagent_1 = __importDefault(require("superagent"));
const intl_messageformat_1 = __importDefault(require("intl-messageformat"));
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
import React from 'react';
import IntlMessageFormat from 'intl-messageformat';
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsx as _jsx } from "react/jsx-runtime";
/**

@@ -14,62 +18,152 @@ * 修改语言类型

*/
const setLocale = (lan) => {
if (!lan) {
return;
}
window.localStorage.setItem('umi_locale', lan);
window.location.reload();
export var setLocale = function setLocale(lan) {
if (!lan) {
return;
}
window.localStorage.setItem('umi_locale', lan);
window.location.reload();
};
exports.setLocale = setLocale;
/**
* 获取语言类型
*/
const getLocale = () => {
const lan = window.localStorage.getItem('umi_locale') || navigator.language || 'zh';
return lan.includes('en') ? 'en-US' : lan.includes('ja') ? 'ja-JP' : 'zh-CN';
export var getLocale = function getLocale() {
var lan = window.localStorage.getItem('umi_locale') || navigator.language || 'zh';
if (lan.includes('en')) {
return 'en-US';
}
if (lan.includes('ja') || lan.includes('jp')) {
return 'ja-JP';
}
if (lan.includes('ko') || lan.includes('kor')) {
return 'ko-KR';
}
return 'zh-CN';
};
exports.getLocale = getLocale;
/**
* 获取文案内容
*/
const getIntlMessage = async (tags = [], t) => {
const lan = (0, exports.getLocale)();
const intl = window.intl || {};
await Promise.all(tags.map(tag => superagent_1.default.get(`/intl/${lan}-${tag}.json?t=${t || ''}`)
.then((res) => {
return res.body || {};
})
.catch((err) => {
console.log(err);
return {};
}))).then((arr) => {
window.intl = Object.assign(intl, ...arr);
});
};
exports.getIntlMessage = getIntlMessage;
const lan = (0, exports.getLocale)();
export var getIntlMessage = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var tags,
t,
lan,
intl,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
tags = _args.length > 0 && _args[0] !== undefined ? _args[0] : [];
t = _args.length > 1 ? _args[1] : undefined;
lan = getLocale();
intl = window.intl || {};
_context.next = 6;
return Promise.all(tags.map(function (tag) {
return new Promise(function (r) {
try {
var xMLHttpRequest = new XMLHttpRequest();
var ActiveXObject = window.ActiveXObject;
if (ActiveXObject) {
xMLHttpRequest = new ActiveXObject("MsXml2.XmlHttp");
}
xMLHttpRequest.onreadystatechange = function () {
if (xMLHttpRequest.readyState == 4) {
window.intl = Object.assign(intl, JSON.parse(xMLHttpRequest.responseText) || {});
r(0);
}
};
xMLHttpRequest.open('GET', "/intl/".concat(lan, "-").concat(tag, ".json?t=").concat(t || ''));
xMLHttpRequest.send(null);
} catch (e) {
console.error("\u83B7\u53D6\u8BED\u8A00\u5305\u5931\u8D25\u3010tag=".concat(tag, "\u3011"));
r(1);
}
});
}));
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function getIntlMessage() {
return _ref.apply(this, arguments);
};
}();
var lan = getLocale();
var intlError = 0;
/**
* 国际化渲染函数
* @param infoObj
* @param varObj
* @returns
* @param infoObj
* @param varObj
* @returns
*/
const formatMessage = (infoObj, varObj) => {
const { id } = infoObj;
const { intl } = window;
export var formatMessage = function formatMessage(_ref2) {
var id = _ref2.id;
var varObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
try {
var intl = window.intl.intl;
if (!intl) {
if (intlError === 0) {
console.error('文案仓库加载失败或为空!');
return id;
intlError += 1;
}
return id;
}
if (intl[id] === null || intl[id] === undefined || intl[id] === NaN) {
console.error(`请检查文案【${id}】是否存在!`);
return id;
console.error("\u8BF7\u68C0\u67E5\u6587\u6848\u3010".concat(id, "\u3011\u662F\u5426\u5B58\u5728\uFF01"));
return id;
}
const value = intl ? intl[id] : id;
const intlObj = new intl_messageformat_1.default(value, lan);
const arr = intlObj.formatToParts(varObj).map(v => v.value);
if (arr.find(item => typeof item === 'object')) { // 对象的属性值为对象时就认为是react对象
return react_1.default.createElement(react_1.default.Fragment, null, arr);
varObj.get = function () {};
var intlObj = new IntlMessageFormat(intl[id], lan); // 自动填补参数避免报错
intlObj.getAst().forEach(function (ast) {
if ((ast.type === 1 || ast.type === 6) && (varObj[ast.value] === null || varObj[ast.value] === undefined || varObj[ast.value] === NaN)) {
varObj[ast.value] = '';
}
});
var arr = intlObj.formatToParts(varObj).map(function (v, index) {
if (_typeof(v.value) === "object") {
return /*#__PURE__*/React.cloneElement(v.value, {
key: v.value.key || index
});
}
return v.value;
});
if (arr.find(function (item) {
return _typeof(item) === 'object';
})) {
// 对象的属性值为对象时就认为是react对象
return /*#__PURE__*/_jsx(_Fragment, {
children: arr
});
}
return arr.join('');
};
exports.formatMessage = formatMessage;
} catch (e) {
console.error(e);
return id;
}
};
#!/usr/bin/env node
"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());
});
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
// src/cli.ts
var import_fs = require("fs");
var import_dayjs = __toESM(require("dayjs"));
var import_node_fetch = __toESM(require("node-fetch"));
var import_lodash = require("lodash");
var csvtojsonV2 = require("csvtojson");
var error = (obj) => {
console.log("\x1B[31m", `\u3010${(0, import_dayjs.default)().format("YYYY-MM-DD hh:mm:ss.SSS")}\u3011\u3010tant-intl\u3011${obj}`, "\x1B[37m");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
var warn = (obj) => {
console.log("\x1B[33m", `\u3010${(0, import_dayjs.default)().format("YYYY-MM-DD hh:mm:ss.SSS")}\u3011\u3010tant-intl\u3011${obj}`, "\x1B[37m");
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = require("fs");
var dayjs_1 = __importDefault(require("dayjs"));
var superagent_1 = __importDefault(require("superagent"));
var lodash_1 = require("lodash");
var error = function (obj) {
console.log('\x1B[31m', "\u3010".concat((0, dayjs_1.default)().format('YYYY-MM-DD hh:mm:ss.SSS'), "\u3011\u3010tant-intl\u3011").concat(obj.stack || obj), '\x1B[37m');
var success = (obj) => {
console.log("\x1B[32m", `\u3010${(0, import_dayjs.default)().format("YYYY-MM-DD hh:mm:ss.SSS")}\u3011\u3010tant-intl\u3011${obj}`, "\x1B[37m");
};
var warn = function (obj) {
console.log('\x1B[33m', "\u3010".concat((0, dayjs_1.default)().format('YYYY-MM-DD hh:mm:ss.SSS'), "\u3011\u3010tant-intl\u3011").concat(obj.stack || obj), '\x1B[37m');
};
var success = function (obj) {
console.log('\x1B[32m', "\u3010".concat((0, dayjs_1.default)().format('YYYY-MM-DD hh:mm:ss.SSS'), "\u3011\u3010tant-intl\u3011").concat(obj.stack || obj), '\x1B[37m');
};
var projectDir = process.cwd();
var Cli = /** @class */ (function () {
function Cli(isBuild) {
var _this = this;
var _a, _b;
this._token = '';
this._branch = '';
this._projectIds = [];
this._tags = [];
this._loading = false;
this._localeList = [];
this._lastMap = {};
this._isBuild = false;
this.init = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._queryLocaleDev()];
case 1:
_a.sent();
return [4 /*yield*/, this._download(function () { }, true)];
case 2:
_a.sent();
return [2 /*return*/];
var Cli = class {
constructor() {
this._config = {};
this._tranMap = {};
this._oldTranMap = {};
this._loading = false;
this.init = async () => {
await this._download(() => {
}, true);
};
this.listen = async (cb) => {
await this._download(cb, false);
setInterval(async () => {
await this._download(cb, false);
}, 1e4);
};
this._download = async (cb, isBuild) => {
if (this._loading) {
warn("\u672C\u6B21\u66F4\u65B0\u5835\u585E\uFF0C\u4E0B\u6B21\u5468\u671F\u91CD\u8BD5");
return;
}
this._loading = true;
this._oldTranMap = (0, import_lodash.cloneDeep)(this._tranMap);
if (isBuild && this._config.usePhrase) {
await this._queryLocale(isBuild);
} else {
await this._queryLocaleDev(isBuild);
}
await this._saveToFile(cb, isBuild);
this._loading = false;
};
this._queryLocaleDev = async (isBuild) => {
const flagMap = {};
for (const { projectIds } of this._config.outPaths) {
for (const { projectId, branch } of projectIds) {
if (flagMap[`${projectId}_${branch}`]) {
continue;
}
flagMap[`${projectId}_${branch}`] = true;
const list = await (0, import_node_fetch.default)("https://ta-tant-intl.thinkingdata.cn:10000/locale/queryLocales", {
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8"
},
body: JSON.stringify({
projectId,
branchName: branch
})
}).then((res) => res.json()).then((res) => res.data).catch(() => []);
for (const { id, name } of list) {
await this._queryDev(projectId, branch, id, name, isBuild);
}
}
}
};
this._queryLocale = async (isBuild) => {
const flagMap = {};
for (const { projectIds } of this._config.outPaths) {
for (const { projectId, branch } of projectIds) {
if (flagMap[`${projectId}_${branch}`]) {
continue;
}
flagMap[`${projectId}_${branch}`] = true;
const list = await this.request(`https://api.phrase.com/v2/projects/${projectId}/locales?per_page=100&branch=${encodeURIComponent(branch)}`, true);
for (const { id, name } of list) {
await this._query(projectId, branch, id, name, isBuild);
}
}
}
};
this._queryDev = async (projectId, branch, localeId, lan, isBuild) => {
const list = await (0, import_node_fetch.default)("https://ta-tant-intl.thinkingdata.cn:10000/tran/downloadtrans", {
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8"
},
body: JSON.stringify({
projectId,
branchName: branch,
localeId
})
}).then((res) => res.json()).then((res) => res.data).catch(() => []);
for (const { projectIds, path, buildPath } of this._config.outPaths) {
const dir = isBuild ? buildPath : path;
for (const project of projectIds) {
if (project.branch === branch && project.projectId === projectId) {
if (!this._tranMap[dir]) {
this._tranMap[dir] = {};
}
list.forEach(({ name, content, tagNameMap }) => {
var _a;
if (((_a = project.tags) == null ? void 0 : _a.length) > 0) {
for (const tag of project.tags) {
if (tagNameMap[tag]) {
if (!this._tranMap[dir][`${lan}-${tag}`]) {
this._tranMap[dir][`${lan}-${tag}`] = {};
}
this._tranMap[dir][`${lan}-${tag}`][name] = content;
}
}
});
}); };
this.listen = function (cb) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._queryLocaleDev()];
case 1:
_a.sent();
return [4 /*yield*/, this._download(cb, true)];
case 2:
_a.sent();
setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._download(cb, true)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); }, 10000);
return [2 /*return*/];
} else {
for (const tag of Object.keys(tagNameMap)) {
if (!this._tranMap[dir][`${lan}-${tag}`]) {
this._tranMap[dir][`${lan}-${tag}`] = {};
}
this._tranMap[dir][`${lan}-${tag}`][name] = content;
}
}
});
}); };
this._download = function (cb, isDev) { return __awaiter(_this, void 0, void 0, function () {
var map;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._loading) {
warn('本次更新堵塞,下次周期重试');
return [2 /*return*/];
}
this._loading = true;
map = {};
if (!isDev) return [3 /*break*/, 2];
return [4 /*yield*/, this._queryDev(map)];
case 1:
_a.sent();
_a.label = 2;
case 2: return [4 /*yield*/, this._saveToFile(map, cb)];
case 3:
_a.sent();
this._loading = false;
return [2 /*return*/];
}
});
}); };
this._queryLocaleDev = function () { return __awaiter(_this, void 0, void 0, function () {
var _loop_1, this_1, _i, _a, pid;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
this._localeList = [];
_loop_1 = function (pid) {
var list;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, superagent_1.default
.post('https://ta-tant-intl.thinkingdata.cn:10000/locale/queryLocales')
.send({ projectId: pid, branchName: this_1._branch })
.then(function (response) {
var _a;
return ((_a = response.body) === null || _a === void 0 ? void 0 : _a.data) || [];
})
.catch(function (err) {
return [];
})];
case 1:
list = _c.sent();
list.forEach(function (locale) {
_this._localeList.push({ pid: pid, lid: locale.id, code: locale.code });
});
return [2 /*return*/];
}
});
};
this_1 = this;
_i = 0, _a = this._projectIds;
_b.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
pid = _a[_i];
return [5 /*yield**/, _loop_1(pid)];
case 2:
_b.sent();
_b.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
}); };
this._queryDev = function (map) { return __awaiter(_this, void 0, void 0, function () {
var tranArrList;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(this._localeList.map(function (_a) {
var pid = _a.pid, lid = _a.lid;
return superagent_1.default
.post('https://ta-tant-intl.thinkingdata.cn:10000/tran/downloadtrans')
.send({ projectId: pid, branchName: _this._branch, localeId: lid })
.then(function (response) {
var _a;
return ((_a = response.body) === null || _a === void 0 ? void 0 : _a.data) || [];
})
.catch(function (err) {
return [];
});
}))];
case 1:
tranArrList = _a.sent();
tranArrList.forEach(function (tranArr, index) {
var code = _this._localeList[index].code;
tranArr.forEach(function (tran) {
Object.keys(tran.tagNameMap || {}).forEach(function (tag) {
if (!_this._tags.find(function (v) { return v === tag; }) || tag.includes('-')) {
return;
}
var key = "".concat(code, "-").concat(tag);
if (!map[key]) {
map[key] = {};
}
map[key][tran.name] = tran.content;
});
});
});
return [2 /*return*/];
}
});
}); };
/**
* 将数据保存进本地
*/
this._saveToFile = function (map, cb) { return __awaiter(_this, void 0, void 0, function () {
var path, hasChange, _i, _a, key, str, oldStr;
return __generator(this, function (_b) {
path = this._isBuild ? "".concat(projectDir, "/dist/intl") : "".concat(projectDir, "/apps/portal/public/intl");
if (!(0, fs_1.existsSync)(path)) {
(0, fs_1.mkdirSync)(path, { recursive: true });
}
hasChange = false;
for (_i = 0, _a = Object.keys(map); _i < _a.length; _i++) {
key = _a[_i];
str = JSON.stringify(map[key]) || '';
oldStr = JSON.stringify(this._lastMap[key] || '{}') || '';
if (str !== oldStr) {
hasChange = true;
break;
}
}
}
};
this._query = async (projectId, branch, localeId, lan, isBuild) => {
const result = await this.request(`https://api.phrase.com/v2/projects/${projectId}/locales/${localeId}/download?branch=${encodeURIComponent(branch)}&file_format=csv&format_options[export_tags]=true&format_options[export_max_characters_allowed]=true`, false);
const list = await csvtojsonV2().fromString(result);
for (const { projectIds, path, buildPath } of this._config.outPaths) {
const dir = isBuild ? buildPath : path;
for (const project of projectIds) {
if (project.branch === branch && project.projectId === projectId) {
if (!this._tranMap[dir]) {
this._tranMap[dir] = {};
}
list.forEach((v) => {
var _a, _b, _c, _d;
const tagNameMap = {};
(_b = (_a = v.tags) == null ? void 0 : _a.split(",")) == null ? void 0 : _b.forEach((tag) => {
tagNameMap[tag] = tag;
});
const name = (_c = v.key_name) == null ? void 0 : _c.trim();
const content = v[lan];
if (((_d = project.tags) == null ? void 0 : _d.length) > 0) {
for (const tag of project.tags) {
if (tagNameMap[tag]) {
if (!this._tranMap[dir][`${lan}-${tag}`]) {
this._tranMap[dir][`${lan}-${tag}`] = {};
}
this._tranMap[dir][`${lan}-${tag}`][name] = content;
}
}
if (hasChange) {
(0, fs_1.readdirSync)(path).forEach(function (fileName) {
if (fileName.endsWith('.json')) {
(0, fs_1.unlinkSync)("".concat(path, "/").concat(fileName));
}
});
Object.keys(map).forEach(function (key) {
var str = JSON.stringify(map[key]) || '';
(0, fs_1.writeFileSync)("".concat(path, "/").concat(key, ".json"), str);
});
this._lastMap = (0, lodash_1.cloneDeep)(map);
cb();
} else {
for (const tag of Object.keys(tagNameMap)) {
if (!this._tranMap[dir][`${lan}-${tag}`]) {
this._tranMap[dir][`${lan}-${tag}`] = {};
}
this._tranMap[dir][`${lan}-${tag}`][name] = content;
}
return [2 /*return*/];
}
});
}); };
this.request = function (path) { return new Promise(function (r) {
superagent_1.default
.get(path)
.set('Authorization', "token ".concat(_this._token))
.then(function (response) {
if (response.status === 200) {
r(response.text || response.body);
return '';
}
r('');
return '';
})
.catch(function (err) {
var _a, _b;
if (((_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.status) === 429) {
var date = Number(((_b = err === null || err === void 0 ? void 0 : err.response) === null || _b === void 0 ? void 0 : _b.header['x-rate-limit-reset']) || 0) * 1000;
var now = Date.now();
if (date) {
setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = r;
return [4 /*yield*/, this.request(path)];
case 1:
_a.apply(void 0, [_b.sent()]);
return [2 /*return*/];
}
});
}); }, date - now + 500);
}
else {
r('');
}
return '';
}
r('');
return '';
});
}); };
this._isBuild = isBuild;
var config = JSON.parse((0, fs_1.readFileSync)("".concat(projectDir, "/intl.json")).toString());
if (!config) {
}
}
if (!config.token) {
error('配置文件缺少token配置');
throw (null);
}
};
this._saveToFile = async (cb, isBuild) => {
let hasChange = false;
Object.entries(this._tranMap).forEach(([dir, map]) => {
const intlDir = `${projectDir}${dir}`;
if (!(0, import_fs.existsSync)(intlDir)) {
(0, import_fs.mkdirSync)(intlDir, { recursive: true });
}
this._token = config.token;
if (!config.projectIds || config.projectIds.length === 0) {
error('配置文件至少需要配置一个项目id');
throw (null);
if (JSON.stringify(map) !== JSON.stringify(this._oldTranMap[dir])) {
hasChange = true;
(0, import_fs.readdirSync)(intlDir).forEach((fileName) => {
if (fileName.endsWith(".json")) {
(0, import_fs.unlinkSync)(`${intlDir}${fileName}`);
}
});
Object.entries(map).forEach(([key, content]) => {
(0, import_fs.writeFileSync)(`${intlDir}${key}.json`, JSON.stringify(content));
});
}
this._projectIds = config.projectIds;
this._tags = (_b = (_a = config.tags) === null || _a === void 0 ? void 0 : _a.map(function (v) { return v.trim(); })) === null || _b === void 0 ? void 0 : _b.filter(function (v) { return v; });
this._branch = config.branch || '';
}
return Cli;
}());
var cli = new Cli(process.argv[2] === 'build');
(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(process.argv[2] !== 'build')) return [3 /*break*/, 1];
cli.listen(function () {
success('本地国际化文案已更新,请刷新页面');
});
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, cli.init()];
case 2:
_a.sent();
success('获取最新文案成功');
_a.label = 3;
case 3: return [2 /*return*/];
});
if (hasChange) {
cb();
}
};
this.request = (path, isJSON) => new Promise((r) => {
console.log(1);
(0, import_node_fetch.default)(path, {
method: "GET",
headers: {
Authorization: `token ${this._config.token}`
}
}).then(async (response) => {
if (response.status === 200) {
if (isJSON) {
r(await response.json());
return "";
}
r(await response.text());
return "";
}
r("");
return "";
}).catch((err) => {
console.log(err);
setTimeout(async () => {
r(await this.request(path, false));
}, 3e5);
});
});
}); })();
if (!(0, import_fs.existsSync)(`${projectDir}/intl.json`)) {
warn("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6intl.json\uFF0C\u83B7\u53D6\u56FD\u9645\u5316\u6587\u6848\u8DF3\u8FC7");
}
let config = {};
try {
config = JSON.parse((0, import_fs.readFileSync)(`${projectDir}/intl.json`).toString());
if (!config || !(config == null ? void 0 : config.token)) {
error("\u914D\u7F6E\u6587\u4EF6intl.json\u5185\u5BB9\u7F3A\u5C11\u6216\u4E0D\u6B63\u786E");
return;
}
} catch {
error("\u914D\u7F6E\u6587\u4EF6intl.json\u5185\u5BB9\u4E0D\u6B63\u786E");
return;
}
this._config = config;
}
};
var cli = new Cli();
(async () => {
if (process.argv[2] !== "build") {
cli.listen(() => {
success("\u672C\u5730\u56FD\u9645\u5316\u6587\u6848\u5DF2\u66F4\u65B0\uFF0C\u8BF7\u5237\u65B0\u9875\u9762");
});
} else {
await cli.init();
success("\u83B7\u53D6\u6700\u65B0\u6587\u6848\u6210\u529F");
}
})();

@@ -1,133 +0,124 @@

"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());
});
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.tsx
var src_exports = {};
__export(src_exports, {
formatMessage: () => formatMessage,
getIntlMessage: () => getIntlMessage,
getLocale: () => getLocale,
setLocale: () => setLocale
});
module.exports = __toCommonJS(src_exports);
var import_react = __toESM(require("react"));
var import_intl_messageformat = __toESM(require("intl-messageformat"));
var setLocale = (lan2) => {
if (!lan2) {
return;
}
window.localStorage.setItem("umi_locale", lan2);
window.location.reload();
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
var getLocale = () => {
const lan2 = window.localStorage.getItem("umi_locale") || navigator.language || "zh";
if (lan2.includes("en")) {
return "en-US";
}
if (lan2.includes("ja") || lan2.includes("jp")) {
return "ja-JP";
}
if (lan2.includes("ko") || lan2.includes("kor")) {
return "ko-KR";
}
return "zh-CN";
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatMessage = exports.getIntlMessage = exports.getLocale = exports.setLocale = void 0;
var react_1 = __importDefault(require("react"));
var superagent_1 = __importDefault(require("superagent"));
var intl_messageformat_1 = __importDefault(require("intl-messageformat"));
/**
* 修改语言类型
* @param lan
*/
var setLocale = function (lan) {
if (!lan) {
return;
}
window.localStorage.setItem('umi_locale', lan);
window.location.reload();
};
exports.setLocale = setLocale;
/**
* 获取语言类型
*/
var getLocale = function () {
var lan = window.localStorage.getItem('umi_locale') || navigator.language || 'zh';
return lan.includes('en') ? 'en-US' : lan.includes('ja') ? 'ja-JP' : 'zh-CN';
};
exports.getLocale = getLocale;
/**
* 获取文案内容
*/
var getIntlMessage = function (tags, t) {
if (tags === void 0) { tags = []; }
return __awaiter(void 0, void 0, void 0, function () {
var lan, intl;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
lan = (0, exports.getLocale)();
intl = window.intl || {};
return [4 /*yield*/, Promise.all(tags.map(function (tag) {
return superagent_1.default.get("/intl/".concat(lan, "-").concat(tag, ".json?t=").concat(t || ''))
.then(function (res) {
return res.body || {};
})
.catch(function (err) {
console.log(err);
return {};
});
})).then(function (arr) {
window.intl = Object.assign.apply(Object, __spreadArray([intl], arr, false));
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
var getIntlMessage = async (tags = [], t) => {
const lan2 = getLocale();
const intl = window.intl || {};
await Promise.all(tags.map((tag) => {
return new Promise((r) => {
try {
let xMLHttpRequest = new XMLHttpRequest();
const ActiveXObject = window.ActiveXObject;
if (ActiveXObject) {
xMLHttpRequest = new ActiveXObject("MsXml2.XmlHttp");
}
xMLHttpRequest.onreadystatechange = () => {
if (xMLHttpRequest.readyState == 4) {
window.intl = Object.assign(intl, JSON.parse(xMLHttpRequest.responseText) || {});
r(0);
}
};
xMLHttpRequest.open("GET", `/intl/${lan2}-${tag}.json?t=${t || ""}`);
xMLHttpRequest.send(null);
} catch (e) {
console.error(`\u83B7\u53D6\u8BED\u8A00\u5305\u5931\u8D25\u3010tag=${tag}\u3011`);
r(1);
}
});
}));
};
exports.getIntlMessage = getIntlMessage;
var lan = (0, exports.getLocale)();
/**
* 国际化渲染函数
* @param infoObj
* @param varObj
* @returns
*/
var formatMessage = function (infoObj, varObj) {
var id = infoObj.id;
var intl = window.intl;
var lan = getLocale();
var intlError = 0;
var formatMessage = ({ id }, varObj = {}) => {
try {
const { intl } = window.intl;
if (!intl) {
console.error('文案仓库加载失败或为空!');
return id;
if (intlError === 0) {
console.error("\u6587\u6848\u4ED3\u5E93\u52A0\u8F7D\u5931\u8D25\u6216\u4E3A\u7A7A\uFF01");
intlError += 1;
}
return id;
}
if (intl[id] === null || intl[id] === undefined || intl[id] === NaN) {
console.error("\u8BF7\u68C0\u67E5\u6587\u6848\u3010".concat(id, "\u3011\u662F\u5426\u5B58\u5728\uFF01"));
return id;
if (intl[id] === null || intl[id] === void 0 || intl[id] === NaN) {
console.error(`\u8BF7\u68C0\u67E5\u6587\u6848\u3010${id}\u3011\u662F\u5426\u5B58\u5728\uFF01`);
return id;
}
var value = intl ? intl[id] : id;
var intlObj = new intl_messageformat_1.default(value, lan);
var arr = intlObj.formatToParts(varObj).map(function (v) { return v.value; });
if (arr.find(function (item) { return typeof item === 'object'; })) { // 对象的属性值为对象时就认为是react对象
return react_1.default.createElement(react_1.default.Fragment, null, arr);
varObj.get = () => {
};
const intlObj = new import_intl_messageformat.default(intl[id], lan);
intlObj.getAst().forEach((ast) => {
if ((ast.type === 1 || ast.type === 6) && (varObj[ast.value] === null || varObj[ast.value] === void 0 || varObj[ast.value] === NaN)) {
varObj[ast.value] = "";
}
});
const arr = intlObj.formatToParts(varObj).map((v, index) => {
if (typeof v.value === "object") {
return import_react.default.cloneElement(v.value, { key: v.value.key || index });
}
return v.value;
});
if (arr.find((item) => typeof item === "object")) {
return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, arr);
}
return arr.join('');
return arr.join("");
} catch (e) {
console.error(e);
return id;
}
};
exports.formatMessage = formatMessage;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
formatMessage,
getIntlMessage,
getLocale,
setLocale
});
{
"name": "tant-intl",
"version": "0.1.8",
"version": "0.2.0",
"description": "数数科技依托于phrase平台的多语言组件",
"main": "es/index.js",
"scripts": {
"start": "tsc --target es5 --outDir lib -watch",
"build": "tsc --target ESNext --outDir es && tsc --target es5 --outDir lib",
"build-es": "tsc --target ESNext --outDir es",
"build-lib": "tsc --target es5 --outDir lib",
"build-dist": "npx webpack --mode=production"
"build": "father build",
"dev:cli": "father build && node lib/cli",
"build:cli": "father build && node lib/cli build"
},

@@ -20,13 +18,6 @@ "repository": {

"devDependencies": {
"@babel/cli": "^7.17.6",
"@babel/parser": "^7.17.0",
"@babel/preset-env": "^7.16.11",
"@babel/preset-typescript": "^7.16.7",
"@babel/traverse": "^7.17.0",
"@types/lodash": "^4.14.186",
"@types/node": "^17.0.21",
"@types/superagent": "^4.1.15",
"babel-core": "^6.26.3",
"ts-loader": "^8.3.0",
"typescript": "^4.5.5",
"webpack-cli": "^4.9.2"
"@types/node-fetch": "^2.6.2",
"father": "^4.1.0"
},

@@ -45,5 +36,4 @@ "bin": {

"react": "^17.0.2",
"react-intl": "^5.24.6",
"superagent": "^7.1.1"
"react-intl": "^5.24.6"
}
}

@@ -24,6 +24,18 @@ # tant-intl:新的国际化解决方案

```javascript
{
{
"token": string;phrase平台的用户token,
"projectIds": string[];项目id列表,至少一个,可以多个,
"tags": string[];标签数组,为空或不配置表示全部。需要保证多个项目内的tag都是唯一的,不然会只取前者
"usePhrase": boolean;生产模式是否直接只用phrase文案,
"outPaths": [
{
"path": string;开发模式下输出目录,
"buildPath": string;生产模式下输出目录,
"projectIds": [
{
"projectId": string;项目id,
"branch": string;分支名,
"tags": string[];标签数组,为空或不配置表示全部。需要保证多个项目内的tag都是唯一的,不然会只取前者
}
]
}
]
}

@@ -30,0 +42,0 @@ ```

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc