@terai/dev 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,688 @@
1
- import{runtime as P}from"@terai/runtime";import{stringify as ae}from"@terai/utils";async function W({dictionaries:t,locale:e,cwd:r,outDir:n}){let o=P.path.resolve(r,n,e),i=[];for(let l in t){let g=P.path.resolve(o,l+".json"),O=t[l],C=ae(O);P.fs.write(g,C),i.push(C)}return i}import{loadConfig as je,runtime as u}from"@terai/runtime";import ne from"node:process";import F from"node:process";import he from"node:os";import q from"node:tty";var J=(t=0)=>e=>`\x1B[${e+t}m`,H=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,K=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`,s={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},We=Object.keys(s.modifier),ce=Object.keys(s.color),ue=Object.keys(s.bgColor),Je=[...ce,...ue];function fe(){let t=new Map;for(let[e,r]of Object.entries(s)){for(let[n,o]of Object.entries(r))s[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[n]=s[n],t.set(o[0],o[1]);Object.defineProperty(s,e,{value:r,enumerable:!1})}return Object.defineProperty(s,"codes",{value:t,enumerable:!1}),s.color.close="\x1B[39m",s.bgColor.close="\x1B[49m",s.color.ansi=J(),s.color.ansi256=H(),s.color.ansi16m=K(),s.bgColor.ansi=J(10),s.bgColor.ansi256=H(10),s.bgColor.ansi16m=K(10),Object.defineProperties(s,{rgbToAnsi256:{value(e,r,n){return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(i=>i+i).join(""));let o=Number.parseInt(n,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:e=>s.rgbToAnsi256(...s.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,n,o;if(e>=232)r=((e-232)*10+8)/255,n=r,o=r;else{e-=16;let g=e%36;r=Math.floor(e/36)/5,n=Math.floor(g/6)/5,o=g%6/5}let i=Math.max(r,n,o)*2;if(i===0)return 30;let l=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(r));return i===2&&(l+=60),l},enumerable:!1},rgbToAnsi:{value:(e,r,n)=>s.ansi256ToAnsi(s.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>s.ansi256ToAnsi(s.hexToAnsi256(e)),enumerable:!1}}),s}var ge=fe(),h=ge;function f(t,e=globalThis.Deno?globalThis.Deno.args:F.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}var{env:a}=F,E;f("no-color")||f("no-colors")||f("color=false")||f("color=never")?E=0:(f("color")||f("colors")||f("color=true")||f("color=always"))&&(E=1);function me(){if("FORCE_COLOR"in a)return a.FORCE_COLOR==="true"?1:a.FORCE_COLOR==="false"?0:a.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(a.FORCE_COLOR,10),3)}function de(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function pe(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=me();n!==void 0&&(E=n);let o=r?E:n;if(o===0)return 0;if(r){if(f("color=16m")||f("color=full")||f("color=truecolor"))return 3;if(f("color=256"))return 2}if("TF_BUILD"in a&&"AGENT_NAME"in a)return 1;if(t&&!e&&o===void 0)return 0;let i=o||0;if(a.TERM==="dumb")return i;if(F.platform==="win32"){let l=he.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in a)return"GITHUB_ACTIONS"in a||"GITEA_ACTIONS"in a?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(l=>l in a)||a.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM==="truecolor"||a.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in a){let l=Number.parseInt((a.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(a.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||"COLORTERM"in a?1:i}function z(t,e={}){let r=pe(t,{streamIsTTY:t&&t.isTTY,...e});return de(r)}var be={stdout:z({isTTY:q.isatty(1)}),stderr:z({isTTY:q.isatty(2)})},ve=be;function ye(t,e,r){let n=t.indexOf(e);if(n===-1)return t;let o=e.length,i=0,l="";do l+=t.slice(i,n)+e+r,i=n+o,n=t.indexOf(e,i);while(n!==-1);return l+=t.slice(i),l}function Te(t,e,r,n){let o=0,i="";do{let l=t[n-1]==="\r";i+=t.slice(o,l?n-1:n)+e+(l?`\r
2
- `:`
3
- `)+r,o=n+1,n=t.indexOf(`
4
- `,o)}while(n!==-1);return i+=t.slice(o),i}var{stdout:Q,stderr:X}=ve,k=Symbol("GENERATOR"),v=Symbol("STYLER"),R=Symbol("IS_EMPTY"),Z=["ansi","ansi","ansi256","ansi16m"],y=Object.create(null),Oe=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=Q?Q.level:0;t.level=e.level===void 0?r:e.level},Ce=t=>{let e=(...r)=>r.join(" ");return Oe(e,t),Object.setPrototypeOf(e,M.prototype),e};function M(t){return Ce(t)}Object.setPrototypeOf(M.prototype,Function.prototype);for(let[t,e]of Object.entries(h))y[t]={get(){let r=w(this,_(e.open,e.close,this[v]),this[R]);return Object.defineProperty(this,t,{value:r}),r}};y.visible={get(){let t=w(this,this[v],!0);return Object.defineProperty(this,"visible",{value:t}),t}};var D=(t,e,r,...n)=>t==="rgb"?e==="ansi16m"?h[r].ansi16m(...n):e==="ansi256"?h[r].ansi256(h.rgbToAnsi256(...n)):h[r].ansi(h.rgbToAnsi(...n)):t==="hex"?D("rgb",e,r,...h.hexToRgb(...n)):h[r][t](...n),xe=["rgb","hex","ansi256"];for(let t of xe){y[t]={get(){let{level:r}=this;return function(...n){let o=_(D(t,Z[r],"color",...n),h.color.close,this[v]);return w(this,o,this[R])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);y[e]={get(){let{level:r}=this;return function(...n){let o=_(D(t,Z[r],"bgColor",...n),h.bgColor.close,this[v]);return w(this,o,this[R])}}}}var Re=Object.defineProperties(()=>{},{...y,level:{enumerable:!0,get(){return this[k].level},set(t){this[k].level=t}}}),_=(t,e,r)=>{let n,o;return r===void 0?(n=t,o=e):(n=r.openAll+t,o=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:o,parent:r}},w=(t,e,r)=>{let n=(...o)=>Me(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,Re),n[k]=t,n[v]=e,n[R]=r,n},Me=(t,e)=>{if(t.level<=0||!e)return t[R]?"":e;let r=t[v];if(r===void 0)return e;let{openAll:n,closeAll:o}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=ye(e,r.close,r.open),r=r.parent;let i=e.indexOf(`
5
- `);return i!==-1&&(e=Te(e,o,n,i)),n+e+o};Object.defineProperties(M.prototype,y);var Ae=M(),ze=M({level:X?X.level:0}),c=Ae;function b(t){return ne.stdout.write(t+`
6
- `)}function Be(t){return ne.stderr.write(t+`
7
- `)}function A(t,e,r,n,o,i){let l=(Array.isArray(i)?i:[i||""].filter(Boolean)).map(g=>r(g)).join("");t(`${" ".repeat(3)} ${e(n)} ${e(o)} ${l}`)}function Ee(t,e){A(b,c.yellow,c.yellow,"\u25CF",t,e)}function ee(t,e){A(b,c.yellow,c.dim,"\u25CF",t,e)}function te(t,e){A(b,c.cyan,c.dim,"\u25FC",t,e)}function re(t){A(b,c.green,c.dim,"\u2714",t)}function we(t,e){b(""),A(Be,c.red,c.red,"\u25B2",t,e)}function $e(t,e){return b(`
8
- ${c.bgWhite(` ${c.whiteBright(t)} `)} ${c.bold(e)}
9
- `)}var N=t=>()=>{let e=performance.now();return r=>{let n=performance.now()-e;t(`${r} ${c.gray(`(${n.toFixed(2)}ms)`)}`)}},T={colors:c,log:b,heading:$e,debug:ee,info:te,warn:Ee,success:re,error:we,time:{success:N(re),info:N(te),debug:N(ee)}};import{translate as Ie}from"@terai/translator";import{merge as Pe,stringify as Ne,groupDictionaryByChunks as ke}from"@terai/utils";function ot(t,e){return t.command("translate","Translate messages from your project").option("--cwd <cwd>","Current working directory",{default:e}).action(De)}async function De({cwd:t}){T.heading("translate","Translate messages from your project");let e=T.time.success(),r=await je({cwd:t}),n=u.path.resolve(t,r.outDir),o=u.path.resolve(t,r.outDir,".terai"),i=u.path.resolve(o,"locale-manifest.json");if(!u.fs.exists(i))return T.error("translate",`No locale-manifest.json found in ${o}. Please run "extract" first.`);let g=JSON.parse(u.fs.readFile(i)),O=0,C=0;if(await Promise.all(r.outLocales.map(async m=>{try{let d={},S={},L=u.path.resolve(n,m),$=u.path.resolve(o,"cache",`${m}.cache.json`),x=u.fs.exists($)?JSON.parse(u.fs.readFile($)):{},j=0,B=0;for(let p in g.messages){let{value:ie,chunksIds:G}=g.messages[p],se=G.length?G:[m];for(let le of se){let Y=u.path.resolve(L,`${le}.json`),I=(u.fs.exists(Y)?JSON.parse(u.fs.readFile(Y)):{})[p]??x[p];I?(d[p]=I,x[p]=I,j++):(S[p]=ie,B++)}}if(B>0){let p=await Ie({...r,dictionary:S,locale:m});d=Pe(p,d)}x={...x,...d},u.fs.remove(L);let oe=ke(d,g,m);await W({...r,dictionaries:oe,locale:m,cwd:t}),u.fs.write($,Ne(x)),O+=B,C+=j,T.info(`Locale ${m.toUpperCase()}:`,`${B} new messages translated, ${j} recovered from cache`)}catch(d){d instanceof Error&&T.error(`${m} translation:`,`Error translating to ${m}: ${d.message}
10
- `)}})),!O)return e("Everything up-to-date");e(`Translated ${O} messages, ${C} read from cache`)}export{ot as createTranslateCommand,De as translateCmd};
1
+ // ../generator/dist/index.mjs
2
+ import { runtime } from "@terai/runtime";
3
+ import { stringify } from "@terai/utils";
4
+ async function generate({
5
+ dictionaries,
6
+ locale,
7
+ cwd,
8
+ outDir
9
+ }) {
10
+ const folderPath = runtime.path.resolve(cwd, outDir, locale);
11
+ const output = [];
12
+ for (const id in dictionaries) {
13
+ const fileDir = runtime.path.resolve(folderPath, `${id}.json`);
14
+ const fileContent = dictionaries[id];
15
+ const idOutput = stringify(fileContent);
16
+ runtime.fs.write(fileDir, idOutput);
17
+ output.push(idOutput);
18
+ }
19
+ return output;
20
+ }
21
+
22
+ // src/commands/translate.ts
23
+ import { loadConfig, runtime as runtime2 } from "@terai/runtime";
24
+
25
+ // ../logger/dist/index.mjs
26
+ import process2 from "node:process";
27
+ import process from "node:process";
28
+ import os from "node:os";
29
+ import tty from "node:tty";
30
+ var ANSI_BACKGROUND_OFFSET = 10;
31
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
32
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
33
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
34
+ var styles = {
35
+ modifier: {
36
+ reset: [0, 0],
37
+ // 21 isn't widely supported and 22 does the same thing
38
+ bold: [1, 22],
39
+ dim: [2, 22],
40
+ italic: [3, 23],
41
+ underline: [4, 24],
42
+ overline: [53, 55],
43
+ inverse: [7, 27],
44
+ hidden: [8, 28],
45
+ strikethrough: [9, 29]
46
+ },
47
+ color: {
48
+ black: [30, 39],
49
+ red: [31, 39],
50
+ green: [32, 39],
51
+ yellow: [33, 39],
52
+ blue: [34, 39],
53
+ magenta: [35, 39],
54
+ cyan: [36, 39],
55
+ white: [37, 39],
56
+ // Bright color
57
+ blackBright: [90, 39],
58
+ gray: [90, 39],
59
+ // Alias of `blackBright`
60
+ grey: [90, 39],
61
+ // Alias of `blackBright`
62
+ redBright: [91, 39],
63
+ greenBright: [92, 39],
64
+ yellowBright: [93, 39],
65
+ blueBright: [94, 39],
66
+ magentaBright: [95, 39],
67
+ cyanBright: [96, 39],
68
+ whiteBright: [97, 39]
69
+ },
70
+ bgColor: {
71
+ bgBlack: [40, 49],
72
+ bgRed: [41, 49],
73
+ bgGreen: [42, 49],
74
+ bgYellow: [43, 49],
75
+ bgBlue: [44, 49],
76
+ bgMagenta: [45, 49],
77
+ bgCyan: [46, 49],
78
+ bgWhite: [47, 49],
79
+ // Bright color
80
+ bgBlackBright: [100, 49],
81
+ bgGray: [100, 49],
82
+ // Alias of `bgBlackBright`
83
+ bgGrey: [100, 49],
84
+ // Alias of `bgBlackBright`
85
+ bgRedBright: [101, 49],
86
+ bgGreenBright: [102, 49],
87
+ bgYellowBright: [103, 49],
88
+ bgBlueBright: [104, 49],
89
+ bgMagentaBright: [105, 49],
90
+ bgCyanBright: [106, 49],
91
+ bgWhiteBright: [107, 49]
92
+ }
93
+ };
94
+ var modifierNames = Object.keys(styles.modifier);
95
+ var foregroundColorNames = Object.keys(styles.color);
96
+ var backgroundColorNames = Object.keys(styles.bgColor);
97
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
98
+ function assembleStyles() {
99
+ const codes = /* @__PURE__ */ new Map();
100
+ for (const [groupName, group] of Object.entries(styles)) {
101
+ for (const [styleName, style] of Object.entries(group)) {
102
+ styles[styleName] = {
103
+ open: `\x1B[${style[0]}m`,
104
+ close: `\x1B[${style[1]}m`
105
+ };
106
+ group[styleName] = styles[styleName];
107
+ codes.set(style[0], style[1]);
108
+ }
109
+ Object.defineProperty(styles, groupName, {
110
+ value: group,
111
+ enumerable: false
112
+ });
113
+ }
114
+ Object.defineProperty(styles, "codes", {
115
+ value: codes,
116
+ enumerable: false
117
+ });
118
+ styles.color.close = "\x1B[39m";
119
+ styles.bgColor.close = "\x1B[49m";
120
+ styles.color.ansi = wrapAnsi16();
121
+ styles.color.ansi256 = wrapAnsi256();
122
+ styles.color.ansi16m = wrapAnsi16m();
123
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
124
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
125
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
126
+ Object.defineProperties(styles, {
127
+ rgbToAnsi256: {
128
+ value(red, green, blue) {
129
+ if (red === green && green === blue) {
130
+ if (red < 8) {
131
+ return 16;
132
+ }
133
+ if (red > 248) {
134
+ return 231;
135
+ }
136
+ return Math.round((red - 8) / 247 * 24) + 232;
137
+ }
138
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
139
+ },
140
+ enumerable: false
141
+ },
142
+ hexToRgb: {
143
+ value(hex) {
144
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
145
+ if (!matches) {
146
+ return [0, 0, 0];
147
+ }
148
+ let [colorString] = matches;
149
+ if (colorString.length === 3) {
150
+ colorString = [...colorString].map((character) => character + character).join("");
151
+ }
152
+ const integer = Number.parseInt(colorString, 16);
153
+ return [
154
+ /* eslint-disable no-bitwise */
155
+ integer >> 16 & 255,
156
+ integer >> 8 & 255,
157
+ integer & 255
158
+ /* eslint-enable no-bitwise */
159
+ ];
160
+ },
161
+ enumerable: false
162
+ },
163
+ hexToAnsi256: {
164
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
165
+ enumerable: false
166
+ },
167
+ ansi256ToAnsi: {
168
+ value(code) {
169
+ if (code < 8) {
170
+ return 30 + code;
171
+ }
172
+ if (code < 16) {
173
+ return 90 + (code - 8);
174
+ }
175
+ let red;
176
+ let green;
177
+ let blue;
178
+ if (code >= 232) {
179
+ red = ((code - 232) * 10 + 8) / 255;
180
+ green = red;
181
+ blue = red;
182
+ } else {
183
+ code -= 16;
184
+ const remainder = code % 36;
185
+ red = Math.floor(code / 36) / 5;
186
+ green = Math.floor(remainder / 6) / 5;
187
+ blue = remainder % 6 / 5;
188
+ }
189
+ const value = Math.max(red, green, blue) * 2;
190
+ if (value === 0) {
191
+ return 30;
192
+ }
193
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
194
+ if (value === 2) {
195
+ result += 60;
196
+ }
197
+ return result;
198
+ },
199
+ enumerable: false
200
+ },
201
+ rgbToAnsi: {
202
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
203
+ enumerable: false
204
+ },
205
+ hexToAnsi: {
206
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
207
+ enumerable: false
208
+ }
209
+ });
210
+ return styles;
211
+ }
212
+ var ansiStyles = assembleStyles();
213
+ var ansi_styles_default = ansiStyles;
214
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
215
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
216
+ const position = argv.indexOf(prefix + flag);
217
+ const terminatorPosition = argv.indexOf("--");
218
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
219
+ }
220
+ var { env } = process;
221
+ var flagForceColor;
222
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
223
+ flagForceColor = 0;
224
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
225
+ flagForceColor = 1;
226
+ }
227
+ function envForceColor() {
228
+ if ("FORCE_COLOR" in env) {
229
+ if (env.FORCE_COLOR === "true") {
230
+ return 1;
231
+ }
232
+ if (env.FORCE_COLOR === "false") {
233
+ return 0;
234
+ }
235
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
236
+ }
237
+ }
238
+ function translateLevel(level) {
239
+ if (level === 0) {
240
+ return false;
241
+ }
242
+ return {
243
+ level,
244
+ hasBasic: true,
245
+ has256: level >= 2,
246
+ has16m: level >= 3
247
+ };
248
+ }
249
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
250
+ const noFlagForceColor = envForceColor();
251
+ if (noFlagForceColor !== void 0) {
252
+ flagForceColor = noFlagForceColor;
253
+ }
254
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
255
+ if (forceColor === 0) {
256
+ return 0;
257
+ }
258
+ if (sniffFlags) {
259
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
260
+ return 3;
261
+ }
262
+ if (hasFlag("color=256")) {
263
+ return 2;
264
+ }
265
+ }
266
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
267
+ return 1;
268
+ }
269
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
270
+ return 0;
271
+ }
272
+ const min = forceColor || 0;
273
+ if (env.TERM === "dumb") {
274
+ return min;
275
+ }
276
+ if (process.platform === "win32") {
277
+ const osRelease = os.release().split(".");
278
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
279
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
280
+ }
281
+ return 1;
282
+ }
283
+ if ("CI" in env) {
284
+ if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
285
+ return 3;
286
+ }
287
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
288
+ return 1;
289
+ }
290
+ return min;
291
+ }
292
+ if ("TEAMCITY_VERSION" in env) {
293
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
294
+ }
295
+ if (env.COLORTERM === "truecolor") {
296
+ return 3;
297
+ }
298
+ if (env.TERM === "xterm-kitty") {
299
+ return 3;
300
+ }
301
+ if ("TERM_PROGRAM" in env) {
302
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
303
+ switch (env.TERM_PROGRAM) {
304
+ case "iTerm.app": {
305
+ return version >= 3 ? 3 : 2;
306
+ }
307
+ case "Apple_Terminal": {
308
+ return 2;
309
+ }
310
+ }
311
+ }
312
+ if (/-256(color)?$/i.test(env.TERM)) {
313
+ return 2;
314
+ }
315
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
316
+ return 1;
317
+ }
318
+ if ("COLORTERM" in env) {
319
+ return 1;
320
+ }
321
+ return min;
322
+ }
323
+ function createSupportsColor(stream, options = {}) {
324
+ const level = _supportsColor(stream, {
325
+ streamIsTTY: stream && stream.isTTY,
326
+ ...options
327
+ });
328
+ return translateLevel(level);
329
+ }
330
+ var supportsColor = {
331
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
332
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
333
+ };
334
+ var supports_color_default = supportsColor;
335
+ function stringReplaceAll(string, substring, replacer) {
336
+ let index = string.indexOf(substring);
337
+ if (index === -1) {
338
+ return string;
339
+ }
340
+ const substringLength = substring.length;
341
+ let endIndex = 0;
342
+ let returnValue = "";
343
+ do {
344
+ returnValue += string.slice(endIndex, index) + substring + replacer;
345
+ endIndex = index + substringLength;
346
+ index = string.indexOf(substring, endIndex);
347
+ } while (index !== -1);
348
+ returnValue += string.slice(endIndex);
349
+ return returnValue;
350
+ }
351
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
352
+ let endIndex = 0;
353
+ let returnValue = "";
354
+ do {
355
+ const gotCR = string[index - 1] === "\r";
356
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
357
+ endIndex = index + 1;
358
+ index = string.indexOf("\n", endIndex);
359
+ } while (index !== -1);
360
+ returnValue += string.slice(endIndex);
361
+ return returnValue;
362
+ }
363
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
364
+ var GENERATOR = Symbol("GENERATOR");
365
+ var STYLER = Symbol("STYLER");
366
+ var IS_EMPTY = Symbol("IS_EMPTY");
367
+ var levelMapping = [
368
+ "ansi",
369
+ "ansi",
370
+ "ansi256",
371
+ "ansi16m"
372
+ ];
373
+ var styles2 = /* @__PURE__ */ Object.create(null);
374
+ var applyOptions = (object, options = {}) => {
375
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
376
+ throw new Error("The `level` option should be an integer from 0 to 3");
377
+ }
378
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
379
+ object.level = options.level === void 0 ? colorLevel : options.level;
380
+ };
381
+ var chalkFactory = (options) => {
382
+ const chalk2 = (...strings) => strings.join(" ");
383
+ applyOptions(chalk2, options);
384
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
385
+ return chalk2;
386
+ };
387
+ function createChalk(options) {
388
+ return chalkFactory(options);
389
+ }
390
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
391
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
392
+ styles2[styleName] = {
393
+ get() {
394
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
395
+ Object.defineProperty(this, styleName, { value: builder });
396
+ return builder;
397
+ }
398
+ };
399
+ }
400
+ styles2.visible = {
401
+ get() {
402
+ const builder = createBuilder(this, this[STYLER], true);
403
+ Object.defineProperty(this, "visible", { value: builder });
404
+ return builder;
405
+ }
406
+ };
407
+ var getModelAnsi = (model, level, type, ...arguments_) => {
408
+ if (model === "rgb") {
409
+ if (level === "ansi16m") {
410
+ return ansi_styles_default[type].ansi16m(...arguments_);
411
+ }
412
+ if (level === "ansi256") {
413
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
414
+ }
415
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
416
+ }
417
+ if (model === "hex") {
418
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
419
+ }
420
+ return ansi_styles_default[type][model](...arguments_);
421
+ };
422
+ var usedModels = ["rgb", "hex", "ansi256"];
423
+ for (const model of usedModels) {
424
+ styles2[model] = {
425
+ get() {
426
+ const { level } = this;
427
+ return function(...arguments_) {
428
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
429
+ return createBuilder(this, styler, this[IS_EMPTY]);
430
+ };
431
+ }
432
+ };
433
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
434
+ styles2[bgModel] = {
435
+ get() {
436
+ const { level } = this;
437
+ return function(...arguments_) {
438
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
439
+ return createBuilder(this, styler, this[IS_EMPTY]);
440
+ };
441
+ }
442
+ };
443
+ }
444
+ var proto = Object.defineProperties(() => {
445
+ }, {
446
+ ...styles2,
447
+ level: {
448
+ enumerable: true,
449
+ get() {
450
+ return this[GENERATOR].level;
451
+ },
452
+ set(level) {
453
+ this[GENERATOR].level = level;
454
+ }
455
+ }
456
+ });
457
+ var createStyler = (open, close, parent) => {
458
+ let openAll;
459
+ let closeAll;
460
+ if (parent === void 0) {
461
+ openAll = open;
462
+ closeAll = close;
463
+ } else {
464
+ openAll = parent.openAll + open;
465
+ closeAll = close + parent.closeAll;
466
+ }
467
+ return {
468
+ open,
469
+ close,
470
+ openAll,
471
+ closeAll,
472
+ parent
473
+ };
474
+ };
475
+ var createBuilder = (self, _styler, _isEmpty) => {
476
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
477
+ Object.setPrototypeOf(builder, proto);
478
+ builder[GENERATOR] = self;
479
+ builder[STYLER] = _styler;
480
+ builder[IS_EMPTY] = _isEmpty;
481
+ return builder;
482
+ };
483
+ var applyStyle = (self, string) => {
484
+ if (self.level <= 0 || !string) {
485
+ return self[IS_EMPTY] ? "" : string;
486
+ }
487
+ let styler = self[STYLER];
488
+ if (styler === void 0) {
489
+ return string;
490
+ }
491
+ const { openAll, closeAll } = styler;
492
+ if (string.includes("\x1B")) {
493
+ while (styler !== void 0) {
494
+ string = stringReplaceAll(string, styler.close, styler.open);
495
+ styler = styler.parent;
496
+ }
497
+ }
498
+ const lfIndex = string.indexOf("\n");
499
+ if (lfIndex !== -1) {
500
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
501
+ }
502
+ return openAll + string + closeAll;
503
+ };
504
+ Object.defineProperties(createChalk.prototype, styles2);
505
+ var chalk = createChalk();
506
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
507
+ var source_default = chalk;
508
+ function log(message) {
509
+ return process2.stdout.write(`${message}
510
+ `);
511
+ }
512
+ function logError(message) {
513
+ return process2.stderr.write(`${message}
514
+ `);
515
+ }
516
+ function logBullet(logger2, colorizePrefix, colorizeText, symbol, prefix, text) {
517
+ const textParts = Array.isArray(text) ? text : [text || ""].filter(Boolean);
518
+ const formattedText = textParts.map((textPart) => colorizeText(textPart)).join("");
519
+ logger2(
520
+ `${" ".repeat(3)} ${colorizePrefix(symbol)} ${colorizePrefix(
521
+ prefix
522
+ )} ${formattedText}`
523
+ );
524
+ }
525
+ function warn(prefix, text) {
526
+ logBullet(log, source_default.yellow, source_default.yellow, "\u25CF", prefix, text);
527
+ }
528
+ function debug(prefix, text) {
529
+ logBullet(log, source_default.yellow, source_default.dim, "\u25CF", prefix, text);
530
+ }
531
+ function info(prefix, text) {
532
+ logBullet(log, source_default.cyan, source_default.dim, "\u25FC", prefix, text);
533
+ }
534
+ function success(text) {
535
+ logBullet(log, source_default.green, source_default.dim, "\u2714", text);
536
+ }
537
+ function error(prefix, text) {
538
+ log("");
539
+ logBullet(logError, source_default.red, source_default.red, "\u25B2", prefix, text);
540
+ }
541
+ function heading(heading2, description) {
542
+ return log(
543
+ `
544
+ ${source_default.bgWhite(` ${source_default.whiteBright(heading2)} `)} ${source_default.bold(
545
+ description
546
+ )}
547
+ `
548
+ );
549
+ }
550
+ var timing = (fn) => () => {
551
+ const start = performance.now();
552
+ return (msg) => {
553
+ const end = performance.now();
554
+ const ms = end - start;
555
+ fn(`${msg} ${source_default.gray(`(${ms.toFixed(2)}ms)`)}`);
556
+ };
557
+ };
558
+ var logger = {
559
+ colors: source_default,
560
+ log,
561
+ heading,
562
+ debug,
563
+ info,
564
+ warn,
565
+ success,
566
+ error,
567
+ time: {
568
+ success: timing(success),
569
+ info: timing(info),
570
+ debug: timing(debug)
571
+ }
572
+ };
573
+
574
+ // src/commands/translate.ts
575
+ import { translate } from "@terai/translator";
576
+ import { merge, stringify as stringify2, groupDictionaryByChunks } from "@terai/utils";
577
+ function createTranslateCommand(cli, cwd) {
578
+ return cli.command("translate", "Translate messages from your project").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(translateCmd);
579
+ }
580
+ async function translateCmd({ cwd }) {
581
+ logger.heading("translate", "Translate messages from your project");
582
+ const done = logger.time.success();
583
+ const config = await loadConfig({ cwd });
584
+ const outDirPath = runtime2.path.resolve(cwd, config.outDir);
585
+ const tmuDirPath = runtime2.path.resolve(cwd, config.outDir, ".terai");
586
+ const manifestPath = runtime2.path.resolve(tmuDirPath, "locale-manifest.json");
587
+ const existsManifest = runtime2.fs.exists(manifestPath);
588
+ if (!existsManifest) {
589
+ return logger.error(
590
+ "translate",
591
+ `No locale-manifest.json found in ${tmuDirPath}. Please run "extract" first.`
592
+ );
593
+ }
594
+ const buildManifest = JSON.parse(
595
+ runtime2.fs.readFile(manifestPath)
596
+ );
597
+ let totalTranslatedMsgs = 0;
598
+ let totalCachedMsgs = 0;
599
+ await Promise.all(
600
+ config.outLocales.map(async (locale) => {
601
+ try {
602
+ let translatedDictionary = {};
603
+ const untranslatedDictionary = {};
604
+ const localeDirPath = runtime2.path.resolve(outDirPath, locale);
605
+ const localeCachePath = runtime2.path.resolve(
606
+ tmuDirPath,
607
+ "cache",
608
+ `${locale}.cache.json`
609
+ );
610
+ const cacheExists = runtime2.fs.exists(localeCachePath);
611
+ let cache = cacheExists ? JSON.parse(runtime2.fs.readFile(localeCachePath)) : {};
612
+ let localeCachedMsgs = 0;
613
+ let localeTranslatedMsgs = 0;
614
+ for (const id in buildManifest.messages) {
615
+ const { value, chunksIds } = buildManifest.messages[id];
616
+ const chnks = chunksIds.length ? chunksIds : [locale];
617
+ for (const chunkId of chnks) {
618
+ const chunkPath = runtime2.path.resolve(
619
+ localeDirPath,
620
+ `${chunkId}.json`
621
+ );
622
+ const existsChunk = runtime2.fs.exists(chunkPath);
623
+ const chunk = existsChunk ? JSON.parse(runtime2.fs.readFile(chunkPath)) : {};
624
+ const localeValue = chunk[id] ?? cache[id];
625
+ if (!localeValue) {
626
+ untranslatedDictionary[id] = value;
627
+ localeTranslatedMsgs++;
628
+ } else {
629
+ translatedDictionary[id] = localeValue;
630
+ cache[id] = localeValue;
631
+ localeCachedMsgs++;
632
+ }
633
+ }
634
+ }
635
+ if (localeTranslatedMsgs > 0) {
636
+ const translation = await translate({
637
+ ...config,
638
+ dictionary: untranslatedDictionary,
639
+ locale
640
+ });
641
+ translatedDictionary = merge(translation, translatedDictionary);
642
+ }
643
+ cache = {
644
+ ...cache,
645
+ ...translatedDictionary
646
+ };
647
+ runtime2.fs.remove(localeDirPath);
648
+ const dictionaries = groupDictionaryByChunks(
649
+ translatedDictionary,
650
+ buildManifest,
651
+ locale
652
+ );
653
+ await generate({
654
+ ...config,
655
+ dictionaries,
656
+ locale,
657
+ cwd
658
+ });
659
+ runtime2.fs.write(localeCachePath, stringify2(cache));
660
+ totalTranslatedMsgs += localeTranslatedMsgs;
661
+ totalCachedMsgs += localeCachedMsgs;
662
+ logger.info(
663
+ `Locale ${locale.toUpperCase()}:`,
664
+ `${localeTranslatedMsgs} new messages translated, ${localeCachedMsgs} recovered from cache`
665
+ );
666
+ } catch (err) {
667
+ if (err instanceof Error) {
668
+ logger.error(
669
+ `${locale} translation:`,
670
+ `Error translating to ${locale}: ${err.message}
671
+ `
672
+ );
673
+ }
674
+ }
675
+ })
676
+ );
677
+ if (!totalTranslatedMsgs) {
678
+ return done("Everything up-to-date");
679
+ }
680
+ done(
681
+ `Translated ${totalTranslatedMsgs} messages, ${totalCachedMsgs} read from cache`
682
+ );
683
+ }
684
+ export {
685
+ createTranslateCommand,
686
+ translateCmd
687
+ };
11
688
  //# sourceMappingURL=translate.mjs.map