gt 2.26.8 → 2.26.10
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.
- package/CHANGELOG.md +18 -0
- package/dist/console/logger.d.ts +6 -2
- package/dist/console/logger.js +25 -5
- package/dist/console/logger.js.map +1 -1
- package/dist/console/logging.js +1 -1
- package/dist/console/logging.js.map +1 -1
- package/dist/fs/config/setupConfig.js +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/generated/version.js.map +1 -1
- package/dist/git/setupMergeDrivers.js +1 -1
- package/dist/utils/batchProcess.d.ts +10 -0
- package/dist/utils/batchProcess.js +29 -0
- package/dist/utils/batchProcess.js.map +1 -0
- package/dist/utils/credentials.js +1 -1
- package/dist/utils/flattenJsonFiles.js +6 -8
- package/dist/utils/flattenJsonFiles.js.map +1 -1
- package/dist/utils/gitDiff.js +1 -1
- package/dist/utils/localizeMintlifyFrontmatterUrls.js +6 -8
- package/dist/utils/localizeMintlifyFrontmatterUrls.js.map +1 -1
- package/dist/utils/localizeRelativeAssets.js +6 -6
- package/dist/utils/localizeRelativeAssets.js.map +1 -1
- package/dist/utils/localizeStaticImports.js +10 -18
- package/dist/utils/localizeStaticImports.js.map +1 -1
- package/dist/utils/localizeStaticUrls.js +11 -18
- package/dist/utils/localizeStaticUrls.js.map +1 -1
- package/dist/utils/sharedStaticAssets.js +3 -3
- package/dist/utils/sharedStaticAssets.js.map +1 -1
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# gtx-cli
|
|
2
2
|
|
|
3
|
+
## 2.26.10
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#2526](https://github.com/generaltranslation/gt/pull/2526) [`9e9b6d8`](https://github.com/generaltranslation/gt/commit/9e9b6d866cae109f7ec13f5b1d1182ccfb87d947) Thanks [@brian-lou](https://github.com/brian-lou)! - Add `GT_LOG_FORMAT=agent`, which prints plain `[time] LEVEL: msg` lines, and use it by default in CI or when stdout is not a TTY. Set `GT_LOG_FORMAT=default` to keep the interactive output. The ASCII banner no longer prints when `GT_LOG_FORMAT` is `json` or `agent`.
|
|
8
|
+
|
|
9
|
+
## 2.26.9
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#2525](https://github.com/generaltranslation/gt/pull/2525) [`aee1350`](https://github.com/generaltranslation/gt/commit/aee135077ebef9d98378b68d5898df548d83f137) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Limit how many files postprocessing reads and writes at once so large docs projects no longer fail with `EMFILE: too many open files`
|
|
14
|
+
|
|
15
|
+
- Updated dependencies []:
|
|
16
|
+
- generaltranslation@9.5.8
|
|
17
|
+
- @generaltranslation/python-extractor@0.2.63
|
|
18
|
+
- @generaltranslation/supported-locales@2.1.44
|
|
19
|
+
- @generaltranslation/vue-extractor@0.1.22
|
|
20
|
+
|
|
3
21
|
## 2.26.8
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/console/logger.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type { SpinnerResult, ProgressResult } from '@clack/prompts';
|
|
2
|
-
export type LogFormat = 'default' | 'json';
|
|
2
|
+
export type LogFormat = 'default' | 'json' | 'agent';
|
|
3
3
|
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
4
4
|
export type ConsoleOutput = 'stdout' | 'stderr';
|
|
5
5
|
/**
|
|
6
|
-
* GT_LOG_FORMAT: default | json.
|
|
6
|
+
* GT_LOG_FORMAT: default | json | agent. If unset, defaults to agent in CI
|
|
7
|
+
* or when stdout is not a TTY, and to default otherwise.
|
|
7
8
|
* - If default, logs will be pretty-printed using @clack/prompts.
|
|
8
9
|
* - If json, logs will be written in JSON format to the console.
|
|
10
|
+
* - If agent, logs will be written as plain `[time] LEVEL: msg` lines.
|
|
9
11
|
* GT_LOG_FILE: If specified, logs will be written to the file.
|
|
10
12
|
* GT_LOG_LEVEL: The level of logs to write. If not specified, defaults to 'info'.
|
|
11
13
|
* - Valid levels: debug, info, warn, error.
|
|
@@ -23,6 +25,7 @@ declare class Logger {
|
|
|
23
25
|
private clackOutput;
|
|
24
26
|
private constructor();
|
|
25
27
|
private createPinoLogger;
|
|
28
|
+
private createConsoleLogger;
|
|
26
29
|
static getInstance(): Logger;
|
|
27
30
|
/**
|
|
28
31
|
* Route console output (Clack chatter and the JSON console logger) to
|
|
@@ -48,6 +51,7 @@ declare class Logger {
|
|
|
48
51
|
*/
|
|
49
52
|
setAnimatedProgress(animated: boolean): boolean;
|
|
50
53
|
isQuiet(): boolean;
|
|
54
|
+
getLogFormat(): LogFormat;
|
|
51
55
|
trace(message: string): void;
|
|
52
56
|
debug(message: string): void;
|
|
53
57
|
info(message: string): void;
|
package/dist/console/logger.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { intro, log, outro, progress, spinner } from "@clack/prompts";
|
|
2
2
|
import chalk from "chalk";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
5
|
import { destination, pino } from "pino";
|
|
6
|
+
import { build } from "pino-pretty";
|
|
5
7
|
//#region src/console/logger.ts
|
|
6
8
|
const LOG_LEVEL_RANK = {
|
|
7
9
|
debug: 10,
|
|
@@ -10,6 +12,10 @@ const LOG_LEVEL_RANK = {
|
|
|
10
12
|
error: 40
|
|
11
13
|
};
|
|
12
14
|
const QUIET_FLOOR_LEVEL = "warn";
|
|
15
|
+
function getDefaultLogFormat() {
|
|
16
|
+
const ci = process.env.CI;
|
|
17
|
+
return !!ci && ci !== "false" && ci !== "0" || !process.stdout.isTTY ? "agent" : "default";
|
|
18
|
+
}
|
|
13
19
|
var MockSpinner = class {
|
|
14
20
|
currentMessage = "";
|
|
15
21
|
logger;
|
|
@@ -73,10 +79,10 @@ const logger = class Logger {
|
|
|
73
79
|
consoleLoggers = {};
|
|
74
80
|
clackOutput;
|
|
75
81
|
constructor() {
|
|
76
|
-
const format = (process.env.GT_LOG_FORMAT ||
|
|
82
|
+
const format = (process.env.GT_LOG_FORMAT || getDefaultLogFormat()).toLowerCase();
|
|
77
83
|
const logFile = process.env.GT_LOG_FILE;
|
|
78
84
|
const logLevel = process.env.GT_LOG_LEVEL || "info";
|
|
79
|
-
if (format !== "default" && format !== "json") {
|
|
85
|
+
if (format !== "default" && format !== "json" && format !== "agent") {
|
|
80
86
|
console.error("Invalid log format");
|
|
81
87
|
process.exit(1);
|
|
82
88
|
}
|
|
@@ -86,8 +92,8 @@ const logger = class Logger {
|
|
|
86
92
|
}
|
|
87
93
|
this.logFormat = format;
|
|
88
94
|
this.logLevel = logLevel;
|
|
89
|
-
if (format
|
|
90
|
-
this.pinoLogger = this.
|
|
95
|
+
if (format !== "default") {
|
|
96
|
+
this.pinoLogger = this.createConsoleLogger(process.stdout.fd, logLevel);
|
|
91
97
|
this.consoleLoggers.stdout = this.pinoLogger;
|
|
92
98
|
}
|
|
93
99
|
if (logFile) this.fileLogger = this.createPinoLogger(logFile, logLevel);
|
|
@@ -98,6 +104,17 @@ const logger = class Logger {
|
|
|
98
104
|
mixin: () => ({ logId: randomUUID() })
|
|
99
105
|
}, destination(dest));
|
|
100
106
|
}
|
|
107
|
+
createConsoleLogger(fd, level) {
|
|
108
|
+
if (this.logFormat === "json") return this.createPinoLogger(fd, level);
|
|
109
|
+
return pino({ level }, build({
|
|
110
|
+
destination: fd,
|
|
111
|
+
sync: true,
|
|
112
|
+
colorize: false,
|
|
113
|
+
translateTime: "SYS:yyyy-mm-dd HH:MM:ss",
|
|
114
|
+
ignore: "pid,hostname",
|
|
115
|
+
messageFormat: (log, messageKey) => stripVTControlCharacters(String(log[messageKey]))
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
101
118
|
static getInstance() {
|
|
102
119
|
if (!Logger.instance) Logger.instance = new Logger();
|
|
103
120
|
return Logger.instance;
|
|
@@ -115,7 +132,7 @@ const logger = class Logger {
|
|
|
115
132
|
this.clackOutput = output === "stderr" ? { output: process.stderr } : void 0;
|
|
116
133
|
if (this.pinoLogger) {
|
|
117
134
|
this.pinoLogger.flush();
|
|
118
|
-
const next = this.consoleLoggers[output] ?? this.
|
|
135
|
+
const next = this.consoleLoggers[output] ?? this.createConsoleLogger(process[output].fd, this.pinoLogger.level);
|
|
119
136
|
next.level = this.pinoLogger.level;
|
|
120
137
|
this.consoleLoggers[output] = next;
|
|
121
138
|
this.pinoLogger = next;
|
|
@@ -146,6 +163,9 @@ const logger = class Logger {
|
|
|
146
163
|
isQuiet() {
|
|
147
164
|
return this.quiet;
|
|
148
165
|
}
|
|
166
|
+
getLogFormat() {
|
|
167
|
+
return this.logFormat;
|
|
168
|
+
}
|
|
149
169
|
trace(message) {
|
|
150
170
|
if (!this.quiet) if (this.logFormat === "default") log.message(message, {
|
|
151
171
|
symbol: chalk.dim("•"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.js","names":[],"sources":["../../src/console/logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { randomUUID } from 'node:crypto';\nimport { pino, destination } from 'pino';\nimport {\n log as clackLog,\n spinner,\n progress,\n intro,\n outro,\n} from '@clack/prompts';\nimport type { Logger as PinoLogger } from 'pino';\nimport type { SpinnerResult, ProgressResult } from '@clack/prompts';\nimport type { Writable } from 'node:stream';\n\nexport type LogFormat = 'default' | 'json';\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\nexport type ConsoleOutput = 'stdout' | 'stderr';\n\n// Numeric ordering used to decide the quiet floor without lowering an\n// already-more-restrictive level chosen via GT_LOG_LEVEL.\nconst LOG_LEVEL_RANK: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\n// Under --quiet, informational output is suppressed but warnings and errors\n// still print, so the console never drops below this level.\nconst QUIET_FLOOR_LEVEL: LogLevel = 'warn';\n\n// Mock spinner that logs to console instead of updating terminal UI\nclass MockSpinner implements SpinnerResult {\n private currentMessage: string = '';\n private logger: Logger;\n isCancelled: boolean = false;\n\n constructor(logger: Logger) {\n this.logger = logger;\n }\n\n start(message?: string): void {\n if (message) {\n this.currentMessage = message;\n this.logger.info(`[Spinner] ${message}`);\n }\n }\n\n stop(message?: string): void {\n const msg = message || this.currentMessage;\n if (msg) {\n this.logger.info(`[Spinner] ${msg}`);\n }\n this.currentMessage = '';\n }\n\n message(message?: string): void {\n if (message) {\n this.currentMessage = message;\n this.logger.info(`[Spinner] ${message}`);\n }\n }\n}\n\n// Mock progress bar that logs to console instead of updating terminal UI\nclass MockProgress implements ProgressResult {\n private max: number;\n private current: number = 0;\n private logger: Logger;\n isCancelled: boolean = false;\n\n constructor(max: number, logger: Logger) {\n this.max = max;\n this.logger = logger;\n }\n\n start(message?: string): void {\n const msg = message || 'Starting progress';\n this.logger.info(`[Progress] ${msg} (0/${this.max})`);\n }\n\n stop(message?: string): void {\n const msg = message || 'Complete';\n this.logger.info(`[Progress] ${msg} (${this.current}/${this.max})`);\n }\n\n message(message?: string): void {\n if (message) {\n this.logger.info(`[Progress] ${message} (${this.current}/${this.max})`);\n }\n }\n\n advance(amount: number, message?: string): void {\n this.current += amount;\n const msg = message || 'Progress';\n this.logger.info(`[Progress] ${msg} (${this.current}/${this.max})`);\n }\n}\n\n/**\n * GT_LOG_FORMAT: default | json.\n * - If default, logs will be pretty-printed using @clack/prompts.\n * - If json, logs will be written in JSON format to the console.\n * GT_LOG_FILE: If specified, logs will be written to the file.\n * GT_LOG_LEVEL: The level of logs to write. If not specified, defaults to 'info'.\n * - Valid levels: debug, info, warn, error.\n */\nclass Logger {\n private static instance: Logger;\n private pinoLogger: PinoLogger | null = null;\n private fileLogger: PinoLogger | null = null;\n private logFormat: LogFormat;\n private logLevel: LogLevel;\n private quiet = false;\n private animatedProgress = true;\n private consoleOutput: ConsoleOutput = 'stdout';\n // One JSON console logger per stream so switching direction within a\n // process reuses the existing SonicBoom instead of recreating it.\n private consoleLoggers: Partial<Record<ConsoleOutput, PinoLogger>> = {};\n // Clack writes to stdout unless told otherwise; unset keeps its default so\n // ordinary commands are untouched while stderr routing redirects it.\n private clackOutput: { output: Writable } | undefined;\n\n private constructor() {\n // Read configuration from environment variables\n const format = (\n process.env.GT_LOG_FORMAT || 'default'\n ).toLowerCase() as LogFormat;\n const logFile = process.env.GT_LOG_FILE;\n const logLevel = process.env.GT_LOG_LEVEL || 'info';\n\n if (format !== 'default' && format !== 'json') {\n console.error('Invalid log format');\n process.exit(1);\n }\n if (\n logLevel !== 'debug' &&\n logLevel !== 'info' &&\n logLevel !== 'warn' &&\n logLevel !== 'error'\n ) {\n console.error('Invalid log level');\n process.exit(1);\n }\n\n this.logFormat = format;\n this.logLevel = logLevel as LogLevel;\n\n // Console output (stdout) - only for JSON format\n // For 'default' format, we use @clack/prompts directly\n if (format === 'json') {\n this.pinoLogger = this.createPinoLogger(process.stdout.fd, logLevel);\n this.consoleLoggers.stdout = this.pinoLogger;\n }\n\n // File output (if specified) - always JSON format\n if (logFile) {\n this.fileLogger = this.createPinoLogger(logFile, logLevel);\n }\n }\n\n private createPinoLogger(dest: number | string, level: string): PinoLogger {\n return pino(\n {\n level,\n mixin: () => ({\n logId: randomUUID(),\n }),\n },\n destination(dest)\n );\n }\n\n static getInstance(): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n\n /**\n * Route console output (Clack chatter and the JSON console logger) to\n * stdout (the historical default) or stderr, so a command whose stdout is\n * machine-readable can keep diagnostics off it. Reversible per invocation;\n * a no-op when the direction is unchanged. The JSON logger keeps its\n * current level and is flushed before switching. File logging is unaffected.\n */\n setConsoleOutput(output: ConsoleOutput): void {\n if (output === this.consoleOutput) return;\n this.consoleOutput = output;\n this.clackOutput =\n output === 'stderr' ? { output: process.stderr } : undefined;\n if (this.pinoLogger) {\n this.pinoLogger.flush();\n const next =\n this.consoleLoggers[output] ??\n this.createPinoLogger(process[output].fd, this.pinoLogger.level);\n next.level = this.pinoLogger.level;\n this.consoleLoggers[output] = next;\n this.pinoLogger = next;\n }\n }\n\n /**\n * Enable or disable quiet mode. When quiet, informational chatter\n * (info/step/success/message/debug/trace, spinners, progress bars, and\n * command intro/outro markers) is suppressed on the console, while warnings\n * and errors still print. Quiet wins over GT_LOG_LEVEL but never lowers an\n * already-more-restrictive level. File logging is unaffected so an explicit\n * GT_LOG_FILE still captures everything.\n */\n setQuiet(quiet: boolean): void {\n this.quiet = quiet;\n if (this.pinoLogger) {\n this.pinoLogger.level = quiet\n ? LOG_LEVEL_RANK[this.logLevel] > LOG_LEVEL_RANK[QUIET_FLOOR_LEVEL]\n ? this.logLevel\n : QUIET_FLOOR_LEVEL\n : this.logLevel;\n }\n }\n\n /**\n * Noninteractive setup reports progress as plain log lines instead of\n * redrawing spinners and progress bars on the console. Returns the previous\n * mode so a run can restore it.\n */\n setAnimatedProgress(animated: boolean): boolean {\n const previous = this.animatedProgress;\n this.animatedProgress = animated;\n return previous;\n }\n\n isQuiet(): boolean {\n return this.quiet;\n }\n\n // Standard logging methods\n trace(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n // @clack/prompts doesn't have trace, use message\n clackLog.message(message, {\n symbol: chalk.dim('•'),\n ...this.clackOutput,\n });\n } else {\n this.pinoLogger?.trace(message);\n }\n }\n this.fileLogger?.trace(message);\n }\n\n debug(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n // @clack/prompts doesn't have debug, use message\n clackLog.message(message, {\n symbol: chalk.dim('◆'),\n ...this.clackOutput,\n });\n } else {\n this.pinoLogger?.debug(message);\n }\n }\n this.fileLogger?.debug(message);\n }\n\n info(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.info(message, this.clackOutput);\n } else {\n this.pinoLogger?.info(message);\n }\n }\n this.fileLogger?.info(message);\n }\n\n warn(message: string): void {\n if (this.logFormat === 'default') {\n clackLog.warn(message, this.clackOutput);\n } else {\n this.pinoLogger?.warn(message);\n }\n this.fileLogger?.warn(message);\n }\n\n error(message: string): void {\n if (this.logFormat === 'default') {\n clackLog.error(message, this.clackOutput);\n } else {\n this.pinoLogger?.error(message);\n }\n this.fileLogger?.error(message);\n }\n\n fatal(message: string): void {\n if (this.logFormat === 'default') {\n // @clack/prompts doesn't have fatal, use error\n clackLog.error(message, this.clackOutput);\n } else {\n this.pinoLogger?.fatal(message);\n }\n this.fileLogger?.fatal(message);\n }\n\n silent(message: string): void {\n // Silent doesn't log to console, only to file\n this.fileLogger?.silent(message);\n }\n\n // @clack/prompts specific methods (for 'default' format)\n success(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.success(message, this.clackOutput);\n } else {\n this.pinoLogger?.info(message); // Map to info for non-default formats\n }\n }\n this.fileLogger?.info(message);\n }\n\n step(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.step(message, this.clackOutput);\n } else {\n this.pinoLogger?.info(message); // Map to info for non-default formats\n }\n }\n this.fileLogger?.info(message);\n }\n\n message(message: string, symbol?: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.message(\n message,\n symbol ? { symbol, ...this.clackOutput } : this.clackOutput\n );\n } else {\n this.pinoLogger?.info(message); // Map to info for non-default formats\n }\n }\n this.fileLogger?.info(message);\n }\n\n // Spinner functionality\n createSpinner(indicator: 'dots' | 'timer' = 'timer'): SpinnerResult {\n // Quiet mode suppresses spinner UI; the mock routes through the gated\n // info() so nothing reaches the console while file logging is preserved.\n if (this.quiet || !this.animatedProgress) {\n return new MockSpinner(this);\n }\n if (this.logFormat === 'default') {\n return spinner({ indicator, ...this.clackOutput });\n } else {\n return new MockSpinner(this);\n }\n }\n\n // Progress bar functionality\n createProgressBar(total: number): ProgressResult {\n if (this.quiet || !this.animatedProgress) {\n return new MockProgress(total, this);\n }\n if (this.logFormat === 'default') {\n return progress({ max: total, ...this.clackOutput });\n } else {\n return new MockProgress(total, this);\n }\n }\n\n // Command start/end markers\n startCommand(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n intro(chalk.cyan(message), this.clackOutput);\n } else {\n this.info(`╭─ ${message}`);\n }\n }\n this.fileLogger?.info(`[START] ${message}`);\n }\n\n endCommand(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n outro(chalk.cyan(message), this.clackOutput);\n } else {\n this.info(`╰─ ${message}`);\n }\n }\n this.fileLogger?.info(`[END] ${message}`);\n }\n\n // Flush logs to ensure they're written before process exit\n flush(): void {\n this.pinoLogger?.flush();\n this.fileLogger?.flush();\n }\n}\n\nexport const logger = Logger.getInstance();\n"],"mappings":";;;;;AAoBA,MAAM,iBAA2C;CAC/C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACR;AAID,MAAM,oBAA8B;AAGpC,IAAM,cAAN,MAA2C;CACzC,iBAAiC;CACjC;CACA,cAAuB;CAEvB,YAAY,QAAgB;AAC1B,OAAK,SAAS;;CAGhB,MAAM,SAAwB;AAC5B,MAAI,SAAS;AACX,QAAK,iBAAiB;AACtB,QAAK,OAAO,KAAK,aAAa,UAAU;;;CAI5C,KAAK,SAAwB;EAC3B,MAAM,MAAM,WAAW,KAAK;AAC5B,MAAI,IACF,MAAK,OAAO,KAAK,aAAa,MAAM;AAEtC,OAAK,iBAAiB;;CAGxB,QAAQ,SAAwB;AAC9B,MAAI,SAAS;AACX,QAAK,iBAAiB;AACtB,QAAK,OAAO,KAAK,aAAa,UAAU;;;;AAM9C,IAAM,eAAN,MAA6C;CAC3C;CACA,UAA0B;CAC1B;CACA,cAAuB;CAEvB,YAAY,KAAa,QAAgB;AACvC,OAAK,MAAM;AACX,OAAK,SAAS;;CAGhB,MAAM,SAAwB;EAC5B,MAAM,MAAM,WAAW;AACvB,OAAK,OAAO,KAAK,cAAc,IAAI,MAAM,KAAK,IAAI,GAAG;;CAGvD,KAAK,SAAwB;EAC3B,MAAM,MAAM,WAAW;AACvB,OAAK,OAAO,KAAK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GAAG,KAAK;GAAa,CAAC;MAElD,QAAO,IAAI,YAAY,KAAK;;CAKhC,kBAAkB,OAA+B;AAC/C,MAAI,KAAK,SAAS,CAAC,KAAK,iBACtB,QAAO,IAAI,aAAa,OAAO,KAAK;AAEtC,MAAI,KAAK,cAAc,UACrB,QAAO,SAAS;GAAE,KAAK;GAAO,GAAG,KAAK;GAAa,CAAC;MAEpD,QAAO,IAAI,aAAa,OAAO,KAAK;;CAKxC,aAAa,SAAuB;AAClC,MAAI,CAAC,KAAK,MACR,KAAI,KAAK,cAAc,UACrB,OAAM,MAAM,KAAK,QAAQ,EAAE,KAAK,YAAY;MAE5C,MAAK,KAAK,MAAM,UAAU;AAG9B,OAAK,YAAY,KAAK,WAAW,UAAU;;CAG7C,WAAW,SAAuB;AAChC,MAAI,CAAC,KAAK,MACR,KAAI,KAAK,cAAc,UACrB,OAAM,MAAM,KAAK,QAAQ,EAAE,KAAK,YAAY;MAE5C,MAAK,KAAK,MAAM,UAAU;AAG9B,OAAK,YAAY,KAAK,SAAS,UAAU;;CAI3C,QAAc;AACZ,OAAK,YAAY,OAAO;AACxB,OAAK,YAAY,OAAO;;EAIC,aAAa"}
|
|
1
|
+
{"version":3,"file":"logger.js","names":["pinoPretty"],"sources":["../../src/console/logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { randomUUID } from 'node:crypto';\nimport { stripVTControlCharacters } from 'node:util';\nimport { pino, destination } from 'pino';\nimport { build as pinoPretty } from 'pino-pretty';\nimport {\n log as clackLog,\n spinner,\n progress,\n intro,\n outro,\n} from '@clack/prompts';\nimport type { Logger as PinoLogger } from 'pino';\nimport type { SpinnerResult, ProgressResult } from '@clack/prompts';\nimport type { Writable } from 'node:stream';\n\nexport type LogFormat = 'default' | 'json' | 'agent';\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\nexport type ConsoleOutput = 'stdout' | 'stderr';\n\n// Numeric ordering used to decide the quiet floor without lowering an\n// already-more-restrictive level chosen via GT_LOG_LEVEL.\nconst LOG_LEVEL_RANK: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\n// Under --quiet, informational output is suppressed but warnings and errors\n// still print, so the console never drops below this level.\nconst QUIET_FLOOR_LEVEL: LogLevel = 'warn';\n\n// Without an explicit GT_LOG_FORMAT, CI and non-TTY output get plain agent\n// lines instead of Clack's interactive rendering.\nfunction getDefaultLogFormat(): LogFormat {\n const ci = process.env.CI;\n const isCI = !!ci && ci !== 'false' && ci !== '0';\n return isCI || !process.stdout.isTTY ? 'agent' : 'default';\n}\n\n// Mock spinner that logs to console instead of updating terminal UI\nclass MockSpinner implements SpinnerResult {\n private currentMessage: string = '';\n private logger: Logger;\n isCancelled: boolean = false;\n\n constructor(logger: Logger) {\n this.logger = logger;\n }\n\n start(message?: string): void {\n if (message) {\n this.currentMessage = message;\n this.logger.info(`[Spinner] ${message}`);\n }\n }\n\n stop(message?: string): void {\n const msg = message || this.currentMessage;\n if (msg) {\n this.logger.info(`[Spinner] ${msg}`);\n }\n this.currentMessage = '';\n }\n\n message(message?: string): void {\n if (message) {\n this.currentMessage = message;\n this.logger.info(`[Spinner] ${message}`);\n }\n }\n}\n\n// Mock progress bar that logs to console instead of updating terminal UI\nclass MockProgress implements ProgressResult {\n private max: number;\n private current: number = 0;\n private logger: Logger;\n isCancelled: boolean = false;\n\n constructor(max: number, logger: Logger) {\n this.max = max;\n this.logger = logger;\n }\n\n start(message?: string): void {\n const msg = message || 'Starting progress';\n this.logger.info(`[Progress] ${msg} (0/${this.max})`);\n }\n\n stop(message?: string): void {\n const msg = message || 'Complete';\n this.logger.info(`[Progress] ${msg} (${this.current}/${this.max})`);\n }\n\n message(message?: string): void {\n if (message) {\n this.logger.info(`[Progress] ${message} (${this.current}/${this.max})`);\n }\n }\n\n advance(amount: number, message?: string): void {\n this.current += amount;\n const msg = message || 'Progress';\n this.logger.info(`[Progress] ${msg} (${this.current}/${this.max})`);\n }\n}\n\n/**\n * GT_LOG_FORMAT: default | json | agent. If unset, defaults to agent in CI\n * or when stdout is not a TTY, and to default otherwise.\n * - If default, logs will be pretty-printed using @clack/prompts.\n * - If json, logs will be written in JSON format to the console.\n * - If agent, logs will be written as plain `[time] LEVEL: msg` lines.\n * GT_LOG_FILE: If specified, logs will be written to the file.\n * GT_LOG_LEVEL: The level of logs to write. If not specified, defaults to 'info'.\n * - Valid levels: debug, info, warn, error.\n */\nclass Logger {\n private static instance: Logger;\n private pinoLogger: PinoLogger | null = null;\n private fileLogger: PinoLogger | null = null;\n private logFormat: LogFormat;\n private logLevel: LogLevel;\n private quiet = false;\n private animatedProgress = true;\n private consoleOutput: ConsoleOutput = 'stdout';\n // One JSON console logger per stream so switching direction within a\n // process reuses the existing SonicBoom instead of recreating it.\n private consoleLoggers: Partial<Record<ConsoleOutput, PinoLogger>> = {};\n // Clack writes to stdout unless told otherwise; unset keeps its default so\n // ordinary commands are untouched while stderr routing redirects it.\n private clackOutput: { output: Writable } | undefined;\n\n private constructor() {\n // Read configuration from environment variables\n const format = (\n process.env.GT_LOG_FORMAT || getDefaultLogFormat()\n ).toLowerCase() as LogFormat;\n const logFile = process.env.GT_LOG_FILE;\n const logLevel = process.env.GT_LOG_LEVEL || 'info';\n\n if (format !== 'default' && format !== 'json' && format !== 'agent') {\n console.error('Invalid log format');\n process.exit(1);\n }\n if (\n logLevel !== 'debug' &&\n logLevel !== 'info' &&\n logLevel !== 'warn' &&\n logLevel !== 'error'\n ) {\n console.error('Invalid log level');\n process.exit(1);\n }\n\n this.logFormat = format;\n this.logLevel = logLevel as LogLevel;\n\n // Console output (stdout) - only for JSON and agent formats\n // For 'default' format, we use @clack/prompts directly\n if (format !== 'default') {\n this.pinoLogger = this.createConsoleLogger(process.stdout.fd, logLevel);\n this.consoleLoggers.stdout = this.pinoLogger;\n }\n\n // File output (if specified) - always JSON format\n if (logFile) {\n this.fileLogger = this.createPinoLogger(logFile, logLevel);\n }\n }\n\n private createPinoLogger(dest: number | string, level: string): PinoLogger {\n return pino(\n {\n level,\n mixin: () => ({\n logId: randomUUID(),\n }),\n },\n destination(dest)\n );\n }\n\n private createConsoleLogger(fd: number, level: string): PinoLogger {\n if (this.logFormat === 'json') {\n return this.createPinoLogger(fd, level);\n }\n // Synchronous, in-thread pretty printing so lines are not lost when the\n // CLI exits via process.exit().\n return pino(\n { level },\n pinoPretty({\n destination: fd,\n sync: true,\n colorize: false,\n translateTime: 'SYS:yyyy-mm-dd HH:MM:ss',\n ignore: 'pid,hostname',\n messageFormat: (log, messageKey) =>\n stripVTControlCharacters(String(log[messageKey])),\n })\n );\n }\n\n static getInstance(): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n\n /**\n * Route console output (Clack chatter and the JSON console logger) to\n * stdout (the historical default) or stderr, so a command whose stdout is\n * machine-readable can keep diagnostics off it. Reversible per invocation;\n * a no-op when the direction is unchanged. The JSON logger keeps its\n * current level and is flushed before switching. File logging is unaffected.\n */\n setConsoleOutput(output: ConsoleOutput): void {\n if (output === this.consoleOutput) return;\n this.consoleOutput = output;\n this.clackOutput =\n output === 'stderr' ? { output: process.stderr } : undefined;\n if (this.pinoLogger) {\n this.pinoLogger.flush();\n const next =\n this.consoleLoggers[output] ??\n this.createConsoleLogger(process[output].fd, this.pinoLogger.level);\n next.level = this.pinoLogger.level;\n this.consoleLoggers[output] = next;\n this.pinoLogger = next;\n }\n }\n\n /**\n * Enable or disable quiet mode. When quiet, informational chatter\n * (info/step/success/message/debug/trace, spinners, progress bars, and\n * command intro/outro markers) is suppressed on the console, while warnings\n * and errors still print. Quiet wins over GT_LOG_LEVEL but never lowers an\n * already-more-restrictive level. File logging is unaffected so an explicit\n * GT_LOG_FILE still captures everything.\n */\n setQuiet(quiet: boolean): void {\n this.quiet = quiet;\n if (this.pinoLogger) {\n this.pinoLogger.level = quiet\n ? LOG_LEVEL_RANK[this.logLevel] > LOG_LEVEL_RANK[QUIET_FLOOR_LEVEL]\n ? this.logLevel\n : QUIET_FLOOR_LEVEL\n : this.logLevel;\n }\n }\n\n /**\n * Noninteractive setup reports progress as plain log lines instead of\n * redrawing spinners and progress bars on the console. Returns the previous\n * mode so a run can restore it.\n */\n setAnimatedProgress(animated: boolean): boolean {\n const previous = this.animatedProgress;\n this.animatedProgress = animated;\n return previous;\n }\n\n isQuiet(): boolean {\n return this.quiet;\n }\n\n getLogFormat(): LogFormat {\n return this.logFormat;\n }\n\n // Standard logging methods\n trace(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n // @clack/prompts doesn't have trace, use message\n clackLog.message(message, {\n symbol: chalk.dim('•'),\n ...this.clackOutput,\n });\n } else {\n this.pinoLogger?.trace(message);\n }\n }\n this.fileLogger?.trace(message);\n }\n\n debug(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n // @clack/prompts doesn't have debug, use message\n clackLog.message(message, {\n symbol: chalk.dim('◆'),\n ...this.clackOutput,\n });\n } else {\n this.pinoLogger?.debug(message);\n }\n }\n this.fileLogger?.debug(message);\n }\n\n info(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.info(message, this.clackOutput);\n } else {\n this.pinoLogger?.info(message);\n }\n }\n this.fileLogger?.info(message);\n }\n\n warn(message: string): void {\n if (this.logFormat === 'default') {\n clackLog.warn(message, this.clackOutput);\n } else {\n this.pinoLogger?.warn(message);\n }\n this.fileLogger?.warn(message);\n }\n\n error(message: string): void {\n if (this.logFormat === 'default') {\n clackLog.error(message, this.clackOutput);\n } else {\n this.pinoLogger?.error(message);\n }\n this.fileLogger?.error(message);\n }\n\n fatal(message: string): void {\n if (this.logFormat === 'default') {\n // @clack/prompts doesn't have fatal, use error\n clackLog.error(message, this.clackOutput);\n } else {\n this.pinoLogger?.fatal(message);\n }\n this.fileLogger?.fatal(message);\n }\n\n silent(message: string): void {\n // Silent doesn't log to console, only to file\n this.fileLogger?.silent(message);\n }\n\n // @clack/prompts specific methods (for 'default' format)\n success(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.success(message, this.clackOutput);\n } else {\n this.pinoLogger?.info(message); // Map to info for non-default formats\n }\n }\n this.fileLogger?.info(message);\n }\n\n step(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.step(message, this.clackOutput);\n } else {\n this.pinoLogger?.info(message); // Map to info for non-default formats\n }\n }\n this.fileLogger?.info(message);\n }\n\n message(message: string, symbol?: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n clackLog.message(\n message,\n symbol ? { symbol, ...this.clackOutput } : this.clackOutput\n );\n } else {\n this.pinoLogger?.info(message); // Map to info for non-default formats\n }\n }\n this.fileLogger?.info(message);\n }\n\n // Spinner functionality\n createSpinner(indicator: 'dots' | 'timer' = 'timer'): SpinnerResult {\n // Quiet mode suppresses spinner UI; the mock routes through the gated\n // info() so nothing reaches the console while file logging is preserved.\n if (this.quiet || !this.animatedProgress) {\n return new MockSpinner(this);\n }\n if (this.logFormat === 'default') {\n return spinner({ indicator, ...this.clackOutput });\n } else {\n return new MockSpinner(this);\n }\n }\n\n // Progress bar functionality\n createProgressBar(total: number): ProgressResult {\n if (this.quiet || !this.animatedProgress) {\n return new MockProgress(total, this);\n }\n if (this.logFormat === 'default') {\n return progress({ max: total, ...this.clackOutput });\n } else {\n return new MockProgress(total, this);\n }\n }\n\n // Command start/end markers\n startCommand(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n intro(chalk.cyan(message), this.clackOutput);\n } else {\n this.info(`╭─ ${message}`);\n }\n }\n this.fileLogger?.info(`[START] ${message}`);\n }\n\n endCommand(message: string): void {\n if (!this.quiet) {\n if (this.logFormat === 'default') {\n outro(chalk.cyan(message), this.clackOutput);\n } else {\n this.info(`╰─ ${message}`);\n }\n }\n this.fileLogger?.info(`[END] ${message}`);\n }\n\n // Flush logs to ensure they're written before process exit\n flush(): void {\n this.pinoLogger?.flush();\n this.fileLogger?.flush();\n }\n}\n\nexport const logger = Logger.getInstance();\n"],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MAAI,KAAK,cAAc,UACrB,QAAO,QAAQ;GAAE;GAAW,GAAG,KAAK;GAAa,CAAC;MAElD,QAAO,IAAI,YAAY,KAAK;;CAKhC,kBAAkB,OAA+B;AAC/C,MAAI,KAAK,SAAS,CAAC,KAAK,iBACtB,QAAO,IAAI,aAAa,OAAO,KAAK;AAEtC,MAAI,KAAK,cAAc,UACrB,QAAO,SAAS;GAAE,KAAK;GAAO,GAAG,KAAK;GAAa,CAAC;MAEpD,QAAO,IAAI,aAAa,OAAO,KAAK;;CAKxC,aAAa,SAAuB;AAClC,MAAI,CAAC,KAAK,MACR,KAAI,KAAK,cAAc,UACrB,OAAM,MAAM,KAAK,QAAQ,EAAE,KAAK,YAAY;MAE5C,MAAK,KAAK,MAAM,UAAU;AAG9B,OAAK,YAAY,KAAK,WAAW,UAAU;;CAG7C,WAAW,SAAuB;AAChC,MAAI,CAAC,KAAK,MACR,KAAI,KAAK,cAAc,UACrB,OAAM,MAAM,KAAK,QAAQ,EAAE,KAAK,YAAY;MAE5C,MAAK,KAAK,MAAM,UAAU;AAG9B,OAAK,YAAY,KAAK,SAAS,UAAU;;CAI3C,QAAc;AACZ,OAAK,YAAY,OAAO;AACxB,OAAK,YAAY,OAAO;;EAIC,aAAa"}
|
package/dist/console/logging.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logging.js","names":[],"sources":["../../src/console/logging.ts"],"sourcesContent":["import {\n text,\n select,\n confirm,\n isCancel,\n cancel,\n multiselect,\n autocomplete,\n autocompleteMultiselect,\n} from '@clack/prompts';\nimport type { Option } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { getCLIVersion } from '../utils/packageJson.js';\nimport { logger } from './logger.js';\nimport { TEMPLATE_FILE_NAME } from '../utils/constants.js';\nimport type { CustomMapping, FileToUpload } from 'generaltranslation/types';\nimport { parseTypedLocale } from './promptParsing.js';\nimport { getFilteredLocaleOptions } from './localeOptions.js';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../types/libraries.js';\n\nfunction exitIfCancelled<T>(\n result: T | symbol,\n message = 'Operation cancelled'\n): T {\n if (isCancel(result)) {\n cancel(message);\n return exitSync(0);\n }\n return result as T;\n}\n\n/**\n * Strip ANSI escape codes from a string (e.g., chalk color codes)\n */\nexport function stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex, no-useless-escape\n return str.replace(/\\x1B\\[[0-9;]*m/g, '');\n}\n\nlet lastExitError: string | undefined;\n\n/** The message of the last logErrorAndExit call, for exit-time reporting. */\nexport function getLastExitError(): string | undefined {\n return lastExitError;\n}\n\nexport function logErrorAndExit(message: string): never {\n lastExitError = message;\n logger.error(message);\n return exitSync(1);\n}\n\nexport function exitSync(code: number): never {\n // Flush logs before exit\n logger.flush();\n process.exit(code);\n}\n\n// GT specific logging\nexport function displayHeader(introString?: string) {\n // The ASCII banner is pure chatter and writes to console directly, bypassing\n // the logger, so gate it here to honor --quiet. startCommand stays outside\n // the gate: it is quiet-aware itself and must still run so the file log\n // gets its [START] marker.\n if (!logger.isQuiet()) {\n displayAsciiTitle();\n displayInitializingText();\n }\n\n if (introString) {\n logger.startCommand(introString);\n }\n}\n\nfunction displayAsciiTitle() {\n // eslint-disable-next-line no-console\n console.log(\n chalk.cyan(\n `\\n @@@@@@@@@@@@@@@@@@@@@@\n @@ @@@@@@@@@@@@ @@@@@@@\n @@ @@@ @ @\n@@ @@ @ @\n@@ @ @@@@@ @ @\n@@ @@ @@@ @ @ @\n @@ @@ @ @ @ @\n @@ @@@@@@@ @ @ @\n @@@@@@@@@ @ @`\n )\n );\n}\n\nfunction displayInitializingText() {\n const version = getCLIVersion();\n // eslint-disable-next-line no-console\n console.log(\n `\\n${chalk.bold.blue('General Translation, Inc.')}\n${chalk.dim('https://generaltranslation.com/docs')}\n${chalk.dim(`CLI Version: ${version}\\n`)}`\n );\n}\n\nexport function displayProjectId(projectId: string) {\n logger.message(\n chalk.dim(`Project ID: ${chalk.bold(projectId)}`),\n chalk.cyan('~')\n );\n}\n\nexport function displayResolvedPaths(resolvedPaths: [string, string][]) {\n const paths = resolvedPaths.map(([key, resolvedPath]) => {\n return chalk.dim(`'${chalk.white(key)}' → '${chalk.green(resolvedPath)}'`);\n });\n logger.step(`Resolved path aliases:\\n${paths.join('\\n')}`);\n}\n\nexport function displayCreatedConfigFile(configFilepath: string) {\n logger.step(`Created config file ${chalk.cyan(configFilepath)}`);\n}\n\nexport function displayUpdatedConfigFile(configFilepath: string) {\n logger.success(`Updated config file ${chalk.cyan(configFilepath)}`);\n}\n\nexport function displayUpdatedVersionsFile(versionFilepath: string) {\n logger.success(`Updated versions file ${chalk.cyan(versionFilepath)}`);\n}\n\n// Input prompts\nexport async function promptText({\n message,\n defaultValue,\n validate,\n}: {\n message: string;\n defaultValue?: string;\n validate?: (value: string) => boolean | string;\n}) {\n const result = await text({\n message,\n placeholder: defaultValue,\n defaultValue,\n validate: validate\n ? (value) => {\n // Clack applies defaultValue after validation; check what Enter returns.\n const validation = validate(value || defaultValue || '');\n return validation === true ? undefined : validation.toString();\n }\n : undefined,\n });\n return exitIfCancelled(result);\n}\n\ntype LocalePromptContext = {\n userInput: string;\n selectedValues: string[];\n focusedValue?: string;\n};\n\n/**\n * Clack keeps the focused option while it still matches a new search, so\n * typing `fr` could leave `af` (Afrikaans) focused. Refocus the top-ranked\n * option whenever the search changes.\n */\nfunction searchableLocaleOptions(\n getOptions: (query: string, selected: string[]) => Option<string>[]\n) {\n let lastQuery = '';\n return function (this: LocalePromptContext) {\n const query = this.userInput ?? '';\n if (query !== lastQuery) {\n lastQuery = query;\n this.focusedValue = undefined;\n }\n return getOptions(query, this.selectedValues ?? []);\n };\n}\n\n/**\n * Searchable locale options: supported locales ranked by the query, the\n * configured customMapping aliases, and any other valid locale typed or\n * already selected, so aliases and custom tags stay selectable.\n */\nexport function getLocalePromptOptions(\n query: string,\n selected: string[] = [],\n customMapping?: CustomMapping\n): Option<string>[] {\n const normalizedQuery = query.trim().toLowerCase();\n const supported = getFilteredLocaleOptions(query).map((option) => ({\n value: option.code,\n label: option.label,\n }));\n const known = new Set(supported.map((option) => option.value));\n const aliases = Object.keys(customMapping ?? {})\n .filter((alias) => alias.toLowerCase().includes(normalizedQuery))\n .map((alias) => ({ value: alias, label: alias, hint: 'custom mapping' }));\n const typed = parseTypedLocale(query, customMapping);\n const extras = [...selected, ...(typed ? [typed] : [])]\n .filter(\n (locale) =>\n !known.has(locale) && !aliases.some((alias) => alias.value === locale)\n )\n .map((locale) => ({ value: locale, label: locale }));\n return [\n ...new Map(\n [...aliases, ...extras, ...supported].map((option) => [\n option.value,\n option,\n ])\n ).values(),\n ].sort(\n (a, b) =>\n Number(b.value.toLowerCase() === normalizedQuery) -\n Number(a.value.toLowerCase() === normalizedQuery)\n );\n}\n\n// Body-only: Clack shows it inline under the prompt.\nconst noLocaleSelectedError = createDiagnosticMessage({\n whatHappened: 'No locale matches the search',\n fix: 'Change the search and select a locale from the list',\n});\n\nexport async function promptLocale({\n message,\n defaultValue,\n customMapping,\n}: {\n message: string;\n defaultValue?: string;\n customMapping?: CustomMapping;\n}) {\n const result = await autocomplete<string>({\n message,\n placeholder: 'Type to search locales',\n initialValue: defaultValue,\n options: searchableLocaleOptions((query) =>\n getLocalePromptOptions(query, [], customMapping)\n ),\n // Enter with no matching option submits nothing; keep asking.\n validate: (value) => (value ? undefined : noLocaleSelectedError),\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptLocaleList({\n message,\n defaultValue,\n required = true,\n customMapping,\n}: {\n message: string;\n defaultValue?: string[];\n required?: boolean;\n customMapping?: CustomMapping;\n}) {\n const result = await autocompleteMultiselect<string>({\n message,\n placeholder: 'Type to search, Tab or Space to select',\n initialValues: defaultValue,\n required,\n // Clack only preselects defaults present in the first options list, so\n // keep custom default tags listed even before they are selected.\n options: searchableLocaleOptions((query, selected) =>\n getLocalePromptOptions(\n query,\n [...(defaultValue ?? []), ...selected],\n customMapping\n )\n ),\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptGlobPatterns(options: {\n label: string;\n message: string;\n defaultValue?: string;\n validate?: (value: string) => boolean | string;\n}) {\n return promptText(options);\n}\n\nexport async function promptSelect<T>({\n message,\n options,\n defaultValue,\n}: {\n message: string;\n options: Array<{ value: T; label: string; hint?: string }>;\n defaultValue?: T;\n}) {\n const result = await select({\n message,\n options: options as Option<T>[],\n initialValue: defaultValue,\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptMultiSelect<T extends string>({\n message,\n options,\n required = true,\n}: {\n message: string;\n options: Array<{ value: T; label: string; hint?: string }>;\n required?: boolean;\n}) {\n const result = await multiselect({\n message,\n options: options as Option<T>[],\n required,\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptConfirm({\n message,\n defaultValue = true,\n cancelMessage = 'Operation cancelled',\n}: {\n message: string;\n defaultValue?: boolean;\n cancelMessage?: string;\n}) {\n const result = await confirm({\n message,\n initialValue: defaultValue,\n });\n return exitIfCancelled(result, cancelMessage);\n}\n\n// Warning display functions\nexport function warnApiKeyInConfig(optionsFilepath: string) {\n logger.warn(\n `Found ${chalk.cyan('apiKey')} in \"${chalk.green(optionsFilepath)}\". ` +\n chalk.white(\n 'Your API key is exposed! Remove it from the file and include it as an environment variable.'\n )\n );\n}\n\nexport function warnVariableProp(\n file: string,\n attrName: string,\n value: string\n) {\n logger.warn(\n `Found ${chalk.green('<T>')} component in ${chalk.cyan(file)} with variable ${attrName}: \"${chalk.white(value)}\". ` +\n `Change \"${attrName}\" to ensure this content is translated.`\n );\n}\n\nexport function warnNoId(file: string) {\n logger.warn(\n `Found ${chalk.green('<T>')} component in ${chalk.cyan(file)} with no id. ` +\n chalk.white('Add an id to ensure the content is translated.')\n );\n}\n\nexport function warnHasUnwrappedExpression(\n file: string,\n id: string,\n unwrappedExpressions: string[]\n) {\n logger.warn(\n `${chalk.green('<T>')} with id \"${id}\" in ${chalk.cyan(file)} has children: ${unwrappedExpressions.join(', ')} that could change at runtime. ` +\n chalk.white('Use a variable component like ') +\n chalk.green('<Var>') +\n chalk.white(' (') +\n chalk.blue('https://generaltranslation.com/docs') +\n chalk.white(') to translate this properly.')\n );\n}\n\nexport function warnTemplateLiteral(file: string, value: string) {\n logger.warn(\n `Found template literal with quasis (${value}) in ${chalk.cyan(file)}. ` +\n chalk.white(\n 'Change the template literal to a string to ensure this content is translated.'\n )\n );\n}\n\nexport function warnTernary(file: string) {\n logger.warn(\n `Found ternary expression in ${chalk.cyan(file)}. ` +\n chalk.white('A Branch component may be more appropriate here.')\n );\n}\n\nexport function warnDeprecatedField(\n deprecatedField: string,\n replacement: string\n) {\n logger.warn(\n `${chalk.green(deprecatedField)} is deprecated. ` +\n chalk.white(`Use ${chalk.green(replacement)} instead.`)\n );\n}\n\n/**\n * Helper: Log all collected files\n */\nexport function logCollectedFiles(\n files: Pick<FileToUpload, 'fileName'>[],\n inlineComponents?: number,\n inlineLibrary?: InlineLibrary\n): void {\n const elementLabel = getInlineElementsLabel(inlineLibrary);\n logger.message(\n chalk.cyan('Files found in project:') +\n '\\n' +\n files\n .map((file) => {\n if (file.fileName === TEMPLATE_FILE_NAME) {\n return `- <${elementLabel}>${inlineComponents ? ` (${inlineComponents})` : ''}`;\n }\n return `- ${file.fileName}`;\n })\n .join('\\n')\n );\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAS,gBACP,QACA,UAAU,uBACP;AACH,KAAI,SAAS,OAAO,EAAE;AACpB,SAAO,QAAQ;AACf,SAAO,SAAS,EAAE;;AAEpB,QAAO;;;;;AAMT,SAAgB,UAAU,KAAqB;AAE7C,QAAO,IAAI,QAAQ,mBAAmB,GAAG;;AAG3C,IAAI;;AAGJ,SAAgB,mBAAuC;AACrD,QAAO;;AAGT,SAAgB,gBAAgB,SAAwB;AACtD,iBAAgB;AAChB,QAAO,MAAM,QAAQ;AACrB,QAAO,SAAS,EAAE;;AAGpB,SAAgB,SAAS,MAAqB;AAE5C,QAAO,OAAO;AACd,SAAQ,KAAK,KA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ACvB;;AAGH,SAAgB,SAAS,MAAc;AACrC,QAAO,KACL,SAAS,MAAM,MAAM,MAAM,CAAC,gBAAgB,MAAM,KAAK,KAAK,CAAC,iBAC3D,MAAM,MAAM,iDAAiD,CAChE;;AAGH,SAAgB,2BACd,MACA,IACA,sBACA;AACA,QAAO,KACL,GAAG,MAAM,MAAM,MAAM,CAAC,YAAY,GAAG,OAAO,MAAM,KAAK,KAAK,CAAC,iBAAiB,qBAAqB,KAAK,KAAK,CAAC,mCAC5G,MAAM,MAAM,iCAAiC,GAC7C,MAAM,MAAM,QAAQ,GACpB,MAAM,MAAM,KAAK,GACjB,MAAM,KAAK,sCAAsC,GACjD,MAAM,MAAM,gCAAgC,CAC/C;;AAGH,SAAgB,oBAAoB,MAAc,OAAe;AAC/D,QAAO,KACL,uCAAuC,MAAM,OAAO,MAAM,KAAK,KAAK,CAAC,MACnE,MAAM,MACJ,gFACD,CACJ;;AAGH,SAAgB,YAAY,MAAc;AACxC,QAAO,KACL,+BAA+B,MAAM,KAAK,KAAK,CAAC,MAC9C,MAAM,MAAM,mDAAmD,CAClE;;AAGH,SAAgB,oBACd,iBACA,aACA;AACA,QAAO,KACL,GAAG,MAAM,MAAM,gBAAgB,CAAC,oBAC9B,MAAM,MAAM,OAAO,MAAM,MAAM,YAAY,CAAC,WAAW,CAC1D;;;;;AAMH,SAAgB,kBACd,OACA,kBACA,eACM;CACN,MAAM,eAAe,uBAAuB,cAAc;AAC1D,QAAO,QACL,MAAM,KAAK,0BAA0B,GACnC,OACA,MACG,KAAK,SAAS;AACb,MAAI,KAAK,aAAA,gCACP,QAAO,MAAM,aAAa,GAAG,mBAAmB,KAAK,iBAAiB,KAAK;AAE7E,SAAO,KAAK,KAAK;GACjB,CACD,KAAK,KAAK,CAChB"}
|
|
1
|
+
{"version":3,"file":"logging.js","names":[],"sources":["../../src/console/logging.ts"],"sourcesContent":["import {\n text,\n select,\n confirm,\n isCancel,\n cancel,\n multiselect,\n autocomplete,\n autocompleteMultiselect,\n} from '@clack/prompts';\nimport type { Option } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { getCLIVersion } from '../utils/packageJson.js';\nimport { logger } from './logger.js';\nimport { TEMPLATE_FILE_NAME } from '../utils/constants.js';\nimport type { CustomMapping, FileToUpload } from 'generaltranslation/types';\nimport { parseTypedLocale } from './promptParsing.js';\nimport { getFilteredLocaleOptions } from './localeOptions.js';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../types/libraries.js';\n\nfunction exitIfCancelled<T>(\n result: T | symbol,\n message = 'Operation cancelled'\n): T {\n if (isCancel(result)) {\n cancel(message);\n return exitSync(0);\n }\n return result as T;\n}\n\n/**\n * Strip ANSI escape codes from a string (e.g., chalk color codes)\n */\nexport function stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex, no-useless-escape\n return str.replace(/\\x1B\\[[0-9;]*m/g, '');\n}\n\nlet lastExitError: string | undefined;\n\n/** The message of the last logErrorAndExit call, for exit-time reporting. */\nexport function getLastExitError(): string | undefined {\n return lastExitError;\n}\n\nexport function logErrorAndExit(message: string): never {\n lastExitError = message;\n logger.error(message);\n return exitSync(1);\n}\n\nexport function exitSync(code: number): never {\n // Flush logs before exit\n logger.flush();\n process.exit(code);\n}\n\n// GT specific logging\nexport function displayHeader(introString?: string) {\n // The ASCII banner is pure chatter and writes to console directly, bypassing\n // the logger, so gate it here to honor --quiet and to keep json/agent output\n // free of decoration. startCommand stays outside the gate: it is\n // quiet-aware itself and must still run so the file log gets its [START]\n // marker.\n if (!logger.isQuiet() && logger.getLogFormat() === 'default') {\n displayAsciiTitle();\n displayInitializingText();\n }\n\n if (introString) {\n logger.startCommand(introString);\n }\n}\n\nfunction displayAsciiTitle() {\n // eslint-disable-next-line no-console\n console.log(\n chalk.cyan(\n `\\n @@@@@@@@@@@@@@@@@@@@@@\n @@ @@@@@@@@@@@@ @@@@@@@\n @@ @@@ @ @\n@@ @@ @ @\n@@ @ @@@@@ @ @\n@@ @@ @@@ @ @ @\n @@ @@ @ @ @ @\n @@ @@@@@@@ @ @ @\n @@@@@@@@@ @ @`\n )\n );\n}\n\nfunction displayInitializingText() {\n const version = getCLIVersion();\n // eslint-disable-next-line no-console\n console.log(\n `\\n${chalk.bold.blue('General Translation, Inc.')}\n${chalk.dim('https://generaltranslation.com/docs')}\n${chalk.dim(`CLI Version: ${version}\\n`)}`\n );\n}\n\nexport function displayProjectId(projectId: string) {\n logger.message(\n chalk.dim(`Project ID: ${chalk.bold(projectId)}`),\n chalk.cyan('~')\n );\n}\n\nexport function displayResolvedPaths(resolvedPaths: [string, string][]) {\n const paths = resolvedPaths.map(([key, resolvedPath]) => {\n return chalk.dim(`'${chalk.white(key)}' → '${chalk.green(resolvedPath)}'`);\n });\n logger.step(`Resolved path aliases:\\n${paths.join('\\n')}`);\n}\n\nexport function displayCreatedConfigFile(configFilepath: string) {\n logger.step(`Created config file ${chalk.cyan(configFilepath)}`);\n}\n\nexport function displayUpdatedConfigFile(configFilepath: string) {\n logger.success(`Updated config file ${chalk.cyan(configFilepath)}`);\n}\n\nexport function displayUpdatedVersionsFile(versionFilepath: string) {\n logger.success(`Updated versions file ${chalk.cyan(versionFilepath)}`);\n}\n\n// Input prompts\nexport async function promptText({\n message,\n defaultValue,\n validate,\n}: {\n message: string;\n defaultValue?: string;\n validate?: (value: string) => boolean | string;\n}) {\n const result = await text({\n message,\n placeholder: defaultValue,\n defaultValue,\n validate: validate\n ? (value) => {\n // Clack applies defaultValue after validation; check what Enter returns.\n const validation = validate(value || defaultValue || '');\n return validation === true ? undefined : validation.toString();\n }\n : undefined,\n });\n return exitIfCancelled(result);\n}\n\ntype LocalePromptContext = {\n userInput: string;\n selectedValues: string[];\n focusedValue?: string;\n};\n\n/**\n * Clack keeps the focused option while it still matches a new search, so\n * typing `fr` could leave `af` (Afrikaans) focused. Refocus the top-ranked\n * option whenever the search changes.\n */\nfunction searchableLocaleOptions(\n getOptions: (query: string, selected: string[]) => Option<string>[]\n) {\n let lastQuery = '';\n return function (this: LocalePromptContext) {\n const query = this.userInput ?? '';\n if (query !== lastQuery) {\n lastQuery = query;\n this.focusedValue = undefined;\n }\n return getOptions(query, this.selectedValues ?? []);\n };\n}\n\n/**\n * Searchable locale options: supported locales ranked by the query, the\n * configured customMapping aliases, and any other valid locale typed or\n * already selected, so aliases and custom tags stay selectable.\n */\nexport function getLocalePromptOptions(\n query: string,\n selected: string[] = [],\n customMapping?: CustomMapping\n): Option<string>[] {\n const normalizedQuery = query.trim().toLowerCase();\n const supported = getFilteredLocaleOptions(query).map((option) => ({\n value: option.code,\n label: option.label,\n }));\n const known = new Set(supported.map((option) => option.value));\n const aliases = Object.keys(customMapping ?? {})\n .filter((alias) => alias.toLowerCase().includes(normalizedQuery))\n .map((alias) => ({ value: alias, label: alias, hint: 'custom mapping' }));\n const typed = parseTypedLocale(query, customMapping);\n const extras = [...selected, ...(typed ? [typed] : [])]\n .filter(\n (locale) =>\n !known.has(locale) && !aliases.some((alias) => alias.value === locale)\n )\n .map((locale) => ({ value: locale, label: locale }));\n return [\n ...new Map(\n [...aliases, ...extras, ...supported].map((option) => [\n option.value,\n option,\n ])\n ).values(),\n ].sort(\n (a, b) =>\n Number(b.value.toLowerCase() === normalizedQuery) -\n Number(a.value.toLowerCase() === normalizedQuery)\n );\n}\n\n// Body-only: Clack shows it inline under the prompt.\nconst noLocaleSelectedError = createDiagnosticMessage({\n whatHappened: 'No locale matches the search',\n fix: 'Change the search and select a locale from the list',\n});\n\nexport async function promptLocale({\n message,\n defaultValue,\n customMapping,\n}: {\n message: string;\n defaultValue?: string;\n customMapping?: CustomMapping;\n}) {\n const result = await autocomplete<string>({\n message,\n placeholder: 'Type to search locales',\n initialValue: defaultValue,\n options: searchableLocaleOptions((query) =>\n getLocalePromptOptions(query, [], customMapping)\n ),\n // Enter with no matching option submits nothing; keep asking.\n validate: (value) => (value ? undefined : noLocaleSelectedError),\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptLocaleList({\n message,\n defaultValue,\n required = true,\n customMapping,\n}: {\n message: string;\n defaultValue?: string[];\n required?: boolean;\n customMapping?: CustomMapping;\n}) {\n const result = await autocompleteMultiselect<string>({\n message,\n placeholder: 'Type to search, Tab or Space to select',\n initialValues: defaultValue,\n required,\n // Clack only preselects defaults present in the first options list, so\n // keep custom default tags listed even before they are selected.\n options: searchableLocaleOptions((query, selected) =>\n getLocalePromptOptions(\n query,\n [...(defaultValue ?? []), ...selected],\n customMapping\n )\n ),\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptGlobPatterns(options: {\n label: string;\n message: string;\n defaultValue?: string;\n validate?: (value: string) => boolean | string;\n}) {\n return promptText(options);\n}\n\nexport async function promptSelect<T>({\n message,\n options,\n defaultValue,\n}: {\n message: string;\n options: Array<{ value: T; label: string; hint?: string }>;\n defaultValue?: T;\n}) {\n const result = await select({\n message,\n options: options as Option<T>[],\n initialValue: defaultValue,\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptMultiSelect<T extends string>({\n message,\n options,\n required = true,\n}: {\n message: string;\n options: Array<{ value: T; label: string; hint?: string }>;\n required?: boolean;\n}) {\n const result = await multiselect({\n message,\n options: options as Option<T>[],\n required,\n });\n return exitIfCancelled(result);\n}\n\nexport async function promptConfirm({\n message,\n defaultValue = true,\n cancelMessage = 'Operation cancelled',\n}: {\n message: string;\n defaultValue?: boolean;\n cancelMessage?: string;\n}) {\n const result = await confirm({\n message,\n initialValue: defaultValue,\n });\n return exitIfCancelled(result, cancelMessage);\n}\n\n// Warning display functions\nexport function warnApiKeyInConfig(optionsFilepath: string) {\n logger.warn(\n `Found ${chalk.cyan('apiKey')} in \"${chalk.green(optionsFilepath)}\". ` +\n chalk.white(\n 'Your API key is exposed! Remove it from the file and include it as an environment variable.'\n )\n );\n}\n\nexport function warnVariableProp(\n file: string,\n attrName: string,\n value: string\n) {\n logger.warn(\n `Found ${chalk.green('<T>')} component in ${chalk.cyan(file)} with variable ${attrName}: \"${chalk.white(value)}\". ` +\n `Change \"${attrName}\" to ensure this content is translated.`\n );\n}\n\nexport function warnNoId(file: string) {\n logger.warn(\n `Found ${chalk.green('<T>')} component in ${chalk.cyan(file)} with no id. ` +\n chalk.white('Add an id to ensure the content is translated.')\n );\n}\n\nexport function warnHasUnwrappedExpression(\n file: string,\n id: string,\n unwrappedExpressions: string[]\n) {\n logger.warn(\n `${chalk.green('<T>')} with id \"${id}\" in ${chalk.cyan(file)} has children: ${unwrappedExpressions.join(', ')} that could change at runtime. ` +\n chalk.white('Use a variable component like ') +\n chalk.green('<Var>') +\n chalk.white(' (') +\n chalk.blue('https://generaltranslation.com/docs') +\n chalk.white(') to translate this properly.')\n );\n}\n\nexport function warnTemplateLiteral(file: string, value: string) {\n logger.warn(\n `Found template literal with quasis (${value}) in ${chalk.cyan(file)}. ` +\n chalk.white(\n 'Change the template literal to a string to ensure this content is translated.'\n )\n );\n}\n\nexport function warnTernary(file: string) {\n logger.warn(\n `Found ternary expression in ${chalk.cyan(file)}. ` +\n chalk.white('A Branch component may be more appropriate here.')\n );\n}\n\nexport function warnDeprecatedField(\n deprecatedField: string,\n replacement: string\n) {\n logger.warn(\n `${chalk.green(deprecatedField)} is deprecated. ` +\n chalk.white(`Use ${chalk.green(replacement)} instead.`)\n );\n}\n\n/**\n * Helper: Log all collected files\n */\nexport function logCollectedFiles(\n files: Pick<FileToUpload, 'fileName'>[],\n inlineComponents?: number,\n inlineLibrary?: InlineLibrary\n): void {\n const elementLabel = getInlineElementsLabel(inlineLibrary);\n logger.message(\n chalk.cyan('Files found in project:') +\n '\\n' +\n files\n .map((file) => {\n if (file.fileName === TEMPLATE_FILE_NAME) {\n return `- <${elementLabel}>${inlineComponents ? ` (${inlineComponents})` : ''}`;\n }\n return `- ${file.fileName}`;\n })\n .join('\\n')\n );\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAS,gBACP,QACA,UAAU,uBACP;AACH,KAAI,SAAS,OAAO,EAAE;AACpB,SAAO,QAAQ;AACf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,cAAc;AAC1D,QAAO,QACL,MAAM,KAAK,0BAA0B,GACnC,OACA,MACG,KAAK,SAAS;AACb,MAAI,KAAK,aAAA,gCACP,QAAO,MAAM,aAAa,GAAG,mBAAmB,KAAK,iBAAiB,KAAK;AAE7E,SAAO,KAAK,KAAK;GACjB,CACD,KAAK,KAAK,CAChB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { GT_CONFIG_SCHEMA_URL } from "../../utils/constants.js";
|
|
2
2
|
import { displayCreatedConfigFile, displayUpdatedConfigFile } from "../../console/logging.js";
|
|
3
3
|
import { createDiagnosticMessage, formatDiagnosticErrorDetails } from "generaltranslation/internal";
|
|
4
|
-
import fs from "node:fs";
|
|
5
4
|
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import fs from "node:fs";
|
|
6
6
|
//#region src/fs/config/setupConfig.ts
|
|
7
7
|
function asObject(value) {
|
|
8
8
|
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "2.26.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.26.10";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.26.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.26.10';\n"],"mappings":";AACA,MAAa,kBAAkB"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import updateConfig from "../fs/config/updateConfig.js";
|
|
2
|
+
import { promisify } from "node:util";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import fs from "node:fs";
|
|
4
5
|
import { createDiagnosticMessage } from "generaltranslation/diagnostics";
|
|
5
6
|
import { execFile } from "node:child_process";
|
|
6
|
-
import { promisify } from "node:util";
|
|
7
7
|
//#region src/git/setupMergeDrivers.ts
|
|
8
8
|
const execFileAsync = promisify(execFile);
|
|
9
9
|
const GT_LOCK_DRIVER = "merge=gt-lock";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const FILE_IO_CONCURRENCY = 512;
|
|
2
|
+
/**
|
|
3
|
+
* Keeps up to `batchSize` items in flight and returns results in input order.
|
|
4
|
+
* Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.
|
|
5
|
+
* @param items - The items to process
|
|
6
|
+
* @param processor - Processes one item
|
|
7
|
+
* @param batchSize - The maximum number of items in flight at once
|
|
8
|
+
* @returns The processor results, in input order
|
|
9
|
+
*/
|
|
10
|
+
export declare function batchProcess<T, R>(items: T[], processor: (item: T, index: number) => Promise<R>, batchSize?: number): Promise<R[]>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
//#region src/utils/batchProcess.ts
|
|
2
|
+
const FILE_IO_CONCURRENCY = 512;
|
|
3
|
+
/**
|
|
4
|
+
* Keeps up to `batchSize` items in flight and returns results in input order.
|
|
5
|
+
* Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.
|
|
6
|
+
* @param items - The items to process
|
|
7
|
+
* @param processor - Processes one item
|
|
8
|
+
* @param batchSize - The maximum number of items in flight at once
|
|
9
|
+
* @returns The processor results, in input order
|
|
10
|
+
*/
|
|
11
|
+
async function batchProcess(items, processor, batchSize = 25) {
|
|
12
|
+
if (items.length === 0) return [];
|
|
13
|
+
const results = Array.from({ length: items.length });
|
|
14
|
+
const executing = /* @__PURE__ */ new Set();
|
|
15
|
+
for (let i = 0; i < items.length; i++) {
|
|
16
|
+
const promise = processor(items[i], i).then((result) => {
|
|
17
|
+
results[i] = result;
|
|
18
|
+
executing.delete(promise);
|
|
19
|
+
});
|
|
20
|
+
executing.add(promise);
|
|
21
|
+
if (executing.size >= batchSize) await Promise.race(executing);
|
|
22
|
+
}
|
|
23
|
+
await Promise.all(executing);
|
|
24
|
+
return results;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { FILE_IO_CONCURRENCY, batchProcess };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=batchProcess.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batchProcess.js","names":[],"sources":["../../src/utils/batchProcess.ts"],"sourcesContent":["// Max files a postprocess pass reads or writes at once. Unbounded\n// Promise.all over every translated file opens a descriptor per file and\n// fails with EMFILE on large projects.\nexport const FILE_IO_CONCURRENCY = 512;\n\n/**\n * Keeps up to `batchSize` items in flight and returns results in input order.\n * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.\n * @param items - The items to process\n * @param processor - Processes one item\n * @param batchSize - The maximum number of items in flight at once\n * @returns The processor results, in input order\n */\nexport async function batchProcess<T, R>(\n items: T[],\n processor: (item: T, index: number) => Promise<R>,\n batchSize: number = 25\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n const results = Array.from({ length: items.length }) as R[];\n const executing = new Set<Promise<void>>();\n\n for (let i = 0; i < items.length; i++) {\n const promise = processor(items[i], i).then((result) => {\n results[i] = result;\n executing.delete(promise);\n });\n\n executing.add(promise);\n\n if (executing.size >= batchSize) {\n await Promise.race(executing);\n }\n }\n\n await Promise.all(executing);\n\n return results;\n}\n"],"mappings":";AAGA,MAAa,sBAAsB;;;;;;;;;AAUnC,eAAsB,aACpB,OACA,WACA,YAAoB,IACN;AACd,KAAI,MAAM,WAAW,EACnB,QAAO,EAAE;CAEX,MAAM,UAAU,MAAM,KAAK,EAAE,QAAQ,MAAM,QAAQ,CAAC;CACpD,MAAM,4BAAY,IAAI,KAAoB;AAE1C,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,UAAU,UAAU,MAAM,IAAI,EAAE,CAAC,MAAM,WAAW;AACtD,WAAQ,KAAK;AACb,aAAU,OAAO,QAAQ;IACzB;AAEF,YAAU,IAAI,QAAQ;AAEtB,MAAI,UAAU,QAAQ,UACpB,OAAM,QAAQ,KAAK,UAAU;;AAIjC,OAAM,QAAQ,IAAI,UAAU;AAE5B,QAAO"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createDiagnosticMessage, formatDiagnosticErrorDetails } from "generaltranslation/internal";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { promisify } from "node:util";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
import { execFile } from "node:child_process";
|
|
6
|
-
import { promisify } from "node:util";
|
|
7
7
|
import dotenv from "dotenv";
|
|
8
8
|
//#region src/utils/credentials.ts
|
|
9
9
|
const execFileAsync = promisify(execFile);
|
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
import { createFileMapping } from "../formats/files/fileMapping.js";
|
|
2
|
+
import { batchProcess } from "./batchProcess.js";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
//#region src/utils/flattenJsonFiles.ts
|
|
4
5
|
async function flattenJsonFiles(settings, includeFiles) {
|
|
5
6
|
if (!settings.files || Object.keys(settings.files.placeholderPaths).length === 1 && settings.files.placeholderPaths.gt) return;
|
|
6
7
|
const { resolvedPaths: sourceFiles } = settings.files;
|
|
7
8
|
const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths, settings.files.transformFormats, settings.locales, settings.defaultLocale);
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
await
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
return flattenedJson;
|
|
14
|
-
}));
|
|
15
|
-
}));
|
|
9
|
+
for (const filesMap of Object.values(fileMapping)) await batchProcess(Object.values(filesMap).filter((p) => p.endsWith(".json") && (!includeFiles || includeFiles.has(p))), async (file) => {
|
|
10
|
+
const flattenedJson = flattenJson(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
11
|
+
await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
|
|
12
|
+
return flattenedJson;
|
|
13
|
+
}, 512);
|
|
16
14
|
}
|
|
17
15
|
function flattenJson(json, prefix = "") {
|
|
18
16
|
const result = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n
|
|
1
|
+
{"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // One locale at a time so the concurrency bound covers the whole pass\n for (const filesMap of Object.values(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await batchProcess(\n targetFiles,\n async (file) => {\n // Read each json file\n const json = JSON.parse(fs.readFileSync(file, 'utf8'));\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n JSON.stringify(flattenedJson, null, 2)\n );\n return flattenedJson;\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;;AAKA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAGD,MAAK,MAAM,YAAY,OAAO,OAAO,YAAY,CAK/C,OAAM,aAJc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EAIxD,EACX,OAAO,SAAS;EAId,MAAM,gBAAgB,YAFT,KAAK,MAAM,GAAG,aAAa,MAAM,OAAO,CAEf,CAAC;AAGvC,QAAM,GAAG,SAAS,UAChB,MACA,KAAK,UAAU,eAAe,MAAM,EAAE,CACvC;AACD,SAAO;QAGV;;AAIL,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
|
package/dist/utils/gitDiff.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createFileMapping } from "../formats/files/fileMapping.js";
|
|
2
|
+
import { batchProcess } from "./batchProcess.js";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import fs from "node:fs";
|
|
4
5
|
import YAML, { isMap, isScalar } from "yaml";
|
|
@@ -77,14 +78,11 @@ async function localizeMintlifyFrontmatterUrls(settings, includeFiles) {
|
|
|
77
78
|
if (settings.framework !== "mintlify" || !settings.files) return;
|
|
78
79
|
const fileMapping = createFileMapping(settings.files.resolvedPaths, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
|
|
79
80
|
const knownLocaleValues = [settings.defaultLocale, ...settings.locales];
|
|
80
|
-
for (const [locale, filesMap] of Object.entries(fileMapping)) {
|
|
81
|
-
|
|
82
|
-
await
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
if (result.changed) await fs.promises.writeFile(filePath, result.content, "utf8");
|
|
86
|
-
}));
|
|
87
|
-
}
|
|
81
|
+
for (const [locale, filesMap] of Object.entries(fileMapping)) await batchProcess(Object.values(filesMap).filter((filePath) => (filePath.endsWith(".md") || filePath.endsWith(".mdx")) && shouldProcessFile(filePath, includeFiles)), async (filePath) => {
|
|
82
|
+
if (!fs.existsSync(filePath)) return;
|
|
83
|
+
const result = localizeMintlifyFrontmatterUrlForContent(await fs.promises.readFile(filePath, "utf8"), locale, knownLocaleValues);
|
|
84
|
+
if (result.changed) await fs.promises.writeFile(filePath, result.content, "utf8");
|
|
85
|
+
}, 512);
|
|
88
86
|
}
|
|
89
87
|
//#endregion
|
|
90
88
|
export { localizeMintlifyFrontmatterUrls as default, localizeMintlifyFrontmatterUrlForContent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localizeMintlifyFrontmatterUrls.js","names":[],"sources":["../../src/utils/localizeMintlifyFrontmatterUrls.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport YAML, { isMap, isScalar } from 'yaml';\nimport type { Content, Root, Yaml } from 'mdast';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport type { Settings } from '../types/index.js';\n\nconst SKIPPABLE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#|\\.\\/|\\.\\.\\/)/i;\n\nfunction getYamlFrontmatter(content: string): Yaml | null {\n let tree: Root;\n try {\n tree = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml'])\n .parse(content) as Root;\n } catch {\n return null;\n }\n\n const yamlNode = (tree.children as Content[]).find(\n (node): node is Yaml => (node as Yaml).type === 'yaml'\n );\n if (\n !yamlNode ||\n !yamlNode.position ||\n yamlNode.position.start?.offset === undefined ||\n yamlNode.position.end?.offset === undefined\n ) {\n return null;\n }\n return yamlNode;\n}\n\nfunction normalizeMintlifyFrontmatterUrl(\n url: string,\n targetLocale: string,\n knownLocales: Set<string>\n): string | null {\n const trimmed = url.trim();\n if (!trimmed || SKIPPABLE_URL_REGEX.test(trimmed)) {\n return null;\n }\n\n const leadingWhitespace = url.match(/^\\s*/)?.[0] ?? '';\n const trailingWhitespace = url.match(/\\s*$/)?.[0] ?? '';\n const leadingSlash = trimmed.startsWith('/') ? '/' : '';\n const pathBody = trimmed.replace(/^\\/+/, '');\n const [firstSegment, ...restSegments] = pathBody.split('/');\n\n if (firstSegment === targetLocale) {\n const normalized = `${leadingWhitespace}${leadingSlash}${pathBody}${trailingWhitespace}`;\n return normalized === url ? null : normalized;\n }\n\n const unprefixedPath = knownLocales.has(firstSegment)\n ? restSegments.join('/')\n : pathBody;\n const localizedPath = unprefixedPath\n ? `${targetLocale}/${unprefixedPath}`\n : `${targetLocale}/`;\n const normalized = `${leadingWhitespace}${leadingSlash}${localizedPath}${trailingWhitespace}`;\n\n return normalized === url ? null : normalized;\n}\n\nexport function localizeMintlifyFrontmatterUrlForContent(\n content: string,\n targetLocale: string,\n knownLocaleValues: string[]\n): { content: string; changed: boolean } {\n const yamlNode = getYamlFrontmatter(content);\n if (!yamlNode) {\n return { content, changed: false };\n }\n\n const frontmatterRaw: string = yamlNode.value || '';\n const doc = YAML.parseDocument(frontmatterRaw, {\n prettyErrors: false,\n keepSourceTokens: true,\n });\n if (doc.errors?.length || !isMap(doc.contents)) {\n return { content, changed: false };\n }\n\n const urlNode = doc.get('url', true);\n if (!isScalar(urlNode) || typeof urlNode.value !== 'string') {\n return { content, changed: false };\n }\n\n const localizedUrl = normalizeMintlifyFrontmatterUrl(\n urlNode.value,\n targetLocale,\n new Set(knownLocaleValues)\n );\n if (!localizedUrl) {\n return { content, changed: false };\n }\n\n urlNode.value = localizedUrl;\n\n const start = yamlNode.position!.start.offset as number;\n const end = yamlNode.position!.end.offset as number;\n const newline = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const frontmatter = doc.toString().trimEnd().replace(/\\n/g, newline);\n return {\n content: `${content.slice(0, start)}---${newline}${frontmatter}${newline}---${content.slice(end)}`,\n changed: true,\n };\n}\n\nfunction shouldProcessFile(filePath: string, includeFiles?: Set<string>) {\n if (!includeFiles) return true;\n return includeFiles.has(filePath) || includeFiles.has(path.resolve(filePath));\n}\n\nexport default async function localizeMintlifyFrontmatterUrls(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (settings.framework !== 'mintlify' || !settings.files) return;\n\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales,\n settings.defaultLocale\n );\n const knownLocaleValues = [settings.defaultLocale, ...settings.locales];\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (filePath) =>\n (filePath.endsWith('.md') || filePath.endsWith('.mdx')) &&\n shouldProcessFile(filePath, includeFiles)\n );\n\n await
|
|
1
|
+
{"version":3,"file":"localizeMintlifyFrontmatterUrls.js","names":[],"sources":["../../src/utils/localizeMintlifyFrontmatterUrls.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport YAML, { isMap, isScalar } from 'yaml';\nimport type { Content, Root, Yaml } from 'mdast';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport type { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nconst SKIPPABLE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#|\\.\\/|\\.\\.\\/)/i;\n\nfunction getYamlFrontmatter(content: string): Yaml | null {\n let tree: Root;\n try {\n tree = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml'])\n .parse(content) as Root;\n } catch {\n return null;\n }\n\n const yamlNode = (tree.children as Content[]).find(\n (node): node is Yaml => (node as Yaml).type === 'yaml'\n );\n if (\n !yamlNode ||\n !yamlNode.position ||\n yamlNode.position.start?.offset === undefined ||\n yamlNode.position.end?.offset === undefined\n ) {\n return null;\n }\n return yamlNode;\n}\n\nfunction normalizeMintlifyFrontmatterUrl(\n url: string,\n targetLocale: string,\n knownLocales: Set<string>\n): string | null {\n const trimmed = url.trim();\n if (!trimmed || SKIPPABLE_URL_REGEX.test(trimmed)) {\n return null;\n }\n\n const leadingWhitespace = url.match(/^\\s*/)?.[0] ?? '';\n const trailingWhitespace = url.match(/\\s*$/)?.[0] ?? '';\n const leadingSlash = trimmed.startsWith('/') ? '/' : '';\n const pathBody = trimmed.replace(/^\\/+/, '');\n const [firstSegment, ...restSegments] = pathBody.split('/');\n\n if (firstSegment === targetLocale) {\n const normalized = `${leadingWhitespace}${leadingSlash}${pathBody}${trailingWhitespace}`;\n return normalized === url ? null : normalized;\n }\n\n const unprefixedPath = knownLocales.has(firstSegment)\n ? restSegments.join('/')\n : pathBody;\n const localizedPath = unprefixedPath\n ? `${targetLocale}/${unprefixedPath}`\n : `${targetLocale}/`;\n const normalized = `${leadingWhitespace}${leadingSlash}${localizedPath}${trailingWhitespace}`;\n\n return normalized === url ? null : normalized;\n}\n\nexport function localizeMintlifyFrontmatterUrlForContent(\n content: string,\n targetLocale: string,\n knownLocaleValues: string[]\n): { content: string; changed: boolean } {\n const yamlNode = getYamlFrontmatter(content);\n if (!yamlNode) {\n return { content, changed: false };\n }\n\n const frontmatterRaw: string = yamlNode.value || '';\n const doc = YAML.parseDocument(frontmatterRaw, {\n prettyErrors: false,\n keepSourceTokens: true,\n });\n if (doc.errors?.length || !isMap(doc.contents)) {\n return { content, changed: false };\n }\n\n const urlNode = doc.get('url', true);\n if (!isScalar(urlNode) || typeof urlNode.value !== 'string') {\n return { content, changed: false };\n }\n\n const localizedUrl = normalizeMintlifyFrontmatterUrl(\n urlNode.value,\n targetLocale,\n new Set(knownLocaleValues)\n );\n if (!localizedUrl) {\n return { content, changed: false };\n }\n\n urlNode.value = localizedUrl;\n\n const start = yamlNode.position!.start.offset as number;\n const end = yamlNode.position!.end.offset as number;\n const newline = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const frontmatter = doc.toString().trimEnd().replace(/\\n/g, newline);\n return {\n content: `${content.slice(0, start)}---${newline}${frontmatter}${newline}---${content.slice(end)}`,\n changed: true,\n };\n}\n\nfunction shouldProcessFile(filePath: string, includeFiles?: Set<string>) {\n if (!includeFiles) return true;\n return includeFiles.has(filePath) || includeFiles.has(path.resolve(filePath));\n}\n\nexport default async function localizeMintlifyFrontmatterUrls(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (settings.framework !== 'mintlify' || !settings.files) return;\n\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales,\n settings.defaultLocale\n );\n const knownLocaleValues = [settings.defaultLocale, ...settings.locales];\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (filePath) =>\n (filePath.endsWith('.md') || filePath.endsWith('.mdx')) &&\n shouldProcessFile(filePath, includeFiles)\n );\n\n await batchProcess(\n targetFiles,\n async (filePath) => {\n if (!fs.existsSync(filePath)) return;\n\n const content = await fs.promises.readFile(filePath, 'utf8');\n const result = localizeMintlifyFrontmatterUrlForContent(\n content,\n locale,\n knownLocaleValues\n );\n if (result.changed) {\n await fs.promises.writeFile(filePath, result.content, 'utf8');\n }\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;AAE5B,SAAS,mBAAmB,SAA8B;CACxD,IAAI;AACJ,KAAI;AACF,SAAO,SAAS,CACb,IAAI,YAAY,CAChB,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAChC,MAAM,QAAQ;SACX;AACN,SAAO;;CAGT,MAAM,WAAY,KAAK,SAAuB,MAC3C,SAAwB,KAAc,SAAS,OACjD;AACD,KACE,CAAC,YACD,CAAC,SAAS,YACV,SAAS,SAAS,OAAO,WAAW,KAAA,KACpC,SAAS,SAAS,KAAK,WAAW,KAAA,EAElC,QAAO;AAET,QAAO;;AAGT,SAAS,gCACP,KACA,cACA,cACe;CACf,MAAM,UAAU,IAAI,MAAM;AAC1B,KAAI,CAAC,WAAW,oBAAoB,KAAK,QAAQ,CAC/C,QAAO;CAGT,MAAM,oBAAoB,IAAI,MAAM,OAAO,GAAG,MAAM;CACpD,MAAM,qBAAqB,IAAI,MAAM,OAAO,GAAG,MAAM;CACrD,MAAM,eAAe,QAAQ,WAAW,IAAI,GAAG,MAAM;CACrD,MAAM,WAAW,QAAQ,QAAQ,QAAQ,GAAG;CAC5C,MAAM,CAAC,cAAc,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M,IAAI;EAChG,SAAS;EACV;;AAGH,SAAS,kBAAkB,UAAkB,cAA4B;AACvE,KAAI,CAAC,aAAc,QAAO;AAC1B,QAAO,aAAa,IAAI,SAAS,IAAI,aAAa,IAAI,KAAK,QAAQ,SAAS,CAAC;;AAG/E,eAA8B,gCAC5B,UACA,cACA;AACA,KAAI,SAAS,cAAc,cAAc,CAAC,SAAS,MAAO;CAE1D,MAAM,cAAc,kBAClB,SAAS,MAAM,eACf,SAAS,MAAM,kBACf,SAAS,MAAM,kBAAkB,EAAE,EACnC,SAAS,MAAM,oBAAoB,EAAE,EACrC,SAAS,SACT,SAAS,cACV;CACD,MAAM,oBAAoB,CAAC,SAAS,eAAe,GAAG,SAAS,QAAQ;AAEvE,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,YAAY,CAO1D,OAAM,aANc,OAAO,OAAO,SAAS,CAAC,QACzC,cACE,SAAS,SAAS,MAAM,IAAI,SAAS,SAAS,OAAO,KACtD,kBAAkB,UAAU,aAAa,CAIhC,EACX,OAAO,aAAa;AAClB,MAAI,CAAC,GAAG,WAAW,SAAS,CAAE;EAG9B,MAAM,SAAS,yCACb,MAFoB,GAAG,SAAS,SAAS,UAAU,OAAO,EAG1D,QACA,kBACD;AACD,MAAI,OAAO,QACT,OAAM,GAAG,SAAS,UAAU,UAAU,OAAO,SAAS,OAAO;QAIlE"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createFileMapping } from "../formats/files/fileMapping.js";
|
|
2
2
|
import { parseMdxForRoundTrip, restoreAnchorIds } from "./mdxAnchorSyntax.js";
|
|
3
|
+
import { batchProcess } from "./batchProcess.js";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import * as fs$1 from "fs";
|
|
5
6
|
import { unified } from "unified";
|
|
@@ -106,20 +107,19 @@ async function localizeRelativeAssets(settings, targetLocales, includeFiles) {
|
|
|
106
107
|
const locales = targetLocales || settings.locales;
|
|
107
108
|
const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
|
|
108
109
|
const cwd = process.cwd();
|
|
109
|
-
const
|
|
110
|
+
const targetMappings = Object.entries(fileMapping).filter(([locale]) => locales.includes(locale));
|
|
111
|
+
for (const [, filesMap] of targetMappings) {
|
|
110
112
|
const reverseMap = /* @__PURE__ */ new Map();
|
|
111
113
|
for (const [sourcePath, targetPath] of Object.entries(filesMap)) reverseMap.set(targetPath, sourcePath);
|
|
112
|
-
|
|
113
|
-
await Promise.all(targetFiles.map(async (targetPath) => {
|
|
114
|
+
await batchProcess(Object.values(filesMap).filter((p) => (p.endsWith(".md") || p.endsWith(".mdx")) && (!includeFiles || includeFiles.has(p))), async (targetPath) => {
|
|
114
115
|
if (!fs$1.existsSync(targetPath)) return;
|
|
115
116
|
const sourcePath = reverseMap.get(targetPath);
|
|
116
117
|
if (!sourcePath) return;
|
|
117
118
|
if (!fs$1.existsSync(sourcePath)) return;
|
|
118
119
|
const result = localizeRelativeAssetsForContent(await fs$1.promises.readFile(targetPath, "utf8"), sourcePath, targetPath, cwd);
|
|
119
120
|
if (result.hasChanges) await fs$1.promises.writeFile(targetPath, result.content);
|
|
120
|
-
})
|
|
121
|
-
}
|
|
122
|
-
await Promise.all(processPromises);
|
|
121
|
+
}, 512);
|
|
122
|
+
}
|
|
123
123
|
}
|
|
124
124
|
//#endregion
|
|
125
125
|
export { localizeRelativeAssets as default, localizeRelativeAssetsForContent };
|