@terai/dev 0.0.2 → 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,15 +1,961 @@
1
- import{findConfig as Ke,setupConfig as qe,setupTemplate as Qe}from"@terai/runtime";import{input as me,select as Xe}from"@inquirer/prompts";import le from"node:process";import U from"node:process";import Ce from"node:os";import ee from"node:tty";var Q=(e=0)=>t=>`\x1B[${t+e}m`,X=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Z=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,l={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]}},yt=Object.keys(l.modifier),ye=Object.keys(l.color),be=Object.keys(l.bgColor),bt=[...ye,...be];function we(){let e=new Map;for(let[t,r]of Object.entries(l)){for(let[n,o]of Object.entries(r))l[n]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[n]=l[n],e.set(o[0],o[1]);Object.defineProperty(l,t,{value:r,enumerable:!1})}return Object.defineProperty(l,"codes",{value:e,enumerable:!1}),l.color.close="\x1B[39m",l.bgColor.close="\x1B[49m",l.color.ansi=Q(),l.color.ansi256=X(),l.color.ansi16m=Z(),l.bgColor.ansi=Q(10),l.bgColor.ansi256=X(10),l.bgColor.ansi16m=Z(10),Object.defineProperties(l,{rgbToAnsi256:{value(t,r,n){return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.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:t=>l.rgbToAnsi256(...l.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,n,o;if(t>=232)r=((t-232)*10+8)/255,n=r,o=r;else{t-=16;let s=t%36;r=Math.floor(t/36)/5,n=Math.floor(s/6)/5,o=s%6/5}let i=Math.max(r,n,o)*2;if(i===0)return 30;let a=30+(Math.round(o)<<2|Math.round(n)<<1|Math.round(r));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(t,r,n)=>l.ansi256ToAnsi(l.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>l.ansi256ToAnsi(l.hexToAnsi256(t)),enumerable:!1}}),l}var xe=we(),b=xe;function y(e,t=globalThis.Deno?globalThis.Deno.args:U.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(r+e),o=t.indexOf("--");return n!==-1&&(o===-1||n<o)}var{env:c}=U,P;y("no-color")||y("no-colors")||y("color=false")||y("color=never")?P=0:(y("color")||y("colors")||y("color=true")||y("color=always"))&&(P=1);function Oe(){if("FORCE_COLOR"in c)return c.FORCE_COLOR==="true"?1:c.FORCE_COLOR==="false"?0:c.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(c.FORCE_COLOR,10),3)}function Te(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Me(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let n=Oe();n!==void 0&&(P=n);let o=r?P:n;if(o===0)return 0;if(r){if(y("color=16m")||y("color=full")||y("color=truecolor"))return 3;if(y("color=256"))return 2}if("TF_BUILD"in c&&"AGENT_NAME"in c)return 1;if(e&&!t&&o===void 0)return 0;let i=o||0;if(c.TERM==="dumb")return i;if(U.platform==="win32"){let a=Ce.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in c)return"GITHUB_ACTIONS"in c||"GITEA_ACTIONS"in c?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in c)||c.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in c)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(c.TEAMCITY_VERSION)?1:0;if(c.COLORTERM==="truecolor"||c.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in c){let a=Number.parseInt((c.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(c.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(c.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(c.TERM)||"COLORTERM"in c?1:i}function te(e,t={}){let r=Me(e,{streamIsTTY:e&&e.isTTY,...t});return Te(r)}var Ee={stdout:te({isTTY:ee.isatty(1)}),stderr:te({isTTY:ee.isatty(2)})},Re=Ee;function Ae(e,t,r){let n=e.indexOf(t);if(n===-1)return e;let o=t.length,i=0,a="";do a+=e.slice(i,n)+t+r,i=n+o,n=e.indexOf(t,i);while(n!==-1);return a+=e.slice(i),a}function Be(e,t,r,n){let o=0,i="";do{let a=e[n-1]==="\r";i+=e.slice(o,a?n-1:n)+t+(a?`\r
2
- `:`
3
- `)+r,o=n+1,n=e.indexOf(`
4
- `,o)}while(n!==-1);return i+=e.slice(o),i}var{stdout:re,stderr:ne}=Re,Y=Symbol("GENERATOR"),E=Symbol("STYLER"),$=Symbol("IS_EMPTY"),oe=["ansi","ansi","ansi256","ansi16m"],R=Object.create(null),je=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=re?re.level:0;e.level=t.level===void 0?r:t.level},$e=e=>{let t=(...r)=>r.join(" ");return je(t,e),Object.setPrototypeOf(t,I.prototype),t};function I(e){return $e(e)}Object.setPrototypeOf(I.prototype,Function.prototype);for(let[e,t]of Object.entries(b))R[e]={get(){let r=L(this,V(t.open,t.close,this[E]),this[$]);return Object.defineProperty(this,e,{value:r}),r}};R.visible={get(){let e=L(this,this[E],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var G=(e,t,r,...n)=>e==="rgb"?t==="ansi16m"?b[r].ansi16m(...n):t==="ansi256"?b[r].ansi256(b.rgbToAnsi256(...n)):b[r].ansi(b.rgbToAnsi(...n)):e==="hex"?G("rgb",t,r,...b.hexToRgb(...n)):b[r][e](...n),Ie=["rgb","hex","ansi256"];for(let e of Ie){R[e]={get(){let{level:r}=this;return function(...n){let o=V(G(e,oe[r],"color",...n),b.color.close,this[E]);return L(this,o,this[$])}}};let t="bg"+e[0].toUpperCase()+e.slice(1);R[t]={get(){let{level:r}=this;return function(...n){let o=V(G(e,oe[r],"bgColor",...n),b.bgColor.close,this[E]);return L(this,o,this[$])}}}}var ke=Object.defineProperties(()=>{},{...R,level:{enumerable:!0,get(){return this[Y].level},set(e){this[Y].level=e}}}),V=(e,t,r)=>{let n,o;return r===void 0?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},L=(e,t,r)=>{let n=(...o)=>Ne(n,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(n,ke),n[Y]=e,n[E]=t,n[$]=r,n},Ne=(e,t)=>{if(e.level<=0||!t)return e[$]?"":t;let r=e[E];if(r===void 0)return t;let{openAll:n,closeAll:o}=r;if(t.includes("\x1B"))for(;r!==void 0;)t=Ae(t,r.close,r.open),r=r.parent;let i=t.indexOf(`
5
- `);return i!==-1&&(t=Be(t,o,n,i)),n+t+o};Object.defineProperties(I.prototype,R);var Pe=I(),Ot=I({level:ne?ne.level:0}),h=Pe;function T(e){return le.stdout.write(e+`
6
- `)}function Le(e){return le.stderr.write(e+`
7
- `)}function k(e,t,r,n,o,i){let a=(Array.isArray(i)?i:[i||""].filter(Boolean)).map(s=>r(s)).join("");e(`${" ".repeat(3)} ${t(n)} ${t(o)} ${a}`)}function De(e,t){k(T,h.yellow,h.yellow,"\u25CF",e,t)}function ie(e,t){k(T,h.yellow,h.dim,"\u25CF",e,t)}function ae(e,t){k(T,h.cyan,h.dim,"\u25FC",e,t)}function se(e){k(T,h.green,h.dim,"\u2714",e)}function Se(e,t){T(""),k(Le,h.red,h.red,"\u25B2",e,t)}function Fe(e,t){return T(`
8
- ${h.bgWhite(` ${h.whiteBright(e)} `)} ${h.bold(t)}
9
- `)}var _=e=>()=>{let t=performance.now();return r=>{let n=performance.now()-t;e(`${r} ${h.gray(`(${n.toFixed(2)}ms)`)}`)}},u={colors:h,log:T,heading:Fe,debug:ie,info:ae,warn:De,success:se,error:Se,time:{success:_(se),info:_(ae),debug:_(ie)}};function D(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t]}function ce(){return typeof WeakMap<"u"?new WeakMap:We()}function We(){return{add:D,delete:D,get:D,set:D,has:function(e){return!1}}}var _e=Object.prototype.hasOwnProperty,J=function(e,t){return _e.call(e,t)};function z(e,t){for(var r in t)J(t,r)&&(e[r]=t[r]);return e}var Ye=/^[ \t]*(?:\r\n|\r|\n)/,Ge=/(?:\r\n|\r|\n)[ \t]*$/,Ve=/^(?:[\r\n]|$)/,Ue=/(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/,ze=/^[ \t]*[\r\n][ \t\r\n]*$/;function ue(e,t,r){var n=0,o=e[0].match(Ue);o&&(n=o[1].length);var i="(\\r\\n|\\r|\\n).{0,"+n+"}",a=new RegExp(i,"g");t&&(e=e.slice(1));var s=r.newline,g=r.trimLeadingNewline,d=r.trimTrailingNewline,m=typeof s=="string",f=e.length,w=e.map(function(p,M){return p=p.replace(a,"$1"),M===0&&g&&(p=p.replace(Ye,"")),M===f-1&&d&&(p=p.replace(Ge,"")),m&&(p=p.replace(/\r\n|\n|\r/g,function(ge){return s})),p});return w}function Je(e,t){for(var r="",n=0,o=e.length;n<o;n++)r+=e[n],n<o-1&&(r+=t[n]);return r}function He(e){return J(e,"raw")&&J(e,"length")}function fe(e){var t=ce(),r=ce();function n(i){for(var a=[],s=1;s<arguments.length;s++)a[s-1]=arguments[s];if(He(i)){var g=i,d=(a[0]===n||a[0]===x)&&ze.test(g[0])&&Ve.test(g[1]),m=d?r:t,f=m.get(g);if(f||(f=ue(g,d,e),m.set(g,f)),a.length===0)return f[0];var w=Je(f,d?a.slice(1):a);return w}else return fe(z(z({},e),i||{}))}var o=z(n,{string:function(i){return ue([i],!1,e)[0]}});return o}var x=fe({trimLeadingNewline:!0,trimTrailingNewline:!0});if(typeof module<"u")try{module.exports=x,Object.defineProperty(x,"__esModule",{value:!0}),x.default=x,x.outdent=x}catch{}import Ze from"preferred-pm";function kt(e,t){return e.command("init","Initialize config file").option("-f, --force","Force overwrite existing config files").option("--cwd <cwd>","Current working directory",{default:t}).action(et)}async function et({cwd:e,force:t}){u.heading("init","Initialize config file");let r=Ke({cwd:e}),o=(await Ze(e))?.name??"npm",i=o==="npm"?"npm run":o;if(r&&!t)return u.log(x`
1
+ // src/commands/init.ts
2
+ import { findConfig, setupConfig, setupTemplate } from "@terai/runtime";
3
+ import { input, select } from "@inquirer/prompts";
4
+
5
+ // ../logger/dist/index.mjs
6
+ import process2 from "node:process";
7
+ import process from "node:process";
8
+ import os from "node:os";
9
+ import tty from "node:tty";
10
+ var ANSI_BACKGROUND_OFFSET = 10;
11
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
12
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
13
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
14
+ var styles = {
15
+ modifier: {
16
+ reset: [0, 0],
17
+ // 21 isn't widely supported and 22 does the same thing
18
+ bold: [1, 22],
19
+ dim: [2, 22],
20
+ italic: [3, 23],
21
+ underline: [4, 24],
22
+ overline: [53, 55],
23
+ inverse: [7, 27],
24
+ hidden: [8, 28],
25
+ strikethrough: [9, 29]
26
+ },
27
+ color: {
28
+ black: [30, 39],
29
+ red: [31, 39],
30
+ green: [32, 39],
31
+ yellow: [33, 39],
32
+ blue: [34, 39],
33
+ magenta: [35, 39],
34
+ cyan: [36, 39],
35
+ white: [37, 39],
36
+ // Bright color
37
+ blackBright: [90, 39],
38
+ gray: [90, 39],
39
+ // Alias of `blackBright`
40
+ grey: [90, 39],
41
+ // Alias of `blackBright`
42
+ redBright: [91, 39],
43
+ greenBright: [92, 39],
44
+ yellowBright: [93, 39],
45
+ blueBright: [94, 39],
46
+ magentaBright: [95, 39],
47
+ cyanBright: [96, 39],
48
+ whiteBright: [97, 39]
49
+ },
50
+ bgColor: {
51
+ bgBlack: [40, 49],
52
+ bgRed: [41, 49],
53
+ bgGreen: [42, 49],
54
+ bgYellow: [43, 49],
55
+ bgBlue: [44, 49],
56
+ bgMagenta: [45, 49],
57
+ bgCyan: [46, 49],
58
+ bgWhite: [47, 49],
59
+ // Bright color
60
+ bgBlackBright: [100, 49],
61
+ bgGray: [100, 49],
62
+ // Alias of `bgBlackBright`
63
+ bgGrey: [100, 49],
64
+ // Alias of `bgBlackBright`
65
+ bgRedBright: [101, 49],
66
+ bgGreenBright: [102, 49],
67
+ bgYellowBright: [103, 49],
68
+ bgBlueBright: [104, 49],
69
+ bgMagentaBright: [105, 49],
70
+ bgCyanBright: [106, 49],
71
+ bgWhiteBright: [107, 49]
72
+ }
73
+ };
74
+ var modifierNames = Object.keys(styles.modifier);
75
+ var foregroundColorNames = Object.keys(styles.color);
76
+ var backgroundColorNames = Object.keys(styles.bgColor);
77
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
78
+ function assembleStyles() {
79
+ const codes = /* @__PURE__ */ new Map();
80
+ for (const [groupName, group] of Object.entries(styles)) {
81
+ for (const [styleName, style] of Object.entries(group)) {
82
+ styles[styleName] = {
83
+ open: `\x1B[${style[0]}m`,
84
+ close: `\x1B[${style[1]}m`
85
+ };
86
+ group[styleName] = styles[styleName];
87
+ codes.set(style[0], style[1]);
88
+ }
89
+ Object.defineProperty(styles, groupName, {
90
+ value: group,
91
+ enumerable: false
92
+ });
93
+ }
94
+ Object.defineProperty(styles, "codes", {
95
+ value: codes,
96
+ enumerable: false
97
+ });
98
+ styles.color.close = "\x1B[39m";
99
+ styles.bgColor.close = "\x1B[49m";
100
+ styles.color.ansi = wrapAnsi16();
101
+ styles.color.ansi256 = wrapAnsi256();
102
+ styles.color.ansi16m = wrapAnsi16m();
103
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
104
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
105
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
106
+ Object.defineProperties(styles, {
107
+ rgbToAnsi256: {
108
+ value(red, green, blue) {
109
+ if (red === green && green === blue) {
110
+ if (red < 8) {
111
+ return 16;
112
+ }
113
+ if (red > 248) {
114
+ return 231;
115
+ }
116
+ return Math.round((red - 8) / 247 * 24) + 232;
117
+ }
118
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
119
+ },
120
+ enumerable: false
121
+ },
122
+ hexToRgb: {
123
+ value(hex) {
124
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
125
+ if (!matches) {
126
+ return [0, 0, 0];
127
+ }
128
+ let [colorString] = matches;
129
+ if (colorString.length === 3) {
130
+ colorString = [...colorString].map((character) => character + character).join("");
131
+ }
132
+ const integer = Number.parseInt(colorString, 16);
133
+ return [
134
+ /* eslint-disable no-bitwise */
135
+ integer >> 16 & 255,
136
+ integer >> 8 & 255,
137
+ integer & 255
138
+ /* eslint-enable no-bitwise */
139
+ ];
140
+ },
141
+ enumerable: false
142
+ },
143
+ hexToAnsi256: {
144
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
145
+ enumerable: false
146
+ },
147
+ ansi256ToAnsi: {
148
+ value(code) {
149
+ if (code < 8) {
150
+ return 30 + code;
151
+ }
152
+ if (code < 16) {
153
+ return 90 + (code - 8);
154
+ }
155
+ let red;
156
+ let green;
157
+ let blue;
158
+ if (code >= 232) {
159
+ red = ((code - 232) * 10 + 8) / 255;
160
+ green = red;
161
+ blue = red;
162
+ } else {
163
+ code -= 16;
164
+ const remainder = code % 36;
165
+ red = Math.floor(code / 36) / 5;
166
+ green = Math.floor(remainder / 6) / 5;
167
+ blue = remainder % 6 / 5;
168
+ }
169
+ const value = Math.max(red, green, blue) * 2;
170
+ if (value === 0) {
171
+ return 30;
172
+ }
173
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
174
+ if (value === 2) {
175
+ result += 60;
176
+ }
177
+ return result;
178
+ },
179
+ enumerable: false
180
+ },
181
+ rgbToAnsi: {
182
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
183
+ enumerable: false
184
+ },
185
+ hexToAnsi: {
186
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
187
+ enumerable: false
188
+ }
189
+ });
190
+ return styles;
191
+ }
192
+ var ansiStyles = assembleStyles();
193
+ var ansi_styles_default = ansiStyles;
194
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
195
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
196
+ const position = argv.indexOf(prefix + flag);
197
+ const terminatorPosition = argv.indexOf("--");
198
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
199
+ }
200
+ var { env } = process;
201
+ var flagForceColor;
202
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
203
+ flagForceColor = 0;
204
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
205
+ flagForceColor = 1;
206
+ }
207
+ function envForceColor() {
208
+ if ("FORCE_COLOR" in env) {
209
+ if (env.FORCE_COLOR === "true") {
210
+ return 1;
211
+ }
212
+ if (env.FORCE_COLOR === "false") {
213
+ return 0;
214
+ }
215
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
216
+ }
217
+ }
218
+ function translateLevel(level) {
219
+ if (level === 0) {
220
+ return false;
221
+ }
222
+ return {
223
+ level,
224
+ hasBasic: true,
225
+ has256: level >= 2,
226
+ has16m: level >= 3
227
+ };
228
+ }
229
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
230
+ const noFlagForceColor = envForceColor();
231
+ if (noFlagForceColor !== void 0) {
232
+ flagForceColor = noFlagForceColor;
233
+ }
234
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
235
+ if (forceColor === 0) {
236
+ return 0;
237
+ }
238
+ if (sniffFlags) {
239
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
240
+ return 3;
241
+ }
242
+ if (hasFlag("color=256")) {
243
+ return 2;
244
+ }
245
+ }
246
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
247
+ return 1;
248
+ }
249
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
250
+ return 0;
251
+ }
252
+ const min = forceColor || 0;
253
+ if (env.TERM === "dumb") {
254
+ return min;
255
+ }
256
+ if (process.platform === "win32") {
257
+ const osRelease = os.release().split(".");
258
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
259
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
260
+ }
261
+ return 1;
262
+ }
263
+ if ("CI" in env) {
264
+ if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
265
+ return 3;
266
+ }
267
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
268
+ return 1;
269
+ }
270
+ return min;
271
+ }
272
+ if ("TEAMCITY_VERSION" in env) {
273
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
274
+ }
275
+ if (env.COLORTERM === "truecolor") {
276
+ return 3;
277
+ }
278
+ if (env.TERM === "xterm-kitty") {
279
+ return 3;
280
+ }
281
+ if ("TERM_PROGRAM" in env) {
282
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
283
+ switch (env.TERM_PROGRAM) {
284
+ case "iTerm.app": {
285
+ return version >= 3 ? 3 : 2;
286
+ }
287
+ case "Apple_Terminal": {
288
+ return 2;
289
+ }
290
+ }
291
+ }
292
+ if (/-256(color)?$/i.test(env.TERM)) {
293
+ return 2;
294
+ }
295
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
296
+ return 1;
297
+ }
298
+ if ("COLORTERM" in env) {
299
+ return 1;
300
+ }
301
+ return min;
302
+ }
303
+ function createSupportsColor(stream, options = {}) {
304
+ const level = _supportsColor(stream, {
305
+ streamIsTTY: stream && stream.isTTY,
306
+ ...options
307
+ });
308
+ return translateLevel(level);
309
+ }
310
+ var supportsColor = {
311
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
312
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
313
+ };
314
+ var supports_color_default = supportsColor;
315
+ function stringReplaceAll(string, substring, replacer) {
316
+ let index = string.indexOf(substring);
317
+ if (index === -1) {
318
+ return string;
319
+ }
320
+ const substringLength = substring.length;
321
+ let endIndex = 0;
322
+ let returnValue = "";
323
+ do {
324
+ returnValue += string.slice(endIndex, index) + substring + replacer;
325
+ endIndex = index + substringLength;
326
+ index = string.indexOf(substring, endIndex);
327
+ } while (index !== -1);
328
+ returnValue += string.slice(endIndex);
329
+ return returnValue;
330
+ }
331
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
332
+ let endIndex = 0;
333
+ let returnValue = "";
334
+ do {
335
+ const gotCR = string[index - 1] === "\r";
336
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
337
+ endIndex = index + 1;
338
+ index = string.indexOf("\n", endIndex);
339
+ } while (index !== -1);
340
+ returnValue += string.slice(endIndex);
341
+ return returnValue;
342
+ }
343
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
344
+ var GENERATOR = Symbol("GENERATOR");
345
+ var STYLER = Symbol("STYLER");
346
+ var IS_EMPTY = Symbol("IS_EMPTY");
347
+ var levelMapping = [
348
+ "ansi",
349
+ "ansi",
350
+ "ansi256",
351
+ "ansi16m"
352
+ ];
353
+ var styles2 = /* @__PURE__ */ Object.create(null);
354
+ var applyOptions = (object, options = {}) => {
355
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
356
+ throw new Error("The `level` option should be an integer from 0 to 3");
357
+ }
358
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
359
+ object.level = options.level === void 0 ? colorLevel : options.level;
360
+ };
361
+ var chalkFactory = (options) => {
362
+ const chalk2 = (...strings) => strings.join(" ");
363
+ applyOptions(chalk2, options);
364
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
365
+ return chalk2;
366
+ };
367
+ function createChalk(options) {
368
+ return chalkFactory(options);
369
+ }
370
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
371
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
372
+ styles2[styleName] = {
373
+ get() {
374
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
375
+ Object.defineProperty(this, styleName, { value: builder });
376
+ return builder;
377
+ }
378
+ };
379
+ }
380
+ styles2.visible = {
381
+ get() {
382
+ const builder = createBuilder(this, this[STYLER], true);
383
+ Object.defineProperty(this, "visible", { value: builder });
384
+ return builder;
385
+ }
386
+ };
387
+ var getModelAnsi = (model, level, type, ...arguments_) => {
388
+ if (model === "rgb") {
389
+ if (level === "ansi16m") {
390
+ return ansi_styles_default[type].ansi16m(...arguments_);
391
+ }
392
+ if (level === "ansi256") {
393
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
394
+ }
395
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
396
+ }
397
+ if (model === "hex") {
398
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
399
+ }
400
+ return ansi_styles_default[type][model](...arguments_);
401
+ };
402
+ var usedModels = ["rgb", "hex", "ansi256"];
403
+ for (const model of usedModels) {
404
+ styles2[model] = {
405
+ get() {
406
+ const { level } = this;
407
+ return function(...arguments_) {
408
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
409
+ return createBuilder(this, styler, this[IS_EMPTY]);
410
+ };
411
+ }
412
+ };
413
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
414
+ styles2[bgModel] = {
415
+ get() {
416
+ const { level } = this;
417
+ return function(...arguments_) {
418
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
419
+ return createBuilder(this, styler, this[IS_EMPTY]);
420
+ };
421
+ }
422
+ };
423
+ }
424
+ var proto = Object.defineProperties(() => {
425
+ }, {
426
+ ...styles2,
427
+ level: {
428
+ enumerable: true,
429
+ get() {
430
+ return this[GENERATOR].level;
431
+ },
432
+ set(level) {
433
+ this[GENERATOR].level = level;
434
+ }
435
+ }
436
+ });
437
+ var createStyler = (open, close, parent) => {
438
+ let openAll;
439
+ let closeAll;
440
+ if (parent === void 0) {
441
+ openAll = open;
442
+ closeAll = close;
443
+ } else {
444
+ openAll = parent.openAll + open;
445
+ closeAll = close + parent.closeAll;
446
+ }
447
+ return {
448
+ open,
449
+ close,
450
+ openAll,
451
+ closeAll,
452
+ parent
453
+ };
454
+ };
455
+ var createBuilder = (self, _styler, _isEmpty) => {
456
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
457
+ Object.setPrototypeOf(builder, proto);
458
+ builder[GENERATOR] = self;
459
+ builder[STYLER] = _styler;
460
+ builder[IS_EMPTY] = _isEmpty;
461
+ return builder;
462
+ };
463
+ var applyStyle = (self, string) => {
464
+ if (self.level <= 0 || !string) {
465
+ return self[IS_EMPTY] ? "" : string;
466
+ }
467
+ let styler = self[STYLER];
468
+ if (styler === void 0) {
469
+ return string;
470
+ }
471
+ const { openAll, closeAll } = styler;
472
+ if (string.includes("\x1B")) {
473
+ while (styler !== void 0) {
474
+ string = stringReplaceAll(string, styler.close, styler.open);
475
+ styler = styler.parent;
476
+ }
477
+ }
478
+ const lfIndex = string.indexOf("\n");
479
+ if (lfIndex !== -1) {
480
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
481
+ }
482
+ return openAll + string + closeAll;
483
+ };
484
+ Object.defineProperties(createChalk.prototype, styles2);
485
+ var chalk = createChalk();
486
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
487
+ var source_default = chalk;
488
+ function log(message) {
489
+ return process2.stdout.write(`${message}
490
+ `);
491
+ }
492
+ function logError(message) {
493
+ return process2.stderr.write(`${message}
494
+ `);
495
+ }
496
+ function logBullet(logger2, colorizePrefix, colorizeText, symbol, prefix, text) {
497
+ const textParts = Array.isArray(text) ? text : [text || ""].filter(Boolean);
498
+ const formattedText = textParts.map((textPart) => colorizeText(textPart)).join("");
499
+ logger2(
500
+ `${" ".repeat(3)} ${colorizePrefix(symbol)} ${colorizePrefix(
501
+ prefix
502
+ )} ${formattedText}`
503
+ );
504
+ }
505
+ function warn(prefix, text) {
506
+ logBullet(log, source_default.yellow, source_default.yellow, "\u25CF", prefix, text);
507
+ }
508
+ function debug(prefix, text) {
509
+ logBullet(log, source_default.yellow, source_default.dim, "\u25CF", prefix, text);
510
+ }
511
+ function info(prefix, text) {
512
+ logBullet(log, source_default.cyan, source_default.dim, "\u25FC", prefix, text);
513
+ }
514
+ function success(text) {
515
+ logBullet(log, source_default.green, source_default.dim, "\u2714", text);
516
+ }
517
+ function error(prefix, text) {
518
+ log("");
519
+ logBullet(logError, source_default.red, source_default.red, "\u25B2", prefix, text);
520
+ }
521
+ function heading(heading2, description) {
522
+ return log(
523
+ `
524
+ ${source_default.bgWhite(` ${source_default.whiteBright(heading2)} `)} ${source_default.bold(
525
+ description
526
+ )}
527
+ `
528
+ );
529
+ }
530
+ var timing = (fn) => () => {
531
+ const start = performance.now();
532
+ return (msg) => {
533
+ const end = performance.now();
534
+ const ms = end - start;
535
+ fn(`${msg} ${source_default.gray(`(${ms.toFixed(2)}ms)`)}`);
536
+ };
537
+ };
538
+ var logger = {
539
+ colors: source_default,
540
+ log,
541
+ heading,
542
+ debug,
543
+ info,
544
+ warn,
545
+ success,
546
+ error,
547
+ time: {
548
+ success: timing(success),
549
+ info: timing(info),
550
+ debug: timing(debug)
551
+ }
552
+ };
553
+
554
+ // ../../node_modules/.pnpm/outdent@0.8.0/node_modules/outdent/lib-module/index.js
555
+ function noop() {
556
+ var args = [];
557
+ for (var _i = 0; _i < arguments.length; _i++) {
558
+ args[_i] = arguments[_i];
559
+ }
560
+ }
561
+ function createWeakMap() {
562
+ if (typeof WeakMap !== "undefined") {
563
+ return /* @__PURE__ */ new WeakMap();
564
+ } else {
565
+ return fakeSetOrMap();
566
+ }
567
+ }
568
+ function fakeSetOrMap() {
569
+ return {
570
+ add: noop,
571
+ delete: noop,
572
+ get: noop,
573
+ set: noop,
574
+ has: function(k) {
575
+ return false;
576
+ }
577
+ };
578
+ }
579
+ var hop = Object.prototype.hasOwnProperty;
580
+ var has = function(obj, prop) {
581
+ return hop.call(obj, prop);
582
+ };
583
+ function extend(target, source) {
584
+ for (var prop in source) {
585
+ if (has(source, prop)) {
586
+ target[prop] = source[prop];
587
+ }
588
+ }
589
+ return target;
590
+ }
591
+ var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
592
+ var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
593
+ var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
594
+ var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
595
+ var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
596
+ function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
597
+ var indentationLevel = 0;
598
+ var match = strings[0].match(reDetectIndentation);
599
+ if (match) {
600
+ indentationLevel = match[1].length;
601
+ }
602
+ var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
603
+ var reMatchIndent = new RegExp(reSource, "g");
604
+ if (firstInterpolatedValueSetsIndentationLevel) {
605
+ strings = strings.slice(1);
606
+ }
607
+ var newline = options.newline, trimLeadingNewline = options.trimLeadingNewline, trimTrailingNewline = options.trimTrailingNewline;
608
+ var normalizeNewlines = typeof newline === "string";
609
+ var l = strings.length;
610
+ var outdentedStrings = strings.map(function(v, i) {
611
+ v = v.replace(reMatchIndent, "$1");
612
+ if (i === 0 && trimLeadingNewline) {
613
+ v = v.replace(reLeadingNewline, "");
614
+ }
615
+ if (i === l - 1 && trimTrailingNewline) {
616
+ v = v.replace(reTrailingNewline, "");
617
+ }
618
+ if (normalizeNewlines) {
619
+ v = v.replace(/\r\n|\n|\r/g, function(_) {
620
+ return newline;
621
+ });
622
+ }
623
+ return v;
624
+ });
625
+ return outdentedStrings;
626
+ }
627
+ function concatStringsAndValues(strings, values) {
628
+ var ret = "";
629
+ for (var i = 0, l = strings.length; i < l; i++) {
630
+ ret += strings[i];
631
+ if (i < l - 1) {
632
+ ret += values[i];
633
+ }
634
+ }
635
+ return ret;
636
+ }
637
+ function isTemplateStringsArray(v) {
638
+ return has(v, "raw") && has(v, "length");
639
+ }
640
+ function createInstance(options) {
641
+ var arrayAutoIndentCache = createWeakMap();
642
+ var arrayFirstInterpSetsIndentCache = createWeakMap();
643
+ function outdent(stringsOrOptions) {
644
+ var values = [];
645
+ for (var _i = 1; _i < arguments.length; _i++) {
646
+ values[_i - 1] = arguments[_i];
647
+ }
648
+ if (isTemplateStringsArray(stringsOrOptions)) {
649
+ var strings = stringsOrOptions;
650
+ var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]);
651
+ var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
652
+ var renderedArray = cache.get(strings);
653
+ if (!renderedArray) {
654
+ renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
655
+ cache.set(strings, renderedArray);
656
+ }
657
+ if (values.length === 0) {
658
+ return renderedArray[0];
659
+ }
660
+ var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
661
+ return rendered;
662
+ } else {
663
+ return createInstance(extend(extend({}, options), stringsOrOptions || {}));
664
+ }
665
+ }
666
+ var fullOutdent = extend(outdent, {
667
+ string: function(str) {
668
+ return _outdentArray([str], false, options)[0];
669
+ }
670
+ });
671
+ return fullOutdent;
672
+ }
673
+ var defaultOutdent = createInstance({
674
+ trimLeadingNewline: true,
675
+ trimTrailingNewline: true
676
+ });
677
+ if (typeof module !== "undefined") {
678
+ try {
679
+ module.exports = defaultOutdent;
680
+ Object.defineProperty(defaultOutdent, "__esModule", { value: true });
681
+ defaultOutdent.default = defaultOutdent;
682
+ defaultOutdent.outdent = defaultOutdent;
683
+ } catch (e) {
684
+ }
685
+ }
686
+
687
+ // src/commands/init.ts
688
+ import getPackageManager from "preferred-pm";
689
+ function createInitCommand(cli, cwd) {
690
+ return cli.command("init", "Initialize config file").option("-f, --force", "Force overwrite existing config files").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(initCmd);
691
+ }
692
+ async function initCmd({ cwd, force }) {
693
+ logger.heading("init", "Initialize config file");
694
+ const configFile = findConfig({ cwd });
695
+ const pmResult = await getPackageManager(cwd);
696
+ const pm = pmResult?.name ?? "npm";
697
+ const cmd = pm === "npm" ? "npm run" : pm;
698
+ if (configFile && !force) {
699
+ return logger.log(
700
+ defaultOutdent`
10
701
  It looks like you already have terai created.
11
- You can now run ${u.colors.cyan(`'${i} terai extract --watch'`)}
12
- `);let a=await me({message:"What locale do you use for development?",default:"en"}),s=await me({message:"Where do you want to place your generated files?",default:"./locale-system"}),g=await Xe({message:"Would you like to use any of these templates? (recommended)",choices:[{name:"No",value:null},{name:"Next",value:"next"},{name:"Vite",value:"vite"}]}),d=u.time.success();await qe({cwd:e,projectLocale:a,outDir:s}),g&&await Qe({cwd:e,outDir:s,framework:g}),d("Config file created"),u.log("\u{1F680} You are set up to start using terai! Thanks for choosing it.")}import{debounce as rt}from"perfect-debounce";import{extract as nt}from"@terai/extractor";import{runtime as H}from"@terai/runtime";import{stringify as tt}from"@terai/utils";async function S({dictionaries:e,locale:t,cwd:r,outDir:n}){let o=H.path.resolve(r,n,t),i=[];for(let a in e){let s=H.path.resolve(o,a+".json"),g=e[a],d=tt(g);H.fs.write(s,d),i.push(d)}return i}import{loadConfig as ot,runtime as O}from"@terai/runtime";import{convertExtractedMessagesToDictionary as it,stringify as at,groupDictionaryByChunks as st}from"@terai/utils";function zt(e,t){return e.command("extract","Statically extract messages from your project").option("-w, --watch","Watch files and rebuild").option("--cwd <cwd>","Current working directory",{default:t}).action(lt)}async function lt(e){u.heading("extract","Statically extract messages from your project");let t=u.time.success(),r=await ot(e),n=O.fs.glob({...r,cwd:e.cwd}),o=O.path.resolve(e.cwd,r.outDir),i=O.path.resolve(o,r.projectLocale),a=O.path.resolve(o,".terai","locale-manifest.json");u.info("Scan:","Processing files...");async function s(d=n){let m=await nt({...r,filesPaths:d,cwd:e.cwd}),f=it(m),w={messages:m},p=st(f,w,r.projectLocale);return O.fs.remove(O.path.resolve(i)),await S({...r,dictionaries:p,locale:r.projectLocale,cwd:e.cwd}),O.fs.write(a,at(w)),Object.keys(f).length}u.info("Extraction:","Extracting messages...");let g=await s();t(`Extracted ${g} messages`),e.watch&&(u.log(""),u.info("Watch:",`Watching files for changes...
13
- `),O.fs.watch({...r,...e}).on("change",rt(async()=>{let m=u.time.success();u.info("Extraction:","Files changed, processing messages...");let f=await s();m(`Extracted ${f} messages`),u.log("")})))}import{loadConfig as ct,runtime as v}from"@terai/runtime";import{translate as ut}from"@terai/translator";import{merge as ft,stringify as mt,groupDictionaryByChunks as gt}from"@terai/utils";function er(e,t){return e.command("translate","Translate messages from your project").option("--cwd <cwd>","Current working directory",{default:t}).action(dt)}async function dt({cwd:e}){u.heading("translate","Translate messages from your project");let t=u.time.success(),r=await ct({cwd:e}),n=v.path.resolve(e,r.outDir),o=v.path.resolve(e,r.outDir,".terai"),i=v.path.resolve(o,"locale-manifest.json");if(!v.fs.exists(i))return u.error("translate",`No locale-manifest.json found in ${o}. Please run "extract" first.`);let s=JSON.parse(v.fs.readFile(i)),g=0,d=0;if(await Promise.all(r.outLocales.map(async m=>{try{let f={},w={},p=v.path.resolve(n,m),M=v.path.resolve(o,"cache",`${m}.cache.json`),j=v.fs.exists(M)?JSON.parse(v.fs.readFile(M)):{},F=0,N=0;for(let C in s.messages){let{value:he,chunksIds:K}=s.messages[C],pe=K.length?K:[m];for(let ve of pe){let q=v.path.resolve(p,`${ve}.json`),W=(v.fs.exists(q)?JSON.parse(v.fs.readFile(q)):{})[C]??j[C];W?(f[C]=W,j[C]=W,F++):(w[C]=he,N++)}}if(N>0){let C=await ut({...r,dictionary:w,locale:m});f=ft(C,f)}j={...j,...f},v.fs.remove(p);let de=gt(f,s,m);await S({...r,dictionaries:de,locale:m,cwd:e}),v.fs.write(M,mt(j)),g+=N,d+=F,u.info(`Locale ${m.toUpperCase()}:`,`${N} new messages translated, ${F} recovered from cache`)}catch(f){f instanceof Error&&u.error(`${m} translation:`,`Error translating to ${m}: ${f.message}
14
- `)}})),!g)return t("Everything up-to-date");t(`Translated ${g} messages, ${d} read from cache`)}export{zt as createExtractCommand,kt as createInitCommand,er as createTranslateCommand,lt as extractCmd,et as initCmd,dt as translateCmd};
702
+ You can now run ${logger.colors.cyan(`'${cmd} terai extract --watch'`)}
703
+ `
704
+ );
705
+ }
706
+ const projectLocale = await input({
707
+ message: "What locale do you use for development?",
708
+ default: "en"
709
+ });
710
+ const outDir = await input({
711
+ message: "Where do you want to place your generated files?",
712
+ default: "./locale-system"
713
+ });
714
+ const framework = await select({
715
+ message: "Would you like to use any of these templates? (recommended)",
716
+ choices: [
717
+ {
718
+ name: "No",
719
+ value: null
720
+ },
721
+ {
722
+ name: "Next",
723
+ value: "next"
724
+ },
725
+ {
726
+ name: "Vite",
727
+ value: "vite"
728
+ }
729
+ ]
730
+ });
731
+ const done = logger.time.success();
732
+ await setupConfig({ cwd, projectLocale, outDir });
733
+ if (framework) {
734
+ await setupTemplate({ cwd, outDir, framework });
735
+ }
736
+ done("Config file created");
737
+ logger.log("\u{1F680} You are set up to start using Terai! Thanks for choosing it.");
738
+ }
739
+
740
+ // src/commands/extract.ts
741
+ import { debounce } from "perfect-debounce";
742
+ import { extract } from "@terai/extractor";
743
+
744
+ // ../generator/dist/index.mjs
745
+ import { runtime } from "@terai/runtime";
746
+ import { stringify } from "@terai/utils";
747
+ async function generate({
748
+ dictionaries,
749
+ locale,
750
+ cwd,
751
+ outDir
752
+ }) {
753
+ const folderPath = runtime.path.resolve(cwd, outDir, locale);
754
+ const output = [];
755
+ for (const id in dictionaries) {
756
+ const fileDir = runtime.path.resolve(folderPath, `${id}.json`);
757
+ const fileContent = dictionaries[id];
758
+ const idOutput = stringify(fileContent);
759
+ runtime.fs.write(fileDir, idOutput);
760
+ output.push(idOutput);
761
+ }
762
+ return output;
763
+ }
764
+
765
+ // src/commands/extract.ts
766
+ import { loadConfig, runtime as runtime2 } from "@terai/runtime";
767
+ import {
768
+ convertExtractedMessagesToDictionary,
769
+ stringify as stringify2,
770
+ groupDictionaryByChunks
771
+ } from "@terai/utils";
772
+ function createExtractCommand(cli, cwd) {
773
+ return cli.command("extract", "Statically extract messages from your project").option("-w, --watch", "Watch files and rebuild").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(extractCmd);
774
+ }
775
+ async function extractCmd(options) {
776
+ logger.heading("extract", "Statically extract messages from your project");
777
+ const done = logger.time.success();
778
+ const config = await loadConfig(options);
779
+ const filesPaths = runtime2.fs.glob({
780
+ ...config,
781
+ cwd: options.cwd
782
+ });
783
+ const outDirPath = runtime2.path.resolve(options.cwd, config.outDir);
784
+ const projectLocalePath = runtime2.path.resolve(
785
+ outDirPath,
786
+ config.projectLocale
787
+ );
788
+ const manifestPath = runtime2.path.resolve(
789
+ outDirPath,
790
+ ".terai",
791
+ "locale-manifest.json"
792
+ );
793
+ logger.info("Scan:", "Processing files...");
794
+ async function extractor(files = filesPaths) {
795
+ const extractedMessages = await extract({
796
+ ...config,
797
+ filesPaths: files,
798
+ cwd: options.cwd
799
+ });
800
+ const dictionary = convertExtractedMessagesToDictionary(extractedMessages);
801
+ const manifest = {
802
+ messages: extractedMessages
803
+ };
804
+ const dictionaries = groupDictionaryByChunks(
805
+ dictionary,
806
+ manifest,
807
+ config.projectLocale
808
+ );
809
+ runtime2.fs.remove(runtime2.path.resolve(projectLocalePath));
810
+ await generate({
811
+ ...config,
812
+ dictionaries,
813
+ locale: config.projectLocale,
814
+ cwd: options.cwd
815
+ });
816
+ runtime2.fs.write(manifestPath, stringify2(manifest));
817
+ return Object.keys(dictionary).length;
818
+ }
819
+ logger.info("Extraction:", "Extracting messages...");
820
+ const msgCount = await extractor();
821
+ done(`Extracted ${msgCount} messages`);
822
+ if (options.watch) {
823
+ logger.log("");
824
+ logger.info("Watch:", "Watching files for changes...\n");
825
+ const configWatcher = runtime2.fs.watch({
826
+ ...config,
827
+ ...options
828
+ });
829
+ configWatcher.on(
830
+ "change",
831
+ debounce(async () => {
832
+ const done2 = logger.time.success();
833
+ logger.info("Extraction:", "Files changed, processing messages...");
834
+ const msgCount2 = await extractor();
835
+ done2(`Extracted ${msgCount2} messages`);
836
+ logger.log("");
837
+ })
838
+ );
839
+ }
840
+ }
841
+
842
+ // src/commands/translate.ts
843
+ import { loadConfig as loadConfig2, runtime as runtime3 } from "@terai/runtime";
844
+ import { translate } from "@terai/translator";
845
+ import { merge, stringify as stringify3, groupDictionaryByChunks as groupDictionaryByChunks2 } from "@terai/utils";
846
+ function createTranslateCommand(cli, cwd) {
847
+ return cli.command("translate", "Translate messages from your project").option("--cwd <cwd>", "Current working directory", { default: cwd }).action(translateCmd);
848
+ }
849
+ async function translateCmd({ cwd }) {
850
+ logger.heading("translate", "Translate messages from your project");
851
+ const done = logger.time.success();
852
+ const config = await loadConfig2({ cwd });
853
+ const outDirPath = runtime3.path.resolve(cwd, config.outDir);
854
+ const tmuDirPath = runtime3.path.resolve(cwd, config.outDir, ".terai");
855
+ const manifestPath = runtime3.path.resolve(tmuDirPath, "locale-manifest.json");
856
+ const existsManifest = runtime3.fs.exists(manifestPath);
857
+ if (!existsManifest) {
858
+ return logger.error(
859
+ "translate",
860
+ `No locale-manifest.json found in ${tmuDirPath}. Please run "extract" first.`
861
+ );
862
+ }
863
+ const buildManifest = JSON.parse(
864
+ runtime3.fs.readFile(manifestPath)
865
+ );
866
+ let totalTranslatedMsgs = 0;
867
+ let totalCachedMsgs = 0;
868
+ await Promise.all(
869
+ config.outLocales.map(async (locale) => {
870
+ try {
871
+ let translatedDictionary = {};
872
+ const untranslatedDictionary = {};
873
+ const localeDirPath = runtime3.path.resolve(outDirPath, locale);
874
+ const localeCachePath = runtime3.path.resolve(
875
+ tmuDirPath,
876
+ "cache",
877
+ `${locale}.cache.json`
878
+ );
879
+ const cacheExists = runtime3.fs.exists(localeCachePath);
880
+ let cache = cacheExists ? JSON.parse(runtime3.fs.readFile(localeCachePath)) : {};
881
+ let localeCachedMsgs = 0;
882
+ let localeTranslatedMsgs = 0;
883
+ for (const id in buildManifest.messages) {
884
+ const { value, chunksIds } = buildManifest.messages[id];
885
+ const chnks = chunksIds.length ? chunksIds : [locale];
886
+ for (const chunkId of chnks) {
887
+ const chunkPath = runtime3.path.resolve(
888
+ localeDirPath,
889
+ `${chunkId}.json`
890
+ );
891
+ const existsChunk = runtime3.fs.exists(chunkPath);
892
+ const chunk = existsChunk ? JSON.parse(runtime3.fs.readFile(chunkPath)) : {};
893
+ const localeValue = chunk[id] ?? cache[id];
894
+ if (!localeValue) {
895
+ untranslatedDictionary[id] = value;
896
+ localeTranslatedMsgs++;
897
+ } else {
898
+ translatedDictionary[id] = localeValue;
899
+ cache[id] = localeValue;
900
+ localeCachedMsgs++;
901
+ }
902
+ }
903
+ }
904
+ if (localeTranslatedMsgs > 0) {
905
+ const translation = await translate({
906
+ ...config,
907
+ dictionary: untranslatedDictionary,
908
+ locale
909
+ });
910
+ translatedDictionary = merge(translation, translatedDictionary);
911
+ }
912
+ cache = {
913
+ ...cache,
914
+ ...translatedDictionary
915
+ };
916
+ runtime3.fs.remove(localeDirPath);
917
+ const dictionaries = groupDictionaryByChunks2(
918
+ translatedDictionary,
919
+ buildManifest,
920
+ locale
921
+ );
922
+ await generate({
923
+ ...config,
924
+ dictionaries,
925
+ locale,
926
+ cwd
927
+ });
928
+ runtime3.fs.write(localeCachePath, stringify3(cache));
929
+ totalTranslatedMsgs += localeTranslatedMsgs;
930
+ totalCachedMsgs += localeCachedMsgs;
931
+ logger.info(
932
+ `Locale ${locale.toUpperCase()}:`,
933
+ `${localeTranslatedMsgs} new messages translated, ${localeCachedMsgs} recovered from cache`
934
+ );
935
+ } catch (err) {
936
+ if (err instanceof Error) {
937
+ logger.error(
938
+ `${locale} translation:`,
939
+ `Error translating to ${locale}: ${err.message}
940
+ `
941
+ );
942
+ }
943
+ }
944
+ })
945
+ );
946
+ if (!totalTranslatedMsgs) {
947
+ return done("Everything up-to-date");
948
+ }
949
+ done(
950
+ `Translated ${totalTranslatedMsgs} messages, ${totalCachedMsgs} read from cache`
951
+ );
952
+ }
953
+ export {
954
+ createExtractCommand,
955
+ createInitCommand,
956
+ createTranslateCommand,
957
+ extractCmd,
958
+ initCmd,
959
+ translateCmd
960
+ };
15
961
  //# sourceMappingURL=index.mjs.map