gt 2.26.9 → 2.26.11
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 +12 -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/formats/files/postprocess/keepUntranslatedPagePaths.js +4 -2
- package/dist/formats/files/postprocess/keepUntranslatedPagePaths.js.map +1 -1
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js +3 -2
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js.map +1 -1
- package/dist/fs/config/downloadedVersions.js +3 -2
- package/dist/fs/config/downloadedVersions.js.map +1 -1
- package/dist/fs/config/setupConfig.js +1 -1
- package/dist/fs/config/updateConfig.js +6 -4
- package/dist/fs/config/updateConfig.js.map +1 -1
- package/dist/fs/config/updateVersions.js +2 -1
- package/dist/fs/config/updateVersions.js.map +1 -1
- package/dist/fs/saveJSON.js +2 -1
- package/dist/fs/saveJSON.js.map +1 -1
- package/dist/fs/stringifyJson.d.ts +7 -0
- package/dist/fs/stringifyJson.js +15 -0
- package/dist/fs/stringifyJson.js.map +1 -0
- 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/credentials.js +1 -1
- package/dist/utils/flattenJsonFiles.js +4 -2
- package/dist/utils/flattenJsonFiles.js.map +1 -1
- package/dist/utils/gitDiff.js +1 -1
- package/dist/utils/packageJson.js +4 -1
- package/dist/utils/packageJson.js.map +1 -1
- package/dist/utils/processOpenApi.js +2 -1
- package/dist/utils/processOpenApi.js.map +1 -1
- package/dist/utils/splitMintlifyLanguageRefs.js +10 -3
- package/dist/utils/splitMintlifyLanguageRefs.js.map +1 -1
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# gtx-cli
|
|
2
2
|
|
|
3
|
+
## 2.26.11
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#2532](https://github.com/generaltranslation/gt/pull/2532) [`de29049`](https://github.com/generaltranslation/gt/commit/de29049fa16e7c4f60c4cf2baf1a83def5168479) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Keep the trailing newline of JSON files the CLI rewrites in place, such as `redirects.json`, `docs.json`, `gt.config.json`, and `package.json`, and end JSON files the CLI generates, such as `gt-lock.json`, with a newline
|
|
8
|
+
|
|
9
|
+
## 2.26.10
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#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`.
|
|
14
|
+
|
|
3
15
|
## 2.26.9
|
|
4
16
|
|
|
5
17
|
### 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,M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,cAAc,YAA8B,SAAwB;AAGlE,MAAI,KAAK,SAAS,CAAC,KAAK,iBACtB,QAAO,IAAI,YAAY,KAAK;AAE9B,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"}
|
|
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"],"mappings":";;;;;;;AAsBA,MAAM,iBAA2C;CAC/C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACR;AAID,MAAM,oBAA8B;AAIpC,SAAS,sBAAiC;CACxC,MAAM,KAAK,QAAQ,IAAI;AAEvB,QADa,CAAC,CAAC,MAAM,OAAO,WAAW,OAAO,OAC/B,CAAC,QAAQ,OAAO,QAAQ,UAAU;;AAInD,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,cAAc,IAAI,IAAI,KAAK,QAAQ,GAAG,KAAK,IAAI,GAAG;;CAGrE,QAAQ,SAAwB;AAC9B,MAAI,QACF,MAAK,OAAO,KAAK,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K,QAAQ;AAGlC,OAAK,YAAY,KAAK,QAAQ;;CAIhC,cAAc,YAA8B,SAAwB;AAGlE,MAAI,KAAK,SAAS,CAAC,KAAK,iBACtB,QAAO,IAAI,YAAY,KAAK;AAE9B,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,g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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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AAM,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,3 +1,4 @@
|
|
|
1
|
+
import { stringifyJson } from "../../../fs/stringifyJson.js";
|
|
1
2
|
import { getRelative } from "../../../fs/findFilepath.js";
|
|
2
3
|
import { api } from "../../../utils/api.js";
|
|
3
4
|
import { getConfiguredLocaleProperties } from "../../utils.js";
|
|
@@ -31,7 +32,8 @@ function keepUntranslatedPagePaths(settings, includeFiles) {
|
|
|
31
32
|
for (const filePath of settings.files.resolvedPaths.json ?? []) {
|
|
32
33
|
const schema = validateJsonSchema(options, filePath);
|
|
33
34
|
if (!schema?.composite || !isIncluded(filePath)) continue;
|
|
34
|
-
const
|
|
35
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
36
|
+
const json = JSON.parse(content);
|
|
35
37
|
const dir = path.dirname(filePath);
|
|
36
38
|
if (schema.structuralTransform) applyStructuralTransforms(json, schema.structuralTransform, schema.composite);
|
|
37
39
|
const localeKey = (locale) => options.experimentalCanonicalLocaleKeys ? api.resolveCanonicalLocale(locale) : locale;
|
|
@@ -52,7 +54,7 @@ function keepUntranslatedPagePaths(settings, includeFiles) {
|
|
|
52
54
|
}
|
|
53
55
|
if (changed) {
|
|
54
56
|
if (schema.structuralTransform) unapplyStructuralTransforms(json, schema.structuralTransform, schema.composite);
|
|
55
|
-
fs.writeFileSync(filePath,
|
|
57
|
+
fs.writeFileSync(filePath, stringifyJson(json, content));
|
|
56
58
|
}
|
|
57
59
|
}
|
|
58
60
|
const yamlSources = settings.files.resolvedPaths.yaml ?? [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keepUntranslatedPagePaths.js","names":[],"sources":["../../../../src/formats/files/postprocess/keepUntranslatedPagePaths.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport type { Settings, TransformOptions } from '../../../types/index.js';\nimport type { JSONValue } from '../../../types/data/json.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n} from '../../../utils/localizeStaticUrls.js';\nimport { getConfiguredLocaleProperties } from '../../utils.js';\nimport { getJSONPathMatches } from '../../json/jsonPath.js';\nimport {\n getJSONPointerValue,\n setJSONPointerValue,\n} from '../../json/jsonPointer.js';\nimport { transformValue } from '../../json/mergeJson.js';\nimport {\n applyStructuralTransforms,\n unapplyStructuralTransforms,\n} from '../../json/transformJson.js';\nimport { api } from '../../../utils/api.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../../json/utils.js';\nimport { validateYamlSchema } from '../../yaml/utils.js';\nimport { createFileMapping } from '../fileMapping.js';\n\n/**\n * With `skipUntranslatedPages`, undo `transform` rewrites that point a\n * localized JSON or YAML file (such as a docs navigation file) at a page that\n * was not translated. A value is restored to its source form when the source\n * value names an existing .md/.mdx page and the transformed value does not.\n * Values that are not page paths are left alone. Runs after all downloads, so\n * every translated page from this run is on disk.\n */\nexport function keepUntranslatedPagePaths(\n settings: Settings,\n includeFiles?: Set<string>\n): void {\n const options = settings.options;\n const localizeOptions = options?.experimentalLocalizeStaticUrls;\n if (\n !options ||\n typeof localizeOptions !== 'object' ||\n localizeOptions.skipUntranslatedPages !== true ||\n !settings.files\n ) {\n return;\n }\n const { defaultLocale } = settings;\n const targetLocales = settings.locales.filter((l) => l !== defaultLocale);\n const isIncluded = (filePath: string) =>\n !includeFiles ||\n includeFiles.has(filePath) ||\n includeFiles.has(getRelative(filePath));\n\n // Composite JSON: every locale's entry lives in the source file itself.\n for (const filePath of settings.files.resolvedPaths.json ?? []) {\n const schema = validateJsonSchema(options, filePath);\n if (!schema?.composite || !isIncluded(filePath)) continue;\n const json = JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONValue;\n const dir = path.dirname(filePath);\n // Match entries the way mergeJson wrote them: same structural transforms\n // and the same locale keys.\n if (schema.structuralTransform) {\n applyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n const localeKey = (locale: string) =>\n options.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n let changed = false;\n const sourceObjects = generateSourceObjectPointers(schema.composite, json);\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(sourceObjects)) {\n if (!sourceObjectOptions.transform) continue;\n // Every entry for a locale, in order. mergeJson builds one target entry\n // per default-locale entry in the same order, so they pair by position.\n const entriesFor = (locale: string): JSONValue[] => {\n if (Array.isArray(sourceObjectValue)) {\n return Object.values(\n findMatchingItemArray(\n localeKey(locale),\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n )\n )\n .sort((a, b) => a.index - b.index)\n .map(({ sourceItem }) => sourceItem);\n }\n const { sourceItem } = findMatchingItemObject(\n localeKey(locale),\n pointer,\n sourceObjectOptions,\n sourceObjectValue as Record<string, JSONValue>\n );\n return sourceItem === undefined ? [] : [sourceItem];\n };\n const sources = entriesFor(defaultLocale);\n for (const locale of targetLocales) {\n entriesFor(locale).forEach((target, i) => {\n if (sources[i] === undefined) return;\n changed =\n restorePagePaths(\n sources[i],\n target,\n sourceObjectOptions.transform!,\n locale,\n defaultLocale,\n dir,\n dir\n ) || changed;\n });\n }\n }\n if (changed) {\n if (schema.structuralTransform) {\n unapplyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n fs.writeFileSync(filePath, JSON.stringify(json, null, 2));\n }\n }\n\n // YAML: each locale has its own output file, mapped from the source file.\n const yamlSources = settings.files.resolvedPaths.yaml ?? [];\n if (!yamlSources.length) return;\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n defaultLocale\n );\n for (const filePath of yamlSources) {\n const schema = validateYamlSchema(options, filePath);\n if (!schema?.transform) continue;\n const source = YAML.parse(fs.readFileSync(filePath, 'utf8')) as JSONValue;\n for (const locale of targetLocales) {\n const outputPath = fileMapping[locale]?.[getRelative(filePath)];\n if (!outputPath || !fs.existsSync(outputPath) || !isIncluded(outputPath))\n continue;\n const target = YAML.parse(\n fs.readFileSync(outputPath, 'utf8')\n ) as JSONValue;\n const restored = restorePagePaths(\n source,\n target,\n schema.transform,\n locale,\n defaultLocale,\n path.dirname(filePath),\n path.dirname(outputPath)\n );\n if (restored) fs.writeFileSync(outputPath, YAML.stringify(target));\n }\n }\n}\n\n/**\n * For each value a transform produced in `target` from the value at the same\n * position in `source`, restore the source page path when the transformed\n * page does not exist. Returns whether anything changed.\n */\nfunction restorePagePaths(\n source: JSONValue,\n target: JSONValue,\n transform: TransformOptions,\n locale: string,\n defaultLocale: string,\n sourceDir: string,\n targetDir: string\n): boolean {\n const targetLocaleProperties = getConfiguredLocaleProperties(locale);\n const defaultLocaleProperties = getConfiguredLocaleProperties(defaultLocale);\n let changed = false;\n for (const [transformPath, transformOption] of Object.entries(transform)) {\n for (const match of getJSONPathMatches(source, transformPath) ?? []) {\n if (typeof match.value !== 'string') continue;\n const transformed = transformValue(\n match.value,\n transformOption,\n targetLocaleProperties,\n defaultLocaleProperties\n );\n if (\n transformed === match.value ||\n getJSONPointerValue(target, match.pointer) !== transformed ||\n pageExists(transformed, targetDir) ||\n !pageExists(match.value, sourceDir)\n ) {\n continue;\n }\n const restored =\n sourceDir === targetDir\n ? match.value\n : path\n .relative(targetDir, path.join(sourceDir, match.value))\n .split(path.sep)\n .join('/');\n setJSONPointerValue(target, match.pointer, restored);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Whether a path value names an .md/.mdx page, with or without extension. An\n * empty value or one ending in `/` names a folder's index page\n */\nfunction pageExists(value: string, dir: string): boolean {\n const filePath = path.join(dir, value);\n if (value === '' || value.endsWith('/')) {\n return PAGE_EXTENSIONS.some((ext) =>\n fs.existsSync(path.join(filePath, `${INDEX_PAGE}${ext}`))\n );\n }\n if (PAGE_EXTENSIONS.includes(path.extname(filePath))) {\n return fs.existsSync(filePath);\n }\n return PAGE_EXTENSIONS.some((ext) => fs.existsSync(`${filePath}${ext}`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,0BACd,UACA,cACM;CACN,MAAM,UAAU,SAAS;CACzB,MAAM,kBAAkB,SAAS;AACjC,KACE,CAAC,WACD,OAAO,oBAAoB,YAC3B,gBAAgB,0BAA0B,QAC1C,CAAC,SAAS,MAEV;CAEF,MAAM,EAAE,kBAAkB;CAC1B,MAAM,gBAAgB,SAAS,QAAQ,QAAQ,MAAM,MAAM,cAAc;CACzE,MAAM,cAAc,aAClB,CAAC,gBACD,aAAa,IAAI,SAAS,IAC1B,aAAa,IAAI,YAAY,SAAS,CAAC;AAGzC,MAAK,MAAM,YAAY,SAAS,MAAM,cAAc,QAAQ,EAAE,EAAE;EAC9D,MAAM,SAAS,mBAAmB,SAAS,SAAS;AACpD,MAAI,CAAC,QAAQ,aAAa,CAAC,WAAW,SAAS,CAAE;EACjD,MAAM,OAAO,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;EAC1D,MAAM,MAAM,KAAK,QAAQ,SAAS;AAGlC,MAAI,OAAO,oBACT,2BACE,MACA,OAAO,qBACP,OAAO,UACR;EAEH,MAAM,aAAa,WACjB,QAAQ,kCACJ,IAAI,uBAAuB,OAAO,GAClC;EACN,IAAI,UAAU;EACd,MAAM,gBAAgB,6BAA6B,OAAO,WAAW,KAAK;AAC1E,OAAK,MAAM,CACT,SACA,EA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AEhC,QAAO,gBAAgB,MAAM,QAAQ,GAAG,WAAW,GAAG,WAAW,MAAM,CAAC"}
|
|
1
|
+
{"version":3,"file":"keepUntranslatedPagePaths.js","names":[],"sources":["../../../../src/formats/files/postprocess/keepUntranslatedPagePaths.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport type { Settings, TransformOptions } from '../../../types/index.js';\nimport type { JSONValue } from '../../../types/data/json.js';\nimport { stringifyJson } from '../../../fs/stringifyJson.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n} from '../../../utils/localizeStaticUrls.js';\nimport { getConfiguredLocaleProperties } from '../../utils.js';\nimport { getJSONPathMatches } from '../../json/jsonPath.js';\nimport {\n getJSONPointerValue,\n setJSONPointerValue,\n} from '../../json/jsonPointer.js';\nimport { transformValue } from '../../json/mergeJson.js';\nimport {\n applyStructuralTransforms,\n unapplyStructuralTransforms,\n} from '../../json/transformJson.js';\nimport { api } from '../../../utils/api.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../../json/utils.js';\nimport { validateYamlSchema } from '../../yaml/utils.js';\nimport { createFileMapping } from '../fileMapping.js';\n\n/**\n * With `skipUntranslatedPages`, undo `transform` rewrites that point a\n * localized JSON or YAML file (such as a docs navigation file) at a page that\n * was not translated. A value is restored to its source form when the source\n * value names an existing .md/.mdx page and the transformed value does not.\n * Values that are not page paths are left alone. Runs after all downloads, so\n * every translated page from this run is on disk.\n */\nexport function keepUntranslatedPagePaths(\n settings: Settings,\n includeFiles?: Set<string>\n): void {\n const options = settings.options;\n const localizeOptions = options?.experimentalLocalizeStaticUrls;\n if (\n !options ||\n typeof localizeOptions !== 'object' ||\n localizeOptions.skipUntranslatedPages !== true ||\n !settings.files\n ) {\n return;\n }\n const { defaultLocale } = settings;\n const targetLocales = settings.locales.filter((l) => l !== defaultLocale);\n const isIncluded = (filePath: string) =>\n !includeFiles ||\n includeFiles.has(filePath) ||\n includeFiles.has(getRelative(filePath));\n\n // Composite JSON: every locale's entry lives in the source file itself.\n for (const filePath of settings.files.resolvedPaths.json ?? []) {\n const schema = validateJsonSchema(options, filePath);\n if (!schema?.composite || !isIncluded(filePath)) continue;\n const content = fs.readFileSync(filePath, 'utf8');\n const json = JSON.parse(content) as JSONValue;\n const dir = path.dirname(filePath);\n // Match entries the way mergeJson wrote them: same structural transforms\n // and the same locale keys.\n if (schema.structuralTransform) {\n applyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n const localeKey = (locale: string) =>\n options.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n let changed = false;\n const sourceObjects = generateSourceObjectPointers(schema.composite, json);\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(sourceObjects)) {\n if (!sourceObjectOptions.transform) continue;\n // Every entry for a locale, in order. mergeJson builds one target entry\n // per default-locale entry in the same order, so they pair by position.\n const entriesFor = (locale: string): JSONValue[] => {\n if (Array.isArray(sourceObjectValue)) {\n return Object.values(\n findMatchingItemArray(\n localeKey(locale),\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n )\n )\n .sort((a, b) => a.index - b.index)\n .map(({ sourceItem }) => sourceItem);\n }\n const { sourceItem } = findMatchingItemObject(\n localeKey(locale),\n pointer,\n sourceObjectOptions,\n sourceObjectValue as Record<string, JSONValue>\n );\n return sourceItem === undefined ? [] : [sourceItem];\n };\n const sources = entriesFor(defaultLocale);\n for (const locale of targetLocales) {\n entriesFor(locale).forEach((target, i) => {\n if (sources[i] === undefined) return;\n changed =\n restorePagePaths(\n sources[i],\n target,\n sourceObjectOptions.transform!,\n locale,\n defaultLocale,\n dir,\n dir\n ) || changed;\n });\n }\n }\n if (changed) {\n if (schema.structuralTransform) {\n unapplyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n fs.writeFileSync(filePath, stringifyJson(json, content));\n }\n }\n\n // YAML: each locale has its own output file, mapped from the source file.\n const yamlSources = settings.files.resolvedPaths.yaml ?? [];\n if (!yamlSources.length) return;\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n defaultLocale\n );\n for (const filePath of yamlSources) {\n const schema = validateYamlSchema(options, filePath);\n if (!schema?.transform) continue;\n const source = YAML.parse(fs.readFileSync(filePath, 'utf8')) as JSONValue;\n for (const locale of targetLocales) {\n const outputPath = fileMapping[locale]?.[getRelative(filePath)];\n if (!outputPath || !fs.existsSync(outputPath) || !isIncluded(outputPath))\n continue;\n const target = YAML.parse(\n fs.readFileSync(outputPath, 'utf8')\n ) as JSONValue;\n const restored = restorePagePaths(\n source,\n target,\n schema.transform,\n locale,\n defaultLocale,\n path.dirname(filePath),\n path.dirname(outputPath)\n );\n if (restored) fs.writeFileSync(outputPath, YAML.stringify(target));\n }\n }\n}\n\n/**\n * For each value a transform produced in `target` from the value at the same\n * position in `source`, restore the source page path when the transformed\n * page does not exist. Returns whether anything changed.\n */\nfunction restorePagePaths(\n source: JSONValue,\n target: JSONValue,\n transform: TransformOptions,\n locale: string,\n defaultLocale: string,\n sourceDir: string,\n targetDir: string\n): boolean {\n const targetLocaleProperties = getConfiguredLocaleProperties(locale);\n const defaultLocaleProperties = getConfiguredLocaleProperties(defaultLocale);\n let changed = false;\n for (const [transformPath, transformOption] of Object.entries(transform)) {\n for (const match of getJSONPathMatches(source, transformPath) ?? []) {\n if (typeof match.value !== 'string') continue;\n const transformed = transformValue(\n match.value,\n transformOption,\n targetLocaleProperties,\n defaultLocaleProperties\n );\n if (\n transformed === match.value ||\n getJSONPointerValue(target, match.pointer) !== transformed ||\n pageExists(transformed, targetDir) ||\n !pageExists(match.value, sourceDir)\n ) {\n continue;\n }\n const restored =\n sourceDir === targetDir\n ? match.value\n : path\n .relative(targetDir, path.join(sourceDir, match.value))\n .split(path.sep)\n .join('/');\n setJSONPointerValue(target, match.pointer, restored);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Whether a path value names an .md/.mdx page, with or without extension. An\n * empty value or one ending in `/` names a folder's index page\n */\nfunction pageExists(value: string, dir: string): boolean {\n const filePath = path.join(dir, value);\n if (value === '' || value.endsWith('/')) {\n return PAGE_EXTENSIONS.some((ext) =>\n fs.existsSync(path.join(filePath, `${INDEX_PAGE}${ext}`))\n );\n }\n if (PAGE_EXTENSIONS.includes(path.extname(filePath))) {\n return fs.existsSync(filePath);\n }\n return PAGE_EXTENSIONS.some((ext) => fs.existsSync(`${filePath}${ext}`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,0BACd,UACA,cACM;CACN,MAAM,UAAU,SAAS;CACzB,MAAM,kBAAkB,SAAS;AACjC,KACE,CAAC,WACD,OAAO,oBAAoB,YAC3B,gBAAgB,0BAA0B,QAC1C,CAAC,SAAS,MAEV;CAEF,MAAM,EAAE,kBAAkB;CAC1B,MAAM,gBAAgB,SAAS,QAAQ,QAAQ,MAAM,MAAM,cAAc;CACzE,MAAM,cAAc,aAClB,CAAC,gBACD,aAAa,IAAI,SAAS,IAC1B,aAAa,IAAI,YAAY,SAAS,CAAC;AAGzC,MAAK,MAAM,YAAY,SAAS,MAAM,cAAc,QAAQ,EAAE,EAAE;EAC9D,MAAM,SAAS,mBAAmB,SAAS,SAAS;AACpD,MAAI,CAAC,QAAQ,aAAa,CAAC,WAAW,SAAS,CAAE;EACjD,MAAM,UAAU,GAAG,aAAa,UAAU,OAAO;EACjD,MAAM,OAAO,KAAK,MAAM,QAAQ;EAChC,MAAM,MAAM,KAAK,QAAQ,SAAS;AAGlC,MAAI,OAAO,oBACT,2BACE,MACA,OAAO,qBACP,OAAO,UACR;EAEH,MAAM,aAAa,WACjB,QAAQ,kCACJ,IAAI,uBAAuB,OAAO,GAClC;EACN,IAAI,UAAU;EACd,MAAM,gBAAgB,6BA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SAAS,CAAC,CAClD,QAAO,GAAG,WAAW,SAAS;AAEhC,QAAO,gBAAgB,MAAM,QAAQ,GAAG,WAAW,GAAG,WAAW,MAAM,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { logger } from "../../../console/logger.js";
|
|
2
|
+
import { stringifyJson } from "../../../fs/stringifyJson.js";
|
|
2
3
|
import { getRelative } from "../../../fs/findFilepath.js";
|
|
3
4
|
import loadJSON from "../../../fs/loadJSON.js";
|
|
4
5
|
import { createFileMapping } from "../fileMapping.js";
|
|
@@ -118,10 +119,10 @@ function readRedirects(docsJsonPath) {
|
|
|
118
119
|
const redirectsFile = holder;
|
|
119
120
|
return {
|
|
120
121
|
redirects: value,
|
|
121
|
-
write: (updated) => fs.writeFileSync(redirectsFile,
|
|
122
|
+
write: (updated) => fs.writeFileSync(redirectsFile, stringifyJson(redirectsFile === docsJsonPath ? {
|
|
122
123
|
...docsJson,
|
|
123
124
|
redirects: updated
|
|
124
|
-
} : updated,
|
|
125
|
+
} : updated, fs.readFileSync(redirectsFile, "utf-8")))
|
|
125
126
|
};
|
|
126
127
|
}
|
|
127
128
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localizeMintlifyRedirects.js","names":[],"sources":["../../../../src/formats/files/postprocess/localizeMintlifyRedirects.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { logger } from '../../../console/logger.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport loadJSON from '../../../fs/loadJSON.js';\nimport type { Settings } from '../../../types/index.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n findPatternHead,\n getPatternHeads,\n transformUrlPath,\n translationMissing,\n} from '../../../utils/localizeStaticUrls.js';\nimport { createFileMapping } from '../fileMapping.js';\n\ntype Redirect = { source: string; destination: string; permanent?: unknown };\n\nconst missingDocsUrlPatternWarning = createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: 'Localized redirects were not added',\n why: 'options.mintlify.localizeRedirects uses options.docsUrlPattern to place the locale in redirect URLs',\n fix: 'Set options.docsUrlPattern in gt.config.json, such as \"/docs/[locale]\"',\n});\n\n/**\n * Adds localized copies of the English redirects whose source is a renamed or\n * removed page, and returns the redirects it added. Orphaned file names come\n * from the upload step, so redirects for pages GT never translated are never\n * localized. URLs are localized like links inside\n * pages: with docsUrlPattern, and not for locales missing the destination's\n * translation.\n */\nexport function localizeMintlifyRedirects(\n settings: Settings,\n orphanedFileNames: string[]\n): Redirect[] {\n if (\n settings.options?.mintlify?.localizeRedirects !== true ||\n !settings.files\n ) {\n return [];\n }\n const urlPattern = settings.options.docsUrlPattern;\n if (!urlPattern || urlPattern.length === 0) {\n logger.warn(missingDocsUrlPatternWarning);\n return [];\n }\n const location = readRedirects(path.resolve('docs.json'));\n if (!location) return [];\n\n const oldPageUrls = new Set(\n orphanedFileNames\n .filter((fileName) => PAGE_EXTENSIONS.includes(path.extname(fileName)))\n .map(pageUrl)\n );\n\n const targetLocales = settings.locales.filter(\n (locale) => locale !== settings.defaultLocale\n );\n const { files } = settings;\n const fileMapping = createFileMapping(\n files.resolvedPaths,\n files.placeholderPaths,\n files.transformPaths,\n files.transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n // Localize URLs the way links inside pages are localized\n const urlPatternHeads = getPatternHeads(urlPattern);\n const localizeUrl = (url: string, locale: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return null;\n const localized = transformUrlPath(\n url,\n urlPatternHead,\n locale,\n settings.defaultLocale,\n settings.options?.experimentalHideDefaultLocale ?? false\n );\n return localized === null ? null : normalizeUrl(localized);\n };\n // Translated pages can be orphaned too, so their redirects are already\n // localized. Localizing them again would nest locales (/docs/ja-jp/fr-ca/...)\n const isLocalized = (url: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return false;\n const localeSegmentIndex = urlPatternHead.split('/').filter(Boolean).length;\n return targetLocales.includes(\n url.split('/').filter(Boolean)[localeSegmentIndex]\n );\n };\n const takenSources = new Set(\n location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source))\n );\n\n const added: Redirect[] = [];\n const updated = location.redirects.flatMap((entry) => {\n if (!isRedirect(entry)) return [entry];\n const [destinationPath, anchor] = splitAnchor(entry.destination);\n const sourceUrl = normalizeUrl(entry.source);\n const destinationUrl = normalizeUrl(destinationPath);\n if (\n !oldPageUrls.has(sourceUrl) ||\n isLocalized(sourceUrl) ||\n isLocalized(destinationUrl)\n ) {\n return [entry];\n }\n\n const localized: Redirect[] = [];\n for (const locale of targetLocales) {\n const localizedSource = localizeUrl(sourceUrl, locale);\n const localizedDestination = localizeUrl(destinationUrl, locale);\n if (\n !localizedSource ||\n !localizedDestination ||\n localizedSource === localizedDestination ||\n takenSources.has(localizedSource) ||\n translationMissing(\n destinationUrl,\n localizedDestination,\n fileMapping[locale] ?? {}\n )\n ) {\n continue;\n }\n takenSources.add(localizedSource);\n localized.push({\n source: localizedSource,\n destination: `${localizedDestination}${anchor}`,\n ...('permanent' in entry && { permanent: entry.permanent }),\n });\n }\n added.push(...localized);\n return [entry, ...localized];\n });\n\n if (added.length > 0) location.write(updated);\n return added;\n}\n\nfunction isRedirect(entry: unknown): entry is Redirect {\n return (\n typeof (entry as Redirect)?.source === 'string' &&\n typeof (entry as Redirect)?.destination === 'string'\n );\n}\n\n/** Splits `/docs/page#section` into `/docs/page` and `#section`. */\nfunction splitAnchor(url: string): [string, string] {\n const anchorStart = url.indexOf('#');\n return anchorStart === -1\n ? [url, '']\n : [url.slice(0, anchorStart), url.slice(anchorStart)];\n}\n\n/**\n * The URL of a page file: its path without the extension. Like static URL\n * localization, URLs are relative to the working directory.\n */\nfunction pageUrl(fileName: string): string {\n const relative = getRelative(fileName);\n return normalizeUrl(\n relative\n .slice(0, relative.length - path.extname(relative).length)\n .split(path.sep)\n .join('/')\n );\n}\n\n/**\n * Leading slash, no trailing slash, and index pages named by their folder, so\n * equivalent spellings compare equal.\n */\nfunction normalizeUrl(url: string): string {\n const segments = url.split('/').filter(Boolean);\n if (segments.at(-1) === INDEX_PAGE) segments.pop();\n return `/${segments.join('/')}`;\n}\n\n/**\n * Finds the redirects array in docs.json, either inline or at the end of its\n * `$ref` chain, and returns a writer for the file that holds it.\n */\nfunction readRedirects(\n docsJsonPath: string\n): { redirects: unknown[]; write: (redirects: unknown[]) => void } | null {\n const docsJson = loadJSON(docsJsonPath);\n let holder = docsJsonPath;\n let value: unknown = docsJson?.redirects;\n const visited = new Set([holder]);\n while (typeof (value as { $ref?: unknown })?.$ref === 'string') {\n holder = path.resolve(\n path.dirname(holder),\n (value as { $ref: string }).$ref\n );\n if (visited.has(holder)) return null;\n visited.add(holder);\n value = loadJSON(holder);\n }\n if (!Array.isArray(value)) return null;\n\n const redirectsFile = holder;\n return {\n redirects: value,\n write: (updated) =>\n fs.writeFileSync(\n redirectsFile,\n JSON.stringify(\n redirectsFile === docsJsonPath\n ? { ...docsJson, redirects: updated }\n : updated,\n null,\n 2\n )\n ),\n };\n}\n"],"mappings":";;;;;;;;;AAmBA,MAAM,+BAA+B,wBAAwB;CAC3D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;;;;;;;;;AAUF,SAAgB,0BACd,UACA,mBACY;AACZ,KACE,SAAS,SAAS,UAAU,sBAAsB,QAClD,CAAC,SAAS,MAEV,QAAO,EAAE;CAEX,MAAM,aAAa,SAAS,QAAQ;AACpC,KAAI,CAAC,cAAc,WAAW,WAAW,GAAG;AAC1C,SAAO,KAAK,6BAA6B;AACzC,SAAO,EAAE;;CAEX,MAAM,WAAW,cAAc,KAAK,QAAQ,YAAY,CAAC;AACzD,KAAI,CAAC,SAAU,QAAO,EAAE;CAExB,MAAM,cAAc,IAAI,IACtB,kBACG,QAAQ,aAAa,gBAAgB,SAAS,KAAK,QAAQ,SAAS,CAA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AI,IAAI,CAAC,OAAO,CAAC;AACjC,QAAO,OAAQ,OAA8B,SAAS,UAAU;AAC9D,WAAS,KAAK,QACZ,KAAK,QAAQ,OAAO,EACnB,MAA2B,KAC7B;AACD,MAAI,QAAQ,IAAI,OAAO,CAAE,QAAO;AAChC,UAAQ,IAAI,OAAO;AACnB,UAAQ,SAAS,OAAO;;AAE1B,KAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO;CAElC,MAAM,gBAAgB;AACtB,QAAO;EACL,WAAW;EACX,QAAQ,YACN,GAAG,cACD,eACA,KAAK,UACH,kBAAkB,eACd;GAAE,GAAG;GAAU,WAAW;GAAS,GACnC,SACJ,MACA,EACD,CACF;EACJ"}
|
|
1
|
+
{"version":3,"file":"localizeMintlifyRedirects.js","names":[],"sources":["../../../../src/formats/files/postprocess/localizeMintlifyRedirects.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { logger } from '../../../console/logger.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport loadJSON from '../../../fs/loadJSON.js';\nimport { stringifyJson } from '../../../fs/stringifyJson.js';\nimport type { Settings } from '../../../types/index.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n findPatternHead,\n getPatternHeads,\n transformUrlPath,\n translationMissing,\n} from '../../../utils/localizeStaticUrls.js';\nimport { createFileMapping } from '../fileMapping.js';\n\ntype Redirect = { source: string; destination: string; permanent?: unknown };\n\nconst missingDocsUrlPatternWarning = createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: 'Localized redirects were not added',\n why: 'options.mintlify.localizeRedirects uses options.docsUrlPattern to place the locale in redirect URLs',\n fix: 'Set options.docsUrlPattern in gt.config.json, such as \"/docs/[locale]\"',\n});\n\n/**\n * Adds localized copies of the English redirects whose source is a renamed or\n * removed page, and returns the redirects it added. Orphaned file names come\n * from the upload step, so redirects for pages GT never translated are never\n * localized. URLs are localized like links inside\n * pages: with docsUrlPattern, and not for locales missing the destination's\n * translation.\n */\nexport function localizeMintlifyRedirects(\n settings: Settings,\n orphanedFileNames: string[]\n): Redirect[] {\n if (\n settings.options?.mintlify?.localizeRedirects !== true ||\n !settings.files\n ) {\n return [];\n }\n const urlPattern = settings.options.docsUrlPattern;\n if (!urlPattern || urlPattern.length === 0) {\n logger.warn(missingDocsUrlPatternWarning);\n return [];\n }\n const location = readRedirects(path.resolve('docs.json'));\n if (!location) return [];\n\n const oldPageUrls = new Set(\n orphanedFileNames\n .filter((fileName) => PAGE_EXTENSIONS.includes(path.extname(fileName)))\n .map(pageUrl)\n );\n\n const targetLocales = settings.locales.filter(\n (locale) => locale !== settings.defaultLocale\n );\n const { files } = settings;\n const fileMapping = createFileMapping(\n files.resolvedPaths,\n files.placeholderPaths,\n files.transformPaths,\n files.transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n // Localize URLs the way links inside pages are localized\n const urlPatternHeads = getPatternHeads(urlPattern);\n const localizeUrl = (url: string, locale: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return null;\n const localized = transformUrlPath(\n url,\n urlPatternHead,\n locale,\n settings.defaultLocale,\n settings.options?.experimentalHideDefaultLocale ?? false\n );\n return localized === null ? null : normalizeUrl(localized);\n };\n // Translated pages can be orphaned too, so their redirects are already\n // localized. Localizing them again would nest locales (/docs/ja-jp/fr-ca/...)\n const isLocalized = (url: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return false;\n const localeSegmentIndex = urlPatternHead.split('/').filter(Boolean).length;\n return targetLocales.includes(\n url.split('/').filter(Boolean)[localeSegmentIndex]\n );\n };\n const takenSources = new Set(\n location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source))\n );\n\n const added: Redirect[] = [];\n const updated = location.redirects.flatMap((entry) => {\n if (!isRedirect(entry)) return [entry];\n const [destinationPath, anchor] = splitAnchor(entry.destination);\n const sourceUrl = normalizeUrl(entry.source);\n const destinationUrl = normalizeUrl(destinationPath);\n if (\n !oldPageUrls.has(sourceUrl) ||\n isLocalized(sourceUrl) ||\n isLocalized(destinationUrl)\n ) {\n return [entry];\n }\n\n const localized: Redirect[] = [];\n for (const locale of targetLocales) {\n const localizedSource = localizeUrl(sourceUrl, locale);\n const localizedDestination = localizeUrl(destinationUrl, locale);\n if (\n !localizedSource ||\n !localizedDestination ||\n localizedSource === localizedDestination ||\n takenSources.has(localizedSource) ||\n translationMissing(\n destinationUrl,\n localizedDestination,\n fileMapping[locale] ?? {}\n )\n ) {\n continue;\n }\n takenSources.add(localizedSource);\n localized.push({\n source: localizedSource,\n destination: `${localizedDestination}${anchor}`,\n ...('permanent' in entry && { permanent: entry.permanent }),\n });\n }\n added.push(...localized);\n return [entry, ...localized];\n });\n\n if (added.length > 0) location.write(updated);\n return added;\n}\n\nfunction isRedirect(entry: unknown): entry is Redirect {\n return (\n typeof (entry as Redirect)?.source === 'string' &&\n typeof (entry as Redirect)?.destination === 'string'\n );\n}\n\n/** Splits `/docs/page#section` into `/docs/page` and `#section`. */\nfunction splitAnchor(url: string): [string, string] {\n const anchorStart = url.indexOf('#');\n return anchorStart === -1\n ? [url, '']\n : [url.slice(0, anchorStart), url.slice(anchorStart)];\n}\n\n/**\n * The URL of a page file: its path without the extension. Like static URL\n * localization, URLs are relative to the working directory.\n */\nfunction pageUrl(fileName: string): string {\n const relative = getRelative(fileName);\n return normalizeUrl(\n relative\n .slice(0, relative.length - path.extname(relative).length)\n .split(path.sep)\n .join('/')\n );\n}\n\n/**\n * Leading slash, no trailing slash, and index pages named by their folder, so\n * equivalent spellings compare equal.\n */\nfunction normalizeUrl(url: string): string {\n const segments = url.split('/').filter(Boolean);\n if (segments.at(-1) === INDEX_PAGE) segments.pop();\n return `/${segments.join('/')}`;\n}\n\n/**\n * Finds the redirects array in docs.json, either inline or at the end of its\n * `$ref` chain, and returns a writer for the file that holds it.\n */\nfunction readRedirects(\n docsJsonPath: string\n): { redirects: unknown[]; write: (redirects: unknown[]) => void } | null {\n const docsJson = loadJSON(docsJsonPath);\n let holder = docsJsonPath;\n let value: unknown = docsJson?.redirects;\n const visited = new Set([holder]);\n while (typeof (value as { $ref?: unknown })?.$ref === 'string') {\n holder = path.resolve(\n path.dirname(holder),\n (value as { $ref: string }).$ref\n );\n if (visited.has(holder)) return null;\n visited.add(holder);\n value = loadJSON(holder);\n }\n if (!Array.isArray(value)) return null;\n\n const redirectsFile = holder;\n return {\n redirects: value,\n write: (updated) =>\n fs.writeFileSync(\n redirectsFile,\n stringifyJson(\n redirectsFile === docsJsonPath\n ? { ...docsJson, redirects: updated }\n : updated,\n fs.readFileSync(redirectsFile, 'utf-8')\n )\n ),\n };\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,+BAA+B,wBAAwB;CAC3D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;;;;;;;;;AAUF,SAAgB,0BACd,UACA,mBACY;AACZ,KACE,SAAS,SAAS,UAAU,sBAAsB,QAClD,CAAC,SAAS,MAEV,QAAO,EAAE;CAEX,MAAM,aAAa,SAAS,QAAQ;AACpC,KAAI,CAAC,cAAc,WAAW,WAAW,GAAG;AAC1C,SAAO,KAAK,6BAA6B;AACzC,SAAO,EAAE;;CAEX,MAAM,WAAW,cAAc,KAAK,QAAQ,YAAY,CAAC;AACzD,KAAI,CAAC,SAAU,QAAO,EAAE;CAExB,MAAM,cAAc,IAAI,IACtB,kBACG,QAAQ,aAAa,gBAAgB,SAAS,KAAK,QAAQ,SAAS,CAAC,CAAC,CACtE,IAAI,QAAQ,CAChB;CAED,MAAM,gBAAgB,SAAS,QAAQ,QACpC,WAAW,WAAW,SAAS,cACjC;CACD,MAAM,EAAE,UAAU;CAClB,MAAM,cAAc,kBAClB,MAAM,eACN,MAAM,kBACN,MAAM,gBACN,MAAM,kBACN,eACA,SAAS,cACV;CAED,MAAM,kBAAkB,gBAAgB,WAAW;C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C,MAAM,QAAQ,MAAM,CAAE,QAAO;CAElC,MAAM,gBAAgB;AACtB,QAAO;EACL,WAAW;EACX,QAAQ,YACN,GAAG,cACD,eACA,cACE,kBAAkB,eACd;GAAE,GAAG;GAAU,WAAW;GAAS,GACnC,SACJ,GAAG,aAAa,eAAe,QAAQ,CACxC,CACF;EACJ"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { logger } from "../../console/logger.js";
|
|
2
|
+
import { stringifyJson } from "../stringifyJson.js";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import fs from "node:fs";
|
|
4
5
|
//#region src/fs/config/downloadedVersions.ts
|
|
@@ -119,8 +120,8 @@ function writeLockfile(data, originalV1) {
|
|
|
119
120
|
[data.branchId]: convertV2ToV1Branch(data)
|
|
120
121
|
}
|
|
121
122
|
};
|
|
122
|
-
fs.writeFileSync(filepath,
|
|
123
|
-
} else fs.writeFileSync(filepath,
|
|
123
|
+
fs.writeFileSync(filepath, stringifyJson(mergedV1));
|
|
124
|
+
} else fs.writeFileSync(filepath, stringifyJson(data));
|
|
124
125
|
} catch (error) {
|
|
125
126
|
logger.error(`An error occurred while updating ${GT_LOCK_FILE}: ${error}`);
|
|
126
127
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"downloadedVersions.js","names":[],"sources":["../../../src/fs/config/downloadedVersions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../../console/logger.js';\nimport type { Settings } from '../../types/index.js';\n\nconst GT_LOCK_FILE = 'gt-lock.json';\n\n// ── V2 types (internal working format) ──────────────────────────────\n\nexport type DownloadedTranslation = {\n updatedAt?: string;\n postProcessHash?: string;\n fileName?: string; // output path for this locale, e.g. \"es-US/my/file/path.mdx\"\n};\n\nexport type DownloadedVersionEntry = {\n fileId: string;\n versionId: string;\n fileName?: string; // source file path\n staged?: boolean; // true if this entry was staged but not yet downloaded\n translations: {\n [locale: string]: DownloadedTranslation;\n };\n};\n\nexport type DownloadedVersions = {\n version: 2;\n branchId: string;\n entries: DownloadedVersionEntry[];\n};\n\n// ── V1 types (backwards compatibility) ──────────────────────────────\n\nexport type DownloadedVersionEntryV1 = {\n fileName?: string;\n updatedAt?: string;\n postProcessHash?: string;\n sourceHash?: string;\n};\n\nexport type DownloadedVersionsV1 = {\n version: number;\n entries: {\n [branchId: string]: {\n [fileId: string]: {\n [versionId: string]: { [locale: string]: DownloadedVersionEntryV1 };\n };\n };\n };\n};\n\n// ── Conversion helpers ──────────────────────────────────────────────\n\nfunction convertV1ToV2(\n v1: DownloadedVersionsV1,\n branchId: string\n): DownloadedVersions {\n const branchEntries = v1.entries?.[branchId];\n if (!branchEntries) {\n return { version: 2, branchId, entries: [] };\n }\n\n const entries: DownloadedVersionEntry[] = [];\n\n for (const [fileId, versions] of Object.entries(branchEntries)) {\n const versionIds = Object.keys(versions);\n if (versionIds.length === 0) continue;\n\n // Pick the versionId with the most recent updatedAt, defaulting to the first\n let latestVersionId = versionIds[0];\n let latestTime = 0;\n\n for (const [versionId, locales] of Object.entries(versions)) {\n for (const entry of Object.values(locales)) {\n const t = entry.updatedAt ? Date.parse(entry.updatedAt) : 0;\n if (t > latestTime) {\n latestTime = t;\n latestVersionId = versionId;\n }\n }\n }\n\n const localeEntries = versions[latestVersionId];\n const translations: { [locale: string]: DownloadedTranslation } = {};\n\n for (const [locale, entry] of Object.entries(localeEntries)) {\n translations[locale] = {\n ...(entry.updatedAt ? { updatedAt: entry.updatedAt } : {}),\n ...(entry.postProcessHash\n ? { postProcessHash: entry.postProcessHash }\n : {}),\n };\n }\n\n entries.push({\n fileId,\n versionId: latestVersionId,\n translations,\n });\n }\n\n return { version: 2, branchId, entries };\n}\n\nfunction convertV2ToV1Branch(\n v2: DownloadedVersions\n): DownloadedVersionsV1['entries'][string] {\n const branch: DownloadedVersionsV1['entries'][string] = {};\n\n for (const entry of v2.entries) {\n if (!branch[entry.fileId]) {\n branch[entry.fileId] = {};\n }\n if (!branch[entry.fileId][entry.versionId]) {\n branch[entry.fileId][entry.versionId] = {};\n }\n\n for (const [locale, translation] of Object.entries(entry.translations)) {\n branch[entry.fileId][entry.versionId][locale] = {\n ...(translation.updatedAt ? { updatedAt: translation.updatedAt } : {}),\n ...(translation.postProcessHash\n ? { postProcessHash: translation.postProcessHash }\n : {}),\n };\n }\n }\n\n return branch;\n}\n\n// ── Public API ──────────────────────────────────────────────────────\n\n/**\n * Reads the lockfile and returns v2 data regardless of the on-disk format.\n * If the file is v1, `originalV1` contains the full v1 data so that\n * `writeLockfile` can merge changes back without losing other branches.\n */\nexport function readLockfile(settings: Settings): {\n data: DownloadedVersions;\n entryMap: EntryMap;\n originalV1: DownloadedVersionsV1 | null;\n} {\n let branchId = settings._branchId ?? '';\n\n let data: DownloadedVersions;\n let originalV1: DownloadedVersionsV1 | null = null;\n\n try {\n const rootPath = path.join(process.cwd(), GT_LOCK_FILE);\n if (!fs.existsSync(rootPath)) {\n data = { version: 2, branchId, entries: [] };\n } else {\n const raw = JSON.parse(fs.readFileSync(rootPath, 'utf8'));\n if (!raw || typeof raw !== 'object' || !raw.entries) {\n data = { version: 2, branchId, entries: [] };\n } else if (raw.version === 2 && Array.isArray(raw.entries)) {\n data = raw as DownloadedVersions;\n if (branchId) data.branchId = branchId;\n } else {\n originalV1 = raw as DownloadedVersionsV1;\n if (!branchId) {\n const branches = Object.keys(originalV1.entries);\n if (branches.length > 0) branchId = branches[0];\n }\n data = convertV1ToV2(originalV1, branchId);\n }\n }\n } catch (error) {\n logger.error(`An error occurred while reading ${GT_LOCK_FILE}: ${error}`);\n data = { version: 2, branchId, entries: [] };\n }\n\n return { data, entryMap: buildEntryMap(data.entries), originalV1 };\n}\n\n/**\n * Writes the lockfile. If `originalV1` is provided, merges the current\n * branch's data back into the v1 structure (preserving other branches)\n * and writes v1 format. Otherwise writes v2.\n */\nexport function writeLockfile(\n data: DownloadedVersions,\n originalV1: DownloadedVersionsV1 | null\n): void {\n try {\n const filepath = path.join(process.cwd(), GT_LOCK_FILE);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // V1 format can't represent the staged flag — upgrade to V2 if any entries are staged\n if (originalV1 && !data.entries.some((e) => e.staged)) {\n const mergedV1: DownloadedVersionsV1 = {\n ...originalV1,\n entries: {\n ...originalV1.entries,\n [data.branchId]: convertV2ToV1Branch(data),\n },\n };\n fs.writeFileSync(filepath, JSON.stringify(mergedV1, null, 2));\n } else {\n fs.writeFileSync(filepath, JSON.stringify(data, null, 2));\n }\n } catch (error) {\n logger.error(`An error occurred while updating ${GT_LOCK_FILE}: ${error}`);\n }\n}\n\n// ── Lookup helpers ──────────────────────────────────────────────────\n\nexport type EntryMap = Map<string, DownloadedVersionEntry>;\n\nexport function buildEntryMap(entries: DownloadedVersionEntry[]): EntryMap {\n return new Map(entries.map((e) => [e.fileId, e]));\n}\n\n/**\n * Finds or creates an entry, keeping the map and backing array in sync.\n * If the fileId exists but versionId changed, replaces it in-place.\n */\nexport function findOrCreateEntry(\n entryMap: EntryMap,\n entries: DownloadedVersionEntry[],\n fileId: string,\n versionId: string\n): DownloadedVersionEntry {\n const existing = entryMap.get(fileId);\n if (existing) {\n if (existing.versionId === versionId) return existing;\n // Version changed — replace in array and map\n const updated: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n const idx = entries.indexOf(existing);\n if (idx !== -1) entries[idx] = updated;\n entryMap.set(fileId, updated);\n return updated;\n }\n const entry: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n entries.push(entry);\n entryMap.set(fileId, entry);\n return entry;\n}\n\n// ── Staging helpers ─────────────────────────────────────────────────\n\n/**\n * Writes staged file entries into the lockfile.\n * Each entry is marked with `staged: true` and empty translations.\n */\nexport function writeStagedEntries(\n settings: Settings,\n stagedFiles: { fileId: string; versionId: string; fileName: string }[],\n branchId?: string\n): void {\n const { data, entryMap, originalV1 } = readLockfile(settings);\n\n if (branchId) {\n data.branchId = branchId;\n }\n\n for (const file of stagedFiles) {\n const entry = findOrCreateEntry(\n entryMap,\n data.entries,\n file.fileId,\n file.versionId\n );\n entry.fileName = file.fileName;\n entry.staged = true;\n }\n\n writeLockfile(data, originalV1);\n}\n\n/**\n * Reads staged entries from the lockfile.\n * Returns the same shape as FileTranslationData for compatibility\n * with the download workflow.\n */\nexport function getStagedEntriesFromLockfile(\n settings: Settings\n): Record<string, { versionId: string; fileName: string }> {\n const { data } = readLockfile(settings);\n const result: Record<string, { versionId: string; fileName: string }> = {};\n\n for (const entry of data.entries) {\n if (entry.staged && entry.fileName) {\n result[entry.fileId] = {\n versionId: entry.versionId,\n fileName: entry.fileName,\n };\n }\n }\n\n return result;\n}\n"],"mappings":";;;;AAKA,MAAM,eAAe;AAgDrB,SAAS,cACP,IACA,UACoB;CACpB,MAAM,gBAAgB,GAAG,UAAU;AACnC,KAAI,CAAC,cACH,QAAO;EAAE,SAAS;EAAG;EAAU,SAAS,EAAE;EAAE;CAG9C,MAAM,UAAoC,EAAE;AAE5C,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,EAAE;EAC9D,MAAM,aAAa,OAAO,KAAK,SAAS;AACxC,MAAI,WAAW,WAAW,EAAG;EAG7B,IAAI,kBAAkB,WAAW;EACjC,IAAI,aAAa;AAEjB,OAAK,MAAM,CAAC,WAAW,YAAY,OAAO,QAAQ,SAAS,CACzD,MAAK,MAAM,SAAS,OAAO,OAAO,QAAQ,EAAE;GAC1C,MAAM,IAAI,MAAM,YAAY,KAAK,MAAM,MAAM,UAAU,GAAG;AAC1D,OAAI,IAAI,YAAY;AAClB,iBAAa;AACb,sBAAkB;;;EAKxB,MAAM,gBAAgB,SAAS;EAC/B,MAAM,eAA4D,EAAE;AAEpE,OAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,cAAc,CACzD,cAAa,UAAU;GACrB,GAAI,MAAM,YAAY,EAAE,WAAW,MAAM,WAAW,GAAG,EAAE;GACzD,GAAI,MAAM,kBACN,EAAE,iBAAiB,M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Ac,EAAE;EACjB;AACD,SAAQ,KAAK,MAAM;AACnB,UAAS,IAAI,QAAQ,MAAM;AAC3B,QAAO;;;;;;AAST,SAAgB,mBACd,UACA,aACA,UACM;CACN,MAAM,EAAE,MAAM,UAAU,eAAe,aAAa,SAAS;AAE7D,KAAI,SACF,MAAK,WAAW;AAGlB,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,QAAQ,kBACZ,UACA,KAAK,SACL,KAAK,QACL,KAAK,UACN;AACD,QAAM,WAAW,KAAK;AACtB,QAAM,SAAS;;AAGjB,eAAc,MAAM,WAAW;;;;;;;AAQjC,SAAgB,6BACd,UACyD;CACzD,MAAM,EAAE,SAAS,aAAa,SAAS;CACvC,MAAM,SAAkE,EAAE;AAE1E,MAAK,MAAM,SAAS,KAAK,QACvB,KAAI,MAAM,UAAU,MAAM,SACxB,QAAO,MAAM,UAAU;EACrB,WAAW,MAAM;EACjB,UAAU,MAAM;EACjB;AAIL,QAAO"}
|
|
1
|
+
{"version":3,"file":"downloadedVersions.js","names":[],"sources":["../../../src/fs/config/downloadedVersions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../../console/logger.js';\nimport { stringifyJson } from '../stringifyJson.js';\nimport type { Settings } from '../../types/index.js';\n\nconst GT_LOCK_FILE = 'gt-lock.json';\n\n// ── V2 types (internal working format) ──────────────────────────────\n\nexport type DownloadedTranslation = {\n updatedAt?: string;\n postProcessHash?: string;\n fileName?: string; // output path for this locale, e.g. \"es-US/my/file/path.mdx\"\n};\n\nexport type DownloadedVersionEntry = {\n fileId: string;\n versionId: string;\n fileName?: string; // source file path\n staged?: boolean; // true if this entry was staged but not yet downloaded\n translations: {\n [locale: string]: DownloadedTranslation;\n };\n};\n\nexport type DownloadedVersions = {\n version: 2;\n branchId: string;\n entries: DownloadedVersionEntry[];\n};\n\n// ── V1 types (backwards compatibility) ──────────────────────────────\n\nexport type DownloadedVersionEntryV1 = {\n fileName?: string;\n updatedAt?: string;\n postProcessHash?: string;\n sourceHash?: string;\n};\n\nexport type DownloadedVersionsV1 = {\n version: number;\n entries: {\n [branchId: string]: {\n [fileId: string]: {\n [versionId: string]: { [locale: string]: DownloadedVersionEntryV1 };\n };\n };\n };\n};\n\n// ── Conversion helpers ──────────────────────────────────────────────\n\nfunction convertV1ToV2(\n v1: DownloadedVersionsV1,\n branchId: string\n): DownloadedVersions {\n const branchEntries = v1.entries?.[branchId];\n if (!branchEntries) {\n return { version: 2, branchId, entries: [] };\n }\n\n const entries: DownloadedVersionEntry[] = [];\n\n for (const [fileId, versions] of Object.entries(branchEntries)) {\n const versionIds = Object.keys(versions);\n if (versionIds.length === 0) continue;\n\n // Pick the versionId with the most recent updatedAt, defaulting to the first\n let latestVersionId = versionIds[0];\n let latestTime = 0;\n\n for (const [versionId, locales] of Object.entries(versions)) {\n for (const entry of Object.values(locales)) {\n const t = entry.updatedAt ? Date.parse(entry.updatedAt) : 0;\n if (t > latestTime) {\n latestTime = t;\n latestVersionId = versionId;\n }\n }\n }\n\n const localeEntries = versions[latestVersionId];\n const translations: { [locale: string]: DownloadedTranslation } = {};\n\n for (const [locale, entry] of Object.entries(localeEntries)) {\n translations[locale] = {\n ...(entry.updatedAt ? { updatedAt: entry.updatedAt } : {}),\n ...(entry.postProcessHash\n ? { postProcessHash: entry.postProcessHash }\n : {}),\n };\n }\n\n entries.push({\n fileId,\n versionId: latestVersionId,\n translations,\n });\n }\n\n return { version: 2, branchId, entries };\n}\n\nfunction convertV2ToV1Branch(\n v2: DownloadedVersions\n): DownloadedVersionsV1['entries'][string] {\n const branch: DownloadedVersionsV1['entries'][string] = {};\n\n for (const entry of v2.entries) {\n if (!branch[entry.fileId]) {\n branch[entry.fileId] = {};\n }\n if (!branch[entry.fileId][entry.versionId]) {\n branch[entry.fileId][entry.versionId] = {};\n }\n\n for (const [locale, translation] of Object.entries(entry.translations)) {\n branch[entry.fileId][entry.versionId][locale] = {\n ...(translation.updatedAt ? { updatedAt: translation.updatedAt } : {}),\n ...(translation.postProcessHash\n ? { postProcessHash: translation.postProcessHash }\n : {}),\n };\n }\n }\n\n return branch;\n}\n\n// ── Public API ──────────────────────────────────────────────────────\n\n/**\n * Reads the lockfile and returns v2 data regardless of the on-disk format.\n * If the file is v1, `originalV1` contains the full v1 data so that\n * `writeLockfile` can merge changes back without losing other branches.\n */\nexport function readLockfile(settings: Settings): {\n data: DownloadedVersions;\n entryMap: EntryMap;\n originalV1: DownloadedVersionsV1 | null;\n} {\n let branchId = settings._branchId ?? '';\n\n let data: DownloadedVersions;\n let originalV1: DownloadedVersionsV1 | null = null;\n\n try {\n const rootPath = path.join(process.cwd(), GT_LOCK_FILE);\n if (!fs.existsSync(rootPath)) {\n data = { version: 2, branchId, entries: [] };\n } else {\n const raw = JSON.parse(fs.readFileSync(rootPath, 'utf8'));\n if (!raw || typeof raw !== 'object' || !raw.entries) {\n data = { version: 2, branchId, entries: [] };\n } else if (raw.version === 2 && Array.isArray(raw.entries)) {\n data = raw as DownloadedVersions;\n if (branchId) data.branchId = branchId;\n } else {\n originalV1 = raw as DownloadedVersionsV1;\n if (!branchId) {\n const branches = Object.keys(originalV1.entries);\n if (branches.length > 0) branchId = branches[0];\n }\n data = convertV1ToV2(originalV1, branchId);\n }\n }\n } catch (error) {\n logger.error(`An error occurred while reading ${GT_LOCK_FILE}: ${error}`);\n data = { version: 2, branchId, entries: [] };\n }\n\n return { data, entryMap: buildEntryMap(data.entries), originalV1 };\n}\n\n/**\n * Writes the lockfile. If `originalV1` is provided, merges the current\n * branch's data back into the v1 structure (preserving other branches)\n * and writes v1 format. Otherwise writes v2.\n */\nexport function writeLockfile(\n data: DownloadedVersions,\n originalV1: DownloadedVersionsV1 | null\n): void {\n try {\n const filepath = path.join(process.cwd(), GT_LOCK_FILE);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // V1 format can't represent the staged flag — upgrade to V2 if any entries are staged\n if (originalV1 && !data.entries.some((e) => e.staged)) {\n const mergedV1: DownloadedVersionsV1 = {\n ...originalV1,\n entries: {\n ...originalV1.entries,\n [data.branchId]: convertV2ToV1Branch(data),\n },\n };\n fs.writeFileSync(filepath, stringifyJson(mergedV1));\n } else {\n fs.writeFileSync(filepath, stringifyJson(data));\n }\n } catch (error) {\n logger.error(`An error occurred while updating ${GT_LOCK_FILE}: ${error}`);\n }\n}\n\n// ── Lookup helpers ──────────────────────────────────────────────────\n\nexport type EntryMap = Map<string, DownloadedVersionEntry>;\n\nexport function buildEntryMap(entries: DownloadedVersionEntry[]): EntryMap {\n return new Map(entries.map((e) => [e.fileId, e]));\n}\n\n/**\n * Finds or creates an entry, keeping the map and backing array in sync.\n * If the fileId exists but versionId changed, replaces it in-place.\n */\nexport function findOrCreateEntry(\n entryMap: EntryMap,\n entries: DownloadedVersionEntry[],\n fileId: string,\n versionId: string\n): DownloadedVersionEntry {\n const existing = entryMap.get(fileId);\n if (existing) {\n if (existing.versionId === versionId) return existing;\n // Version changed — replace in array and map\n const updated: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n const idx = entries.indexOf(existing);\n if (idx !== -1) entries[idx] = updated;\n entryMap.set(fileId, updated);\n return updated;\n }\n const entry: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n entries.push(entry);\n entryMap.set(fileId, entry);\n return entry;\n}\n\n// ── Staging helpers ─────────────────────────────────────────────────\n\n/**\n * Writes staged file entries into the lockfile.\n * Each entry is marked with `staged: true` and empty translations.\n */\nexport function writeStagedEntries(\n settings: Settings,\n stagedFiles: { fileId: string; versionId: string; fileName: string }[],\n branchId?: string\n): void {\n const { data, entryMap, originalV1 } = readLockfile(settings);\n\n if (branchId) {\n data.branchId = branchId;\n }\n\n for (const file of stagedFiles) {\n const entry = findOrCreateEntry(\n entryMap,\n data.entries,\n file.fileId,\n file.versionId\n );\n entry.fileName = file.fileName;\n entry.staged = true;\n }\n\n writeLockfile(data, originalV1);\n}\n\n/**\n * Reads staged entries from the lockfile.\n * Returns the same shape as FileTranslationData for compatibility\n * with the download workflow.\n */\nexport function getStagedEntriesFromLockfile(\n settings: Settings\n): Record<string, { versionId: string; fileName: string }> {\n const { data } = readLockfile(settings);\n const result: Record<string, { versionId: string; fileName: string }> = {};\n\n for (const entry of data.entries) {\n if (entry.staged && entry.fileName) {\n result[entry.fileId] = {\n versionId: entry.versionId,\n fileName: entry.fileName,\n };\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;AAMA,MAAM,eAAe;AAgDrB,SAAS,cACP,IACA,UACoB;CACpB,MAAM,gBAAgB,GAAG,UAAU;AACnC,KAAI,CAAC,cACH,QAAO;EAAE,SAAS;EAAG;EAAU,SAAS,EAAE;EAAE;CAG9C,MAAM,UAAoC,EAAE;AAE5C,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,EAAE;EAC9D,MAAM,aAAa,OAAO,KAAK,SAAS;AACxC,MAAI,WAAW,WAAW,EAAG;EAG7B,IAAI,kBAAkB,WAAW;EACjC,IAAI,aAAa;AAEjB,OAAK,MAAM,CAAC,WAAW,YAAY,OAAO,QAAQ,SAAS,CACzD,MAAK,MAAM,SAAS,OAAO,OAAO,QAAQ,EAAE;GAC1C,MAAM,IAAI,MAAM,YAAY,KAAK,MAAM,MAAM,UAAU,GAAG;AAC1D,OAAI,IAAI,YAAY;AAClB,iBAAa;AACb,sBAAkB;;;EAKxB,MAAM,gBAAgB,SAAS;EAC/B,MAAM,eAA4D,EAAE;AAEpE,OAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,cAAc,CACzD,cAAa,UAAU;GACrB,GAAI,MAAM,YAAY,EAAE,WAAW,MAAM,WAAW,GAAG,EAAE;GACzD,GAAI,MAAM,kBACN,EAAE,iBAAiB,MAAM,iBAAiB,GAC1C,EAAE;GACP;AAGH,UAAQ,KAAK;GACX;GACA,WAAW;GACX;GACD,CAAC;;AAGJ,QAAO;EAAE,SAAS;EAAG;EAAU;EAAS;;AAG1C,SAAS,oBACP,IACyC;CACzC,M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AW;AAGlB,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,QAAQ,kBACZ,UACA,KAAK,SACL,KAAK,QACL,KAAK,UACN;AACD,QAAM,WAAW,KAAK;AACtB,QAAM,SAAS;;AAGjB,eAAc,MAAM,WAAW;;;;;;;AAQjC,SAAgB,6BACd,UACyD;CACzD,MAAM,EAAE,SAAS,aAAa,SAAS;CACvC,MAAM,SAAkE,EAAE;AAE1E,MAAK,MAAM,SAAS,KAAK,QACvB,KAAI,MAAM,UAAU,MAAM,SACxB,QAAO,MAAM,UAAU;EACrB,WAAW,MAAM;EACjB,UAAU,MAAM;EACjB;AAIL,QAAO"}
|
|
@@ -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,4 +1,5 @@
|
|
|
1
1
|
import { logger } from "../../console/logger.js";
|
|
2
|
+
import { stringifyJson } from "../stringifyJson.js";
|
|
2
3
|
import { displayUpdatedConfigFile } from "../../console/logging.js";
|
|
3
4
|
import fs from "node:fs";
|
|
4
5
|
//#region src/fs/config/updateConfig.ts
|
|
@@ -21,15 +22,16 @@ async function updateConfig(configFilepath, options) {
|
|
|
21
22
|
};
|
|
22
23
|
try {
|
|
23
24
|
let oldContent = {};
|
|
25
|
+
let originalText;
|
|
24
26
|
if (fs.existsSync(configFilepath)) {
|
|
25
|
-
|
|
27
|
+
originalText = await fs.promises.readFile(configFilepath, "utf-8");
|
|
28
|
+
const parsed = JSON.parse(originalText);
|
|
26
29
|
oldContent = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
27
30
|
}
|
|
28
|
-
const
|
|
31
|
+
const jsonContent = stringifyJson(applyNullFilter({
|
|
29
32
|
...oldContent,
|
|
30
33
|
...newContent
|
|
31
|
-
}, options);
|
|
32
|
-
const jsonContent = JSON.stringify(filteredContent, null, 2);
|
|
34
|
+
}, options), originalText);
|
|
33
35
|
await fs.promises.writeFile(configFilepath, jsonContent, "utf-8");
|
|
34
36
|
displayUpdatedConfigFile(configFilepath);
|
|
35
37
|
} catch (error) {
|